diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..792f68793b805dc1095438b44300e078f8e2151b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +*.data filter=lfs diff=lfs merge=lfs -text +*.png filter=lfs diff=lfs merge=lfs -text diff --git a/assets/__vite-browser-external-BIHI7g3E.js b/assets/__vite-browser-external-BIHI7g3E.js new file mode 100644 index 0000000000000000000000000000000000000000..b480ffe6ce7040f68468da9d453d371cbc190177 --- /dev/null +++ b/assets/__vite-browser-external-BIHI7g3E.js @@ -0,0 +1 @@ +const e={};export{e as default}; diff --git a/assets/embeddingworker-B0-b0Bg2.js b/assets/embeddingworker-B0-b0Bg2.js new file mode 100644 index 0000000000000000000000000000000000000000..11753dce77cb6cf509648018bd417c5a23fce522 --- /dev/null +++ b/assets/embeddingworker-B0-b0Bg2.js @@ -0,0 +1,2896 @@ +var wT=Object.defineProperty;var MT=(ks,qr,Bn)=>qr in ks?wT(ks,qr,{enumerable:!0,configurable:!0,writable:!0,value:Bn}):ks[qr]=Bn;var J=(ks,qr,Bn)=>MT(ks,typeof qr!="symbol"?qr+"":qr,Bn);(function(){"use strict";const ks=new Map,qr=[],Bn=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=ks.get(e);if(s===void 0)ks.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){const o=qr.indexOf(e);o!==-1&&qr.splice(o,1);for(let n=0;n{const r=ks.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{const t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},fv=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?qr:t;let o;const n=[],i=new Set;for(const l of s){const c=await _v(l);typeof c=="string"?n.push({name:l,err:c}):(o||(o=c),o===c&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:c}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);const a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,c)=>c==="executionProviders"?a:Reflect.get(l,c)})]},gv="1.21.0";let Fu="warning";const ms={wasm:{},webgl:{},webgpu:{},versions:{common:gv},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}`);Fu=e}},get logLevel(){return Fu}};Object.defineProperty(ms,"logLevel",{enumerable:!0});const wv=ms,Mv=(e,r)=>{const t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];const s=t.getContext("2d");if(s!=null){let o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);const i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm;let l,c;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));const p=n*o;let d=0,u=p,f=p*2,_=-1;i==="RGBA"?(d=0,u=p,f=p*2,_=p*3):i==="RGB"?(d=0,u=p,f=p*2):i==="RBG"&&(d=0,f=p,u=p*2);for(let b=0;b{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm;let c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));const d=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const u=4;let f=0,_=1,b=2,k=3,g=0,M=d,$=d*2,v=-1;a==="RGBA"?(g=0,M=d,$=d*2,v=d*3):a==="RGB"?(g=0,M=d,$=d*2):a==="RBG"&&(g=0,$=d,M=d*2),s=t.createImageData(o,n);for(let y=0;y{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:t,width:s}=r,o=r.norm??{mean:255,bias:0};let n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3);let d=4,u=0,f=1,_=2,b=3,k=0,g=c,M=c*2,$=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,b=-1),l==="RGBA"?$=c*3:l==="RBG"?(k=0,M=c,g=c*2):l==="BGR"&&(M=0,g=c,k=c*2);for(let y=0;y{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string";let i,a=r??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){const p=l();p.width=e.width,p.height=e.height;const d=c(p);if(d!=null){let u=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(u=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=u,a.width=f}else a.tensorFormat="RGBA",a.height=u,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,u).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){const u=l();u.width=d,u.height=p;const f=c(u);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");const p=l();p.width=e.width,p.height=e.height;const d=c(p);if(d!=null){const u=e.height,f=e.width;return d.drawImage(e,0,0,f,u),i=d.getImageData(0,0,f,u).data,a.height=u,a.width=f,wa(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,d)=>{const u=l(),f=c(u);if(!e||!f)return d();const _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{u.width=_.width,u.height=_.height,f.drawImage(_,0,0,u.width,u.height);const b=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(wa(b.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return wa(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},vv=(e,r)=>{const{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new as({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},xv=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new as({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},Tv=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new as({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},Ev=(e,r,t)=>new as({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),Rn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ei=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Ou=!1;const Pv=()=>{if(!Ou){Ou=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(Rn.set("int64",BigInt64Array),ei.set(BigInt64Array,"int64")),r&&(Rn.set("uint64",BigUint64Array),ei.set(BigUint64Array,"uint64")),s?(Rn.set("float16",t),ei.set(t,"float16")):Rn.set("float16",Uint16Array)}},Cv=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new as(e.type,e.data,r);case"cpu-pinned":return new as({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new as({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new as({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new as({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let as=class{constructor(r,t,s){Pv();let o,n;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,o=r.type,n=r.dims,r.location){case"cpu-pinned":{const a=Rn.get(o);if(!a)throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`);if(!(r.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=r.data;break}case"texture":{if(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from MLTensor`);this.mlTensorData=r.mlTensor,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,l;if(typeof r=="string")if(o=r,l=s,r==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{const c=Rn.get(r);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&c===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${c.name} as data.`);r==="uint64"||r==="int64"?a=c.from(t,BigInt):a=c.from(t)}else if(t instanceof c)a=t;else if(t instanceof Uint8ClampedArray)if(r==="uint8")a=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(r==="float16"&&t instanceof Uint16Array&&c!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${o} tensor's data must be type of ${c}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const c=typeof r[0];if(c==="string")o="string",a=r;else if(c==="boolean")o="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(r instanceof Uint8ClampedArray)o="uint8",a=Uint8Array.from(r);else{const c=ei.get(r.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);o=c,a=r}if(l===void 0)l=[a.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");n=l,this.cpuData=a,this.dataLocation="cpu"}const i=Cv(n);if(this.cpuData&&i!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=n,this.size=i}static async fromImage(r,t){return yv(r,t)}static fromTexture(r,t){return vv(r,t)}static fromGpuBuffer(r,t){return xv(r,t)}static fromMLTensor(r,t){return Tv(r,t)}static fromPinnedBuffer(r,t,s){return Ev(r,t,s)}toDataURL(r){return Mv(this,r)}toImageData(r){return bv(this,r)}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}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(r){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,r&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=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(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Sv(this,r)}};const jn=as,Du=(e,r)=>{(typeof ms.trace>"u"?!ms.wasm.trace:!ms.trace)||console.timeStamp(`${e}::ORT::${r}`)},Lu=(e,r)=>{var o;const t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[];let s=!1;for(let n=0;n{(typeof ms.trace>"u"?!ms.wasm.trace:!ms.trace)||Lu("BEGIN",e)},ba=e=>{(typeof ms.trace>"u"?!ms.wasm.trace:!ms.trace)||Lu("END",e)};var $v=Object.freeze({__proto__:null,InferenceSession:class pv{constructor(r){this.handler=r}async run(r,t,s){Ma();const o={};let n={};if(typeof r!="object"||r===null||r instanceof jn||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof jn)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(const c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);o[c]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1;const p=Object.getOwnPropertyNames(t);for(const d of this.outputNames)if(p.indexOf(d)!==-1){const u=t[d];(u===null||u instanceof jn)&&(c=!0,i=!1,o[d]=u)}if(c){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const c of this.inputNames)if(typeof r[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(i)for(const c of this.outputNames)o[c]=null;const a=await this.handler.run(r,o,n),l={};for(const c in a)if(Object.hasOwnProperty.call(a,c)){const p=a[c];p instanceof jn?l[c]=p:l[c]=new jn(p.type,p.data,p.dims)}return ba(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){Ma();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){const p=r;let d=0,u=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(u=r.byteLength-d,typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||d+u>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof o=="object"&&o!==null)i=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 t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,d,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await fv(i),c=await a.createInferenceSessionHandler(n,l);return ba(),new pv(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}},TRACE:Du,TRACE_FUNC_BEGIN:Ma,TRACE_FUNC_END:ba,Tensor:jn,env:wv,registerBackend:Bn});/*! + * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var ya=Object.defineProperty,kv=Object.getOwnPropertyDescriptor,Iv=Object.getOwnPropertyNames,Av=Object.prototype.hasOwnProperty,Fv=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ve=(e,r)=>()=>(e&&(r=e(e=0)),r),Nn=(e,r)=>{for(var t in r)ya(e,t,{get:r[t],enumerable:!0})},Ov=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of Iv(r))!Av.call(e,o)&&o!==t&&ya(e,o,{get:()=>r[o],enumerable:!(s=kv(r,o))||s.enumerable});return e},lo=e=>Ov(ya({},"__esModule",{value:!0}),e),co,Gs,cn,zu,Bu,Ru=Ve(()=>{co=new Map,Gs=[],cn=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=co.get(e);if(s===void 0)co.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){let o=Gs.indexOf(e);o!==-1&&Gs.splice(o,1);for(let n=0;n{let r=co.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{let t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},Bu=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Gs:t,o,n=[],i=new Set;for(let l of s){let c=await zu(l);typeof c=="string"?n.push({name:l,err:c}):(o||(o=c),o===c&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,c)=>c==="executionProviders"?a:Reflect.get(l,c)})]}}),Dv=Ve(()=>{Ru()}),ju,Lv=Ve(()=>{ju="1.22.0-dev.20250409-89f8206ba4"}),va,ls,Nu=Ve(()=>{Lv(),va="warning",ls={wasm:{},webgl:{},webgpu:{},versions:{common:ju},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}`);va=e}},get logLevel(){return va}},Object.defineProperty(ls,"logLevel",{enumerable:!0})}),Yt,zv=Ve(()=>{Nu(),Yt=ls}),Vu,Uu,Bv=Ve(()=>{Vu=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];let s=t.getContext("2d");if(s!=null){let o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);let i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm,l,c;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));let p=n*o,d=0,u=p,f=p*2,_=-1;i==="RGBA"?(d=0,u=p,f=p*2,_=p*3):i==="RGB"?(d=0,u=p,f=p*2):i==="RBG"&&(d=0,f=p,u=p*2);for(let b=0;b{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let d=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let u=4,f=0,_=1,b=2,k=3,g=0,M=d,$=d*2,v=-1;a==="RGBA"?(g=0,M=d,$=d*2,v=d*3):a==="RGB"?(g=0,M=d,$=d*2):a==="RBG"&&(g=0,$=d,M=d*2),s=t.createImageData(o,n);for(let y=0;y{Ta(),ti=(e,r)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:s}=r,o=r.norm??{mean:255,bias:0},n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),d=4,u=0,f=1,_=2,b=3,k=0,g=c,M=c*2,$=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,b=-1),l==="RGBA"?$=c*3:l==="RBG"?(k=0,M=c,g=c*2):l==="BGR"&&(M=0,g=c,k=c*2);for(let v=0;v{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string",i,a=r??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){let p=l();p.width=e.width,p.height=e.height;let d=c(p);if(d!=null){let u=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(u=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=u,a.width=f}else a.tensorFormat="RGBA",a.height=u,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,u).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){let u=l();u.width=d,u.height=p;let f=c(u);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=e.width,p.height=e.height;let d=c(p);if(d!=null){let u=e.height,f=e.width;return d.drawImage(e,0,0,f,u),i=d.getImageData(0,0,f,u).data,a.height=u,a.width=f,ti(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,d)=>{let u=l(),f=c(u);if(!e||!f)return d();let _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{u.width=_.width,u.height=_.height,f.drawImage(_,0,0,u.width,u.height);let b=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(ti(b.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return ti(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Gu=(e,r)=>{let{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new ss({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},Ku=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new ss({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},Hu=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new ss({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},qu=(e,r,t)=>new ss({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),un,uo,xa,Qu,jv=Ve(()=>{un=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),uo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),xa=!1,Qu=()=>{if(!xa){xa=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(un.set("int64",BigInt64Array),uo.set(BigInt64Array,"int64")),r&&(un.set("uint64",BigUint64Array),uo.set(BigUint64Array,"uint64")),s?(un.set("float16",t),uo.set(t,"float16")):un.set("float16",Uint16Array)}}}),Xu,Ju,Nv=Ve(()=>{Ta(),Xu=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new ss(e.type,e.data,r);case"cpu-pinned":return new ss({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new ss({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new ss({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new ss({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),ss,Ta=Ve(()=>{Bv(),Rv(),jv(),Nv(),ss=class{constructor(e,r,t){Qu();let s,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=un.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,a;if(typeof e=="string")if(s=e,a=t,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let l=un.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?i=l.from(r,BigInt):i=l.from(r)}else if(r instanceof l)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&l!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(a=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",i=e;else if(l==="boolean")s="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(e);else{let l=uo.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,i=e}if(a===void 0)a=[i.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");o=a,this.cpuData=i,this.dataLocation="cpu"}let n=Xu(o);if(this.cpuData&&n!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(n/2)===this.cpuData.length))throw new Error(`Tensor's size(${n}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=o,this.size=n}static async fromImage(e,r){return Wu(e,r)}static fromTexture(e,r){return Gu(e,r)}static fromGpuBuffer(e,r){return Ku(e,r)}static fromMLTensor(e,r){return Hu(e,r)}static fromPinnedBuffer(e,r,t){return qu(e,r,t)}toDataURL(e){return Vu(this,e)}toImageData(e){return Uu(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Ju(this,e)}}}),_s,Yu=Ve(()=>{Ta(),_s=ss}),po,Ea,fs,cs,Zu=Ve(()=>{Nu(),po=(e,r)=>{(typeof ls.trace>"u"?!ls.wasm.trace:!ls.trace)||console.timeStamp(`${e}::ORT::${r}`)},Ea=(e,r)=>{var o;let t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[],s=!1;for(let n=0;n{(typeof ls.trace>"u"?!ls.wasm.trace:!ls.trace)||Ea("BEGIN",e)},cs=e=>{(typeof ls.trace>"u"?!ls.wasm.trace:!ls.trace)||Ea("END",e)}}),ed,Vv=Ve(()=>{Ru(),Yu(),Zu(),ed=class hv{constructor(r){this.handler=r}async run(r,t,s){fs();let o={},n={};if(typeof r!="object"||r===null||r instanceof _s||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof _s)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);o[c]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(t);for(let d of this.outputNames)if(p.indexOf(d)!==-1){let u=t[d];(u===null||u instanceof _s)&&(c=!0,i=!1,o[d]=u)}if(c){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof r[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(i)for(let c of this.outputNames)o[c]=null;let a=await this.handler.run(r,o,n),l={};for(let c in a)if(Object.hasOwnProperty.call(a,c)){let p=a[c];p instanceof _s?l[c]=p:l[c]=new _s(p.type,p.data,p.dims)}return cs(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){fs();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){let p=r,d=0,u=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(u=r.byteLength-d,typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||d+u>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof o=="object"&&o!==null)i=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 t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,d,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await Bu(i),c=await a.createInferenceSessionHandler(n,l);return cs(),new hv(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Pa,Uv=Ve(()=>{Vv(),Pa=ed}),Wv=Ve(()=>{}),Gv=Ve(()=>{}),Kv=Ve(()=>{}),Hv=Ve(()=>{}),td={};Nn(td,{InferenceSession:()=>Pa,TRACE:()=>po,TRACE_FUNC_BEGIN:()=>fs,TRACE_FUNC_END:()=>cs,Tensor:()=>_s,env:()=>Yt,registerBackend:()=>cn});var gs=Ve(()=>{Dv(),zv(),Uv(),Yu(),Wv(),Gv(),Zu(),Kv(),Hv()}),Ca=Ve(()=>{}),rd={};Nn(rd,{default:()=>sd});var Sa,$a,sd,qv=Ve(()=>{var e;zg(),dn(),za(),Sa="ort-wasm-proxy-worker",$a=((e=globalThis.self)==null?void 0:e.name)===Sa,$a&&(self.onmessage=r=>{let{type:t,in:s}=r.data;try{switch(t){case"init-wasm":ja(s.wasm).then(()=>{Zl(s).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:n}=s;ec(n,o).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:o}=s,n=bi(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=s;rc(o,n).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":sc(s),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:i,outputIndices:a,options:l}=s;oc(o,n,i,a,new Array(a.length).fill(null),l).then(c=>{c.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:c},ac([...i,...c]))},c=>{postMessage({type:t,err:c})});break}case"end-profiling":ic(s),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}}),sd=$a?null:r=>new Worker(r??ns,{type:"module",name:Sa})}),nd={};Nn(nd,{default:()=>od});var ka,Ia,od,id,Qv=Ve(()=>{var e,r;Ia=(ka=self.location.href,async function(t={}){var no;var s,o,n=t,i=new Promise((h,E)=>{s=h,o=E}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",c=l&&((no=self.name)==null?void 0:no.startsWith("em-pthread"));n.mountExternalData=(h,E)=>{h.startsWith("./")&&(h=h.substring(2)),(n.Eb||(n.Eb=new Map)).set(h,E)},n.unmountExternalData=()=>{delete n.Eb};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let d=h=>async(...E)=>{var A;try{if(n.Fb)throw Error("Session already started");let z=n.Fb={dc:E[0],errors:[]},V=await h(...E);if(n.Fb!==z)throw Error("Session mismatch");(A=n.Jb)==null||A.flush();let ce=z.errors;if(0De),0{if(h==="webgpu"){[n.Jb,n.Ub,n.Yb,n.Kb,n.Xb,n.jb,n.Zb,n.ac,n.Vb,n.Wb,n.$b]=E;let A=n.Jb;n.jsepRegisterBuffer=(z,V,ce,Pe)=>A.registerBuffer(z,V,ce,Pe),n.jsepGetBuffer=z=>A.getBuffer(z),n.jsepCreateDownloader=(z,V,ce)=>A.createDownloader(z,V,ce),n.jsepOnCreateSession=z=>{A.onCreateSession(z)},n.jsepOnReleaseSession=z=>{A.onReleaseSession(z)},n.jsepOnRunStart=z=>A.onRunStart(z),n.bc=(z,V)=>{A.upload(z,V)}}else if(h==="webnn"){let A=E[0];[n.nc,n.Nb,n.webnnEnsureTensor,n.Ob,n.webnnDownloadTensor]=E.slice(1),n.webnnReleaseTensorId=n.Nb,n.webnnUploadTensor=n.Ob,n.webnnOnRunStart=z=>A.onRunStart(z),n.webnnOnRunEnd=A.onRunEnd.bind(A),n.webnnRegisterMLContext=(z,V)=>{A.registerMLContext(z,V)},n.webnnOnReleaseSession=z=>{A.onReleaseSession(z)},n.webnnCreateMLTensorDownloader=(z,V)=>A.createMLTensorDownloader(z,V),n.webnnRegisterMLTensor=(z,V,ce,Pe)=>A.registerMLTensor(z,V,ce,Pe),n.webnnCreateMLContext=z=>A.createMLContext(z),n.webnnRegisterMLConstant=(z,V,ce,Pe,De,He)=>A.registerMLConstant(z,V,ce,Pe,De,n.Eb,He),n.webnnRegisterGraphInput=A.registerGraphInput.bind(A),n.webnnIsGraphInput=A.isGraphInput.bind(A),n.webnnCreateTemporaryTensor=A.createTemporaryTensor.bind(A),n.webnnIsInt64Supported=A.isInt64Supported.bind(A)}};let u=()=>{let h=(E,A,z)=>(...V)=>{let ce=fr,Pe=A==null?void 0:A();V=E(...V);let De=A==null?void 0:A();return Pe!==De&&(E=De,z(Pe),A=z=null),fr!=ce?new Promise((He,at)=>{zr={resolve:He,reject:at}}):V};(()=>{for(let E of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])n[E]=h(n[E],()=>n[E],A=>n[E]=A)})(),d!==void 0&&(n._OrtRun=d(n._OrtRun),n._OrtRunWithBinding=d(n._OrtRunWithBinding)),u=void 0};n.asyncInit=()=>{u==null||u()};var f,_,b=Object.assign({},n),k=(h,E)=>{throw E},g="";(a||l)&&(l?g=self.location.href:typeof document<"u"&&document.currentScript&&(g=document.currentScript.src),ka&&(g=ka),g=g.startsWith("blob:")?"":g.slice(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(_=h=>{var E=new XMLHttpRequest;return E.open("GET",h,!1),E.responseType="arraybuffer",E.send(null),new Uint8Array(E.response)}),f=async h=>{if(j(h))return new Promise((A,z)=>{var V=new XMLHttpRequest;V.open("GET",h,!0),V.responseType="arraybuffer",V.onload=()=>{V.status==200||V.status==0&&V.response?A(V.response):z(V.status)},V.onerror=z,V.send(null)});var E=await fetch(h,{credentials:"same-origin"});if(E.ok)return E.arrayBuffer();throw Error(E.status+" : "+E.url)});var M=console.log.bind(console),$=console.error.bind(console),v=M,y=$;Object.assign(n,b),b=null;var T,x,P,O,L,G,K,R,te,H,ee,Z,ne,me=n.wasmBinary,ue=!1,j=h=>h.startsWith("file://");function F(){return T.buffer!=O.buffer&&ae(),O}function U(){return T.buffer!=O.buffer&&ae(),L}function se(){return T.buffer!=O.buffer&&ae(),G}function _e(){return T.buffer!=O.buffer&&ae(),K}function ie(){return T.buffer!=O.buffer&&ae(),R}function ve(){return T.buffer!=O.buffer&&ae(),te}function ze(){return T.buffer!=O.buffer&&ae(),H}function Ge(){return T.buffer!=O.buffer&&ae(),ne}if(c){let h=function(E){try{var A=E.data,z=A.Bb;if(z==="load"){let V=[];self.onmessage=ce=>V.push(ce),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let ce of V)h(ce);self.onmessage=h};for(let ce of A.Rb)n[ce]&&!n[ce].proxy||(n[ce]=(...Pe)=>{postMessage({Bb:"callHandler",Qb:ce,args:Pe})},ce=="print"&&(v=n[ce]),ce=="printErr"&&(y=n[ce]));T=A.kc,ae(),Ie(A.lc)}else if(z==="run"){Xs(A.Ab),Zn(A.Ab,0,0,1,0,0),us(),de(A.Ab),X||(Vo(),X=!0);try{Js(A.fc,A.Hb)}catch(V){if(V!="unwind")throw V}}else A.target!=="setimmediate"&&(z==="checkMailbox"?X&&Te():z&&(y(`worker: received unknown command ${z}`),y(A)))}catch(V){throw eo(),V}};var Ie,X=!1;y=function(...E){E=E.join(" "),console.error(E)},self.alert=function(...E){postMessage({Bb:"alert",text:E.join(" "),ic:Sn()})},self.onunhandledrejection=E=>{throw E.reason||E},self.onmessage=h}function ae(){var h=T.buffer;n.HEAP8=O=new Int8Array(h),n.HEAP16=G=new Int16Array(h),n.HEAPU8=L=new Uint8Array(h),n.HEAPU16=K=new Uint16Array(h),n.HEAP32=R=new Int32Array(h),n.HEAPU32=te=new Uint32Array(h),n.HEAPF32=H=new Float32Array(h),n.HEAPF64=ne=new Float64Array(h),n.HEAP64=ee=new BigInt64Array(h),n.HEAPU64=Z=new BigUint64Array(h)}function W(){c?startWorker(n):dt.Ca()}c||(T=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),ae());var be,ke=0,Ee=null;function Me(){if(--ke==0&&Ee){var h=Ee;Ee=null,h()}}function Se(h){throw y(h="Aborted("+h+")"),ue=!0,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),o(h),h}function we(){return{a:{L:Qe,Aa:Be,b:Zs,$:As,A:S,pa:Q,X:re,Z:ge,qa:Fe,na:rt,ga:ft,ma:ht,J:vt,Y:st,V:zt,oa:Ut,W:Nr,va:Sr,E:Ds,Q:Wr,O:Gr,D:je,u:et,r:Xt,P:Vs,z:I,R:N,ja:Y,T:Ne,aa:We,M:tt,F:Mt,ia:de,sa:Bt,t:Wt,Ba:_r,w:ps,o:ar,l:Hr,c:Ts,n:Hn,j:Ei,v:Pi,p:Ci,f:tn,s:Si,m:$i,e:ki,k:Ii,i:Ai,g:rn,d:Fi,da:Oi,ea:ko,fa:Di,ba:Io,ca:qn,N:Fo,xa:Oo,ua:Li,h:Xn,C:zi,G:Bi,ta:pc,x:Ri,ra:ji,U:Ni,q:Ao,y:Vi,K:Ui,S:Wi,za:Do,ya:Gi,ka:Ki,la:zo,_:It,B:Hi,I:Bo,ha:Jn,H:Ro,a:T,wa:Ye}}}var Ae={829644:(h,E,A,z,V)=>{if(n===void 0||!n.Eb)return 1;if((h=Qt(Number(h>>>0))).startsWith("./")&&(h=h.substring(2)),!(h=n.Eb.get(h)))return 2;if(E=Number(E>>>0),A=Number(A>>>0),z=Number(z>>>0),E+A>h.byteLength)return 3;try{let ce=h.subarray(E,E+A);switch(V){case 0:U().set(ce,z>>>0);break;case 1:n.mc?n.mc(z,ce):n.bc(z,ce);break;default:return 4}return 0}catch{return 4}},830468:(h,E,A)=>{n.Ob(h,U().subarray(E>>>0,E+A>>>0))},830532:()=>n.nc(),830574:h=>{n.Nb(h)},830611:()=>{n.Vb()},830642:()=>{n.Wb()},830671:()=>{n.$b()},830696:h=>n.Ub(h),830729:h=>n.Yb(h),830761:(h,E,A)=>{n.Kb(Number(h),Number(E),Number(A),!0)},830824:(h,E,A)=>{n.Kb(Number(h),Number(E),Number(A))},830881:()=>typeof wasmOffsetConverter<"u",830938:h=>{n.jb("Abs",h,void 0)},830989:h=>{n.jb("Neg",h,void 0)},831040:h=>{n.jb("Floor",h,void 0)},831093:h=>{n.jb("Ceil",h,void 0)},831145:h=>{n.jb("Reciprocal",h,void 0)},831203:h=>{n.jb("Sqrt",h,void 0)},831255:h=>{n.jb("Exp",h,void 0)},831306:h=>{n.jb("Erf",h,void 0)},831357:h=>{n.jb("Sigmoid",h,void 0)},831412:(h,E,A)=>{n.jb("HardSigmoid",h,{alpha:E,beta:A})},831491:h=>{n.jb("Log",h,void 0)},831542:h=>{n.jb("Sin",h,void 0)},831593:h=>{n.jb("Cos",h,void 0)},831644:h=>{n.jb("Tan",h,void 0)},831695:h=>{n.jb("Asin",h,void 0)},831747:h=>{n.jb("Acos",h,void 0)},831799:h=>{n.jb("Atan",h,void 0)},831851:h=>{n.jb("Sinh",h,void 0)},831903:h=>{n.jb("Cosh",h,void 0)},831955:h=>{n.jb("Asinh",h,void 0)},832008:h=>{n.jb("Acosh",h,void 0)},832061:h=>{n.jb("Atanh",h,void 0)},832114:h=>{n.jb("Tanh",h,void 0)},832166:h=>{n.jb("Not",h,void 0)},832217:(h,E,A)=>{n.jb("Clip",h,{min:E,max:A})},832286:h=>{n.jb("Clip",h,void 0)},832338:(h,E)=>{n.jb("Elu",h,{alpha:E})},832396:h=>{n.jb("Gelu",h,void 0)},832448:h=>{n.jb("Relu",h,void 0)},832500:(h,E)=>{n.jb("LeakyRelu",h,{alpha:E})},832564:(h,E)=>{n.jb("ThresholdedRelu",h,{alpha:E})},832634:(h,E)=>{n.jb("Cast",h,{to:E})},832692:h=>{n.jb("Add",h,void 0)},832743:h=>{n.jb("Sub",h,void 0)},832794:h=>{n.jb("Mul",h,void 0)},832845:h=>{n.jb("Div",h,void 0)},832896:h=>{n.jb("Pow",h,void 0)},832947:h=>{n.jb("Equal",h,void 0)},833e3:h=>{n.jb("Greater",h,void 0)},833055:h=>{n.jb("GreaterOrEqual",h,void 0)},833117:h=>{n.jb("Less",h,void 0)},833169:h=>{n.jb("LessOrEqual",h,void 0)},833228:(h,E,A,z,V)=>{n.jb("ReduceMean",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},833403:(h,E,A,z,V)=>{n.jb("ReduceMax",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},833577:(h,E,A,z,V)=>{n.jb("ReduceMin",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},833751:(h,E,A,z,V)=>{n.jb("ReduceProd",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},833926:(h,E,A,z,V)=>{n.jb("ReduceSum",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},834100:(h,E,A,z,V)=>{n.jb("ReduceL1",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},834273:(h,E,A,z,V)=>{n.jb("ReduceL2",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},834446:(h,E,A,z,V)=>{n.jb("ReduceLogSum",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},834623:(h,E,A,z,V)=>{n.jb("ReduceSumSquare",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},834803:(h,E,A,z,V)=>{n.jb("ReduceLogSumExp",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},834983:h=>{n.jb("Where",h,void 0)},835036:(h,E,A)=>{n.jb("Transpose",h,{perm:E?Array.from(ie().subarray(Number(E)>>>0,Number(A)>>>0)):[]})},835160:(h,E,A,z)=>{n.jb("DepthToSpace",h,{blocksize:E,mode:Qt(A),format:z?"NHWC":"NCHW"})},835293:(h,E,A,z)=>{n.jb("DepthToSpace",h,{blocksize:E,mode:Qt(A),format:z?"NHWC":"NCHW"})},835426:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr,Ls)=>{n.jb("ConvTranspose",h,{format:He?"NHWC":"NCHW",autoPad:E,dilations:[A],group:z,kernelShape:[V],pads:[ce,Pe],strides:[De],wIsConst:()=>!!F()[at>>>0],outputPadding:xt?Array.from(ie().subarray(Number(xt)>>>0,Number(Ot)>>>0)):[],outputShape:Gt?Array.from(ie().subarray(Number(Gt)>>>0,Number(yr)>>>0)):[],activation:Qt(Ls)})},835859:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr)=>{n.jb("ConvTranspose",h,{format:De?"NHWC":"NCHW",autoPad:E,dilations:Array.from(ie().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:z,kernelShape:Array.from(ie().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(ie().subarray(Number(ce)>>>0,4+(Number(ce)>>>0)>>>0)),strides:Array.from(ie().subarray(Number(Pe)>>>0,2+(Number(Pe)>>>0)>>>0)),wIsConst:()=>!!F()[He>>>0],outputPadding:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],outputShape:Ot?Array.from(ie().subarray(Number(Ot)>>>0,Number(Gt)>>>0)):[],activation:Qt(yr)})},836520:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr,Ls)=>{n.jb("ConvTranspose",h,{format:He?"NHWC":"NCHW",autoPad:E,dilations:[A],group:z,kernelShape:[V],pads:[ce,Pe],strides:[De],wIsConst:()=>!!F()[at>>>0],outputPadding:xt?Array.from(ie().subarray(Number(xt)>>>0,Number(Ot)>>>0)):[],outputShape:Gt?Array.from(ie().subarray(Number(Gt)>>>0,Number(yr)>>>0)):[],activation:Qt(Ls)})},836953:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr)=>{n.jb("ConvTranspose",h,{format:De?"NHWC":"NCHW",autoPad:E,dilations:Array.from(ie().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:z,kernelShape:Array.from(ie().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(ie().subarray(Number(ce)>>>0,4+(Number(ce)>>>0)>>>0)),strides:Array.from(ie().subarray(Number(Pe)>>>0,2+(Number(Pe)>>>0)>>>0)),wIsConst:()=>!!F()[He>>>0],outputPadding:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],outputShape:Ot?Array.from(ie().subarray(Number(Ot)>>>0,Number(Gt)>>>0)):[],activation:Qt(yr)})},837614:(h,E)=>{n.jb("GlobalAveragePool",h,{format:E?"NHWC":"NCHW"})},837705:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr)=>{n.jb("AveragePool",h,{format:yr?"NHWC":"NCHW",auto_pad:E,ceil_mode:A,count_include_pad:z,storage_order:V,dilations:ce?Array.from(ie().subarray(Number(ce)>>>0,Number(Pe)>>>0)):[],kernel_shape:De?Array.from(ie().subarray(Number(De)>>>0,Number(He)>>>0)):[],pads:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],strides:Ot?Array.from(ie().subarray(Number(Ot)>>>0,Number(Gt)>>>0)):[]})},838184:(h,E)=>{n.jb("GlobalAveragePool",h,{format:E?"NHWC":"NCHW"})},838275:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr)=>{n.jb("AveragePool",h,{format:yr?"NHWC":"NCHW",auto_pad:E,ceil_mode:A,count_include_pad:z,storage_order:V,dilations:ce?Array.from(ie().subarray(Number(ce)>>>0,Number(Pe)>>>0)):[],kernel_shape:De?Array.from(ie().subarray(Number(De)>>>0,Number(He)>>>0)):[],pads:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],strides:Ot?Array.from(ie().subarray(Number(Ot)>>>0,Number(Gt)>>>0)):[]})},838754:(h,E)=>{n.jb("GlobalMaxPool",h,{format:E?"NHWC":"NCHW"})},838841:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr)=>{n.jb("MaxPool",h,{format:yr?"NHWC":"NCHW",auto_pad:E,ceil_mode:A,count_include_pad:z,storage_order:V,dilations:ce?Array.from(ie().subarray(Number(ce)>>>0,Number(Pe)>>>0)):[],kernel_shape:De?Array.from(ie().subarray(Number(De)>>>0,Number(He)>>>0)):[],pads:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],strides:Ot?Array.from(ie().subarray(Number(Ot)>>>0,Number(Gt)>>>0)):[]})},839316:(h,E)=>{n.jb("GlobalMaxPool",h,{format:E?"NHWC":"NCHW"})},839403:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr)=>{n.jb("MaxPool",h,{format:yr?"NHWC":"NCHW",auto_pad:E,ceil_mode:A,count_include_pad:z,storage_order:V,dilations:ce?Array.from(ie().subarray(Number(ce)>>>0,Number(Pe)>>>0)):[],kernel_shape:De?Array.from(ie().subarray(Number(De)>>>0,Number(He)>>>0)):[],pads:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],strides:Ot?Array.from(ie().subarray(Number(Ot)>>>0,Number(Gt)>>>0)):[]})},839878:(h,E,A,z,V)=>{n.jb("Gemm",h,{alpha:E,beta:A,transA:z,transB:V})},839982:h=>{n.jb("MatMul",h,void 0)},840036:(h,E,A,z)=>{n.jb("ArgMax",h,{keepDims:!!E,selectLastIndex:!!A,axis:z})},840144:(h,E,A,z)=>{n.jb("ArgMin",h,{keepDims:!!E,selectLastIndex:!!A,axis:z})},840252:(h,E)=>{n.jb("Softmax",h,{axis:E})},840315:(h,E)=>{n.jb("Concat",h,{axis:E})},840375:(h,E,A,z,V)=>{n.jb("Split",h,{axis:E,numOutputs:A,splitSizes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},840531:h=>{n.jb("Expand",h,void 0)},840585:(h,E)=>{n.jb("Gather",h,{axis:Number(E)})},840656:(h,E)=>{n.jb("GatherElements",h,{axis:Number(E)})},840735:(h,E)=>{n.jb("GatherND",h,{batch_dims:Number(E)})},840814:(h,E,A,z,V,ce,Pe,De,He,at,xt)=>{n.jb("Resize",h,{antialias:E,axes:A?Array.from(ie().subarray(Number(A)>>>0,Number(z)>>>0)):[],coordinateTransformMode:Qt(V),cubicCoeffA:ce,excludeOutside:Pe,extrapolationValue:De,keepAspectRatioPolicy:Qt(He),mode:Qt(at),nearestMode:Qt(xt)})},841176:(h,E,A,z,V,ce,Pe)=>{n.jb("Slice",h,{starts:E?Array.from(ie().subarray(Number(E)>>>0,Number(A)>>>0)):[],ends:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[],axes:ce?Array.from(ie().subarray(Number(ce)>>>0,Number(Pe)>>>0)):[]})},841440:h=>{n.jb("Tile",h,void 0)},841492:(h,E,A)=>{n.jb("InstanceNormalization",h,{epsilon:E,format:A?"NHWC":"NCHW"})},841606:(h,E,A)=>{n.jb("InstanceNormalization",h,{epsilon:E,format:A?"NHWC":"NCHW"})},841720:h=>{n.jb("Range",h,void 0)},841773:(h,E)=>{n.jb("Einsum",h,{equation:Qt(E)})},841854:(h,E,A,z,V)=>{n.jb("Pad",h,{mode:E,value:A,pads:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},841997:(h,E,A,z,V,ce)=>{n.jb("BatchNormalization",h,{epsilon:E,momentum:A,spatial:!!V,trainingMode:!!z,format:ce?"NHWC":"NCHW"})},842166:(h,E,A,z,V,ce)=>{n.jb("BatchNormalization",h,{epsilon:E,momentum:A,spatial:!!V,trainingMode:!!z,format:ce?"NHWC":"NCHW"})},842335:(h,E,A)=>{n.jb("CumSum",h,{exclusive:Number(E),reverse:Number(A)})},842432:(h,E,A)=>{n.jb("DequantizeLinear",h,{axis:E,blockSize:A})},842522:(h,E,A,z,V)=>{n.jb("GridSample",h,{align_corners:E,mode:Qt(A),padding_mode:Qt(z),format:V?"NHWC":"NCHW"})},842692:(h,E,A,z,V)=>{n.jb("GridSample",h,{align_corners:E,mode:Qt(A),padding_mode:Qt(z),format:V?"NHWC":"NCHW"})},842862:(h,E)=>{n.jb("ScatterND",h,{reduction:Qt(E)})},842947:(h,E,A,z,V,ce,Pe,De,He)=>{n.jb("Attention",h,{numHeads:E,isUnidirectional:A,maskFilterValue:z,scale:V,doRotary:ce,qkvHiddenSizes:Pe?Array.from(ie().subarray(Number(De)>>>0,Number(De)+Pe>>>0)):[],pastPresentShareBuffer:!!He})},843219:h=>{n.jb("BiasAdd",h,void 0)},843274:h=>{n.jb("BiasSplitGelu",h,void 0)},843335:h=>{n.jb("FastGelu",h,void 0)},843391:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr,Ls,Qi)=>{n.jb("Conv",h,{format:Ot?"NHWC":"NCHW",auto_pad:E,dilations:A?Array.from(ie().subarray(Number(A)>>>0,Number(z)>>>0)):[],group:V,kernel_shape:ce?Array.from(ie().subarray(Number(ce)>>>0,Number(Pe)>>>0)):[],pads:De?Array.from(ie().subarray(Number(De)>>>0,Number(He)>>>0)):[],strides:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],w_is_const:()=>!!F()[Number(Gt)>>>0],activation:Qt(yr),activation_params:Ls?Array.from(ze().subarray(Number(Ls)>>>0,Number(Qi)>>>0)):[]})},843975:h=>{n.jb("Gelu",h,void 0)},844027:(h,E,A,z,V,ce,Pe,De,He)=>{n.jb("GroupQueryAttention",h,{numHeads:E,kvNumHeads:A,scale:z,softcap:V,doRotary:ce,rotaryInterleaved:Pe,smoothSoftmax:De,localWindowSize:He})},844244:(h,E,A,z)=>{n.jb("LayerNormalization",h,{axis:E,epsilon:A,simplified:!!z})},844355:(h,E,A,z)=>{n.jb("LayerNormalization",h,{axis:E,epsilon:A,simplified:!!z})},844466:(h,E,A,z,V,ce)=>{n.jb("MatMulNBits",h,{k:E,n:A,accuracyLevel:z,bits:V,blockSize:ce})},844593:(h,E,A,z,V,ce)=>{n.jb("MultiHeadAttention",h,{numHeads:E,isUnidirectional:A,maskFilterValue:z,scale:V,doRotary:ce})},844752:(h,E)=>{n.jb("QuickGelu",h,{alpha:E})},844816:(h,E,A,z,V)=>{n.jb("RotaryEmbedding",h,{interleaved:!!E,numHeads:A,rotaryEmbeddingDim:z,scale:V})},844955:(h,E,A)=>{n.jb("SkipLayerNormalization",h,{epsilon:E,simplified:!!A})},845057:(h,E,A)=>{n.jb("SkipLayerNormalization",h,{epsilon:E,simplified:!!A})},845159:(h,E,A,z)=>{n.jb("GatherBlockQuantized",h,{gatherAxis:E,quantizeAxis:A,blockSize:z})},845280:h=>{n.Zb(h)},845314:(h,E)=>n.ac(Number(h),Number(E),n.Fb.dc,n.Fb.errors)};function Be(h,E,A){return Ir(async()=>{await n.Xb(Number(h),Number(E),Number(A))})}function Qe(){return typeof wasmOffsetConverter<"u"}class xe{constructor(E){J(this,"name","ExitStatus");this.message=`Program terminated with exit(${E})`,this.status=E}}var Ze=h=>{h.terminate(),h.onmessage=()=>{}},Ke=[],nt=h=>{St.length==0&&(Cr(),qt(St[0]));var E=St.pop();if(!E)return 6;wt.push(E),Pr[h.Ab]=E,E.Ab=h.Ab;var A={Bb:"run",fc:h.ec,Hb:h.Hb,Ab:h.Ab};return E.postMessage(A,h.Mb),0},Je=0,Oe=(h,E,...A)=>{for(var z=2*A.length,V=An(),ce=ro(8*z),Pe=ce>>>3,De=0;De>>0]=He)}return h=Uo(h,0,z,ce,E),In(V),h};function Ye(h){if(c)return Oe(0,1,h);if(P=h,!(0{if(P=h,c)throw ot(h),"unwind";Ye(h)},St=[],wt=[],Mr=[],Pr={},jr=h=>{var E=h.Ab;delete Pr[E],St.push(h),wt.splice(wt.indexOf(h),1),h.Ab=0,Wo(E)};function us(){Mr.forEach(h=>h())}var qt=h=>new Promise(E=>{h.onmessage=V=>{var ce=(V=V.data).Bb;if(V.Gb&&V.Gb!=Sn()){var Pe=Pr[V.Gb];Pe?Pe.postMessage(V,V.Mb):y(`Internal error! Worker sent a message "${ce}" to target pthread ${V.Gb}, but that thread no longer exists!`)}else ce==="checkMailbox"?Te():ce==="spawnThread"?nt(V):ce==="cleanupThread"?jr(Pr[V.hc]):ce==="loaded"?(h.loaded=!0,E(h)):ce==="alert"?alert(`Thread ${V.ic}: ${V.text}`):V.target==="setimmediate"?h.postMessage(V):ce==="callHandler"?n[V.Qb](...V.args):ce&&y(`worker sent an unknown command ${ce}`)},h.onerror=V=>{throw y(`worker sent an error! ${V.filename}:${V.lineno}: ${V.message}`),V};var A,z=[];for(A of[])n.propertyIsEnumerable(A)&&z.push(A);h.postMessage({Bb:"load",Rb:z,kc:T,lc:x})});function Cr(){var h=new Worker((()=>{let E=URL;return self.location.href>"file:"&&self.location.href<"file;"?new E("ort.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});St.push(h)}var Xs=h=>{ae();var E=ve()[h+52>>>2>>>0];h=ve()[h+56>>>2>>>0],to(E,E-h),In(E)},Js=(h,E)=>{Je=0,h=Ho(h,E),0>>=0);throw E>>>=0,A>>>=0,ve()[z.Ib+16>>>2>>>0]=0,ve()[z.Ib+4>>>2>>>0]=E,ve()[z.Ib+8>>>2>>>0]=A,h}function pt(h,E,A,z){return c?Oe(2,1,h,E,A,z):As(h,E,A,z)}function As(h,E,A,z){if(h>>>=0,A>>>=0,z>>>=0,p===void 0)return 6;var V=[];return c&&V.length===0?pt(h,E>>>=0,A,z):(h={ec:A,Ab:h,Hb:z,Mb:V},c?(h.Bb="spawnThread",postMessage(h,V),0):nt(h))}var Fs=typeof TextDecoder<"u"?new TextDecoder:void 0,Ct=(h,E=0,A=NaN)=>{var z=(E>>>=0)+A;for(A=E;h[A]&&!(A>=z);)++A;if(16(V=(240&V)==224?(15&V)<<12|ce<<6|Pe:(7&V)<<18|ce<<12|Pe<<6|63&h[E++])?z+=String.fromCharCode(V):(V-=65536,z+=String.fromCharCode(55296|V>>10,56320|1023&V))}}else z+=String.fromCharCode(V)}return z},Qt=(h,E)=>(h>>>=0)?Ct(U(),h,E):"";function S(h,E,A){return c?Oe(3,1,h,E,A):0}function Q(h,E){if(c)return Oe(4,1,h,E)}var B=h=>{for(var E=0,A=0;A=z?E++:2047>=z?E+=2:55296<=z&&57343>=z?(E+=4,++A):E+=3}return E},q=(h,E,A)=>{var z=U();if(E>>>=0,0=Pe&&(Pe=65536+((1023&Pe)<<10)|1023&h.charCodeAt(++ce)),127>=Pe){if(E>=A)break;z[E++>>>0]=Pe}else{if(2047>=Pe){if(E+1>=A)break;z[E++>>>0]=192|Pe>>6}else{if(65535>=Pe){if(E+2>=A)break;z[E++>>>0]=224|Pe>>12}else{if(E+3>=A)break;z[E++>>>0]=240|Pe>>18,z[E++>>>0]=128|Pe>>12&63}z[E++>>>0]=128|Pe>>6&63}z[E++>>>0]=128|63&Pe}}z[E>>>0]=0,h=E-V}else h=0;return h};function re(h,E){if(c)return Oe(5,1,h,E)}function ge(h,E,A){if(c)return Oe(6,1,h,E,A)}function Fe(h,E,A){return c?Oe(7,1,h,E,A):0}function rt(h,E){if(c)return Oe(8,1,h,E)}function ft(h,E,A){if(c)return Oe(9,1,h,E,A)}function ht(h,E,A,z){if(c)return Oe(10,1,h,E,A,z)}function vt(h,E,A,z){if(c)return Oe(11,1,h,E,A,z)}function st(h,E,A,z){if(c)return Oe(12,1,h,E,A,z)}function zt(h){if(c)return Oe(13,1,h)}function Ut(h,E){if(c)return Oe(14,1,h,E)}function Nr(h,E,A){if(c)return Oe(15,1,h,E,A)}var Xr,rr,Sr=()=>Se(""),$r=h=>{for(var E="";U()[h>>>0];)E+=Xr[U()[h++>>>0]];return E},Vr={},ds={};function kr(h,E,A={}){return function(z,V,ce={}){var Pe=V.name;if(!z)throw new rr(`type "${Pe}" must have a positive integer typeid pointer`);if(ds.hasOwnProperty(z)){if(ce.Sb)return;throw new rr(`Cannot register type '${Pe}' twice`)}ds[z]=V,Vr.hasOwnProperty(z)&&(V=Vr[z],delete Vr[z],V.forEach(De=>De()))}(h,E,A)}var Os=(h,E,A)=>{switch(E){case 1:return A?z=>F()[z>>>0]:z=>U()[z>>>0];case 2:return A?z=>se()[z>>>1>>>0]:z=>_e()[z>>>1>>>0];case 4:return A?z=>ie()[z>>>2>>>0]:z=>ve()[z>>>2>>>0];case 8:return A?z=>ee[z>>>3]:z=>Z[z>>>3];default:throw new TypeError(`invalid integer width (${E}): ${h}`)}};function Ds(h,E,A){A>>>=0,kr(h>>>=0,{name:E=$r(E>>>0),fromWireType:z=>z,toWireType:function(z,V){if(typeof V!="bigint"&&typeof V!="number")throw V=V===null?"null":(z=typeof V)=="object"||z==="array"||z==="function"?V.toString():""+V,new TypeError(`Cannot convert "${V}" to ${this.name}`);return typeof V=="number"&&(V=BigInt(V)),V},Cb:Ur,readValueFromPointer:Os(E,A,E.indexOf("u")==-1),Db:null})}var Ur=8;function Wr(h,E,A,z){kr(h>>>=0,{name:E=$r(E>>>0),fromWireType:function(V){return!!V},toWireType:function(V,ce){return ce?A:z},Cb:Ur,readValueFromPointer:function(V){return this.fromWireType(U()[V>>>0])},Db:null})}var ts=[],Dr=[];function Ts(h){9<(h>>>=0)&&--Dr[h+1]==0&&(Dr[h]=void 0,ts.push(h))}var pr=h=>{if(!h)throw new rr("Cannot use deleted val. handle = "+h);return Dr[h]},mr=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let E=ts.pop()||Dr.length;return Dr[E]=h,Dr[E+1]=1,E}};function Jr(h){return this.fromWireType(ve()[h>>>2>>>0])}var Ns={name:"emscripten::val",fromWireType:h=>{var E=pr(h);return Ts(h),E},toWireType:(h,E)=>mr(E),Cb:Ur,readValueFromPointer:Jr,Db:null};function Gr(h){return kr(h>>>0,Ns)}var Re=(h,E)=>{switch(E){case 4:return function(A){return this.fromWireType(ze()[A>>>2>>>0])};case 8:return function(A){return this.fromWireType(Ge()[A>>>3>>>0])};default:throw new TypeError(`invalid float width (${E}): ${h}`)}};function je(h,E,A){A>>>=0,kr(h>>>=0,{name:E=$r(E>>>0),fromWireType:z=>z,toWireType:(z,V)=>V,Cb:Ur,readValueFromPointer:Re(E,A),Db:null})}function et(h,E,A,z,V){if(h>>>=0,A>>>=0,E=$r(E>>>0),V===-1&&(V=4294967295),V=De=>De,z===0){var ce=32-8*A;V=De=>De<>>ce}var Pe=E.includes("unsigned")?function(De,He){return He>>>0}:function(De,He){return He};kr(h,{name:E,fromWireType:V,toWireType:Pe,Cb:Ur,readValueFromPointer:Os(E,A,z!==0),Db:null})}function Xt(h,E,A){function z(ce){var Pe=ve()[ce>>>2>>>0];return ce=ve()[ce+4>>>2>>>0],new V(F().buffer,ce,Pe)}var V=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][E];kr(h>>>=0,{name:A=$r(A>>>0),fromWireType:z,Cb:Ur,readValueFromPointer:z},{Sb:!0})}function Vs(h,E){kr(h>>>=0,{name:E=$r(E>>>0),fromWireType:function(A){for(var z,V=ve()[A>>>2>>>0],ce=A+4,Pe=ce,De=0;De<=V;++De){var He=ce+De;De!=V&&U()[He>>>0]!=0||(Pe=Qt(Pe,He-Pe),z===void 0?z=Pe:(z+="\0",z+=Pe),Pe=He+1)}return rs(A),z},toWireType:function(A,z){z instanceof ArrayBuffer&&(z=new Uint8Array(z));var V=typeof z=="string";if(!(V||z instanceof Uint8Array||z instanceof Uint8ClampedArray||z instanceof Int8Array))throw new rr("Cannot pass non-string to std::string");var ce=V?B(z):z.length,Pe=$n(4+ce+1),De=Pe+4;if(ve()[Pe>>>2>>>0]=ce,V)q(z,De,ce+1);else if(V)for(V=0;V>>0]=He}else for(V=0;V>>0]=z[V];return A!==null&&A.push(rs,Pe),Pe},Cb:Ur,readValueFromPointer:Jr,Db(A){rs(A)}})}var Es=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Us=(h,E)=>{for(var A=h>>1,z=A+E/2;!(A>=z)&&_e()[A>>>0];)++A;if(32<(A<<=1)-h&&Es)return Es.decode(U().slice(h,A));for(A="",z=0;!(z>=E/2);++z){var V=se()[h+2*z>>>1>>>0];if(V==0)break;A+=String.fromCharCode(V)}return A},Ps=(h,E,A)=>{if(A??(A=2147483647),2>A)return 0;var z=E;A=(A-=2)<2*h.length?A/2:h.length;for(var V=0;V>>1>>>0]=ce,E+=2}return se()[E>>>1>>>0]=0,E-z},yn=h=>2*h.length,vn=(h,E)=>{for(var A=0,z="";!(A>=E/4);){var V=ie()[h+4*A>>>2>>>0];if(V==0)break;++A,65536<=V?(V-=65536,z+=String.fromCharCode(55296|V>>10,56320|1023&V)):z+=String.fromCharCode(V)}return z},xn=(h,E,A)=>{if(E>>>=0,A??(A=2147483647),4>A)return 0;var z=E;A=z+A-4;for(var V=0;V=ce&&(ce=65536+((1023&ce)<<10)|1023&h.charCodeAt(++V)),ie()[E>>>2>>>0]=ce,(E+=4)+4>A)break}return ie()[E>>>2>>>0]=0,E-z},pe=h=>{for(var E=0,A=0;A=z&&++A,E+=4}return E};function I(h,E,A){if(h>>>=0,E>>>=0,A=$r(A>>>=0),E===2)var z=Us,V=Ps,ce=yn,Pe=De=>_e()[De>>>1>>>0];else E===4&&(z=vn,V=xn,ce=pe,Pe=De=>ve()[De>>>2>>>0]);kr(h,{name:A,fromWireType:De=>{for(var He,at=ve()[De>>>2>>>0],xt=De+4,Ot=0;Ot<=at;++Ot){var Gt=De+4+Ot*E;Ot!=at&&Pe(Gt)!=0||(xt=z(xt,Gt-xt),He===void 0?He=xt:(He+="\0",He+=xt),xt=Gt+E)}return rs(De),He},toWireType:(De,He)=>{if(typeof He!="string")throw new rr(`Cannot pass non-string to C++ string type ${A}`);var at=ce(He),xt=$n(4+at+E);return ve()[xt>>>2>>>0]=at/E,V(He,xt+4,at+E),De!==null&&De.push(rs,xt),xt},Cb:Ur,readValueFromPointer:Jr,Db(De){rs(De)}})}function N(h,E){kr(h>>>=0,{Tb:!0,name:E=$r(E>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function Y(h){Zn(h>>>0,!l,1,!a,131072,!1),us()}var le=h=>{if(!ue)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(ie(),h>>>2,h).value.then(Te),h+=128,Atomics.store(ie(),h>>>2,1))}var Te=()=>{var h=Sn();h&&(de(h),le(Ko))};function Ne(h,E){(h>>>=0)==E>>>0?setTimeout(Te):c?postMessage({Gb:h,Bb:"checkMailbox"}):(h=Pr[h])&&h.postMessage({Bb:"checkMailbox"})}var qe=[];function We(h,E,A,z,V){for(E>>>=0,z/=2,qe.length=z,A=V>>>0>>>3,V=0;V>>0];return(E?Ae[E]:Yn[h])(...qe)}var tt=()=>{Je=0};function Mt(h){h>>>=0,c?postMessage({Bb:"cleanupThread",hc:h}):jr(Pr[h])}function Bt(h){}var Lt=(h,E)=>{var A=ds[h];if(A===void 0)throw h=No(h),A=$r(h),rs(h),new rr(`${E} has unknown type ${A}`);return A},sr=(h,E,A)=>{var z=[];return h=h.toWireType(z,A),z.length&&(ve()[E>>>2>>>0]=mr(z)),h};function Wt(h,E,A){return E>>>=0,A>>>=0,h=pr(h>>>0),E=Lt(E,"emval::as"),sr(E,A,h)}function _r(h,E){return E>>>=0,h=pr(h>>>0),(E=Lt(E,"emval::as")).toWireType(null,h)}var br=h=>{try{h()}catch(E){Se(E)}},ir=0,fr=null,Lr=0,Yr=[],Zt={},gr={},Kr=0,zr=null,Cs=[];function Ir(h){return function(E){if(!ue){if(ir===0){var A=!1,z=!1;E((V=0)=>{if(!ue&&(Lr=V,A=!0,z)){ir=2,br(()=>Qo(fr)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),V=!1;try{var ce=function(){var He=ie()[fr+8>>>2>>>0];return He=dt[gr[He]],--Je,He()}()}catch(He){ce=He,V=!0}var Pe=!1;if(!fr){var De=zr;De&&(zr=null,(V?De.reject:De.resolve)(ce),Pe=!0)}if(V&&!Pe)throw ce}}),z=!0,A||(ir=1,fr=function(){var V=$n(65548),ce=V+12;ve()[V>>>2>>>0]=ce,ve()[V+4>>>2>>>0]=ce+65536,ce=Yr[0];var Pe=Zt[ce];return Pe===void 0&&(Pe=Kr++,Zt[ce]=Pe,gr[Pe]=ce),ce=Pe,ie()[V+8>>>2>>>0]=ce,V}(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),br(()=>qo(fr)))}else ir===2?(ir=0,br(Xo),rs(fr),fr=null,Cs.forEach(le)):Se(`invalid state: ${ir}`);return Lr}}(E=>{h().then(E)})}function ps(h){return h>>>=0,Ir(async()=>{var E=await pr(h);return mr(E)})}var ur=[];function ar(h,E,A,z){return A>>>=0,z>>>=0,(h=ur[h>>>0])(null,E=pr(E>>>0),A,z)}var hr={},nr=h=>{var E=hr[h];return E===void 0?$r(h):E};function Hr(h,E,A,z,V){return A>>>=0,z>>>=0,V>>>=0,(h=ur[h>>>0])(E=pr(E>>>0),E[A=nr(A)],z,V)}var Ws=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Hn(h){return(h>>>=0)==0?mr(Ws()):(h=nr(h),mr(Ws()[h]))}var en=h=>{var E=ur.length;return ur.push(h),E},Ti=(h,E)=>{for(var A=Array(h),z=0;z>>2>>>0],"parameter "+z);return A},Po=(h,E)=>Object.defineProperty(E,"name",{value:h});function Ei(h,E,A){var z=(E=Ti(h,E>>>0)).shift();h--;var V=`return function (obj, func, destructorsRef, args) { +`,ce=0,Pe=[];A===0&&Pe.push("obj");for(var De=["retType"],He=[z],at=0;atxt.name).join(", ")}) => ${z.name}>`,en(Po(A,h))}function Pi(h){return h=nr(h>>>0),mr(n[h])}function Ci(h,E){return E>>>=0,h=pr(h>>>0),E=pr(E),mr(h[E])}function tn(h){9<(h>>>=0)&&(Dr[h+1]+=1)}function Si(){return mr([])}function $i(h){h=pr(h>>>0);for(var E=Array(h.length),A=0;A>>0))}function Ii(){return mr({})}function Ai(h){for(var E=pr(h>>>=0);E.length;){var A=E.pop();E.pop()(A)}Ts(h)}function rn(h,E,A){E>>>=0,A>>>=0,h=pr(h>>>0),E=pr(E),A=pr(A),h[E]=A}function Fi(h,E){return E>>>=0,h=(h=Lt(h>>>0,"_emval_take_value")).readValueFromPointer(E),mr(h)}function Oi(h,E){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),ie()[E>>>2>>>0]=h.getUTCSeconds(),ie()[E+4>>>2>>>0]=h.getUTCMinutes(),ie()[E+8>>>2>>>0]=h.getUTCHours(),ie()[E+12>>>2>>>0]=h.getUTCDate(),ie()[E+16>>>2>>>0]=h.getUTCMonth(),ie()[E+20>>>2>>>0]=h.getUTCFullYear()-1900,ie()[E+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,ie()[E+28>>>2>>>0]=h}var Co=h=>h%4==0&&(h%100!=0||h%400==0),So=[0,31,60,91,121,152,182,213,244,274,305,335],$o=[0,31,59,90,120,151,181,212,243,273,304,334];function ko(h,E){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),ie()[E>>>2>>>0]=h.getSeconds(),ie()[E+4>>>2>>>0]=h.getMinutes(),ie()[E+8>>>2>>>0]=h.getHours(),ie()[E+12>>>2>>>0]=h.getDate(),ie()[E+16>>>2>>>0]=h.getMonth(),ie()[E+20>>>2>>>0]=h.getFullYear()-1900,ie()[E+24>>>2>>>0]=h.getDay();var A=(Co(h.getFullYear())?So:$o)[h.getMonth()]+h.getDate()-1|0;ie()[E+28>>>2>>>0]=A,ie()[E+36>>>2>>>0]=-60*h.getTimezoneOffset(),A=new Date(h.getFullYear(),6,1).getTimezoneOffset();var z=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(A!=z&&h.getTimezoneOffset()==Math.min(z,A)),ie()[E+32>>>2>>>0]=h}function Di(h){h>>>=0;var E=new Date(ie()[h+20>>>2>>>0]+1900,ie()[h+16>>>2>>>0],ie()[h+12>>>2>>>0],ie()[h+8>>>2>>>0],ie()[h+4>>>2>>>0],ie()[h>>>2>>>0],0),A=ie()[h+32>>>2>>>0],z=E.getTimezoneOffset(),V=new Date(E.getFullYear(),6,1).getTimezoneOffset(),ce=new Date(E.getFullYear(),0,1).getTimezoneOffset(),Pe=Math.min(ce,V);return 0>A?ie()[h+32>>>2>>>0]=+(V!=ce&&Pe==z):0>>2>>>0]=E.getDay(),A=(Co(E.getFullYear())?So:$o)[E.getMonth()]+E.getDate()-1|0,ie()[h+28>>>2>>>0]=A,ie()[h>>>2>>>0]=E.getSeconds(),ie()[h+4>>>2>>>0]=E.getMinutes(),ie()[h+8>>>2>>>0]=E.getHours(),ie()[h+12>>>2>>>0]=E.getDate(),ie()[h+16>>>2>>>0]=E.getMonth(),ie()[h+20>>>2>>>0]=E.getYear(),h=E.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function Io(h,E,A,z,V,ce,Pe){return c?Oe(16,1,h,E,A,z,V,ce,Pe):-52}function qn(h,E,A,z,V,ce){if(c)return Oe(17,1,h,E,A,z,V,ce)}var sn={},Ao=()=>performance.timeOrigin+performance.now();function Fo(h,E){if(c)return Oe(18,1,h,E);if(sn[h]&&(clearTimeout(sn[h].id),delete sn[h]),!E)return 0;var A=setTimeout(()=>{delete sn[h],le(()=>Go(h,performance.timeOrigin+performance.now()))},E);return sn[h]={id:A,qc:E},0}function Oo(h,E,A,z){h>>>=0,E>>>=0,A>>>=0,z>>>=0;var V=new Date().getFullYear(),ce=new Date(V,0,1).getTimezoneOffset();V=new Date(V,6,1).getTimezoneOffset();var Pe=Math.max(ce,V);ve()[h>>>2>>>0]=60*Pe,ie()[E>>>2>>>0]=+(ce!=V),h=(E=De=>{var He=Math.abs(De);return`UTC${0<=De?"-":"+"}${String(Math.floor(He/60)).padStart(2,"0")}${String(He%60).padStart(2,"0")}`})(ce),E=E(V),VDate.now();function Li(h,E,A){return 0<=h&&3>=h?(h===0?h=Date.now():h=performance.timeOrigin+performance.now(),ee[A>>>0>>>3]=BigInt(Math.round(1e6*h)),0):28}var Tn=[],Qn=(h,E)=>{Tn.length=0;for(var A;A=U()[h++>>>0];){var z=A!=105;E+=(z&=A!=112)&&E%8?4:0,Tn.push(A==112?ve()[E>>>2>>>0]:A==106?ee[E>>>3]:A==105?ie()[E>>>2>>>0]:Ge()[E>>>3>>>0]),E+=z?8:4}return Tn};function Xn(h,E,A){return h>>>=0,E=Qn(E>>>0,A>>>0),Ae[h](...E)}function zi(h,E,A){return h>>>=0,E=Qn(E>>>0,A>>>0),Ae[h](...E)}var Bi=()=>{};function Ri(h,E){return y(Qt(h>>>0,E>>>0))}var ji=()=>{throw Je+=1,"unwind"};function Ni(){return 4294901760}var Vi=()=>navigator.hardwareConcurrency;function Ui(){return Se("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Wi(h){h>>>=0;var E=U().length;if(h<=E||4294901760=A;A*=2){var z=E*(1+.2/A);z=Math.min(z,h+100663296);e:{z=(Math.min(4294901760,65536*Math.ceil(Math.max(h,z)/65536))-T.buffer.byteLength+65535)/65536|0;try{T.grow(z),ae();var V=1;break e}catch{}V=void 0}if(V)return!0}return!1}var nn=()=>(Se("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),on={},En=h=>{h.forEach(E=>{nn()})};function Do(){var h=Error().stack.toString().split(` +`);return h[0]=="Error"&&h.shift(),En(h),on.Lb=nn(),on.cc=h,on.Lb}function Gi(h,E,A){if(h>>>=0,E>>>=0,on.Lb==h)var z=on.cc;else(z=Error().stack.toString().split(` +`))[0]=="Error"&&z.shift(),En(z);for(var V=3;z[V]&&nn()!=h;)++V;for(h=0;h>>2>>>0]=nn();return h}var Pn,Ss={},Lo=()=>{if(!Pn){var h,E={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(h in Ss)Ss[h]===void 0?delete E[h]:E[h]=Ss[h];var A=[];for(h in E)A.push(`${h}=${E[h]}`);Pn=A}return Pn};function Ki(h,E){if(c)return Oe(19,1,h,E);h>>>=0,E>>>=0;var A=0;return Lo().forEach((z,V)=>{var ce=E+A;for(V=ve()[h+4*V>>>2>>>0]=ce,ce=0;ce>>0]=z.charCodeAt(ce);F()[V>>>0]=0,A+=z.length+1}),0}function zo(h,E){if(c)return Oe(20,1,h,E);h>>>=0,E>>>=0;var A=Lo();ve()[h>>>2>>>0]=A.length;var z=0;return A.forEach(V=>z+=V.length+1),ve()[E>>>2>>>0]=z,0}function Hi(h){return c?Oe(21,1,h):52}function Bo(h,E,A,z){return c?Oe(22,1,h,E,A,z):52}function Jn(h,E,A,z){return c?Oe(23,1,h,E,A,z):70}var qi=[null,[],[]];function Ro(h,E,A,z){if(c)return Oe(24,1,h,E,A,z);E>>>=0,A>>>=0,z>>>=0;for(var V=0,ce=0;ce>>2>>>0],De=ve()[E+4>>>2>>>0];E+=8;for(var He=0;He>>0],xt=qi[h];at===0||at===10?((h===1?v:y)(Ct(xt)),xt.length=0):xt.push(at)}V+=De}return ve()[z>>>2>>>0]=V,0}c||function(){for(var h=n.numThreads-1;h--;)Cr();Ke.unshift(()=>{ke++,function(E){c?E():Promise.all(St.map(qt)).then(E)}(()=>Me())})}();for(var jo=Array(256),Cn=0;256>Cn;++Cn)jo[Cn]=String.fromCharCode(Cn);Xr=jo,rr=n.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},n.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},Dr.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>Dr.length/2-5-ts.length;var dt,Yn=[Ye,ot,pt,S,Q,re,ge,Fe,rt,ft,ht,vt,st,zt,Ut,Nr,Io,qn,Fo,Ki,zo,Hi,Bo,Jn,Ro];(async function(){function h(z,V){return dt=z.exports,dt=function(){var ce=dt,Pe={};for(let[De,He]of Object.entries(ce))Pe[De]=typeof He=="function"?(...at)=>{Yr.push(De);try{return He(...at)}finally{ue||(Yr.pop(),fr&&ir===1&&Yr.length===0&&(ir=0,Je+=1,br(so),typeof Fibers<"u"&&Fibers.rc()))}}:He;return Pe}(),dt=function(){var ce=dt,Pe=He=>at=>He(at)>>>0,De=He=>()=>He()>>>0;return(ce=Object.assign({},ce)).Da=Pe(ce.Da),ce.fb=De(ce.fb),ce.hb=Pe(ce.hb),ce.tb=Pe(ce.tb),ce.ub=De(ce.ub),ce.__cxa_get_exception_ptr=Pe(ce.__cxa_get_exception_ptr),ce}(),Mr.push(dt.ib),x=V,Me(),dt}ke++;var E=we();if(n.instantiateWasm)return new Promise(z=>{n.instantiateWasm(E,(V,ce)=>{h(V,ce),z(V.exports)})});if(c)return new Promise(z=>{Ie=V=>{var ce=new WebAssembly.Instance(V,we());z(h(ce,V))}});be??(be=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",g):g+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href);try{var A=await async function(z){var V=be;if(!me&&typeof WebAssembly.instantiateStreaming=="function"&&!j(V))try{var ce=fetch(V,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ce,z)}catch(Pe){y(`wasm streaming compile failed: ${Pe}`),y("falling back to ArrayBuffer instantiation")}return async function(Pe,De){try{var He=await async function(at){if(!me)try{var xt=await f(at);return new Uint8Array(xt)}catch{}if(at==be&&me)at=new Uint8Array(me);else{if(!_)throw"both async and sync fetching of the wasm failed";at=_(at)}return at}(Pe);return await WebAssembly.instantiate(He,De)}catch(at){y(`failed to asynchronously prepare wasm: ${at}`),Se(at)}}(V,z)}(E);return h(A.instance,A.module)}catch(z){return o(z),Promise.reject(z)}})();var No=h=>(No=dt.Da)(h),Vo=()=>(Vo=dt.Ea)();n._OrtInit=(h,E)=>(n._OrtInit=dt.Fa)(h,E),n._OrtGetLastError=(h,E)=>(n._OrtGetLastError=dt.Ga)(h,E),n._OrtCreateSessionOptions=(h,E,A,z,V,ce,Pe,De,He,at)=>(n._OrtCreateSessionOptions=dt.Ha)(h,E,A,z,V,ce,Pe,De,He,at),n._OrtAppendExecutionProvider=(h,E,A,z,V)=>(n._OrtAppendExecutionProvider=dt.Ia)(h,E,A,z,V),n._OrtAddFreeDimensionOverride=(h,E,A)=>(n._OrtAddFreeDimensionOverride=dt.Ja)(h,E,A),n._OrtAddSessionConfigEntry=(h,E,A)=>(n._OrtAddSessionConfigEntry=dt.Ka)(h,E,A),n._OrtReleaseSessionOptions=h=>(n._OrtReleaseSessionOptions=dt.La)(h),n._OrtCreateSession=(h,E,A)=>(n._OrtCreateSession=dt.Ma)(h,E,A),n._OrtReleaseSession=h=>(n._OrtReleaseSession=dt.Na)(h),n._OrtGetInputOutputCount=(h,E,A)=>(n._OrtGetInputOutputCount=dt.Oa)(h,E,A),n._OrtGetInputOutputMetadata=(h,E,A,z)=>(n._OrtGetInputOutputMetadata=dt.Pa)(h,E,A,z),n._OrtFree=h=>(n._OrtFree=dt.Qa)(h),n._OrtCreateTensor=(h,E,A,z,V,ce)=>(n._OrtCreateTensor=dt.Ra)(h,E,A,z,V,ce),n._OrtGetTensorData=(h,E,A,z,V)=>(n._OrtGetTensorData=dt.Sa)(h,E,A,z,V),n._OrtReleaseTensor=h=>(n._OrtReleaseTensor=dt.Ta)(h),n._OrtCreateRunOptions=(h,E,A,z)=>(n._OrtCreateRunOptions=dt.Ua)(h,E,A,z),n._OrtAddRunConfigEntry=(h,E,A)=>(n._OrtAddRunConfigEntry=dt.Va)(h,E,A),n._OrtReleaseRunOptions=h=>(n._OrtReleaseRunOptions=dt.Wa)(h),n._OrtCreateBinding=h=>(n._OrtCreateBinding=dt.Xa)(h),n._OrtBindInput=(h,E,A)=>(n._OrtBindInput=dt.Ya)(h,E,A),n._OrtBindOutput=(h,E,A,z)=>(n._OrtBindOutput=dt.Za)(h,E,A,z),n._OrtClearBoundOutputs=h=>(n._OrtClearBoundOutputs=dt._a)(h),n._OrtReleaseBinding=h=>(n._OrtReleaseBinding=dt.$a)(h),n._OrtRunWithBinding=(h,E,A,z,V)=>(n._OrtRunWithBinding=dt.ab)(h,E,A,z,V),n._OrtRun=(h,E,A,z,V,ce,Pe,De)=>(n._OrtRun=dt.bb)(h,E,A,z,V,ce,Pe,De),n._OrtEndProfiling=h=>(n._OrtEndProfiling=dt.cb)(h),n._JsepOutput=(h,E,A)=>(n._JsepOutput=dt.db)(h,E,A),n._JsepGetNodeName=h=>(n._JsepGetNodeName=dt.eb)(h);var Sn=()=>(Sn=dt.fb)(),rs=n._free=h=>(rs=n._free=dt.gb)(h),$n=n._malloc=h=>($n=n._malloc=dt.hb)(h),Zn=(h,E,A,z,V,ce)=>(Zn=dt.kb)(h,E,A,z,V,ce),eo=()=>(eo=dt.lb)(),Uo=(h,E,A,z,V)=>(Uo=dt.mb)(h,E,A,z,V),Wo=h=>(Wo=dt.nb)(h),kn=h=>(kn=dt.ob)(h),Go=(h,E)=>(Go=dt.pb)(h,E),Ko=()=>(Ko=dt.qb)(),to=(h,E)=>(to=dt.rb)(h,E),In=h=>(In=dt.sb)(h),ro=h=>(ro=dt.tb)(h),An=()=>(An=dt.ub)(),Ho=n.dynCall_ii=(h,E)=>(Ho=n.dynCall_ii=dt.vb)(h,E),qo=h=>(qo=dt.wb)(h),so=()=>(so=dt.xb)(),Qo=h=>(Qo=dt.yb)(h),Xo=()=>(Xo=dt.zb)();return n.stackSave=()=>An(),n.stackRestore=h=>In(h),n.stackAlloc=h=>ro(h),n.setValue=function(h,E,A="i8"){switch(A.endsWith("*")&&(A="*"),A){case"i1":case"i8":F()[h>>>0]=E;break;case"i16":se()[h>>>1>>>0]=E;break;case"i32":ie()[h>>>2>>>0]=E;break;case"i64":ee[h>>>3]=BigInt(E);break;case"float":ze()[h>>>2>>>0]=E;break;case"double":Ge()[h>>>3>>>0]=E;break;case"*":ve()[h>>>2>>>0]=E;break;default:Se(`invalid type for setValue: ${A}`)}},n.getValue=function(h,E="i8"){switch(E.endsWith("*")&&(E="*"),E){case"i1":case"i8":return F()[h>>>0];case"i16":return se()[h>>>1>>>0];case"i32":return ie()[h>>>2>>>0];case"i64":return ee[h>>>3];case"float":return ze()[h>>>2>>>0];case"double":return Ge()[h>>>3>>>0];case"*":return ve()[h>>>2>>>0];default:Se(`invalid type for getValue: ${E}`)}},n.UTF8ToString=Qt,n.stringToUTF8=q,n.lengthBytesUTF8=B,function h(){if(0{Ca(),Aa=typeof location>"u"?void 0:location.origin,Fa=self.location.href>"file:"&&self.location.href<"file;",ad=()=>{{if(Fa){let e=URL;return new URL(new e("ort.bundle.min.mjs",self.location.href).href,Aa).href}return self.location.href}},ns=ad(),ld=()=>{if(ns&&!ns.startsWith("blob:"))return ns.substring(0,ns.lastIndexOf("/")+1)},ri=(e,r)=>{try{let t=r??ns;return(t?new URL(e,t):new URL(e)).origin===Aa}catch{return!1}},cd=(e,r)=>{let t=r??ns;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},ud=(e,r)=>`${r??"./"}${e}`,Oa=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},dd=async e=>(await import(e)).default,Da=(qv(),lo(rd)).default,pd=async()=>{if(!ns)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ri(ns))return[void 0,Da()];let e=await Oa(ns);return[e,Da(e)]},La=(Qv(),lo(nd)).default,hd=async(e,r,t)=>{if(!e&&!r&&La&&ns&&ri(ns))return[void 0,La];{let s="ort-wasm-simd-threaded.jsep.mjs",o=e??cd(s,r),n=t&&o&&!ri(o,r),i=n?await Oa(o):o??ud(s,r);return[n?i:void 0,await dd(i)]}}}),Ba,si,ho,Ra,md,_d,fd,ja,Jt,dn=Ve(()=>{za(),si=!1,ho=!1,Ra=!1,md=()=>{if(typeof SharedArrayBuffer>"u")return!1;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}},_d=()=>{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}},fd=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},ja=async e=>{if(si)return Promise.resolve();if(ho)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ra)throw new Error("previous call to 'initializeWebAssembly()' failed.");ho=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!fd())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!_d())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=md();t>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=t=1);let o=e.wasmPaths,n=typeof o=="string"?o:void 0,i=o==null?void 0:o.mjs,a=(i==null?void 0:i.href)??i,l=o==null?void 0:o.wasm,c=(l==null?void 0:l.href)??l,p=e.wasmBinary,[d,u]=await hd(a,n,t>1),f=!1,_=[];if(r>0&&_.push(new Promise(b=>{setTimeout(()=>{f=!0,b()},r)})),_.push(new Promise((b,k)=>{let g={numThreads:t};if(p)g.wasmBinary=p;else if(c||n)g.locateFile=M=>c??n+M;else if(a&&a.indexOf("blob:")!==0)g.locateFile=M=>new URL(M,a).href;else if(d){let M=ld();M&&(g.locateFile=$=>M+$)}u(g).then(M=>{ho=!1,si=!0,Ba=M,b(),d&&URL.revokeObjectURL(d)},M=>{ho=!1,Ra=!0,k(M)})})),await Promise.race(_),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},Jt=()=>{if(si&&Ba)return Ba;throw new Error("WebAssembly is not initialized yet.")}}),ws,ni,Kt,Na=Ve(()=>{dn(),ws=(e,r)=>{let t=Jt(),s=t.lengthBytesUTF8(e)+1,o=t._malloc(s);return t.stringToUTF8(e,o,s),r.push(o),o},ni=(e,r,t,s)=>{if(typeof e=="object"&&e!==null){if(t.has(e))throw new Error("Circular reference in options");t.add(e)}Object.entries(e).forEach(([o,n])=>{let i=r?r+o:o;if(typeof n=="object")ni(n,i+".",t,s);else if(typeof n=="string"||typeof n=="number")s(i,n.toString());else if(typeof n=="boolean")s(i,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},Kt=e=>{let r=Jt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetLastError(o,o+s);let n=Number(r.getValue(o,s===4?"i32":"i64")),i=r.getValue(o+s,"*"),a=i?r.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),gd,Xv=Ve(()=>{dn(),Na(),gd=e=>{let r=Jt(),t=0,s=[],o=e||{};try{if((e==null?void 0: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==null?void 0: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==null?void 0:e.terminate)===void 0&&(o.terminate=!1);let n=0;return(e==null?void 0:e.tag)!==void 0&&(n=ws(e.tag,s)),t=r._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,n),t===0&&Kt("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&ni(e.extra,"",new WeakSet,(i,a)=>{let l=ws(i,s),c=ws(a,s);r._OrtAddRunConfigEntry(t,l,c)!==0&&Kt(`Can't set a run config entry: ${i} - ${a}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(i=>r._free(i)),n}}}),wd,Md,bd,mo,yd,vd,Jv=Ve(()=>{dn(),Na(),wd=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}`)}},Md=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},bd=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)},mo=(e,r,t,s)=>{let o=ws(r,s),n=ws(t,s);Jt()._OrtAddSessionConfigEntry(e,o,n)!==0&&Kt(`Can't set a session config entry: ${r} - ${t}.`)},yd=async(e,r,t)=>{for(let s of r){let o=typeof s=="string"?s:s.name,n=[];switch(o){case"webnn":if(o="WEBNN",typeof s!="string"){let p=s==null?void 0:s.deviceType;p&&mo(e,"deviceType",p,t)}break;case"webgpu":if(o="JS",typeof s!="string"){let p=s;if(p!=null&&p.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);mo(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=ws(o,t),a=n.length,l=0,c=0;if(a>0){l=Jt()._malloc(a*Jt().PTR_SIZE),t.push(l),c=Jt()._malloc(a*Jt().PTR_SIZE),t.push(c);for(let p=0;p{let r=Jt(),t=0,s=[],o=e||{};bd(o);try{let n=wd(o.graphOptimizationLevel??"all"),i=Md(o.executionMode??"sequential"),a=typeof o.logId=="string"?ws(o.logId,s):0,l=o.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let c=o.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof o.optimizedModelFilePath=="string"?ws(o.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,a,l,c,p),t===0&&Kt("Can't create session options."),o.executionProviders&&await yd(t,o.executionProviders,s),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);mo(t,"enableGraphCapture",o.enableGraphCapture.toString(),s)}if(o.freeDimensionOverrides)for(let[d,u]of Object.entries(o.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof u!="number"||!Number.isInteger(u)||u<0)throw new Error(`free dimension override value must be a non-negative integer: ${u}`);let f=ws(d,s);r._OrtAddFreeDimensionOverride(t,f,u)!==0&&Kt(`Can't set a free dimension override: ${d} - ${u}.`)}return o.extra!==void 0&&ni(o.extra,"",new WeakSet,(d,u)=>{mo(t,d,u,s)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&Kt("Can't release session options."),s.forEach(i=>r._free(i)),n}}}),Vn,zs,pn,Va,oi,Ua,Wa,Ga,gt=Ve(()=>{Vn=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;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},zs=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";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},pn=(e,r)=>{let t=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof r=="number"?r:r.reduce((o,n)=>o*n,1);return t>0?Math.ceil(s*t):void 0},Va=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}`)}},oi=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}`)}},Ua=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Wa=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ga=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;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),Ka,xd=Ve(()=>{Ca(),Ka=async e=>{if(typeof e=="string"){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"),s=t?parseInt(t,10):0;if(s<1073741824)return new Uint8Array(await r.arrayBuffer());{if(!r.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=r.body.getReader(),n;try{n=new ArrayBuffer(s)}catch(a){if(a instanceof RangeError){let l=Math.ceil(s/65536);n=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw a}let i=0;for(;;){let{done:a,value:l}=await o.read();if(a)break;let c=l.byteLength;new Uint8Array(n,i,c).set(l),i+=c}return new Uint8Array(n,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Td,Ed,Pd,Cd,Ha,Sd,Dt,Bs=Ve(()=>{gt(),Td=["V","I","W","E","F"],Ed=(e,r)=>{console.log(`[${Td[e]},${new Date().toISOString()}]${r}`)},Ha=(e,r)=>{Pd=e,Cd=r},Sd=(e,r)=>{let t=oi(e),s=oi(Pd);t>=s&&Ed(t,typeof r=="function"?r():r)},Dt=(...e)=>{Cd&&Sd(...e)}}),$d,Un,ye,ii,kd,Id,Ad,Et=Ve(()=>{$d=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},Un=class{static calcShape(e,r,t=!1){let s=e.length,o=r.length;if(s===0)return r;if(o===0)return e;let n=Math.max(e.length,r.length),i=new Array(n);if(t){if(s<2||o<2)return;let a=$d.calcMatMulShape([e[s-2],e[s-1]],[r[o-2],r[o-1]]);if(a===void 0)return;[i[n-2],i[n-1]]=a}for(let a=t?3:1;a<=n;a++){let l=s-a<0?1:e[s-a],c=o-a<0?1:r[o-a];if(l!==c&&l>1&&c>1)return;let p=Math.max(l,c);if(l&&c)i[n-a]=Math.max(l,c);else{if(p>1)return;i[n-a]=0}}return i}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let o=1;o<=t;o++)if(e[t-o]!==1&&e[t-o]!==r[s-o])return!1;return!0}},ye=class ga{static size(r){return ga.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let o=new Array(s),n=s-1;for(;n>=0;){if(r[n]%t===0){o[n]=r[n]/t;break}if(t%r[n]!==0)throw new Error("cannot convert shape");o[n]=1,t/=r[n],n--}for(n--;n>=0;n--)o[n]=r[n];return o}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 ga.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 ga.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let o=1;for(let n=t;n=0;--o)s[o]=s[o+1]*r[o+1];return s}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(s=>this.normalizeAxis(s,t??r.length))}static sortBasedOnPerm(r,t){return t?t.map(s=>r[s]):r.slice().reverse()}static padShape(r,t){let s=r.length;return r.map((o,n)=>o+t[n]+t[n+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,o)=>s===t[o])}},ii=class Zo{static adjustPoolAttributes(r,t,s,o,n,i){if(!r&&s.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 a=0;a=s.length?s.push(t[a+2]):s[a]=t[a+2];for(let a=0;a=s[a]||i[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,o,n,i,a){if(a){if(n.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(o.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{gt(),qa=(e,r)=>new(Va(r))(e)}),Qa,Xa,Od,Ja,Dd,Ya,Za,el,Ld,zd,Yv=Ve(()=>{Bs(),Qa=(e,r=!0)=>{if(e.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let t=e.byteLength/8,s=new BigInt64Array(e.buffer,e.byteOffset,t),o=new Int32Array(t);for(let n=0;n2147483647n||i<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${n}: ${i}`);o[n]=Number(i)}return r?new Uint8Array(o.buffer):o},Xa=(e,r=!0)=>{if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let t=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,t),o=BigInt64Array.from(s,BigInt);return r?new Uint8Array(o.buffer):o},Od=1,Ja=()=>Od++,Dd=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Ya=(e,r)=>{let t=Dd.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,o)=>s*o)*t/8):0},Za=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:r,context:t,tensor:s,dataType:o,shape:n,shouldConvertInt64toInt32:i=!1}=e;this.sessionId=r,this.mlContext=t,this.mlTensor=s,this.dataType=o,this.tensorShape=n,this.shouldConvertInt64toInt32=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Ya(this.dataType,this.tensorShape)}destroy(){Dt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e,r){if(e){let t=await this.mlContext.readTensor(this.mlTensor),s=Xa(new Uint8Array(t));if(r){(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).set(s);return}else return s.buffer}else return r?this.mlContext.readTensor(this.mlTensor,r):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,r,t){return this.mlContext===e&&this.dataType===r&&this.tensorShape.length===t.length&&this.tensorShape.every((s,o)=>s===t[o])}setIsInt64ToInt32Converted(e){this.isInt64ToInt32Converted=e}},el=class{constructor(e,r){this.tensorManager=e,this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,r,t,s){let o=r,n=this.tensorManager.getMLContext(e),i=o==="int64"&&!n.opSupportLimits().input.dataTypes.includes("int64");if(i&&(o="int32",Dt("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(n,o,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Ya(o,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let a=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,o,t,a,!0,!0,i),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let r=e;if(this.wrapper)if(this.wrapper.shouldConvertInt64toInt32&&(r=Qa(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else Dt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(r):this.activeUpload=new Uint8Array(r)}async download(e){var r,t,s;if(this.activeUpload){let o=(r=this.wrapper)!=null&&r.isInt64ToInt32Converted?Xa(this.activeUpload):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(o):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o);return}else return o.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read((t=this.wrapper)==null?void 0:t.shouldConvertInt64toInt32,e):this.wrapper.read((s=this.wrapper)==null?void 0:s.shouldConvertInt64toInt32)}},Ld=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let r=this.backend.getMLContext(e);if(!r)throw new Error("MLContext not found for session.");return r}reserveTensorId(){let e=Ja();return this.tensorTrackersById.set(e,new el(this)),e}releaseTensorId(e){let r=this.tensorTrackersById.get(e);r&&(this.tensorTrackersById.delete(e),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(e,r,t,s,o){Dt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${o}}`);let n=this.tensorTrackersById.get(r);if(!n)throw new Error("Tensor not found.");return n.ensureTensor(e,t,s,o)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){Dt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${r==null?void 0:r.byteLength}}`);let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");return t.download(r)}releaseTensorsForSession(e){for(let r of this.freeTensors)r.sessionId===e&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==e)}registerTensor(e,r,t,s){let o=this.getMLContext(e),n=Ja(),i=new Za({sessionId:e,context:o,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(n,new el(this,i)),this.externalTensors.add(i),n}async getCachedTensor(e,r,t,s,o,n,i=!1){let a=this.getMLContext(e);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(a,r,t)){Dt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let d=this.freeTensors.splice(c,1)[0];return d.sessionId=e,d}Dt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let l=await a.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:o,readable:n});return new Za({sessionId:e,context:a,tensor:l,dataType:r,shape:t,shouldConvertInt64toInt32:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},zd=(...e)=>new Ld(...e)}),ai,Bd,Rd,Zv=Ve(()=>{gt(),dn(),Fd(),Yv(),Bs(),ai=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Bd=(e,r)=>{if(e===r)return!0;if(e===void 0||r===void 0)return!1;let t=Object.keys(e).sort(),s=Object.keys(r).sort();return t.length===s.length&&t.every((o,n)=>o===s[n]&&e[o]===r[o])},Rd=class{constructor(e){this.tensorManager=zd(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Ha(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Dt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Dt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)Dt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(s=>s.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===void 0){let t=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let r=this.mlContextCache.findIndex(t=>Bd(t.options,e));if(r!==-1)return this.mlContextCache[r].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,r){this.mlContextBySessionId.set(e,r);let t=this.sessionIdsByMLContext.get(r);t||(t=new Set,this.sessionIdsByMLContext.set(r,t)),t.add(e),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e);let r=this.mlContextBySessionId.get(e);if(!r)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let t=this.sessionIdsByMLContext.get(r);if(t.delete(e),t.size===0){this.sessionIdsByMLContext.delete(r);let s=this.mlContextCache.findIndex(o=>o.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Dt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,o){let n=ai.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,n,s,o)}async createTemporaryTensor(e,r,t){Dt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=ai.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,s,t,!1);let n=this.temporarySessionTensorIds.get(e);return n?n.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,r){if(!Jt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Dt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${r.byteLength}}`),this.tensorManager.upload(e,r)}async downloadTensor(e,r){return this.tensorManager.download(e,r)}createMLTensorDownloader(e,r){return async()=>{let t=await this.tensorManager.download(e);return qa(t,r)}}registerMLTensor(e,r,t,s){let o=ai.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(e,r,o,s);return Dt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${o}, dimensions: ${s}} -> {tensorId: ${n}}`),n}registerMLConstant(e,r,t,s,o,n,i=!1){if(!n)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let l=n.get(a);if(!l)throw new Error(`File with name ${a} not found in preloaded files.`);if(r+t>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(r,r+t).buffer,p;switch(o.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":i?(p=Qa(new Uint8Array(c),!1),o.dataType="int32"):p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return Dt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(o,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}isInt64Supported(e){var r;return!!((r=this.mlContextBySessionId.get(e))!=null&&r.opSupportLimits().input.dataTypes.includes("int64"))}flush(){}}}),tl=Ve(()=>{}),rl,li,ci,jd,Nd,sl,nl,Vd,Ud,ex=Ve(()=>{Bs(),tl(),rl=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]]),li=[],ci=e=>Math.ceil(Number(e)/16)*16,jd=e=>{for(let r=0;rNd++,nl=async(e,r,t,s)=>{let o=ci(t),n=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(r,0,n,0,o),e.flush(),await n.mapAsync(GPUMapMode.READ);let a=n.getMappedRange();if(s){let l=s();return l.set(new Uint8Array(a,0,t)),l}else return new Uint8Array(a.slice(0,t))}finally{n.destroy()}},Vd=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of rl)li.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,o=r.byteLength,n=ci(o),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${o}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:n,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=a.getMappedRange();new Uint8Array(l).set(new Uint8Array(t,s,o)),a.unmap();let c=this.backend.device.createCommandEncoder();c.copyBufferToBuffer(a,0,i.gpuData.buffer,0,n),this.backend.device.queue.submit([c.finish()]),a.destroy(),Dt("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,r){let t=this.storageCache.get(e);if(!t)throw new Error("source gpu data for memcpy does not exist");let s=this.storageCache.get(r);if(!s)throw new Error("destination gpu data for memcpy does not exist");if(t.originalSize!==s.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=ci(t.originalSize),n=this.backend.getCommandEncoder();this.backend.endComputePass(),n.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,o)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return Dt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => 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. + Please use the previous external buffer!`)}else s=sl();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),Dt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Dt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=jd(e),s,o=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,n=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||n){let a=(o?this.freeBuffers:this.freeUniformBuffers).get(t);a?a.length>0?s=a.pop():s=this.backend.device.createBuffer({size:t,usage:r}):s=this.backend.device.createBuffer({size:t,usage:r})}else s=this.backend.device.createBuffer({size:t,usage:r});let i={id:sl(),type:0,buffer:s};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),Dt("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){var r;return(r=this.storageCache.get(e))==null?void 0:r.gpuData}release(e){let r=typeof e=="bigint"?Number(e):e,t=this.storageCache.get(r);if(!t){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return Dt("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,r){let t=this.storageCache.get(Number(e));if(!t)throw new Error("data does not exist");await nl(this.backend,t.gpuData.buffer,t.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let r=rl.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let t=this.freeBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let t=this.freeUniformBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let r of this.buffersPending)e.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let r=this.capturedPendingBuffers.get(e);r&&(r.forEach(t=>{t.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(Dt("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Ud=(...e)=>new Vd(...e)}),Wd,Nt,cr=Ve(()=>{Wd=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},Nt=e=>new Wd(e)}),Wn,ui,Er,Rr,ct,or,ol,Gn,Ks,lt,_o,$e,it,Gd,il,Kd,Hd,Pt=Ve(()=>{gt(),Et(),Wn=64,ui=(e,r)=>{if(r===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(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"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},Er=(e,r=1)=>{let t=ui(e,r);return typeof t=="string"?t:t[0]},Rr=(e,r=1)=>{let t=ui(e,r);return typeof t=="string"?t:t[1]},ct=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:ye.computeStrides(t)})}),r},or=e=>e%4===0?4:e%2===0?2:1,ol=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,Gn=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,Ks=(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,lt=(e,r,t,s)=>e.startsWith("uniforms.")&&t>4?typeof r=="string"?s==="f16"?`${e}[(${r}) / 8][(${r}) % 8 / 4][(${r}) % 8 % 4]`:`${e}[(${r}) / 4][(${r}) % 4]`:s==="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,_o=(e,r,t,s,o)=>{let n=typeof t=="number",i=n?t:t.length,a=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`array`,c=ui(r,o),p=typeof c=="string"?c:c[1],d=typeof c=="string"?c:c[0],u={indices:l,value:p,storage:d,tensor:r},f=j=>typeof j=="string"?j:`${j}u`,_={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},b=n?"uniforms.":"",k=`${b}${e}_shape`,g=`${b}${e}_strides`,M="";for(let j=0;j ${u.indices} { + var indices: ${u.indices}; + var current = offset; + ${M} + return indices; + }`,v=j=>(_.offsetToIndices=!0,i<2?j:`o2i_${e}(${j})`),y=[];if(i>=2)for(let j=i-1;j>=0;j--)y.push(`${lt(g,j,i)} * (indices[${j}])`);let T=i<2?"":` + fn i2o_${e}(indices: ${u.indices}) -> u32 { + return ${y.join("+")}; + }`,x=j=>(_.indicesToOffset=!0,i<2?j:`i2o_${e}(${j})`),P=(...j)=>i===0?"0u":`${u.indices}(${j.map(f).join(",")})`,O=(j,F)=>i<2?`${j}`:`${lt(j,F,i)}`,L=(j,F,U)=>i<2?`${j}=${U};`:`${lt(j,F,i)}=${U};`,G={},K=(j,F)=>{_.broadcastedIndicesToOffset=!0;let U=`${F.name}broadcastedIndicesTo${e}Offset`;if(U in G)return`${U}(${j})`;let se=[];for(let _e=i-1;_e>=0;_e--){let ie=F.indicesGet("outputIndices",_e+F.rank-i);se.push(`${O(g,_e)} * (${ie} % ${O(k,_e)})`)}return G[U]=`fn ${U}(outputIndices: ${F.type.indices}) -> u32 { + return ${se.length>0?se.join("+"):"0u"}; + }`,`${U}(${j})`},R=(j,F)=>(()=>{if(u.storage===u.value)return`${e}[${j}]=${F};`;if(u.storage==="vec2"&&u.value==="i32")return`${e}[${j}]=vec2(u32(${F}), select(0u, 0xFFFFFFFFu, ${F} < 0));`;if(u.storage==="vec2"&&u.value==="u32")return`${e}[${j}]=vec2(u32(${F}), 0u);`;if(u.storage==="u32"&&u.value==="vec4")return`${e}[${j}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${F}));`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),te=j=>(()=>{if(u.storage===u.value)return`${e}[${j}]`;if(u.storage==="vec2"&&u.value==="i32")return`i32(${e}[${j}].x)`;if(u.storage==="vec2"&&u.value==="u32")return`u32(${e}[${j}].x)`;if(u.storage==="u32"&&u.value==="vec4")return`vec4(bool(${e}[${j}] & 0xFFu), bool(${e}[${j}] & 0xFF00u), bool(${e}[${j}] & 0xFF0000u), bool(${e}[${j}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),H=i<2?"":` + fn get_${e}ByIndices(indices: ${u.indices}) -> ${p} { + return ${te(`i2o_${e}(indices)`)}; + }`,ee=i<2?"":(()=>{let j=a.map(U=>`d${U}: u32`).join(", "),F=a.map(U=>`d${U}`).join(", ");return` + fn get_${e}(${j}) -> ${p} { + return get_${e}ByIndices(${P(F)}); + }`})(),Z=(...j)=>{if(j.length!==i)throw new Error(`indices length must be ${i}`);let F=j.map(f).join(",");return i===0?te("0u"):i===1?te(F[0]):(_.get=!0,_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}(${F})`)},ne=j=>i<2?te(j):(_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}ByIndices(${j})`),me=i<2?"":` + fn set_${e}ByIndices(indices: ${u.indices}, value: ${p}) { + ${R(`i2o_${e}(indices)`,"value")} + }`,ue=i<2?"":(()=>{let j=a.map(U=>`d${U}: u32`).join(", "),F=a.map(U=>`d${U}`).join(", ");return` + fn set_${e}(${j}, value: ${p}) { + set_${e}ByIndices(${P(F)}, value); + }`})();return{impl:()=>{let j=[],F=!1;return _.offsetToIndices&&(j.push($),F=!0),_.indicesToOffset&&(j.push(T),F=!0),_.broadcastedIndicesToOffset&&(Object.values(G).forEach(U=>j.push(U)),F=!0),_.set&&(j.push(ue),F=!0),_.setByIndices&&(j.push(me),F=!0),_.get&&(j.push(ee),F=!0),_.getByIndices&&(j.push(H),F=!0),!n&&F&&j.unshift(`const ${k} = ${u.indices}(${t.join(",")});`,`const ${g} = ${u.indices}(${ye.computeStrides(t).join(",")});`),j.join(` +`)},type:u,offsetToIndices:v,indicesToOffset:x,broadcastedIndicesToOffset:K,indices:P,indicesGet:O,indicesSet:L,set:(...j)=>{if(j.length!==i+1)throw new Error(`indices length must be ${i}`);let F=j[i];if(typeof F!="string")throw new Error("value must be string");let U=j.slice(0,i).map(f).join(",");return i===0?R("0u",F):i===1?R(U[0],F):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}(${U}, ${F})`)},setByOffset:R,setByIndices:(j,F)=>i<2?R(j,F):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}ByIndices(${j}, ${F});`),get:Z,getByOffset:te,getByIndices:ne,usage:s,name:e,strides:g,shape:k,rank:i}},$e=(e,r,t,s=1)=>_o(e,r,t,"input",s),it=(e,r,t,s=1)=>_o(e,r,t,"output",s),Gd=(e,r,t)=>_o(e,r,t,"atomicOutput",1),il=(e,r,t,s=1)=>_o(e,r,t,"internal",s),Kd=class{constructor(e,r){this.normalizedDispatchGroup=e,this.limits=r,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=Wn){let r=typeof e=="number"?e:e[0],t=typeof e=="number"?1:e[1],s=typeof e=="number"?1:e[2];if(r>this.limits.maxComputeWorkgroupSizeX||t>this.limits.maxComputeWorkgroupSizeY||s>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*t*s>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,n=o?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,i=o?`let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${r*t*s}u + local_idx;`;return`@compute @workgroup_size(${r}, ${t}, ${s}) + fn main(${n}) { + ${i} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,r){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let t=e.usage==="input"?"read":"read_write",s=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${r}) var ${e.name}: array<${s}>;`}declareVariables(...e){return e.map(r=>this.declareVariable(r,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(e,r,t=1){return this.uniforms.push({name:e,type:r,length:t}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:r,type:t,length:s}of this.uniforms)if(s&&s>4)t==="f16"?e.push(`@align(16) ${r}:array, ${Math.ceil(s/8)}>`):e.push(`${r}:array, ${Math.ceil(s/4)}>`);else{let o=s==null||s===1?t:`vec${s}<${t}>`;e.push(`${r}:${o}`)}return` + struct Uniforms { ${e.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` +`)+this.internalVariables.map(e=>e.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[e(r.type),r.length??1])}},Hd=(e,r)=>new Kd(e,r)}),qd,al,Qd,Xd,Jd,Yd,os,Zd,ep,Hs=Ve(()=>{gt(),Et(),cr(),Pt(),qd=(e,r)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(r.length!==0&&r.length!==e[0].dims.length)throw new Error(`perm size ${r.length} does not match input rank ${e[0].dims.length}`)},al=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),Qd=(e,r)=>ye.sortBasedOnPerm(e,al(e.length,r)),Xd=(e,r,t,s)=>{let o=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`;for(let n=0;n{let t=[],s=[];for(let o=0;o{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,o=al(s,r),n=Qd(e.dims,o),i=e.dims,a=n,l=s<2||Yd(o,e.dims),c;if(l)return c=_=>{let b=$e("input",t,i,4),k=it("output",t,a,4);return` + ${_.registerUniform("output_size","u32").declareVariables(b,k)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let _=ye.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64/4)},programUniforms:[{type:12,data:Math.ceil(_/4)}]}},getShaderSource:c};let{newShape:p,newPerm:d}=Jd(e.dims,o),u=ye.areEqual(d,[2,3,1]),f=ye.areEqual(d,[3,1,2]);if(p.length===2||u||f){i=u?[p[0],p[1]*p[2]]:f?[p[0]*p[1],p[2]]:p,a=[i[1],i[0]];let _=16;return c=b=>{let k=$e("a",t,i.length),g=it("output",t,a.length);return` + ${b.registerUniform("output_size","u32").declareVariables(k,g)} + var tile : array, ${_}>; + ${b.mainStart([_,_,1])} + let stride = (uniforms.output_shape[1] - 1) / ${_} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${_}u + local_id.x; + let input_row = workgroup_id_x * ${_}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${k.getByIndices(`${k.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${_}u + local_id.x; + let output_row = workgroup_id_y * ${_}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${g.setByIndices(`${g.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let b=ye.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/_),y:Math.ceil(a[0]/_)},programUniforms:[{type:12,data:b},...ct(i,a)]}},getShaderSource:c}}return c=_=>{let b=$e("a",t,i.length),k=it("output",t,a.length);return` + ${_.registerUniform("output_size","u32").declareVariables(b,k)} + + ${Xd(o,s,b,k)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${k.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${k.setByOffset("global_idx",b.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let _=ye.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ct(i,a)]}},getShaderSource:c}},Zd=(e,r)=>{qd(e.inputs,r.perm),e.compute(os(e.inputs[0],r.perm))},ep=e=>Nt({perm:e.perm})}),tp,rp,sp,np,op,ip,ap,lp,cp,up,Ms,dp,pp,hp,mp,_p,fp,gp,wp,Mp,bp,tx=Ve(()=>{gt(),Et(),Pt(),cl(),Hs(),tp={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"},rp={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"},sp={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},np={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},op=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,o]},ap=(e,r)=>{let t=e.length+r.length,s=[],o=0;for(let n=0;n{for(let t=0;t{let t=[];if(!lp(e,r)){for(let s=0;st.push(s))}return t},up=(e,r,t,s,o,n,i)=>{let a=t[0].dims,l=ye.size(n),c=ye.size(i),p=$e("_A",t[0].dataType,a),d=it("output",o,n),u=64;l===1&&(u=256);let f=` + var aBestValues : array; + `,_=b=>` + ${b.registerUniform("reduceSize","u32").declareVariables(p,d)} + ${f} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${b.mainStart(u)} + + let outputIndex = global_idx / ${u}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${sp[s]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${u}) { + let candidate = f32(${p.getByOffset("offset + k")}); + bestValue = ${tp[s]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${u}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 = ${rp[s]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${d.setByOffset("outputIndex",`${s==="mean"?`${d.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${d.type.storage}(${np[s]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${r};${u}`,inputDependencies:["type"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:l},programUniforms:[{type:12,data:c}]})}},Ms=(e,r,t,s)=>{let o=e.inputs.length===1?t:ll(e.inputs,t),n=o.axes;n.length===0&&!o.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((f,_)=>_));let i=ye.normalizeAxes(n,e.inputs[0].dims.length),a=i,l=e.inputs[0],c=cp(a,e.inputs[0].dims.length);c.length>0&&(l=e.compute(os(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],a=op(a.length,l.dims.length));let[p,d]=ip(l.dims,a),u=p;o.keepDims&&(u=ap(p,i)),e.compute(up(r,o.cacheKey,[l],s,e.inputs[0].dataType,u,d),{inputs:[l]})},dp=(e,r)=>{Ms(e,"ReduceMeanShared",r,"mean")},pp=(e,r)=>{Ms(e,"ReduceL1Shared",r,"l1")},hp=(e,r)=>{Ms(e,"ReduceL2Shared",r,"l2")},mp=(e,r)=>{Ms(e,"ReduceLogSumExpShared",r,"logSumExp")},_p=(e,r)=>{Ms(e,"ReduceMaxShared",r,"max")},fp=(e,r)=>{Ms(e,"ReduceMinShared",r,"min")},gp=(e,r)=>{Ms(e,"ReduceProdShared",r,"prod")},wp=(e,r)=>{Ms(e,"ReduceSumShared",r,"sum")},Mp=(e,r)=>{Ms(e,"ReduceSumSquareShared",r,"sumSquare")},bp=(e,r)=>{Ms(e,"ReduceLogSumShared",r,"logSum")}}),bs,yp,di,ll,ys,vp,xp,Tp,Ep,Pp,Cp,Sp,$p,kp,Ip,vs,Ap,Fp,Op,Dp,Lp,zp,Bp,Rp,jp,Np,cl=Ve(()=>{gt(),Et(),cr(),Pt(),tx(),bs=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.")},yp=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],di=(e,r,t,s,o,n,i=!1,a=!1)=>{let l=[],c=t[0].dims,p=c.length,d=ye.normalizeAxes(o,p),u=!a&&d.length===0;c.forEach((b,k)=>{u||d.indexOf(k)>=0?i&&l.push(1):l.push(b)});let f=l.length,_=ye.size(l);return{name:e,shaderCache:r,getShaderSource:b=>{let k=[],g=$e("_A",t[0].dataType,p),M=it("output",n,f),$=s(g,M,d),v=$[2];for(let y=0,T=0;y=0?(i&&T++,v=`for(var j${y}: u32 = 0; j${y} < ${c[y]}; j${y}++) { + ${$[2].includes("last_index")?`let last_index = j${y};`:""} + ${g.indicesSet("input_indices",y,`j${y}`)} + ${v} + }`):(k.push(`${g.indicesSet("input_indices",y,M.indicesGet("output_indices",T))};`),T++);return` + + ${b.registerUniform("output_size","u32").declareVariables(g,M)} + + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${g.type.indices}; + let output_indices = ${M.offsetToIndices("global_idx")}; + + ${k.join(` +`)} + ${$[0]} // init ops for reduce max/min + ${$[1]} + ${v} + ${$[3]} + ${$.length===4?M.setByOffset("global_idx","value"):$.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:l,dataType:n}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ct(c,l)]})}},ll=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),Nt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},ys=(e,r,t,s)=>{let o=e.inputs,n=o.length===1?t:ll(o,t);e.compute(di(r,{hint:n.cacheKey,inputDependencies:["rank"]},[o[0]],n.noopWithEmptyAxes&&n.axes.length===0?yp:s,n.axes,o[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},vp=(e,r)=>{bs(e.inputs),ys(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},xp=(e,r)=>{bs(e.inputs),ys(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},Tp=(e,r)=>{bs(e.inputs),ys(e,"ReduceL2",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Ep=(e,r)=>{bs(e.inputs),ys(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},Pp=(e,r)=>{bs(e.inputs),ys(e,"ReduceMax",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(t.indicesSet("input_indices",i,0));return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},Cp=(e,r)=>{bs(e.inputs),ys(e,"ReduceMean",r,(t,s,o)=>{let n=1;for(let i=0;i=0||o.length===0)&&(n*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${n});`]})},Sp=(e,r)=>{bs(e.inputs),ys(e,"ReduceMin",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(`input_indices[${i}] = 0;`);return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},$p=(e,r)=>{bs(e.inputs),ys(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},kp=(e,r)=>{bs(e.inputs),ys(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},Ip=(e,r)=>{bs(e.inputs),ys(e,"ReduceSumSquare",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},vs=(e,r,t)=>{if(r.length===0)return t;let s=1,o=1;for(let n=0;n1024},Ap=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Cp(e,r):dp(e,r)},Fp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?xp(e,r):pp(e,r)},Op=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Tp(e,r):hp(e,r)},Dp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Ep(e,r):mp(e,r)},Lp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Pp(e,r):_p(e,r)},zp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Sp(e,r):fp(e,r)},Bp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?$p(e,r):gp(e,r)},Rp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?kp(e,r):wp(e,r)},jp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Ip(e,r):Mp(e,r)},Np=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?vp(e,r):bp(e,r)}}),ul,Vp,Up,dl,rx=Ve(()=>{gt(),cr(),cl(),ul=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.")},Vp=(e,r)=>{ul(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` +`)}`,`var value = ${s.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?"<=":"<"} value) { + value = ${s.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(di("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Up=(e,r)=>{ul(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` +`)}`,`var value = ${s.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?">=":">"} value) { + value = ${s.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(di("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},dl=e=>Nt(e)}),Wp,pi,Gp,Kp,Hp,fo,qp,Qp,pl=Ve(()=>{gt(),Et(),tl(),Pt(),Wp=(e,r)=>{let t=e[0],s=e[1],o=e[2],n=e[3],i=e[4],a=e[5];if(i&&a)throw new Error("Attention cannot have both past and attention_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=t.dims[0],c=t.dims[1],p=t.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]!==p)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 d=o.dims[0]/3,u=d,f=u;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let $ of r.qkvHiddenSizes)if($%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");d=r.qkvHiddenSizes[0],u=r.qkvHiddenSizes[1],f=r.qkvHiddenSizes[2]}let _=c;if(d!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==d+u+f)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let b=0;if(i){if(u!==f)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==u/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(b=i.dims[3])}let k=_+b,g=-1,M=0;if(n)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(a){if(a.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(a.dims[0]!==l||a.dims[1]!==r.numHeads||a.dims[2]!==c||a.dims[3]!==k)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:c,pastSequenceLength:b,kvSequenceLength:_,totalSequenceLength:k,maxSequenceLength:g,inputHiddenSize:p,hiddenSize:d,vHiddenSize:f,headSize:Math.floor(d/r.numHeads),vHeadSize:Math.floor(f/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:M,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},pi=(e,r,t)=>r&&e?` + let total_sequence_length_input = u32(${r.getByOffset("0")}); + let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); + let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + `:` + ${t?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,Gp=(e,r,t,s,o,n,i,a)=>{let l=or(i?1:n),c=64,p=n/l;p{let M=it("x",e.dataType,e.dims,l),$=[M],v=i?$e("seq_lens",i.dataType,i.dims):void 0;v&&$.push(v);let y=a?$e("total_sequence_length_input",a.dataType,a.dims):void 0;y&&$.push(y);let T=Rr(e.dataType),x=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${g.registerUniforms(x).declareVariables(...$)} + ${g.mainStart([c,1,1])} + let batchIdx = workgroup_id.z / uniforms.num_heads; + let headIdx = workgroup_id.z % uniforms.num_heads; + let sequence_length = uniforms.sequence_length; + var total_sequence_length = uniforms.total_sequence_length; + ${pi(v,y,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${c}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + var thread_max_vector = ${_}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${_}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(l){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: ${l}`)}})()}; + 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 < seq_causal_length; i++) { + sum_vector += exp(${_}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(l){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: ${l}`)}})()}; + 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 < seq_causal_length; i++) { + x[offset + i] = ${M.type.value}(${T}(1.0) / ${T}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${_}(x[offset + i]); + x[offset + i] = ${M.type.value}(exp(f32input - max_value) / sum); + } + } + ${i?` + for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { + x[offset + total_seq_id] = ${M.type.value}(${T}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${f};${l}`,inputDependencies:b},getShaderSource:k,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:r*t},programUniforms:u})}},Kp=(e,r,t,s,o,n,i,a,l)=>{let c=i+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,c],d=e>1&&s,u=n.kvNumHeads?n.kvNumHeads:n.numHeads,f=d?[n.batchSize,u,c,n.headSize]:void 0,_=n.nReps?n.nReps:1,b=n.scale===0?1/Math.sqrt(n.headSize):n.scale,k=or(n.headSize),g=n.headSize/k,M=12,$={x:Math.ceil(c/M),y:Math.ceil(n.sequenceLength/M),z:n.batchSize*n.numHeads},v=[{type:12,data:n.sequenceLength},{type:12,data:g},{type:12,data:c},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:b},{type:12,data:i},{type:12,data:n.kvSequenceLength},{type:12,data:_}],y=d&&s&&ye.size(s.dims)>0,T=["type","type"];y&&T.push("type"),o&&T.push("type"),a&&T.push("type"),l&&T.push("type");let x=[{dims:p,dataType:r.dataType,gpuDataType:0}];d&&x.push({dims:f,dataType:r.dataType,gpuDataType:0});let P=O=>{let L=$e("q",r.dataType,r.dims,k),G=$e("key",t.dataType,t.dims,k),K=[L,G];if(y){let me=$e("past_key",s.dataType,s.dims,k);K.push(me)}o&&K.push($e("attention_bias",o.dataType,o.dims));let R=a?$e("seq_lens",a.dataType,a.dims):void 0;R&&K.push(R);let te=l?$e("total_sequence_length_input",l.dataType,l.dims):void 0;te&&K.push(te);let H=it("output",r.dataType,p),ee=[H];d&&ee.push(it("present_key",r.dataType,f,k));let Z=Rr(1,k),ne=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${M}u; + + var tileQ: array<${L.type.storage}, ${M*M}>; + var tileK: array<${L.type.storage}, ${M*M}>; + ${O.registerUniforms(ne).declareVariables(...K,...ee)} + ${O.mainStart([M,M,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${_===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${_===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${pi(R,te,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${y&&d?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${d?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${Z}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${y&&d?` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }`:` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${d?`if (n + local_id.y < present_sequence_length) { + present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; + }`:""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${Z}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { + let headOffset = workgroup_id.z * uniforms.M * uniforms.N; + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(k){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: ${k}`)}})()}; + output[outputIdx] = ${H.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${k};${o!==void 0};${s!==void 0};${e}`,inputDependencies:T},getRunData:()=>({outputs:x,dispatchGroup:$,programUniforms:v}),getShaderSource:P}},Hp=(e,r,t,s,o,n,i=void 0,a=void 0)=>{let l=n+o.kvSequenceLength,c=o.nReps?o.nReps:1,p=o.vHiddenSize*c,d=e>1&&s,u=o.kvNumHeads?o.kvNumHeads:o.numHeads,f=d?[o.batchSize,u,l,o.headSize]:void 0,_=[o.batchSize,o.sequenceLength,p],b=12,k={x:Math.ceil(o.vHeadSize/b),y:Math.ceil(o.sequenceLength/b),z:o.batchSize*o.numHeads},g=[{type:12,data:o.sequenceLength},{type:12,data:l},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:p},{type:12,data:n},{type:12,data:o.kvSequenceLength},{type:12,data:c}],M=d&&s&&ye.size(s.dims)>0,$=["type","type"];M&&$.push("type"),i&&$.push("type"),a&&$.push("type");let v=[{dims:_,dataType:r.dataType,gpuDataType:0}];d&&v.push({dims:f,dataType:r.dataType,gpuDataType:0});let y=T=>{let x=$e("probs",r.dataType,r.dims),P=$e("v",t.dataType,t.dims),O=[x,P];M&&O.push($e("past_value",s.dataType,s.dims));let L=i?$e("seq_lens",i.dataType,i.dims):void 0;i&&O.push(L);let G=a?$e("total_sequence_length_input",a.dataType,a.dims):void 0;a&&O.push(G);let K=[it("output",r.dataType,_)];d&&K.push(it("present_value",r.dataType,f));let R=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${b}u; + var tileQ: array<${x.type.value}, ${b*b}>; + var tileV: array<${x.type.value}, ${b*b}>; + ${T.registerUniforms(R).declareVariables(...O,...K)} + ${T.mainStart([b,b,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${c===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${c===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let m = global_id.y; + let n = global_id.x; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.K; + ${pi(L,G,!0)} + let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch + ${M&&d?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${d?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${x.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${M&&d?` + if (w + local_id.y < past_sequence_length) { + tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; + } + `:` + if (w + local_id.y < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; + }`} + ${d?` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }`:""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:$},getRunData:()=>({outputs:v,dispatchGroup:k,programUniforms:g}),getShaderSource:y}},fo=(e,r,t,s,o,n,i,a,l,c,p=void 0,d=void 0)=>{let u=Math.min(e.outputCount,1+(i?1:0)+(a?1:0)),f=u>1?c.pastSequenceLength:0,_=f+c.kvSequenceLength,b=l&&ye.size(l.dims)>0?l:void 0,k=[r,t];u>1&&i&&ye.size(i.dims)>0&&k.push(i),b&&k.push(b),p&&k.push(p),d&&k.push(d);let g=e.compute(Kp(u,r,t,i,b,c,f,p,d),{inputs:k,outputs:u>1?[-1,1]:[-1]})[0];e.compute(Gp(g,c.batchSize,c.numHeads,f,c.sequenceLength,_,p,d),{inputs:p&&d?[g,p,d]:[g],outputs:[]});let M=[g,s];u>1&&a&&ye.size(a.dims)>0&&M.push(a),p&&M.push(p),d&&M.push(d),e.compute(Hp(u,g,s,a,c,f,p,d),{inputs:M,outputs:u>1?[0,2]:[0]})},qp=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,o=r.inputHiddenSize,n=r.headSize,i=12,a={x:Math.ceil(r.headSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:s},{type:12,data:o},{type:12,data:n},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:r.hiddenSize},{type:12,data:r.hiddenSize+r.hiddenSize+r.vHiddenSize}],p=d=>{let u=it("output_q",l[0].dataType,t),f=it("output_k",l[0].dataType,t),_=it("output_v",l[0].dataType,t),b=$e("input",l[0].dataType,l[0].dims),k=$e("weight",l[1].dataType,l[1].dims),g=$e("bias",l[2].dataType,l[2].dims),M=b.type.storage,$=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${i}u; + var tileInput: array<${M}, ${i*i}>; + var tileWeightQ: array<${M}, ${i*i}>; + var tileWeightK: array<${M}, ${i*i}>; + var tileWeightV: array<${M}, ${i*i}>; + ${d.registerUniforms($).declareVariables(b,k,g,u,f,_)} + ${d.mainStart([i,i,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${M}(0); + var valueK = ${M}(0); + var valueV = ${M}(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: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:a,programUniforms:c}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},Qp=(e,r)=>{let t=Wp(e.inputs,r),[s,o,n]=qp(e,t);return fo(e,s,o,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),Xp,Jp,Yp,Zp,sx=Ve(()=>{gs(),gt(),Et(),cr(),Pt(),Xp=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,o,n)=>{let i=o.length;if(i!==s.length)throw new Error(`${n}: num dimensions != ${i}`);o.forEach((a,l)=>{if(a!==s[l])throw new Error(`${n}: dim[${l}] do not match`)})};if(e[0].dims.length>1){let s=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,s,"Invalid input scale"),t(e[2].dims,s,"Invalid input B"),t(e[3].dims,s,"Invalid input mean"),t(e[4].dims,s,"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")},Jp=(e,r)=>{let{epsilon:t,spatial:s,format:o}=r,n=e[0].dims,i=s?or(n[n.length-1]):1,a=o==="NHWC"&&n.length>1?i:1,l=ye.size(n)/i,c=s,p=c?n.length:n,d=$e("x",e[0].dataType,e[0].dims,i),u=$e("scale",e[1].dataType,e[1].dims,a),f=$e("bias",e[2].dataType,e[2].dims,a),_=$e("inputMean",e[3].dataType,e[3].dims,a),b=$e("inputVar",e[4].dataType,e[4].dims,a),k=it("y",e[0].dataType,p,i),g=()=>{let $="";if(s)$=`let cOffset = ${n.length===1?"0u":o==="NHWC"?`outputIndices[${n.length-1}] / ${i}`:"outputIndices[1]"};`;else if(o==="NCHW")$=` + ${k.indicesSet("outputIndices","0","0")} + let cOffset = ${k.indicesToOffset("outputIndices")};`;else{$=`var cIndices = ${u.type.indices}(0); + cIndices[0] = outputIndices[${n.length-1}];`;for(let v=1;v` + const epsilon = ${t}; + ${$.registerUniform("outputSize","u32").declareVariables(d,u,f,_,b,k)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${k.offsetToIndices(`global_idx * ${i}`)}; + ${g()} + let scale = ${u.getByOffset("cOffset")}; + let bias = ${f.getByOffset("cOffset")}; + let inputMean = ${_.getByOffset("cOffset")}; + let inputVar = ${b.getByOffset("cOffset")}; + let x = ${d.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${k.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${i}`,inputDependencies:c?["rank","type","type","type","type"]:void 0},getShaderSource:M,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c?[{type:12,data:l},...ct(n)]:[{type:12,data:l}]})}},Yp=e=>Nt(e),Zp=(e,r)=>{let{inputs:t,outputCount:s}=e,o=Yp({...r,outputCount:s});if(Yt.webgpu.validateInputContent&&Xp(t,o),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Jp(t,o))}}),eh,th,rh,nx=Ve(()=>{Et(),Pt(),eh=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")},th=e=>{let r=e[0].dims,t=e[0].dims[2],s=ye.size(r)/4,o=e[0].dataType,n=$e("input",o,r,4),i=$e("bias",o,[t],4),a=$e("residual",o,r,4),l=it("output",o,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:c=>` + const channels = ${t}u / 4; + ${c.declareVariables(n,i,a,l)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes(s)} + let value = ${n.getByOffset("global_idx")} + + ${i.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; + ${l.setByOffset("global_idx","value")} + }`}},rh=e=>{eh(e.inputs),e.compute(th(e.inputs))}}),sh,Rt,nh,oh,ih,ah,lh,ch,uh,dh,ph,hh,mh,_h,fh,gh,go,wh,hi,Mh,bh,yh,vh,xh,Th,Eh,Ph,Ch,Sh,$h,kh,Ih,Ah,Fh,Oh,hl,Dh,ml,_l,Lh,zh,Bh,Rh,jh,Nh,fl=Ve(()=>{gt(),Et(),cr(),Pt(),sh=(e,r,t,s,o,n,i)=>{let a=Math.ceil(r/4),l="";typeof o=="string"?l=`${o}(a)`:l=o("a");let c=$e("inputData",t,[a],4),p=it("outputData",s,[a],4),d=[{name:"vec_size",type:"u32"}];return i&&d.push(...i),` + ${e.registerUniforms(d).declareVariables(c,p)} + + ${n??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${c.getByOffset("global_idx")}; + ${p.setByOffset("global_idx",l)} + }`},Rt=(e,r,t,s,o,n=e.dataType,i,a)=>{let l=[{type:12,data:Math.ceil(ye.size(e.dims)/4)}];return i&&l.push(...i),{name:r,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:c=>sh(c,ye.size(e.dims),e.dataType,n,t,s,a),getRunData:c=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(ye.size(c[0].dims)/64/4)},programUniforms:l})}},nh=e=>{e.compute(Rt(e.inputs[0],"Abs","abs"))},oh=e=>{e.compute(Rt(e.inputs[0],"Acos","acos"))},ih=e=>{e.compute(Rt(e.inputs[0],"Acosh","acosh"))},ah=e=>{e.compute(Rt(e.inputs[0],"Asin","asin"))},lh=e=>{e.compute(Rt(e.inputs[0],"Asinh","asinh"))},ch=e=>{e.compute(Rt(e.inputs[0],"Atan","atan"))},uh=e=>{e.compute(Rt(e.inputs[0],"Atanh","atanh"))},dh=e=>Nt(e),ph=(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(Rt(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},hh=e=>{let r,t,s=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Nt({min:r,max:t})},mh=(e,r)=>{let t=r||hh(e.inputs),s=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${s}>(uniforms.min), vec4<${s}>(uniforms.max))`,void 0,t.cacheKey,void 0,[{type:e.inputs[0].dataType,data:t.min},{type:e.inputs[0].dataType,data:t.max}],[{name:"min",type:s},{name:"max",type:s}]),{inputs:[0]})},_h=e=>{e.compute(Rt(e.inputs[0],"Ceil","ceil"))},fh=e=>{e.compute(Rt(e.inputs[0],"Cos","cos"))},gh=e=>{e.compute(Rt(e.inputs[0],"Cosh","cosh"))},go=e=>Nt(e),wh=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` + const elu_alpha_ = ${t}(${r.alpha}); + + fn elu_f32(a: ${t}) -> ${t} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${t}>) -> vec4<${t}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,r.cacheKey))},hi=(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)); +}`,Mh=e=>{let r=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,hi(r)))},bh=e=>{e.compute(Rt(e.inputs[0],"Exp","exp"))},yh=e=>{e.compute(Rt(e.inputs[0],"Floor","floor"))},vh=e=>{let r=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,hi(r)))},xh=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"LeakyRelu",s=>`select(leaky_relu_alpha_ * ${s}, ${s}, ${s} >= vec4<${t}>(0.0))`,`const leaky_relu_alpha_ = ${t}(${r.alpha});`,r.cacheKey))},Th=e=>{e.compute(Rt(e.inputs[0],"Not",r=>`!${r}`))},Eh=e=>{e.compute(Rt(e.inputs[0],"Neg",r=>`-${r}`))},Ph=e=>{e.compute(Rt(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},Ch=e=>{let r=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},Sh=e=>{e.compute(Rt(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},$h=e=>Nt(e),kh=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"HardSigmoid",s=>`max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), ${r.alpha} * ${s} + vec4<${t}>(${r.beta})))`,void 0,r.cacheKey))},Ih=e=>{e.compute(Rt(e.inputs[0],"Sin","sin"))},Ah=e=>{e.compute(Rt(e.inputs[0],"Sinh","sinh"))},Fh=e=>{e.compute(Rt(e.inputs[0],"Sqrt","sqrt"))},Oh=e=>{e.compute(Rt(e.inputs[0],"Tan","tan"))},hl=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Dh=e=>{e.compute(Rt(e.inputs[0],"Tanh",hl))},ml=(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 ${hl("v")}; +} +`,_l=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Lh=e=>{let r=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"FastGelu",_l,ml(r),void 0,e.inputs[0].dataType))},zh=(e,r)=>{let t=Rr(e.inputs[0].dataType);return e.compute(Rt(e.inputs[0],"ThresholdedRelu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${t}>(${r.alpha});`,r.cacheKey)),0},Bh=e=>{e.compute(Rt(e.inputs[0],"Log","log"))},Rh=(e,r)=>` +const alpha = vec4<${e}>(${r}); +const one = ${e}(1.0); +const zero = ${e}(0.0); + +fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { + let v = x *alpha; + var x1 : vec4<${e}>; + for (var i = 0; i < 4; i = i + 1) { + if (v[i] >= zero) { + x1[i] = one / (one + exp(-v[i])); + } else { + x1[i] = one - one / (one + exp(v[i])); + } + } + return x * x1; +} +`,jh=e=>`quick_gelu_impl(${e})`,Nh=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"QuickGelu",jh,Rh(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),Vh,Uh,Wh,ox=Ve(()=>{Et(),Pt(),fl(),Vh=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")},Uh=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=$e("input",e[0].dataType,e[0].dims,4),s=$e("bias",e[0].dataType,[e[0].dims[2]],4),o=it("output",e[0].dataType,r,4),n=ye.size(r)/4,i=Er(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:a=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${a.declareVariables(t,s,o)} + + ${hi(i)} + + ${a.mainStart()} + ${a.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${o.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Wh=e=>{Vh(e.inputs),e.compute(Uh(e.inputs))}}),Gh,Kh,xs,Hh,qh,Qh,Xh,Jh,Yh,Zh,em,tm,rm,ix=Ve(()=>{gt(),Et(),Pt(),Gh=(e,r,t,s,o,n,i,a,l,c,p,d)=>{let u,f;typeof a=="string"?u=f=(M,$)=>`${a}((${M}),(${$}))`:typeof a=="function"?u=f=a:(u=a.scalar,f=a.vector);let _=it("outputData",p,s.length,4),b=$e("aData",l,r.length,4),k=$e("bData",c,t.length,4),g;if(o)if(n){let M=ye.size(r)===1,$=ye.size(t)===1,v=r.length>0&&r[r.length-1]%4===0,y=t.length>0&&t[t.length-1]%4===0;M||$?g=_.setByOffset("global_idx",f(M?`${b.type.value}(${b.getByOffset("0")}.x)`:b.getByOffset("global_idx"),$?`${k.type.value}(${k.getByOffset("0")}.x)`:k.getByOffset("global_idx"))):g=` + let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; + let offsetA = ${b.broadcastedIndicesToOffset("outputIndices",_)}; + let offsetB = ${k.broadcastedIndicesToOffset("outputIndices",_)}; + ${_.setByOffset("global_idx",f(i||v?b.getByOffset("offsetA / 4u"):`${b.type.value}(${b.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||y?k.getByOffset("offsetB / 4u"):`${k.type.value}(${k.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else g=_.setByOffset("global_idx",f(b.getByOffset("global_idx"),k.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let M=($,v,y="")=>{let T=`aData[indexA${v}][componentA${v}]`,x=`bData[indexB${v}][componentB${v}]`;return` + let outputIndices${v} = ${_.offsetToIndices(`global_idx * 4u + ${v}u`)}; + let offsetA${v} = ${b.broadcastedIndicesToOffset(`outputIndices${v}`,_)}; + let offsetB${v} = ${k.broadcastedIndicesToOffset(`outputIndices${v}`,_)}; + let indexA${v} = offsetA${v} / 4u; + let indexB${v} = offsetB${v} / 4u; + let componentA${v} = offsetA${v} % 4u; + let componentB${v} = offsetB${v} % 4u; + ${$}[${v}] = ${y}(${u(T,x)}); + `};p===9?g=` + var data = vec4(0); + ${M("data",0,"u32")} + ${M("data",1,"u32")} + ${M("data",2,"u32")} + ${M("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:g=` + ${M("outputData[global_idx]",0)} + ${M("outputData[global_idx]",1)} + ${M("outputData[global_idx]",2)} + ${M("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(b,k,_)} + + ${d??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${g} + }`},Kh=(e,r,t,s,o,n,i=t.dataType)=>{let a=t.dims.map(b=>Number(b)??1),l=s.dims.map(b=>Number(b)??1),c=!ye.areEqual(a,l),p=a,d=ye.size(a),u=!1,f=!1,_=[c];if(c){let b=Un.calcShape(a,l,!1);if(!b)throw new Error("Can't perform binary op on the given tensors");p=b.slice(),d=ye.size(p);let k=ye.size(a)===1,g=ye.size(l)===1,M=a.length>0&&a[a.length-1]%4===0,$=l.length>0&&l[l.length-1]%4===0;_.push(k),_.push(g),_.push(M),_.push($);let v=1;for(let y=1;yb.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:b=>Gh(b,a,l,p,u,c,f,o,t.dataType,s.dataType,i,n),getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(ye.size(p)/4)},...ct(a,l,p)]})}},xs=(e,r,t,s,o,n)=>{e.compute(Kh(r,o??"",e.inputs[0],e.inputs[1],t,s,n))},Hh=e=>{xs(e,"Add",(r,t)=>`${r}+${t}`)},qh=e=>{xs(e,"Div",(r,t)=>`${r}/${t}`)},Qh=e=>{xs(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},Xh=e=>{xs(e,"Mul",(r,t)=>`${r}*${t}`)},Jh=e=>{let r=$e("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;xs(e,"Pow",{scalar:(t,s)=>`pow_custom(${t},${s})`,vector:(t,s)=>`pow_vector_custom(${t},${s})`},` + fn pow_custom(a : ${r}, b : ${r}) -> ${r} { + if (b == ${r}(0.0)) { + return ${r}(1.0); + } else if (a < ${r}(0.0) && f32(b) != floor(f32(b))) { + return ${r}(pow(f32(a), f32(b))); // NaN + } + 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)))); + } + fn pow_vector_custom(a : vec4<${r}>, b : vec4<${r}>) -> vec4<${r}> { + // TODO: implement vectorized pow + 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)); + } + `)},Yh=e=>{xs(e,"Sub",(r,t)=>`${r}-${t}`)},Zh=e=>{xs(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},em=e=>{xs(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},tm=e=>{xs(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},rm=e=>{xs(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),sm,nm,om,im,am,lm,ax=Ve(()=>{gt(),Et(),cr(),Pt(),sm=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],o=s.dataType,n=s.dims.length;e.forEach((i,a)=>{if(a!==t){if(i.dataType!==o)throw new Error("input tensors should be one type");if(i.dims.length!==n)throw new Error("input tensors should have the same shape");i.dims.forEach((l,c)=>{if(c!==r&&l!==s.dims[c])throw new Error("non concat dimensions must match")})}})},nm=(e,r)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${r}); + for (var i: u32 = 0u; i < ${e}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${e}u; + }`,om=(e,r)=>{let t=e.length,s=[];for(let o=0;o{let o=ye.size(t),n=new Array(e.length),i=new Array(e.length),a=0,l=[],c=[],p=[{type:12,data:o}];for(let b=0;b`uniforms.sizeInConcatAxis${b}`).join(","),_=b=>` + + ${(()=>{b.registerUniform("outputSize","u32");for(let k=0;k(${f}); + ${u} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${om(i,d)} + }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}),getShaderSource:_}},am=(e,r)=>{let t=e.inputs,s=t[0].dims,o=ye.normalizeAxis(r.axis,s.length);sm(t,o);let n=s.slice();n[o]=t.reduce((a,l)=>a+(l.dims.length>o?l.dims[o]:0),0);let i=t.filter(a=>ye.size(a.dims)>0);e.compute(im(i,o,n,t[0].dataType),{inputs:i})},lm=e=>Nt({axis:e.axis})}),hn,mn,_n,gl,fn=Ve(()=>{gt(),Et(),hn=(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"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},mn=(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})},_n=(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"})},gl=e=>{let r=(e==null?void 0:e.activation)||"";if(r==="HardSigmoid"){let[t,s]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:r,alpha:t,beta:s}}else if(r==="Clip"){let[t,s]=(e==null?void 0:e.activation_params)||[Id,Ad];return{activation:r,clipMax:s,clipMin:t}}else if(r==="LeakyRelu"){let[t]=(e==null?void 0:e.activation_params)||[.01];return{activation:r,alpha:t}}return{activation:r}}}),Or,cm,wl=Ve(()=>{Or=(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.`)}},cm=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),um,lx=Ve(()=>{um=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)); +} +`}),wo,Ml,bl=Ve(()=>{gt(),Et(),Pt(),fn(),wo=(e,r,t,s,o)=>{let n=s-t;return` + ${Array.from({length:t}).map((i,a)=>` + if (${lt(r.shape,a,r.rank)} != 1) { + ${r.indicesSet(e,a,lt(o,a+n,s))} + } else { + ${r.indicesSet(e,a,0)} + }`).join("")} +`},Ml=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i[i.length-2],c=a[a.length-1],p=i[i.length-1],d=or(c),u=or(p),f=or(l),_=ye.size(t)/d/f,b=e.length>2,k=s?s.slice(0,-2):t.slice(0,-2),g=[ye.size(k),l,c],M=[{type:12,data:_},{type:12,data:l},{type:12,data:c},{type:12,data:p}];mn(r,M),M.push(...ct(k,i,a)),b&&M.push(...ct(e[2].dims)),M.push(...ct(g));let $=v=>{let y=il("batch_dims",e[0].dataType,k.length),T=$e("a",e[0].dataType,i.length,u),x=$e("b",e[1].dataType,a.length,d),P=it("output",e[0].dataType,g.length,d),O=Er(P.type.tensor),L=hn(r,P.type.value,O),G=[T,x],K="";if(b){let H=o?d:1;G.push($e("bias",e[2].dataType,e[2].dims.length,H)),K=`${o?`value += bias[col / ${H}];`:`value += ${P.type.value}(bias[row + i]);`}`}let R=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];_n(r,R);let te=()=>{let H=`var a_data: ${T.type.value};`;for(let ee=0;ee; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) { + ${te()} + } + for (var i = 0u; i < ${f}u; i++) { + var value = values[i]; + ${K} + ${L} + let cur_indices = ${P.type.indices}(batch, row + i, col); + let offset = ${P.indicesToOffset("cur_indices")}; + ${P.setByOffset(`offset / ${d}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${d};${u};${f};${o}`,inputDependencies:b?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:M}),getShaderSource:$}}}),dm,pm,yl,vl,hm,xl,mm,mi,Tl=Ve(()=>{gt(),Et(),Pt(),fn(),bl(),wl(),dm=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${r?", batchIndices":""}); + `,pm=(e,r)=>e?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${r===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]; + ${r===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]; + ${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,yl=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32)=>{let l=r[1]*e[1],c=r[0]*e[0],p=o?l:n,d=o?n:l,u=p/r[0],f=n/r[1];if(!((o&&u===4&&e[1]===4||!o&&(u===3||u===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${u} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${u} must be 3 or 4. + tileAWidth ${p} must be divisible by workgroupSize[0]${r[0]}. tileInner ${n} must be divisible by workgroupSize[1] ${r[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${p/u}>, ${d}>; +var mm_Bsub: array, ${c/e[0]}>, ${n}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${u}; +const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${l}; + + let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${f}; + 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; + ${dm(o,s)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${f}; 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]; + ${u===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${pm(o,u)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},vl=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${r?", batchIndices":""}); + `,hm=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",xl=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32,l=!1)=>{let c=e[1]*r[1],p=e[0]*r[0],d=o?c:n,u=o?n:c;if(!(u%r[1]===0&&d%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${u} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${r[0]}, tileInner ${n} must be divisible by workgroupSize[1]${r[1]}`);let f=u/r[1],_=d/r[0],b=n/r[1],k=l?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${c}; + let globalColStart = i32(workgroupId.x) * ${p}; + + // 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 < ${u}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${r[0]}) { + ${vl(o,s)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${n}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${r[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<${t}, 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 * ${r[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${r[1]}];`:`mm_Asub[localRow + innerRow * ${r[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 * ${r[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${r[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${c}; + +let tileRowA = i32(localId.y) * ${f}; +let tileColA = i32(localId.x) * ${_}; +let tileRowB = i32(localId.y) * ${b}; +// 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 < ${f}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${_}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${vl(o,s)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${b}; 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<${t}, 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) { + ${hm(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, ${u}>; + var mm_Bsub : array, ${n}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc : array, rowPerThread>; + ${k} + } +`},mm=(e,r,t,s,o=!1)=>{let[n,i,a,l]=s,c=Er(s[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${Or(e,c)} { + var value = ${Or(e,c)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${i.type.indices}; + ${wo("aIndices",i,i.rank-2,n.rank,"batchIndices")} + ${i.indicesSet("aIndices",i.rank-2,"u32(row)")} + ${i.indicesSet("aIndices",i.rank-1,"u32(colIn)")} + value = ${i.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${Or(e,c)} { + var value = ${Or(e,c)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${a.type.indices}; + ${wo("bIndices",a,a.rank-2,n.rank,"batchIndices")} + ${a.indicesSet("bIndices",a.rank-2,"u32(row)")} + ${a.indicesSet("bIndices",a.rank-1,"u32(colIn)")} + value = ${a.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Or(e,c)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${r?`value = value + ${o?"bias[colIn]":`${Or(e,c)}(bias[row])`};`:""} + ${t} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},mi=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i.slice(0,-2),c=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),d=ye.size(p),u=i[i.length-2],f=i[i.length-1],_=a[a.length-1],b=f%4===0&&_%4===0,k=u<=8?[4,1,1]:[4,4,1],g=[8,8,1],M=[Math.ceil(_/g[0]/k[0]),Math.ceil(u/g[1]/k[1]),Math.ceil(d/g[2]/k[2])],$=b?4:1,v=[...l,u,f/$],y=v.length,T=[...c,f,_/$],x=T.length,P=[d,u,_/$],O=[{type:6,data:u},{type:6,data:_},{type:6,data:f}];mn(r,O),O.push(...ct(p,v,T));let L=["rank","rank"],G=e.length>2;G&&(O.push(...ct(e[2].dims)),L.push("rank")),O.push(...ct(P));let K=R=>{let te=p.length,H=il("batchDims",e[0].dataType,te,1),ee=Er(e[0].dataType),Z=$e("a",e[0].dataType,y,$),ne=$e("b",e[1].dataType,x,$),me=it("result",e[0].dataType,P.length,$),ue=[Z,ne];if(G){let _e=o?$:1;ue.push($e("bias",e[2].dataType,e[2].dims.length,_e))}let j=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];_n(r,j);let F=Er(me.type.tensor),U=hn(r,me.type.value,F),se=mm($,G,U,[H,Z,ne,me],o);return` + ${R.registerUniforms(j).registerInternalVariables(H).declareVariables(...ue,me)} + ${se} + ${b?yl(k,g,ee,H):xl(k,g,ee,H)} + `};return{name:"MatMul",shaderCache:{hint:`${k};${r.activation};${b};${o}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:M[0],y:M[1],z:M[2]},programUniforms:O}),getShaderSource:K}}}),_m,fm,cx=Ve(()=>{gt(),Bs(),Pt(),fn(),wl(),lx(),Tl(),_m=(e,r,t,s,o=!1,n,i=4,a=4,l=4,c="f32")=>{let p=O=>{switch(O){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${O} is not supported.`)}},d=O=>{switch(O){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 ${O} is not supported.`)}},u=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,f=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,_=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",b=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",k=e?"row":"col",g=e?"col":"row",M=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${k} / outWidth; + let outCol = ${k} % outWidth; + + let WRow = ${g} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${g} / 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 = ${g} % inChannels; + var resData = ${Or(i,c)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${_} && xCol >= 0 && xCol < ${b}) { + ${u} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${p(i)} + } + return resData;`,$=e?r&&s?` + let col = colIn * ${i}; + ${M}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${M} + } + return ${Or(i,c)}(0.0);`:s&&t?` + let col = colIn * ${i}; + ${M}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${M} + } + return ${Or(i,c)}(0.0);`,v=e?s&&t?d(a):` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${d(a)} + } + return ${Or(a,c)}(0.0);`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${d(a)} + } + return ${Or(a,c)}(0.0);`,y=Or(l,c),T=Or(e?i:a,c),x=Or(e?a:i,c),P=hn(n,y,c);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${T} { + ${e?$:v} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${x} { + ${e?v:$} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${y}) { + let col = colIn * ${l}; + 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])"}; + ${f} + ${cm(o)} + ${P} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},fm=(e,r,t,s,o,n,i,a,l)=>{let c=r.format==="NHWC",p=c?e[0].dims[3]:e[0].dims[1],d=t[0],u=c?t[2]:t[3],f=c?t[1]:t[2],_=c?t[3]:t[1],b=c&&(p%4===0||p%3===0)&&_%4===0,k=c?_:u*f,g=c?u*f:_,M=[8,8,1],$=s<=8?[4,1,1]:[4,4,1],v=[Math.ceil(k/M[0]/$[0]),Math.ceil(g/M[1]/$[1]),Math.ceil(d/M[2]/$[2])];Dt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${v}`);let y=b?c&&p%4!==0?3:4:1,T=M[1]*$[1],x=M[0]*$[0],P=Math.max(M[0]*y,M[1]),O=s%T===0,L=o%x===0,G=n%P===0,K=b?[y,4,4]:[1,1,1],R=[{type:6,data:s},{type:6,data:o},{type:6,data:n},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];mn(r,R),R.push(...ct(e[0].dims,e[1].dims));let te=["rank","rank"];i&&(R.push(...ct(e[2].dims)),te.push("rank")),R.push(...ct(t));let H=ee=>{let Z=[{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}];_n(r,Z);let ne=b?4:1,me=Er(e[0].dataType),ue=` + fn setOutputAtIndex(flatIndex : i32, value : ${b?`vec4<${me}>`:me}) { + result[flatIndex] = ${b?`vec4<${me}>`:me}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${b?`vec4<${me}>`:me}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${b?"/ 4":""}, value); + }`,j=$e("x",e[0].dataType,e[0].dims.length,y===3?1:y),F=$e("w",e[1].dataType,e[1].dims.length,ne),U=[j,F],se=it("result",e[0].dataType,t.length,ne);if(i){let _e=$e("bias",e[2].dataType,e[2].dims.length,ne);U.push(_e),ue+=` + fn getBiasByOutputCoords(coords : vec4) -> ${b?`vec4<${me}>`:me} { + return bias[coords.${c?"w":"y"}${b?"/ 4":""}]; + }`}return` + ${um("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 }; + ${ee.registerUniforms(Z).declareVariables(...U,se)} + ${ue} + ${_m(c,O,L,G,i,r,K[0],K[1],K[2],me)} + ${b?yl($,M,me,void 0,!c,P):xl($,M,me,void 0,!c,P,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${y};${b};${O};${L};${G};${T};${x};${P}`,inputDependencies:te},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:R}),getShaderSource:H}}}),gm,El,Mo,wm,Pl,Mm,bm,ym,ux=Ve(()=>{gt(),Bs(),Et(),Pt(),fn(),wl(),gm=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,Mo=(e,r)=>r<=1?e:e+(e-1)*(r-1),wm=(e,r,t,s=1)=>{let o=Mo(r,s);return Math.floor((e[0]*(t-1)-t+o)/2)},Pl=(e,r,t,s,o)=>{o==null&&(o=wm(e,r[0],s[0]));let n=[0,0,0,t];for(let i=0;i<3;i++)e[i]+2*o>=r[i]&&(n[i]=Math.trunc((e[i]-r[i]+2*o)/s[i]+1));return n},Mm=(e,r,t,s,o,n,i,a,l,c)=>{let p,d,u,f;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let _=Pl([r,t,s,1],[a,l,c],1,[o,n,i],e);d=_[0],u=_[1],f=_[2]}else if(Array.isArray(e)){if(!e.every((b,k,g)=>b===g[0]))throw Error(`Unsupported padding parameter: ${e}`);p={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let _=Pl([r,t,s,1],[a,l,c],1,[o,n,i],e[0]);d=_[0],u=_[1],f=_[2]}else if(e==="SAME_UPPER"){d=Math.ceil(r/o),u=Math.ceil(t/n),f=Math.ceil(s/i);let _=(d-1)*o+a-r,b=(u-1)*n+l-t,k=(f-1)*i+c-s,g=Math.floor(_/2),M=_-g,$=Math.floor(b/2),v=b-$,y=Math.floor(k/2),T=k-y;p={top:$,bottom:v,left:y,right:T,front:g,back:M}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:u,outWidth:f}},bm=(e,r,t,s,o,n=!1,i="channelsLast")=>{let a,l,c,p,d;if(i==="channelsLast")[a,l,c,p,d]=e;else if(i==="channelsFirst")[a,d,l,c,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[u,,f,_,b]=r,[k,g,M]=El(t),[$,v,y]=El(s),T=Mo(f,$),x=Mo(_,v),P=Mo(b,y),{padInfo:O,outDepth:L,outHeight:G,outWidth:K}=Mm(o,l,c,p,k,g,M,T,x,P),R=n?u*d:u,te=[0,0,0,0,0];return i==="channelsFirst"?te=[a,R,L,G,K]:i==="channelsLast"&&(te=[a,L,G,K,R]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:c,inWidth:p,inChannels:d,outDepth:L,outHeight:G,outWidth:K,outChannels:R,padInfo:O,strideDepth:k,strideHeight:g,strideWidth:M,filterDepth:f,filterHeight:_,filterWidth:b,effectiveFilterDepth:T,effectiveFilterHeight:x,effectiveFilterWidth:P,dilationDepth:$,dilationHeight:v,dilationWidth:y,inShape:e,outShape:te,filterShape:r}},ym=(e,r,t,s,o,n)=>{let i=n==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((k,g)=>g)},c=[Math.ceil(gm(l.x.map(k=>t[k]))/a[0]),1,1];Dt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${c}`);let p=1,d=ye.size(t),u=[{type:12,data:d},{type:12,data:s},{type:12,data:o},{type:12,data:r.strides},{type:12,data:r.dilations}];mn(r,u),u.push(...ct(e[0].dims,e[1].dims));let f=["rank","rank"],_=e.length===3;_&&(u.push(...ct(e[2].dims)),f.push("rank")),u.push(...ct(t));let b=k=>{let g=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];_n(r,g);let M=1,$=Er(e[0].dataType),v=$e("x",e[0].dataType,e[0].dims.length,p),y=$e("W",e[1].dataType,e[1].dims.length,M),T=[v,y],x=it("result",e[0].dataType,t.length,M),P="";if(_){let G=$e("bias",e[2].dataType,e[2].dims.length,M);T.push(G),P+=` + fn getBiasByOutputCoords(coords : array) -> ${$} { + return bias[${i?lt("coords",4,5):lt("coords",1,5)}]; + }`}let O=Or(p,$),L=hn(r,O,$);return` + ${P} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${v.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${y.getByIndices("aIndices")}; + } + ${k.registerUniforms(g).declareVariables(...T,x)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${x.offsetToIndices("global_idx")}; + let batch = ${lt("coords",0,v.rank)}; + let d2 = ${i?lt("coords",v.rank-1,v.rank):lt("coords",1,v.rank)}; + let xFRCCorner = vec3(${i?lt("coords",1,v.rank):lt("coords",2,v.rank)}, + ${i?lt("coords",2,v.rank):lt("coords",3,v.rank)}, + ${i?lt("coords",3,v.rank):lt("coords",4,v.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${i?lt("uniforms.x_shape",1,v.rank):lt("uniforms.x_shape",2,v.rank)}; + let xShapeZ = ${i?lt("uniforms.x_shape",2,v.rank):lt("uniforms.x_shape",3,v.rank)}; + let xShapeW = ${i?lt("uniforms.x_shape",3,v.rank):lt("uniforms.x_shape",4,v.rank)}; + let xShapeU = ${i?lt("uniforms.x_shape",4,v.rank):lt("uniforms.x_shape",1,v.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${i?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${i?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${i?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${_?"value = value + getBiasByOutputCoords(coords)":""}; + ${L} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${i};${p};${_}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:c[0],y:c[1],z:c[2]},programUniforms:u}),getShaderSource:b}}}),vm,xm,dx=Ve(()=>{gt(),Et(),Pt(),fn(),vm=(e,r,t,s)=>{let o=e.length>2,n=o?"value += b[output_channel];":"",i=e[0].dims,a=e[1].dims,l=r.format==="NHWC",c=l?t[3]:t[1],p=c/r.group,d=l&&p>=4?or(c):1,u=ye.size(t)/d,f=[{type:12,data:u},{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:p}];mn(r,f),f.push(...ct(i,[a[0],a[1],a[2],a[3]/d]));let _=o?["rank","rank","rank"]:["rank","rank"];f.push(...ct([t[0],t[1],t[2],t[3]/d]));let b=k=>{let g=it("output",e[0].dataType,t.length,d),M=Er(g.type.tensor),$=hn(r,g.type.value,M),v=$e("x",e[0].dataType,i.length),y=$e("w",e[1].dataType,a.length,d),T=[v,y];o&&T.push($e("b",e[2].dataType,e[2].dims,d));let x=[{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"}];_n(r,x);let P=l?` + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { + continue; + } + + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + let xVal = ${v.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${y.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + 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[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[3]) { + continue; + } + + let xVal = ${v.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${y.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${k.registerUniforms(x).declareVariables(...T,g)} + + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${g.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${l?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${d} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}]; + + var value: ${g.type.value} = ${g.type.value}(0); + ${P} + ${n} + ${$} + ${g.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${d}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:b}},xm=(e,r,t,s)=>{let o=e.length>2,n=or(t[3]),i=or(t[2]),a=ye.size(t)/n/i,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/n],p=[t[0],t[1],t[2],t[3]/n],d=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];mn(r,d),d.push(...ct(l,c,p));let u=(i-1)*r.strides[1]+c[1],f=_=>{let b=it("output",e[0].dataType,p.length,n),k=Er(b.type.tensor),g=hn(r,b.type.value,k),M=$e("x",e[0].dataType,l.length,n),$=$e("w",e[1].dataType,c.length,n),v=[M,$];o&&v.push($e("b",e[2].dataType,e[2].dims,n));let y=o?"value += b[output_channel];":"",T=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return _n(r,T),` + ${_.registerUniforms(T).declareVariables(...v,b)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${i}u; + let col = (index1 % width1) * ${i}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<${M.type.value}, ${u}>; + var values: array<${b.type.value}, ${i}>; + 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 < ${c[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 < ${u}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${M.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${M.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) { + let w_val = ${$.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${i}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${i}u; i++) { + var value = values[i]; + ${y} + ${g} + ${b.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${i};${u};${c[0]};${c[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:f}}}),Tm,_i,Em,fi,Cl,Sl,Pm,Cm,$l,px=Ve(()=>{Et(),cx(),ux(),Tl(),dx(),fn(),bl(),Hs(),Tm=(e,r,t,s,o,n)=>{let i=e[0],a=e.slice(n?1:2,n?3:4),l=a.length,c=r[0],p=r.slice(2).map((u,f)=>u+(u-1)*(t[f]-1)),d=a.map((u,f)=>u+s[f]+s[f+l]).map((u,f)=>Math.floor((u-p[f]+o[f])/o[f]));return d.splice(0,0,i),d.splice(n?3:1,0,c),d},_i=[2,3,1,0],Em=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");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],s=e[1].dims[1]*r.group;if(t!==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(r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},fi=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=gl(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,n=e.group,i=e.kernel_shape,a=e.pads,l=e.strides,c=e.w_is_const();return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,pads:a,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},Sl=(e,r,t,s)=>{let o=t.format==="NHWC",n=Tm(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,o);if(t.group!==1){let T=[r[0]];if(o){let x=e.kernelCustomData.wT??e.compute(os(r[1],_i),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=x),T.push(x)}else T.push(r[1]);r.length===3&&T.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(xm(T,t,n,s),{inputs:T}):e.compute(vm(T,t,n,s),{inputs:T});return}let i=r.length===3,a=r[0].dims[o?1:2],l=r[0].dims[o?2:3],c=r[0].dims[o?3:1],p=r[1].dims[2],d=r[1].dims[3],u=n[o?1:2],f=n[o?2:3],_=n[o?3:1],b=o&&p===a&&d===l&&t.pads[0]===0&&t.pads[1]===0;if(b||p===1&&d===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 T=n[0],x,P,O,L=[];if(o){let R=e.kernelCustomData.wT??e.compute(os(r[1],_i),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=R),b){let te=a*l*c;x=r[0].reshape([1,T,te]),P=R.reshape([1,te,_]),O=[1,T,_]}else x=r[0].reshape([T,a*l,c]),P=R.reshape([1,c,_]),O=[T,u*f,_];L.push(x),L.push(P)}else x=r[0].reshape([T,c,a*l]),P=r[1].reshape([1,_,c]),O=[T,_,u*f],L.push(P),L.push(x);i&&L.push(r[2]);let G=O[2],K=L[0].dims[L[0].dims.length-1];G<8&&K<8?e.compute(Ml(L,t,n,O,o,s),{inputs:L}):e.compute(mi(L,t,n,O,o,s),{inputs:L});return}let k=!0,g=e.kernelCustomData.wT??e.compute(os(r[1],_i),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=g);let M=[r[0],g];i&&M.push(r[2]);let $=o?u*f:_,v=o?_:u*f,y=p*d*c;e.compute(fm(M,t,n,$,v,y,i,k,s),{inputs:M})},Pm=(e,r)=>{let t=r.format==="NHWC",s=[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&&s.push(e.inputs[2]);let o=[0,r.pads[0],0,r.pads[1]],n=[1].concat(r.strides),i=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=fi({...r,pads:o,strides:n,dilations:i,kernelShape:a},s);Sl(e,s,l,c=>t?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},Cm=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",o=fi(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=bm(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(ym(r,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},$l=(e,r)=>{if(Em(e.inputs,r),e.inputs[0].dims.length===3)Pm(e,r);else if(e.inputs[0].dims.length===5)Cm(e,e.inputs,r);else{let t=fi(r,e.inputs);Sl(e,e.inputs,t)}}}),Sm,hx=Ve(()=>{gt(),Bs(),Et(),Pt(),Sm=(e,r,t)=>{let s=e.length>2,o=r.outputShape,n=r.format==="NHWC",i=r.group,a=e[1].dims,l=a[2]/i,c=a[3],p=n?or(l):1,d=n&&c===1&&l>=4,u=d?Math.floor(l/4)*4:Math.floor(l/p)*p,f=l-u,_=n?or(c):1,b=n?c===1?p:_:1,k=ye.size(o)/_,g=[Math.ceil(k/64),1,1];Dt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${g}`);let M=["rank","rank"],$=[r.strides[0],r.strides[1]],v=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],y=[r.dilations[0],r.dilations[1]],T=[v[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),v[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],x=[T[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),T[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],P=[{type:12,data:k},{type:12,data:$},{type:12,data:v},{type:12,data:y},{type:12,data:T},{type:6,data:x},{type:12,data:u},{type:12,data:l},{type:12,data:c},...ct(e[0].dims,e[1].dims)];s&&(P.push(...ct(e[2].dims)),M.push("rank")),P.push(...ct(o));let O=L=>{let G=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:$.length},{name:"filter_dims",type:"u32",length:v.length},{name:"dilations",type:"u32",length:v.length},{name:"effective_filter_dims",type:"u32",length:T.length},{name:"pads",type:"i32",length:x.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],K=Er(e[0].dataType),R=n?1:2,te=n?2:3,H=n?3:1,ee=$e("W",e[1].dataType,e[1].dims.length,b),Z=$e("Dy",e[0].dataType,e[0].dims.length,p),ne=[Z,ee];s&&ne.push($e("bias",e[2].dataType,[o[H]].length,_));let me=it("result",e[0].dataType,o.length,_),ue=()=>{let U="";if(d)p===4?U+=` + let xValue = ${Z.getByOffset("x_offset")}; + let wValue = ${ee.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue); + x_offset += 1u; + w_offset += 1u;`:p===2?U+=` + dotProd = dotProd + dot(vec4<${K}>(${Z.getByOffset("x_offset")}, ${Z.getByOffset("x_offset + 1u")}), vec4<${K}>(${ee.getByOffset("w_offset")}, ${ee.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;`:p===1&&(U+=` + dotProd = dotProd + dot(vec4<${K}>(${Z.getByOffset("x_offset")}, ${Z.getByOffset("x_offset + 1u")}, ${Z.getByOffset("x_offset + 2u")}, ${Z.getByOffset("x_offset + 3u")}), vec4<${K}>(${ee.getByOffset("w_offset")}, ${ee.getByOffset("w_offset + 1u")}, ${ee.getByOffset("w_offset + 2u")}, ${ee.getByOffset("w_offset + 3u")})); + x_offset += 4u; + w_offset += 4u;`);else if(U+=` + let xValue = ${n?Z.getByOffset(`${Z.indicesToOffset(`${Z.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):Z.get("batch","inputChannel","idyR","idyC")}; + `,p===1)U+=` + let w_offset = ${ee.indicesToOffset(`${ee.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${ee.getByOffset(`w_offset / ${b}`)}; + dotProd = dotProd + xValue * wValue;`;else for(let se=0;se{if(f===0)return"";if(!d)throw new Error(`packInputAs4 ${d} is not true.`);let U="";if(p===1){U+="dotProd = dotProd";for(let se=0;se(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 = ${me.type.value}(0.0); + var wR: u32 = 0; + if (uniforms.dilations.x == 1) { + // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 + wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); + } + for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${K}(dyRCorner) + ${K}(wR)) / ${K}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${K}(uniforms.Dy_shape[${R}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + var wC: u32 = 0; + if (uniforms.dilations.y == 1) { + // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 + wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); + } + for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${K}(dyCCorner) + ${K}(wC)) / ${K}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${K}(uniforms.Dy_shape[${te}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + ${d?` + var x_offset = ${Z.indicesToOffset(`${Z.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; + var w_offset = ${ee.indicesToOffset(`${ee.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${b}; + `:""} + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${d?4:p}) { + ${ue()} + inputChannel = inputChannel + ${d?4:p}; + } + ${j()} + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${s?` + bias[d1 / ${_}]`:""}; + ${me.setByOffset("global_idx","value")}; + `;return` + ${L.registerUniforms(G).declareVariables(...ne,me)} + ${L.mainStart()} + ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${F}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${b}${_}${d}${f}`,inputDependencies:M},getRunData:()=>({dispatchGroup:{x:g[0],y:g[1],z:g[2]},outputs:[{dims:t?t(o):o,dataType:e[0].dataType}],programUniforms:P}),getShaderSource:O}}}),$m,km,Im,kl,Am,Fm,Il,Om,Dm,mx=Ve(()=>{hx(),fn(),Hs(),$m=(e,r,t,s,o,n)=>(e-1)*r+t+(s-1)*o+1-n,km=(e,r,t,s,o)=>{let n=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=n,t[o]=e-n):r==="SAME_LOWER"&&(t[s]=e-n,t[o]=n)},Im=(e,r,t,s,o,n,i,a,l,c)=>{let p=e.length-2,d=c.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((d,u)=>d*u,1)===0){t.length=0;for(let d=2;dd+u,0)===0){let d=r[0].dims.length-2;l=new Array(d).fill(1)}let c=e.strides.slice();if(c.reduce((d,u)=>d+u,0)===0){let d=r[0].dims.length-2;c=new Array(d).fill(1)}Im(a,t,l,e.autoPad,e.group,o,c,s,i,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:o,outputPadding:i,outputShape:n,dilations:l,strides:c}),p},Am=e=>{let r=gl(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,n=e.group,i=e.kernelShape,a=e.pads,l=e.strides,c=e.wIsConst(),p=e.outputPadding,d=e.outputShape;return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,outputPadding:p,outputShape:d,pads:a,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},Fm=(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],s=e[1].dims[0];if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.reduce((i,a)=>i+a,0)>0&&r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.reduce((i,a)=>i+a,0)>0&&r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.reduce((i,a)=>i+a,0)>0&&r.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(r.outputPadding.length!==n&&r.outputPadding.length!==0)throw new Error(`output_padding should be ${n}D`);if(r.kernelShape.reduce((i,a)=>i+a,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")},Il=(e,r,t,s)=>{let o=e.kernelCustomData.wT??e.compute(os(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let n=[r[0],o];r.length===3&&n.push(r[2]),e.compute(Sm(n,t,s),{inputs:n})},Om=(e,r)=>{let t=r.format==="NHWC",s=[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&&s.push(e.inputs[2]);let o=r.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let n=r.dilations;(n.length===0||n[0]===0)&&(n=[1]);let i=r.strides;(i.length===0||i[0]===0)&&(i=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],i=[1].concat(i),n=[1].concat(n),o=[1].concat(o);let l=r.outputPadding;l=[0].concat(l);let c=kl({...r,pads:a,strides:i,dilations:n,kernelShape:o,outputPadding:l},s);Il(e,s,c,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Dm=(e,r)=>{if(Fm(e.inputs,r),e.inputs[0].dims.length===3)Om(e,r);else{let t=kl(r,e.inputs);Il(e,e.inputs,t)}}}),Lm,zm,Bm,_x=Ve(()=>{gt(),Et(),cr(),Pt(),Lm=(e,r,t,s)=>{let o=ye.size(r),n=r.length,i=$e("input",e,n),a=it("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),c=ye.normalizeAxis(l,n),p=d=>{let u=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,f=lt("uniforms.input_shape","uniforms.axis",n),_=s.reverse?u+(s.exclusive?" + 1":""):"0",b=s.reverse?f:u+(s.exclusive?"":" + 1");return` + ${d.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,a)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${a.offsetToIndices("global_idx")}; + var sum = ${a.type.value}(0); + let first : i32 = ${_}; + let last : i32 = ${b}; + for (var i : i32 = first; i < last; i++) { + ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${i.getByIndices("inputIndices")}; + } + ${a.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:c},...ct(r,r)]}),getShaderSource:p}},zm=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,o=e.inputs[1];e.compute(Lm(s,t,o,r),{inputs:[0]})},Bm=e=>{let r=e.exclusive===1,t=e.reverse===1;return Nt({exclusive:r,reverse:t})}}),Rm,jm,Nm,Vm,Um,fx=Ve(()=>{gt(),Et(),cr(),Pt(),Rm=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.")},jm=(e,r,t,s)=>{let o=[];o.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`);for(let n=0;n{let t,s,o,n,i,a,l=r.format==="NHWC",c=r.blocksize,p=r.mode==="DCR";l?([t,s,o,n]=e.dims,i=p?[t,s,o,c,c,n/c**2]:[t,s,o,n/c**2,c,c],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,o,n]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=p?[t,c,c,n/c**2,s,o]:[t,n/c**2,c,c,s,o],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(i),u=d.dims.length,f=e.dataType,_=$e("a",f,u),b=it("output",f,u),k=g=>` + ${g.registerUniform("output_size","u32").declareVariables(_,b)} + + ${jm(a,u,_,b)} + + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${b.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${b.setByOffset("global_idx",_.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:g=>{let M=l?[t,s*c,o*c,n/c**2]:[t,n/c**2,s*c,o*c],$=ye.size(M),v=d.dims,y=ye.sortBasedOnPerm(v,a);return{outputs:[{dims:M,dataType:g[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:[{type:12,data:$},...ct(v,y)]}},getShaderSource:k}},Vm=(e,r)=>{Rm(e.inputs),e.compute(Nm(e.inputs[0],r))},Um=e=>Nt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),gi,bo,Al,Wm,Gm,Km,Hm,Fl,qm,Qm,Xm,gx=Ve(()=>{gt(),Et(),cr(),Pt(),gi="[a-zA-Z]|\\.\\.\\.",bo="("+gi+")+",Al="^"+bo+"$",Wm="("+bo+",)*"+bo,Gm="^"+Wm+"$",Km=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,r){let t=this.symbolToIndices.get(e);t===void 0?t=[r]:t.push(r),this.symbolToIndices.set(e,t)}},Hm=class{constructor(e,r){var o;this.equation=r,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,s]=r.includes("->")?r.split("->",2):[r,""];if(!t.match(RegExp(Gm)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,i)=>{let a=e[i].dims.slice();if(!n.match(RegExp(Al)))throw new Error("Invalid LHS term");let l=this.processTerm(n,!0,a,i);this.lhs.push(l)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,i])=>i.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(bo)))throw new Error("Invalid RHS");(o=s.match(RegExp(gi,"g")))==null||o.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(n);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(e,r,t){let s=this.symbolToInfo.get(e);if(s!==void 0){if(s.dimValue!==r&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(t)}else s={count:1,dimValue:r,inputIndices:[t]};this.symbolToInfo.set(e,s)}processTerm(e,r,t,s=-1){let o=t.length,n=!1,i=[],a=0;if(!e.match(RegExp(Al))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(gi,"g")),c=new Km(s);return l==null||l.forEach((p,d)=>{if(p==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let u=o-l.length+1;if(u<0)throw new Error("Ellipsis out of bounds");if(i=t.slice(a,a+u),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let f=0;fe+"_max",qm=(e,r,t,s)=>{let o=e.map(c=>c.length).map((c,p)=>$e(`input${p}`,r,c)),n=ye.size(s),i=it("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(c=>!t.rhs.symbolToIndices.has(c)),l=c=>{let p=[],d="var prod = 1.0;",u="var sum = 0.0;",f="sum += prod;",_=[],b=[],k=[],g=[],M=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((v,y)=>{var T;if(t.rhs.symbolToIndices.has(y)){let x=(T=t.rhs.symbolToIndices.get(y))==null?void 0:T[0];x!==void 0&&t.lhs.forEach((P,O)=>{if(v.inputIndices.includes(O)){let L=P.symbolToIndices.get(y);if(L===void 0)throw new Error("Invalid symbol error");L.forEach(G=>{p.push(`${o[O].indicesSet(`input${O}Indices`,G,i.indicesGet("outputIndices",x))}`)})}})}else t.lhs.forEach((x,P)=>{if(v.inputIndices.includes(P)){let O=x.symbolToIndices.get(y);if(O===void 0)throw new Error("Invalid symbol error");O.forEach(L=>{_.push(`${o[P].indicesSet(`input${P}Indices`,L,`${y}`)}`)}),g.push(`prod *= ${o[P].getByIndices(`input${P}Indices`)};`)}}),b.push(`for(var ${y}: u32 = 0; ${y} < uniforms.${Fl(y)}; ${y}++) {`),k.push("}")});let $=M?[...p,`let sum = ${o.map((v,y)=>v.getByIndices(`input${y}Indices`)).join(" * ")};`]:[...p,u,...b,..._,d,...g,f,...k];return` + ${c.registerUniforms(a.map(v=>({name:`${Fl(v)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${o.map((v,y)=>`var input${y}Indices: ${o[y].type.indices};`).join(` +`)} + ${$.join(` +`)}; + ${i.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let c=a.filter(d=>t.symbolToInfo.has(d)).map(d=>{var u;return{type:12,data:((u=t.symbolToInfo.get(d))==null?void 0:u.dimValue)||0}});c.push({type:12,data:n});let p=e.map((d,u)=>[...ct(d)]).reduce((d,u)=>d.concat(u),c);return p.push(...ct(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},Qm=(e,r)=>{let t=new Hm(e.inputs,r.equation),s=t.outputDims,o=e.inputs.map((n,i)=>n.dims);e.compute(qm(o,e.inputs[0].dataType,t,s))},Xm=e=>{let r=e.equation.replace(/\s+/g,"");return Nt({equation:r})}}),Jm,Ol,Ym,Zm,e_,wx=Ve(()=>{gt(),Et(),Pt(),Jm=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),s=t.length{let t=e.length-r.length,s=[];for(let o=0;oe.length>r.length?Ol(e,r):Ol(r,e),Zm=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=Ym(r,t),o=e[0].dataType,n=o===9||ye.size(r)===1,i=o===9||r.length>0&&r[r.length-1]%4===0?4:1,a=n||s.length>0&&s[s.length-1]%4===0?4:1,l=Math.ceil(ye.size(s)/a),c=d=>{let u=$e("input",o,r.length,i),f=it("output",o,s.length,a),_;if(o===9){let b=(k,g,M="")=>` + let outputIndices${g} = ${f.offsetToIndices(`outputOffset + ${g}u`)}; + let offset${g} = ${u.broadcastedIndicesToOffset(`outputIndices${g}`,f)}; + let index${g} = offset${g} / 4u; + let component${g} = offset${g} % 4u; + ${k}[${g}] = ${M}(${u.getByOffset(`index${g}`)}[component${g}]); + `;_=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${b("data",0,"u32")} + ${b("data",1,"u32")} + ${b("data",2,"u32")} + ${b("data",3,"u32")} + ${f.setByOffset("global_idx","data")} + }`}else _=` + let outputIndices = ${f.offsetToIndices(`global_idx * ${a}`)}; + let inputOffset = ${u.broadcastedIndicesToOffset("outputIndices",f)}; + let data = ${f.type.value}(${u.getByOffset(`inputOffset / ${i}`)}); + ${f.setByOffset("global_idx","data")} + }`;return` + ${d.registerUniform("vec_size","u32").declareVariables(u,f)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${_}`},p=[{type:12,data:l},...ct(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${i}${a}`,inputDependencies:["rank"]},getShaderSource:c,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},e_=e=>{Jm(e.inputs),e.compute(Zm(e.inputs),{inputs:[0]})}}),t_,r_,Mx=Ve(()=>{gt(),Et(),Pt(),fl(),t_=e=>{let r=e[0].dataType,t=ye.size(e[0].dims),s=ye.size(e[1].dims),o=s%4===0,n=i=>{let a=$e("x",r,[1],4),l=$e("bias",r,[1],4),c=it("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],d=f=>` + let bias${f}_offset: u32 = (global_idx * 4 + ${f}) % uniforms.bias_size; + let bias${f} = ${l.getByOffset(`bias${f}_offset / 4`)}[bias${f}_offset % 4];`,u=o?` + let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${d(0)}${d(1)}${d(2)}${d(3)} + let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(p).declareVariables(a,l,c)} + + ${ml(Rr(r))} + + ${i.mainStart(Wn)} + ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${a.getByOffset("global_idx")}; + ${u} + let x_in = x + bias; + ${c.setByOffset("global_idx",_l("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:n,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/Wn/4)}})}},r_=e=>{e.inputs.length<2||ye.size(e.inputs[1].dims)===0?Lh(e):e.compute(t_(e.inputs))}}),s_,n_,o_,i_,bx=Ve(()=>{gt(),Et(),cr(),Pt(),s_=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},n_=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=ye.normalizeAxis(r.axis,o),i=t.slice(0);i.splice(n,1,...s);let a=t[n],l=e[0].dataType===9?4:1,c=Math.ceil(ye.size(i)/l),p=[{type:12,data:c},{type:6,data:a},{type:12,data:n},...ct(e[0].dims,e[1].dims,i)],d=u=>{let f=$e("data",e[0].dataType,e[0].dims.length,l),_=$e("inputIndices",e[1].dataType,e[1].dims.length),b=it("output",e[0].dataType,i.length,l),k=M=>{let $=s.length,v=`var indicesIndices${M} = ${_.type.indices}(0);`;for(let y=0;y<$;y++)v+=`${$>1?`indicesIndices${M}[${y}]`:`indicesIndices${M}`} = ${i.length>1?`outputIndices${M}[uniforms.axis + ${y}]`:`outputIndices${M}`};`;v+=` + var idx${M} = ${_.getByIndices(`indicesIndices${M}`)}; + if (idx${M} < 0) { + idx${M} = idx${M} + uniforms.axisDimLimit; + } + var dataIndices${M} : ${f.type.indices}; + `;for(let y=0,T=0;y1?`dataIndices${M}[${y}]`:`dataIndices${M}`} = u32(idx${M});`,T+=$):(v+=`${o>1?`dataIndices${M}[${y}]`:`dataIndices${M}`} = ${i.length>1?`outputIndices${M}[${T}]`:`outputIndices${M}`};`,T++);return v},g;if(e[0].dataType===9){let M=($,v,y="")=>` + let outputIndices${v} = ${b.offsetToIndices(`outputOffset + ${v}u`)}; + ${k(v)}; + let offset${v} = ${f.indicesToOffset(`dataIndices${v}`)}; + let index${v} = offset${v} / 4u; + let component${v} = offset${v} % 4u; + ${$}[${v}] = ${y}(${f.getByOffset(`index${v}`)}[component${v}]); + `;g=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${M("value",0,"u32")} + ${M("value",1,"u32")} + ${M("value",2,"u32")} + ${M("value",3,"u32")} + ${b.setByOffset("global_idx","value")} + `}else g=` + let outputIndices = ${b.offsetToIndices("global_idx")}; + ${k("")}; + let value = ${f.getByIndices("dataIndices")}; + ${b.setByOffset("global_idx","value")}; + `;return` + ${u.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(f,_,b)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${g} + }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:d}},o_=e=>Nt({axis:e.axis}),i_=(e,r)=>{let t=e.inputs;s_(t),e.compute(n_(e.inputs,r))}}),a_,l_,c_,yx=Ve(()=>{gt(),Et(),Pt(),a_=(e,r,t,s,o,n,i,a,l)=>{let c=[{type:12,data:n},{type:12,data:s},{type:12,data:o},{type:12,data:t},{type:12,data:i},{type:12,data:a},{type:12,data:l}],p=[n];c.push(...ct(r.dims,p));let d=u=>{let f=$e("indices_data",r.dataType,r.dims.length),_=it("input_slice_offsets_data",12,1,1),b=[f,_],k=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:t.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${u.registerUniforms(k).declareVariables(...b)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${t.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:c}),getShaderSource:d},{inputs:[r],outputs:[-1]})[0]},l_=(e,r)=>{let t=e.inputs,s=t[0].dims,o=t[0].dataType,n=t[1].dims,i=n[n.length-1],a=ye.sizeToDimension(n,n.length-1),l=ye.sizeFromDimension(s,r.batchDims+i),c=ye.sizeToDimension(s,r.batchDims),p=ye.sizeFromDimension(s,r.batchDims),d=a/c,u=new Array(i),f=l;for(let v=0;vs.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let k=n.slice(0,-1).concat(s.slice(b)),g=ye.size(k),M=[{type:12,data:g},{type:12,data:l},...ct(t[0].dims,_.dims,k)],$=v=>{let y=$e("data",t[0].dataType,t[0].dims.length),T=$e("slice_offsets",12,_.dims.length),x=it("output",t[0].dataType,k.length);return` + ${v.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(y,T,x)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; + output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; + }`};e.compute({name:"GatherND",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:k,dataType:o}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:M}),getShaderSource:$},{inputs:[t[0],_]})},c_=e=>({batchDims:e.batch_dims,cacheKey:""})}),u_,d_,p_,h_,vx=Ve(()=>{gt(),Et(),cr(),Pt(),u_=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=ye.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,o=e[0],n=e[2],i=e.length===4?e[3]:void 0;if(n.dims.length!==o.dims.length||!o.dims.map((a,l)=>l===t?Math.ceil(a/s)===n.dims[l]:a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==n.dims.length||!i.dims.map((a,l)=>a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},d_=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=ye.normalizeAxis(r.gatherAxis,o),i=ye.normalizeAxis(r.quantizeAxis,o),a=t.slice(0);a.splice(n,1,...s);let l=ye.size(a),c=e[2].dataType,p=e[0].dataType===22,d=[{type:12,data:l},{type:12,data:i},{type:12,data:n},{type:12,data:r.blockSize},...ct(...e.map((f,_)=>f.dims),a)],u=f=>{let _=$e("data",e[0].dataType,e[0].dims.length),b=$e("inputIndices",e[1].dataType,e[1].dims.length),k=$e("scales",e[2].dataType,e[2].dims.length),g=e.length>3?$e("zeroPoint",e[3].dataType,e[3].dims.length):void 0,M=it("output",c,a.length),$=[_,b,k];g&&$.push(g);let v=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${f.registerUniforms(v).declareVariables(...$,M)} + ${f.mainStart()} + let output_indices = ${M.offsetToIndices("global_idx")}; + var indices_indices = ${b.type.indices}(0); + ${s.length>1?` + for (var i: u32 = 0; i < ${s.length}; i++) { + let index = ${M.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${b.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${M.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${_.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${M.indicesGet("output_indices","i")}; + ${_.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${b.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${t[n]}; + } + ${_.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${a.length}; i++) { + let index = ${M.indicesGet("output_indices",`i + ${s.length} - 1`)}; + ${_.indicesSet("data_indices","i","index")}; + } + let data_offset = ${_.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${_.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); + let quantized_data = quantized_data_vec[data_index / 2]; + var scale_indices = data_indices; + let quantize_axis_index = ${k.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${k.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${k.getByIndices("scale_indices")}; + ${g?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${g.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${g.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${Rr(c)}(quantized_data - zero_point) * scale; + ${M.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((f,_)=>_!==1).map(f=>f.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(f,_)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:c}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:u}},p_=(e,r)=>{let t=e.inputs;u_(t,r),e.compute(d_(e.inputs,r))},h_=e=>Nt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),m_,__,f_,g_,xx=Ve(()=>{gt(),Et(),cr(),Pt(),m_=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.`)},__=(e,r)=>{let t=e[0].dims,s=e[0].dataType,o=t.length,n=e[1].dims,i=e[1].dataType,a=ye.normalizeAxis(r.axis,o),l=t[a],c=n.slice(0),p=ye.size(c),d=$e("input",s,o),u=$e("indicesInput",i,n.length),f=it("output",s,c.length),_=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return _.push(...ct(t,n,c)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:_}),getShaderSource:b=>` + ${b.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,u,f)} + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${f.offsetToIndices("global_idx")}; + + var idx = ${u.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${d.type.indices}(outputIndices); + ${d.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${d.getByIndices("inputIndices")}; + + ${f.setByOffset("global_idx","value")}; + }`}},f_=e=>Nt({axis:e.axis}),g_=(e,r)=>{let t=e.inputs;m_(t),e.compute(__(e.inputs,r))}}),w_,M_,b_,y_,Tx=Ve(()=>{gt(),Et(),Pt(),w_=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")},M_=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[o,n,i]=kd.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[o,n];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,c=Math.ceil(n/l),p=Math.ceil(o/l),d=!0,u=ye.size(a),f=[{type:12,data:d?c:u},{type:12,data:o},{type:12,data:n},{type:12,data:i},{type:1,data:r.alpha},{type:1,data:r.beta}],_=["type","type"];e.length===3&&(f.push(...ct(e[2].dims)),_.push("rank")),f.push(...ct(a));let b=g=>{let M="";r.transA&&r.transB?M="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?M="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?M="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(M="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let $=r.alpha===1?"":"value *= uniforms.alpha;",v=$e("a",e[0].dataType,e[0].dims),y=$e("b",e[1].dataType,e[1].dims),T=v.type.value,x=null,P=[v,y];e.length===3&&(x=$e("c",e[2].dataType,e[2].dims.length),P.push(x));let O=it("output",e[0].dataType,a.length);P.push(O);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` + ${g.registerUniforms(L).declareVariables(...P)} + + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${T}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${M} + } + + ${$} + ${x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",O)}; value += ${T}(uniforms.beta) * ${x.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},k=g=>{let M=$e("a",e[0].dataType,e[0].dims),$=$e("b",e[1].dataType,e[1].dims),v=null,y=[M,$];e.length===3&&(v=$e("c",e[2].dataType,e[2].dims.length),y.push(v));let T=it("output",e[0].dataType,a.length);y.push(T);let x=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],P="",O="";r.transA&&r.transB?(O=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${M.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${$.type.value}(0); + } + `,P="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(O=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${M.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${$.type.value}(0); + } + `,P="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(O=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${M.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${$.type.value}(0); + } + `,P="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(O=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${M.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${$.type.value}(0); + } + `,P="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let L=r.alpha===1?"":"value *= uniforms.alpha;";return` + ${g.registerUniforms(x).declareVariables(...y)} + var tile_a: array, ${l}>; + var tile_b: array, ${l}>; + ${g.mainStart([l,l,1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${l}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${l}; + let num_tiles = (uniforms.K - 1) / ${l} + 1; + var k_start = 0u; + var value = ${T.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${O} + k_start = k_start + ${l}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${l}; k++) { + ${P} + } + workgroupBarrier(); + } + + ${L} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${v!=null?`let cOffset = ${v.broadcastedIndicesToOffset("vec2(m, n)",T)}; value += ${T.type.value}(uniforms.beta) * ${v.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return d?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:c*p},programUniforms:f}),getShaderSource:k}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:b}},b_=e=>{let r=e.transA,t=e.transB,s=e.alpha,o=e.beta;return{transA:r,transB:t,alpha:s,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},y_=(e,r)=>{w_(e.inputs),e.compute(M_(e.inputs,r))}}),Is,Rs,gn,wn,v_,x_,T_,E_,P_,C_,S_,$_,k_,I_,Ex=Ve(()=>{gt(),Et(),cr(),Pt(),[Is,Rs,gn,wn]=[0,1,2,3],v_=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},x_=` + fn gs_get_cubic_coeffs(x: f32) -> vec4 { + let cubic_alpha = -0.75f; + let x_abs = abs(x); + var coeffs: vec4; + coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); + coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); + coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); + coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); + return coeffs; + } +`,T_=e=>` + fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { + var v: vec4; + var coeffs = gs_get_cubic_coeffs(x); + for (var i = 0; i < 4; i++) { + v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; + } + coeffs = gs_get_cubic_coeffs(y); + let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); + return pixel; + } +`,E_=e=>` + fn gs_denormalize(n: f32, length: i32) -> f32 { + ${e.alignCorners===0?` + // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] + return ((n + 1.0) * f32(length) - 1.0) / 2.0; + `:` + // alignCorners: true => [-1, 1] to [0, length - 1] + return (n + 1.0) / 2.0 * (f32(length - 1)); + `} + } +`,P_=e=>` + ${e.paddingMode==="reflection"?` + fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { + var dx = 0.0; + var fx = f32(x); + let range = x_max - x_min; + if (fx < x_min) { + dx = x_min - fx; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_min + r; + } else { + fx = x_max - r; + } + } else if (fx > x_max) { + dx = fx - x_max; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_max - r; + } else { + fx = x_min + r; + } + } + return u32(fx); + }`:""} +`,C_=(e,r,t)=>` + fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${r} { + var pixel = ${r}(0); + var indices = vec4(0); + indices[${Is}] = batch; + indices[${Rs}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${gn}] = u32(r); + indices[${wn}] = u32(c); + } else { + return ${r}(0); + } + `;case"border":return` + indices[${gn}] = u32(clamp(r, 0, H - 1)); + indices[${wn}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${gn}] = gs_reflect(r, border[1], border[3]); + indices[${wn}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,S_=(e,r,t)=>(()=>{switch(t.mode){case"nearest":return` + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Is}], indices[${Rs}], border); + `;case"bilinear":return` + let x1 = i32(floor(x)); + let y1 = i32(floor(y)); + let x2 = x1 + 1; + let y2 = y1 + 1; + + let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Is}], indices[${Rs}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Is}], indices[${Rs}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Is}], indices[${Rs}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Is}], indices[${Rs}], border); + + let dx2 = ${r}(f32(x2) - x); + let dx1 = ${r}(x - f32(x1)); + let dy2 = ${r}(f32(y2) - y); + let dy1 = ${r}(y - f32(y1)); + let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); + `;case"bicubic":return` + let x0 = i32(floor(x)) - 1; + let y0 = i32(floor(y)) - 1; + var p: mat4x4<${r}>; + for (var h = 0; h < 4; h++) { + for (var w = 0; w < 4; w++) { + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Is}], indices[${Rs}], border); + } + } + + let dx = x - f32(x0 + 1); + let dy = y - f32(y0 + 1); + let result = gs_bicubic_interpolate(p, dx, dy); + `;default:throw new Error(`mode ${t.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,$_=(e,r)=>{let t=$e("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=$e("grid",e[1].dataType,s.length,2),n=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];r.format==="NHWC"&&(n=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[Is,Rs,gn,wn]=[0,3,1,2]);let i=it("output",e[0].dataType,n.length),a=t.type.value,l=ye.size(n),c=[{type:12,data:l},...ct(e[0].dims,s,n)],p=d=>` + ${d.registerUniform("output_size","u32").declareVariables(t,o,i)} + ${x_} + ${T_(a)} + ${E_(r)} + ${P_(r)} + ${C_(t,a,r)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${gn}]); + let W_in = i32(uniforms.x_shape[${wn}]); + + ${r.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${i.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${Is}], indices[${gn}], indices[${wn}]); + let nxy = ${o.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${S_(i,a,r)} + }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:d=>{let u=ye.size(n);return{outputs:[{dims:n,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}},getShaderSource:p}},k_=(e,r)=>{v_(e.inputs),e.compute($_(e.inputs,r))},I_=e=>Nt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Qr,A_,F_,Dl,O_,yo,D_,L_=Ve(()=>{gt(),Et(),cr(),tl(),pl(),Pt(),Hs(),Qr=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,A_=(e,r)=>{let t=e[0],s=Qr(e,1),o=Qr(e,2),n=Qr(e,3),i=Qr(e,4),a=Qr(e,5),l=Qr(e,6),c=Qr(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 p=t.dims[0],d=t.dims[1],u=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],f=d,_=0,b=0,k=Math.floor(u/r.numHeads);if(l&&c&&ye.size(l.dims)&&ye.size(c.dims)){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==p||l.dims[1]!==r.numHeads||l.dims[3]!==k)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==p||c.dims[1]!==r.numHeads||c.dims[3]!==k)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');_=l.dims[2],b=l.dims[2]}else if(l&&ye.size(l.dims)||c&&ye.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let g;if(s&&ye.size(s.dims)>0){if(t.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(t.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]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');g=2,f=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==k)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.');g=5,f=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==k)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');g=0,f=s.dims[2]}}else{if(t.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(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');g=3}if(n&&ye.size(n.dims)>0){if(n.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let M=_+f,$=0;if(i&&ye.size(i.dims)>0){$=8;let x=i.dims;throw x.length===1?x[0]===p?$=1:x[0]===3*p+2&&($=3):x.length===2&&x[0]===p&&x[1]===M&&($=5),$===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let v=!1,y=u;if(o&&ye.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.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(f!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');y=o.dims[2]}else{if(f!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');y=o.dims[1]*o.dims[3],v=!0}}let T=!1;if(i&&ye.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(a&&ye.size(a.dims)>0){if(a.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(a.dims[0]!==p||a.dims[1]!==r.numHeads||a.dims[2]!==d||a.dims[3]!==M)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:d,pastSequenceLength:_,kvSequenceLength:f,totalSequenceLength:M,maxSequenceLength:b,inputHiddenSize:0,hiddenSize:u,vHiddenSize:y,headSize:k,vHeadSize:Math.floor(y/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:$,scale:r.scale,broadcastResPosBias:T,passPastInKv:v,qkvFormat:g}},F_=e=>Nt({...e}),Dl=Nt({perm:[0,2,1,3]}),O_=(e,r,t,s,o,n,i)=>{let a=[s,o,n],l=ye.size(a),c=[{type:12,data:l},{type:12,data:i},{type:12,data:n}],p=d=>{let u=it("qkv_with_bias",r.dataType,a),f=$e("qkv",r.dataType,a),_=$e("bias",t.dataType,a),b=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${d.registerUniforms(b).declareVariables(f,_,u)} + ${d.mainStart()} + ${d.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:a,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},yo=(e,r,t,s,o,n,i,a)=>{let l=n;if(i&&ye.size(i.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=O_(e,n,i,r,s,t*o,a),l=l.reshape([r,s,t,o]),t===1||s===1?l:e.compute(os(l,Dl.perm),{inputs:[l],outputs:[-1]})[0]}else return n.dims.length===3&&(l=n.reshape([r,s,t,o])),t===1||s===1?l:e.compute(os(l,Dl.perm),{inputs:[l],outputs:[-1]})[0]},D_=(e,r)=>{let t=A_(e.inputs,r),s=e.inputs[0],o=Qr(e.inputs,1),n=Qr(e.inputs,2),i=Qr(e.inputs,3),a=Qr(e.inputs,4),l=Qr(e.inputs,5),c=Qr(e.inputs,6),p=Qr(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((o==null?void 0:o.dims.length)===5)throw new Error("Packed KV is not implemented");let d=o&&n&&o.dims.length===4&&n.dims.length===4,u=yo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(d)return fo(e,u,o,n,a,void 0,c,p,l,t);if(!o||!n)throw new Error("key and value must be provided");let f=yo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,o,i,t.hiddenSize),_=yo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,i,2*t.hiddenSize);fo(e,u,f,_,a,void 0,c,p,l,t)}}),z_,B_,R_,j_,Ll,N_,V_,U_=Ve(()=>{gt(),Et(),cr(),Pt(),z_=e=>{if(!e||e.length<1)throw new Error("too few inputs")},B_=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>t.push(Number(o))),s=t.length),Nt({numOutputs:s,axis:r.axis,splitSizes:t})},R_=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${lt("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,j_=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=ye.size(t),o=e[0].dataType,n=ye.normalizeAxis(r.axis,t.length),i=new Array(r.numOutputs),a=$e("input",o,t.length),l=new Array(r.numOutputs),c=[],p=[],d=0,u=[{type:12,data:s}];for(let _=0;_` + ${_.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...i)} + ${R_(l.length)} + ${j_(i)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${a.offsetToIndices("global_idx")}; + var index = ${a.indicesGet("indices",n)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${lt("uniforms.size_in_split_axis","output_number - 1u",l.length)}; + ${a.indicesSet("indices",n,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:f,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:u})}},N_=(e,r)=>{z_(e.inputs);let t=e.inputs.length===1?r:B_(e.inputs,r);e.compute(Ll(e.inputs,t),{inputs:[0]})},V_=e=>{let r=e.axis,t=e.splitSizes,s=e.numOutputs<0?t.length:e.numOutputs;if(s!==t.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Nt({axis:r,numOutputs:s,splitSizes:t})}}),W_,wi,G_,K_=Ve(()=>{gt(),Et(),cr(),Pt(),W_=(e,r)=>{let[t,s,o,n]=e,{numHeads:i,rotaryEmbeddingDim:a}=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(!ye.areEqual(s.dims,[])&&!ye.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(n.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(!ye.areEqual(o.dims,n.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],c=t.dims[t.dims.length-2],p=o.dims[0],d=ye.sizeFromDimension(t.dims,1)/c,u=a===0?o.dims[1]*2:d/i;if(a>u)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(l!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(c!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(u/2!==o.dims[1]&&a/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(c>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},wi=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:o,scale:n}=r,i=e[0].dims[0],a=ye.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],c=a/l,p=e[2].dims[1],d=o===0?p*2:c/s,u=new Array(i,l,c/d,d-p),f=ye.computeStrides(u),_=[{type:1,data:n},{type:12,data:u},{type:12,data:f},...e[0].dims.length===3?new Array({type:12,data:[a,c,d,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,d,l*d,1]}):[],...ct(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],b=k=>{let g=$e("input",e[0].dataType,e[0].dims.length),M=$e("position_ids",e[1].dataType,e[1].dims.length),$=$e("cos_cache",e[2].dataType,e[2].dims.length),v=$e("sin_cache",e[3].dataType,e[3].dims.length),y=it("output",e[0].dataType,e[0].dims.length);return k.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:f.length},{name:"input_output_strides",type:"u32",length:f.length}]),` + ${k.declareVariables(g,M,$,v,y)} + + ${k.mainStart(Wn)} + let half_rotary_emb_dim = uniforms.${$.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${k.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${M.broadcastedIndicesToOffset("bsnh.xy",it("",M.type.tensor,2))}; + let position_id = + u32(${M.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${t}); + let j = i + select(half_rotary_emb_dim, 1, ${t}); + let re = ${g.getByOffset("i")} * ${$.get("position_id","bsnh[3]")} - + ${g.getByOffset("j")} * ${v.get("position_id","bsnh[3]")}; + ${y.setByOffset("i","re")} + let im = ${g.getByOffset("i")} * ${v.get("position_id","bsnh[3]")} + + ${g.getByOffset("j")} * ${$.get("position_id","bsnh[3]")}; + ${y.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${y.setByOffset("k",g.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Nt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:b,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ye.size(u)/Wn)},programUniforms:_})}},G_=(e,r)=>{W_(e.inputs,r),e.compute(wi(e.inputs,r))}}),H_,q_,zl,Q_,X_,Px=Ve(()=>{cr(),gt(),pl(),L_(),U_(),Hs(),K_(),Pt(),H_=(e,r)=>{if(r.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let t=e[0],s=e[1],o=e[2],n=e[3],i=e[4];if(r.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(r.localWindowSize!==-1)throw new Error("Local attention is not supported");if(r.softcap!==0)throw new Error("Softcap is not supported");if(r.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(r.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let a=!1,l=t.dims[0],c=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],d=c,u=0,f=!s||s.dims.length===0,_=Math.floor(f?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);f&&(p=_*r.numHeads);let b=n&&n.dims.length!==0,k=i&&i.dims.length!==0;if(b&&n.dims.length===4&&n.dims[0]===l&&n.dims[1]!==r.kvNumHeads&&n.dims[2]===r.kvNumHeads&&n.dims[3]===_)throw new Error("BSNH pastKey/pastValue is not supported");if(b&&k){if(n.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');u=n.dims[2]}else if(b||k)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let g=1;if(s&&s.dims.length>0){if(t.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(t.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(t.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');d=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==_)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.');d=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=s.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');g=3}let M=0,$=!1,v=r.kvNumHeads?_*r.kvNumHeads:p;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.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(d!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');v=o.dims[2]}else{if(d!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');v=o.dims[1]*o.dims[3],$=!0}}let y=e.length>4?e[5]:void 0;if(y&&y.dims.length!==1&&y.dims[0]!==l)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:l,sequenceLength:c,pastSequenceLength:u,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:v,headSize:_,vHeadSize:Math.floor(v/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:M,scale:r.scale,broadcastResPosBias:!1,passPastInKv:$,qkvFormat:g}},q_=Nt({perm:[0,2,1,3]}),zl=(e,r,t)=>{let s=r,o=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,o,t.headSize]),s=e.compute(os(s,q_.perm),{inputs:[s],outputs:[-1]})[0]),s},Q_=(e,r,t,s)=>{let o=7,n=["type","type"],i=[e*r],a=e*r,l=[{type:12,data:a},{type:12,data:r},{type:12,data:e}],c=p=>{let d=$e("seq_lens",t.dataType,t.dims),u=$e("total_seq_lens",s.dataType,s.dims),f=it("pos_ids",o,i),_=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` + ${p.registerUniforms(_).declareVariables(d,u,f)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let total_sequence_length = u32(${u.getByOffset("0")}); + let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length; + let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length; + let batch_idx = global_idx / uniforms.sequence_length; + let sequence_idx = i32(global_idx % uniforms.sequence_length); + var pos_id: i32 = 0; + let seqlen = ${d.getByOffset("batch_idx")}; + let total_seqlen = seqlen + 1; + if (is_first_prompt) { + if (sequence_idx < total_seqlen) { + pos_id = sequence_idx; + } else { + pos_id = 1; + } + ${f.setByOffset("global_idx","pos_id")} + } else if (is_subsequent_prompt) { + let past_seqlen = total_seqlen - i32(uniforms.sequence_length); + if (past_seqlen + sequence_idx < total_seqlen) { + pos_id = past_seqlen + sequence_idx; + } else { + pos_id = 1; + } + ${f.setByOffset("global_idx","pos_id")} + } else if (global_idx < uniforms.batch_size) { + ${f.setByOffset("global_idx","seqlen")} + }; + } + `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${r}`,inputDependencies:n},getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:c}},X_=(e,r)=>{var v;let t=H_(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((v=e.inputs[1])==null?void 0:v.dims.length)===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,n=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,i=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,c=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,d=Nt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[u,f,_]=!o&&!n?e.compute(Ll([s],d),{inputs:[s],outputs:[-1,-1,-1]}):[s,o,n],b,k;if(r.doRotary){let y=e.compute(Q_(t.batchSize,t.sequenceLength,l,c),{inputs:[l,c],outputs:[-1]})[0],T=e.inputs[7],x=e.inputs[8],P=Nt({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),O=[u,y,T,x],L=[-1];b=e.compute(wi(O,P),{inputs:O,outputs:L})[0],O.splice(0,1,f);let G=Nt({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});k=e.compute(wi(O,G),{inputs:O,outputs:L})[0]}let g=yo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?b:u,void 0,0),M=zl(e,r.doRotary?k:f,t),$=zl(e,_,t);fo(e,g,M,$,void 0,void 0,i,a,void 0,t,l,c)}}),Bl,J_,Y_,Z_,Cx=Ve(()=>{gt(),Et(),Hs(),Pt(),Bl=(e,r,t,s,o,n,i,a)=>{let l=or(n),c=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,d=o*i,u=64;d===1&&(u=256);let f=[o,i,n/l],_=[o,i,2],b=["rank","type","type"],k=[];k.push(...ct(f,_));let g=M=>{let $=$e("x",r.dataType,3,l),v=$e("scale",t.dataType,t.dims),y=$e("bias",s.dataType,s.dims),T=it("output",1,3,2),x=[$,v,y,T];return` + var workgroup_shared : array<${p}, ${u}>; + const workgroup_size = ${u}u; + ${M.declareVariables(...x)} + ${M.mainStart(u)} + let batch = workgroup_index / uniforms.x_shape[1]; + let channel = workgroup_index % uniforms.x_shape[1]; + let hight = uniforms.x_shape[2]; + // initialize workgroup memory + var sum = ${c}(0); + var squared_sum = ${c}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${c}(${$.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${p}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${Ks("workgroup_shared[0][0]",l)} / f32(hight * ${l}); + let squared_sum_final = ${Ks("workgroup_shared[0][1]",l)} / f32(hight * ${l}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${a})); + let channel_scale = inv_std_dev * f32(scale[channel]); + let channel_shift = f32(bias[channel]) - sum_final * channel_scale; + output[workgroup_index] = vec2f(channel_scale, channel_shift); + } + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${a};${u}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:_,dataType:1}],dispatchGroup:{x:d},programUniforms:k}),getShaderSource:g},{inputs:[r,t,s],outputs:[-1]})[0]},J_=(e,r,t)=>{let s=r[0].dims,o=s,n=2,i=s[0],a=s[1],l=ye.sizeFromDimension(s,n),c=or(l),p=ye.size(o)/c,d=Bl(e,r[0],r[1],r[2],i,l,a,t.epsilon),u=[i,a,l/c],f=[i,a],_=["type","none"],b=k=>{let g=$e("x",r[0].dataType,u.length,c),M=$e("scale_shift",1,f.length,2),$=it("output",r[0].dataType,u.length,c),v=[g,M,$];return` + ${k.registerUniform("output_size","u32").declareVariables(...v)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${$.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${M.getByIndices("vec2(batch, channel)")}; + let value = ${g.getByOffset("global_idx")} * ${$.type.value}(scale_shift.x) + ${$.type.value}(scale_shift.y); + ${$.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${c}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...ct(u,f,u)]}),getShaderSource:b},{inputs:[r[0],d]})},Y_=(e,r,t)=>{let s=r[0].dims,o=s,n=s[0],i=s[s.length-1],a=ye.sizeFromDimension(s,1)/i,l=or(i),c=ye.size(o)/l,p=[{type:12,data:a},{type:12,data:Math.floor(i/l)}],d=["type","type"],u=!1,f=[0,s.length-1];for(let g=0;gs[f[M]])),b=Bl(e,_,r[1],r[2],n,a,i,t.epsilon),k=g=>{let M=Er(r[0].dataType),$=l===1?"vec2f":`mat${l}x2f`,v=x=>{let P=x===0?"x":"y",O=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${M}(${O}(scale.${P}))`;case 2:return`vec2<${M}>(${O}(scale[0].${P}, scale[1].${P}))`;case 4:return`vec4<${M}>(${O}(scale[0].${P}, scale[1].${P}, scale[2].${P}, scale[3].${P}))`;default:throw new Error(`Not supported compoents ${l}`)}},y=$e("input",r[0].dataType,r[0].dims,l),T=it("output",r[0].dataType,o,l);return` + @group(0) @binding(0) var input : array<${y.type.storage}>; + @group(0) @binding(1) var scale_input : array<${$}>; + @group(0) @binding(2) var output : array<${T.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${g.mainStart()} + let current_image_number = global_idx / (uniforms.C * uniforms.H); + let current_channel_number = global_idx % uniforms.C; + + let scale_offset = current_image_number * uniforms.C + current_channel_number; + let scale = scale_input[scale_offset]; + output[global_idx] = fma(input[global_idx], ${v(0)}, ${v(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:k},{inputs:[r[0],b]})},Z_=(e,r)=>{r.format==="NHWC"?Y_(e,e.inputs,r):J_(e,e.inputs,r)}}),ef,tf,rf,Sx=Ve(()=>{gt(),Et(),Pt(),ef=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},tf=(e,r,t)=>{let s=r.simplified,o=e[0].dims,n=e[1],i=!s&&e[2],a=o,l=ye.normalizeAxis(r.axis,o.length),c=ye.sizeToDimension(o,l),p=ye.sizeFromDimension(o,l),d=ye.size(n.dims),u=i?ye.size(i.dims):0;if(d!==p||i&&u!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. + Size of scale and bias (if provided) must match this. + Got scale size of ${d} and bias size of ${u}`);let f=[];for(let y=0;y1,M=t>2,$=y=>{let T=Er(e[0].dataType),x=[$e("x",e[0].dataType,e[0].dims,_),$e("scale",n.dataType,n.dims,_)];i&&x.push($e("bias",i.dataType,i.dims,_)),x.push(it("output",e[0].dataType,a,_)),g&&x.push(it("mean_data_output",1,f)),M&&x.push(it("inv_std_output",1,f));let P=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${y.registerUniforms(P).declareVariables(...x)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${ol("f32",_)}; + var mean_square_vector = ${ol("f32",_)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Gn(T,_,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Ks("mean_vector",_)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Ks("mean_square_vector",_)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Gn(T,_,"x[j + offset]")}; + let f32scale = ${Gn(T,_,"scale[j]")}; + output[j + offset] = ${x[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${Gn(T,_,"bias[j]")}`:""} + ); + } + + ${g?"mean_data_output[global_idx] = mean":""}; + ${M?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},v=[{dims:a,dataType:e[0].dataType}];return g&&v.push({dims:f,dataType:1}),M&&v.push({dims:f,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${t};${s}`,inputDependencies:b},getRunData:()=>({outputs:v,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:k}),getShaderSource:$}},rf=(e,r)=>{ef(e.inputs),e.compute(tf(e.inputs,r,e.outputCount))}}),sf,nf,$x=Ve(()=>{Et(),bl(),Tl(),sf=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.")},nf=e=>{sf(e.inputs);let r=Un.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],s=e.inputs[0].dims[e.inputs[0].dims.length-1];if(t<8&&s<8)e.compute(Ml(e.inputs,{activation:""},r));else{let o=r[r.length-2],n=ye.size(e.inputs[0].dims.slice(0,-2)),i=ye.size(e.inputs[1].dims.slice(0,-2));if(n!==1&&o===1&&i===1){let a=e.inputs[0].reshape([1,n,s]),l=e.inputs[1].reshape([1,s,t]),c=[1,n,t],p=[a,l];e.compute(mi(p,{activation:""},r,c),{inputs:p})}else e.compute(mi(e.inputs,{activation:""},r))}}}),of,af,lf,cf,uf,kx=Ve(()=>{gt(),Et(),cr(),Pt(),of=(e,r)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=e[0],s=t.dims.length;if(t.dims[s-1]!==r.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((r.k+r.blockSize-1)/r.blockSize),n=r.blockSize/8*r.bits,i=e[1];if(!ye.areEqual(i.dims,[r.n,o,n]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(ye.size(a)!==r.n*o)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,c=r.bits>4?r.n*o:r.n*Math.floor((o+1)/2);if(ye.size(l)!==c)throw new Error("zeroPoints input size error.")}},af=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=ye.size(a),c=e[1].dims[2]/4,p=e[0].dataType,d=or(r.k),u=or(c),f=or(i),_=a.concat([o,i]),b=o>1&&i/f%2===0?2:1,k=ye.size(_)/f/b,g=64,M=[],$=[l,o,n/d],v=ye.convertShape(e[1].dims).slice();v.splice(-1,1,c/u),M.push(...ct($)),M.push(...ct(v)),M.push(...ct(e[2].dims)),e.length===4&&M.push(...ct(ye.convertShape(e[3].dims)));let y=[l,o,i/f];M.push(...ct(y));let T=x=>{let P=$.length,O=$e("a",e[0].dataType,P,d),L=$e("b",12,v.length,u),G=$e("scales",e[2].dataType,e[2].dims.length),K=[O,L,G],R=e.length===4?$e("zero_points",12,e[3].dims.length):void 0;R&&K.push(R);let te=y.length,H=it("output",e[0].dataType,te,f),ee=Er(e[0].dataType),Z=(()=>{switch(d){case 1:return`array<${ee}, 8>`;case 2:return`mat4x2<${ee}>`;case 4:return`mat2x4<${ee}>`;default:throw new Error(`${d}-component is not supported.`)}})(),ne=()=>{let j=` + // reuse a data + var input_offset = ${O.indicesToOffset(`${O.type.indices}(batch, row, word_offset)`)}; + var a_data: ${Z}; + for (var j: u32 = 0; j < ${8/d}; j++) { + a_data[j] = ${O.getByOffset("input_offset")}; + input_offset++; + } + `;for(let F=0;F> 4) & b_mask); + b_quantized_values = ${Z}(${Array.from({length:4},(U,se)=>`${ee}(b_value_lower[${se}]), ${ee}(b_value_upper[${se}])`).join(", ")}); + b_dequantized_values = ${d===1?`${Z}(${Array.from({length:8},(U,se)=>`(b_quantized_values[${se}] - ${R?`zero_point${F}`:"zero_point"}) * scale${F}`).join(", ")});`:`(b_quantized_values - ${Z}(${Array(8).fill(`${R?`zero_point${F}`:"zero_point"}`).join(",")})) * scale${F};`}; + workgroup_shared[local_id.x * ${b} + ${Math.floor(F/f)}]${f>1?`[${F%f}]`:""} += ${Array.from({length:8/d},(U,se)=>`${d===1?`a_data[${se}] * b_dequantized_values[${se}]`:`dot(a_data[${se}], b_dequantized_values[${se}])`}`).join(" + ")}; + `;return j},me=()=>{let j=` + var col_index = col * ${f}; + ${R?` + let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; + var zero_point_byte_count: u32; + var zero_point_word_index: u32; + var zero_point_byte_offset: u32; + let zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32; + var zero_point_word: u32;`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${ee}(8);`} + `;for(let F=0;F> 0x1u); + zero_point_word_index = zero_point_byte_count >> 0x2u; + zero_point_byte_offset = zero_point_byte_count & 0x3u; + zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + zero_point_word = ${R.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${F} = ${ee}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return j},ue=()=>{let j=`col_index = col * ${f};`;for(let F=0;F; + var b_value_upper: vec4; + var b_quantized_values: ${Z}; + var b_dequantized_values: ${Z};`,j};return` + var workgroup_shared: array<${H.type.value}, ${b*g}>; + ${x.declareVariables(...K,H)} + ${x.mainStart([g,1,1])} + let output_indices = ${H.offsetToIndices(`(global_idx / ${g}) * ${b}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let nBlocksPerCol = uniforms.b_shape[1]; + + for (var block = local_id.x; block < nBlocksPerCol; block += ${g}) { + //process one block + var word_offset: u32 = block * ${r.blockSize/d}; + ${me()} + for (var word: u32 = 0; word < ${c}; word += ${u}) { + ${ue()} + for (var i: u32 = 0; i < ${u}; i++) { + ${ne()} + word_offset += ${8/d}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${b}) { + var output_value: ${H.type.value} = ${H.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${g}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${b}; + } + ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${d};${u};${f};${b};${g}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:k},programUniforms:M}),getShaderSource:T}},lf=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=ye.size(a),c=e[1].dims[2]/4,p=e[0].dataType,d=or(r.k),u=or(c),f=a.concat([o,i]),_=128,b=i%8===0?8:i%4===0?4:1,k=_/b,g=k*u*8,M=g/d,$=g/r.blockSize,v=ye.size(f)/b,y=[],T=[l,o,n/d],x=ye.convertShape(e[1].dims).slice();x.splice(-1,1,c/u),y.push(...ct(T)),y.push(...ct(x)),y.push(...ct(e[2].dims)),e.length===4&&y.push(...ct(ye.convertShape(e[3].dims)));let P=[l,o,i];y.push(...ct(P));let O=L=>{let G=T.length,K=$e("a",e[0].dataType,G,d),R=$e("b",12,x.length,u),te=$e("scales",e[2].dataType,e[2].dims.length),H=[K,R,te],ee=e.length===4?$e("zero_points",12,e[3].dims.length):void 0;ee&&H.push(ee);let Z=P.length,ne=it("output",e[0].dataType,Z),me=Er(e[0].dataType),ue=()=>{switch(d){case 1:return` + let a_data0 = vec4<${me}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${me}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` + let a_data0 = vec4<${me}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${me}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` + let a_data0 = sub_a[word_offset]; + let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${d}-component is not supported.`)}};return` + var sub_a: array<${K.type.value}, ${M}>; + var inter_results: array, ${b}>; + ${L.declareVariables(...H,ne)} + ${L.mainStart([k,b,1])} + let output_indices = ${ne.offsetToIndices(`workgroup_index * ${b}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let n_blocks_per_col = uniforms.b_shape[1]; + let num_tiles = (n_blocks_per_col - 1) / ${$} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${M}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${M}; a_offset += ${_}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${K.getByIndices(`${K.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${K.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${$} + local_id.x; + ${ee?` + let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; + let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); + let zero_point_word_index = zero_point_byte_count >> 0x2u; + let zero_point_byte_offset = zero_point_byte_count & 0x3u; + let zero_point_nibble_offset: u32 = block & 0x1u; + let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + let zero_point_word = ${ee.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${me}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${me}(8);`} + let scale = ${te.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${R.getByIndices(`${R.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${r.blockSize/d}; + for (var i: u32 = 0; i < ${u}; i++) { + ${ue()} + let b_value = ${u===1?"b_data":"b_data[i]"}; + let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); + let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); + let b_quantized_values = mat2x4<${me}>(${Array.from({length:4},(j,F)=>`${me}(b_value_lower[${F}]), ${me}(b_value_upper[${F}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${me}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(j,F)=>`${`dot(a_data${F}, b_dequantized_values[${F}])`}`).join(" + ")}; + word_offset += ${8/d}; + } + workgroupBarrier(); + } + + if (local_idx < ${b}) { + var output_value: ${ne.type.value} = ${ne.type.value}(0); + for (var b = 0u; b < ${k}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${ne.setByIndices(`${ne.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${d};${u};${k};${b}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:v},programUniforms:y}),getShaderSource:O}},cf=(e,r)=>{of(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(lf(e.inputs,r)):e.compute(af(e.inputs,r))},uf=e=>Nt(e)}),df,pf,hf,mf,_f,ff,gf,wf,Mf,Ix=Ve(()=>{gt(),Et(),Pt(),df=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].")}},pf=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${lt("uniforms.pads",o,t)}; + if (k < 0) { + break; + } + if (k >= i32(${lt("uniforms.x_shape",o,r)})) { + break; + } + offset += k * i32(${lt("uniforms.x_strides",o,r)}); + `;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]; + } + `},hf=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${lt("uniforms.pads",o,t)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${lt("uniforms.x_shape",o,r)}) - 1); + k = k % _2n_1; + if(k >= i32(${lt("uniforms.x_shape",o,r)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${lt("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},mf=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${lt("uniforms.pads",o,t)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${lt("uniforms.x_shape",o,r)})) { + k = i32(${lt("uniforms.x_shape",o,r)}) - 1; + } + offset += k * i32(${lt("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},_f=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${lt("uniforms.pads",o,t)}; + if (k < 0) { + k += i32(${lt("uniforms.x_shape",o,r)}]); + } + if (k >= i32(${lt("uniforms.x_shape",o,r)})) { + k -= i32(${lt("uniforms.x_shape",o,r)}); + } + offset += k * i32(${lt("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},ff=(e,r,t)=>{switch(t.mode){case 0:return pf(e,r,t.pads.length);case 1:return hf(e,r,t.pads.length);case 2:return mf(e,r,t.pads.length);case 3:return _f(e,r,t.pads.length);default:throw new Error("Invalid mode")}},gf=(e,r)=>{let t=ye.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,o=ye.size(t),n=[{type:12,data:o},{type:6,data:r.pads}],i=e.length>=3&&e[2].data;r.mode===0&&n.push({type:i?e[2].dataType:1,data:r.value}),n.push(...ct(e[0].dims,t));let a=["rank"],l=c=>{let p=it("output",e[0].dataType,t.length),d=$e("x",e[0].dataType,s.length),u=d.type.value,f=ff(p,s.length,r),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&_.push({name:"constant_value",type:i?u:"f32"}),` + ${c.registerUniforms(_).declareVariables(d,p)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${p.offsetToIndices("global_idx")}; + + var value = ${u}(0); + ${f} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${i}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ye.size(t)/64)},programUniforms:n}),getShaderSource:l}},wf=(e,r)=>{if(e.length>1){let t=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,n=new Int32Array(2*o).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;ln[Number(l)]=Number(a));let i=[];return n.forEach(a=>i.push(a)),{mode:r.mode,value:s,pads:i}}else return r},Mf=(e,r)=>{df(e.inputs);let t=wf(e.inputs,r);e.compute(gf(e.inputs,t),{inputs:[0]})}}),vo,Rl,jl,Nl,Vl,bf,yf,Ul,Wl,vf,xf,Gl,Tf,Ef,Kl,Pf,Cf,Sf,$f,Ax=Ve(()=>{gs(),gt(),Et(),Pt(),vo=e=>{if(Yt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Rl=(e,r,t)=>{let s=r.format==="NHWC",o=e.dims.slice();s&&o.splice(1,0,o.pop());let n=Object.hasOwnProperty.call(r,"dilations"),i=r.kernelShape.slice(),a=r.strides.slice(),l=n?r.dilations.slice():[],c=r.pads.slice();ii.adjustPoolAttributes(t,o,i,a,l,c);let p=ii.computePoolOutputShape(t,o,a,l,i,c,r.autoPad),d=Object.assign({},r);n?Object.assign(d,{kernelShape:i,strides:a,pads:c,dilations:l,cacheKey:r.cacheKey}):Object.assign(d,{kernelShape:i,strides:a,pads:c,cacheKey:r.cacheKey});let u=p.slice();return u.push(u.splice(1,1)[0]),[d,s?u:p]},jl=(e,r)=>{let t=r.format==="NHWC",s=ye.size(e),o=ye.size(r.kernelShape),n=[{type:12,data:s},{type:12,data:o}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let a=r.kernelShape[r.kernelShape.length-1],l=r.strides[r.strides.length-1],c=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],d=!!(c+p);n.push({type:12,data:a},{type:12,data:l},{type:12,data:c},{type:12,data:p}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(r.kernelShape.length===2){let f=r.kernelShape[r.kernelShape.length-2],_=r.strides[r.strides.length-2],b=r.pads[r.pads.length/2-2],k=r.pads[r.pads.length-2];u=!!(b+k),n.push({type:12,data:f},{type:12,data:_},{type:12,data:b},{type:12,data:k}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,i,!0,d,u]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=ye.computeStrides(r.kernelShape);n.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),i.push({name:"kernelStrides",type:"u32",length:a.length},{name:"pads",type:"u32",length:r.pads.length},{name:"strides",type:"u32",length:r.strides.length});let l=r.pads.reduce((c,p)=>c+p);return[n,i,!!l,!1,!1]}},Nl=(e,r,t,s,o,n,i,a,l,c,p,d)=>{let u=o.format==="NHWC",f=r.type.value,_=it("output",r.type.tensor,s);if(o.kernelShape.length<=2){let b="",k="",g="",M=t-(u?2:1);if(p?b=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${M}] = indices[${M}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${M}] < 0 || xIndices[${M}] + >= uniforms.x_shape[${M}]) { + pad++; + continue; + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:b=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${M}] = indices[${M}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`,o.kernelShape.length===2){let $=t-(u?3:2);d?k=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${$}] = indices[${$}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${$}] < 0 || xIndices[${$}] >= uniforms.x_shape[${$}]) { + pad += i32(uniforms.kw); + continue; + } + `:k=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${$}] = indices[${$}] * uniforms.sh - uniforms.phStart + j; + `,g=` + } + `}return` + ${e.registerUniforms(l).declareVariables(r,_)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${_.offsetToIndices("global_idx")}; + var xIndices = ${_.offsetToIndices("global_idx")}; + + var value = ${f}(${a}); + var pad = 0; + ${k} + ${b} + ${g} + ${i} + + output[global_idx] = value; + }`}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let b=o.kernelShape.length,k=o.pads.length,g="";return c?g=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:g=` + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + `,` + ${e.registerUniforms(l).declareVariables(r,_)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${_.offsetToIndices("global_idx")}; + var xIndices = ${_.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${f}(${a}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${b-1}u; j++) { + offsets[j] = offset / ${lt("uniforms.kernelStrides","j",b)}; + offset -= offsets[j] * ${lt("uniforms.kernelStrides","j",b)}; + } + offsets[${b-1}] = offset; + + isPad = false; + for (var j = ${t-b}u; j < ${t}u; j++) { + xIndices[j] = indices[j] * ${lt("uniforms.strides",`j - ${t-b}u`,b)} + + offsets[j - ${t-b}u] - ${lt("uniforms.pads","j - 2u",k)}; + ${g} + } + ${i} + + output[global_idx] = value; + }`}},Vl=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,bf=e=>`${Vl(e)};${e.countIncludePad}`,yf=e=>`${Vl(e)};${e.storageOrder};${e.dilations}`,Ul=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}),Wl=(e,r,t,s)=>{let[o,n]=Rl(r,s,t),i=$e("x",r.dataType,r.dims.length),a=i.type.value,l="value += x_val;",c="";o.countIncludePad?c+=`value /= ${a}(uniforms.kernelSize);`:c+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,d,u,f,_]=jl(n,o);p.push(...ct(r.dims,n));let b=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${u};${f};${_}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(ye.size(n)/64)},programUniforms:p}),getShaderSource:k=>Nl(k,i,r.dims.length,n.length,o,l,c,0,d,u,f,_)}},vf=e=>{let r=e.count_include_pad!==0,t=Ul(e);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:r,...t,cacheKey:""};return{...s,cacheKey:bf(s)}},xf=(e,r)=>{vo(e.inputs),e.compute(Wl("AveragePool",e.inputs[0],!1,r))},Gl={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Tf=e=>{let r=e.format;return{format:r,...Gl,cacheKey:r}},Ef=(e,r)=>{vo(e.inputs),e.compute(Wl("GlobalAveragePool",e.inputs[0],!0,r))},Kl=(e,r,t,s)=>{let[o,n]=Rl(r,s,t),i=` + value = max(x_val, value); + `,a="",l=$e("x",r.dataType,r.dims.length),c=["rank"],[p,d,u,f,_]=jl(n,o);return p.push(...ct(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${u};${f};${_}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(ye.size(n)/64)},programUniforms:p}),getShaderSource:b=>Nl(b,l,r.dims.length,n.length,o,i,a,r.dataType===10?-65504:-1e5,d,u,f,_)}},Pf=(e,r)=>{vo(e.inputs),e.compute(Kl("MaxPool",e.inputs[0],!1,r))},Cf=e=>{let r=e.storage_order,t=e.dilations,s=Ul(e);if(r!==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:r,dilations:t,...s,cacheKey:""};return{...o,cacheKey:yf(o)}},Sf=e=>{let r=e.format;return{format:r,...Gl,cacheKey:r}},$f=(e,r)=>{vo(e.inputs),e.compute(Kl("GlobalMaxPool",e.inputs[0],!0,r))}}),kf,If,Af,Ff,Fx=Ve(()=>{gt(),Et(),cr(),Pt(),kf=(e,r)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((t,s)=>t===e[2].dims[s]).reduce((t,s)=>t&&s,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(r.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,n)=>n===r.axis||o===e[0].dims[n]).reduce((o,n)=>o&&n,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let t=e[0].dims[r.axis],s=e[1].dims[r.axis];if(r.blockSizeMath.ceil(t/(s-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},If=(e,r)=>{let t=ye.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,o=s===3,n=e[0].dims,i=e[1].dataType,a=ye.size(n),l=s===3||s===2,c=l?[Math.ceil(ye.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,d=e.length>2?e[2]:void 0,u=d?l?[Math.ceil(ye.size(d.dims)/4)]:d.dims:void 0,f=p.length===0||p.length===1&&p[0]===1,_=f===!1&&p.length===1,b=or(a),k=f&&(!l||b===4),g=k?b:1,M=k&&!l?b:1,$=$e("input",l?12:s,c.length,M),v=$e("scale",i,p.length),y=d?$e("zero_point",l?12:s,u.length):void 0,T=it("output",i,n.length,g),x=[$,v];y&&x.push(y);let P=[c,p];d&&P.push(u);let O=[{type:12,data:a/g},{type:12,data:t},{type:12,data:r.blockSize},...ct(...P,n)],L=G=>{let K=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${G.registerUniforms(K).declareVariables(...x,T)} + ${G.mainStart()} + ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${T.offsetToIndices("global_idx")}; + + // Set input x + ${l?` + let input = ${$.getByOffset("global_idx / 4")}; + let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${g===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${$.getByOffset("global_idx")};`}; + + // Set scale input + ${f?`let scale_value= ${v.getByOffset("0")}`:_?` + let scale_index = ${T.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${v.getByOffset("scale_index")};`:` + var scale_indices: ${v.type.indices} = output_indices; + let index = ${v.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${v.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${v.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${y?f?l?` + let zero_point_input = ${y.getByOffset("0")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${y.getByOffset("0")}`:_?l?` + let zero_point_index = ${T.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${y.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${T.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${y.getByOffset("zero_point_index")};`:l?` + let zero_point_offset = ${v.indicesToOffset("scale_indices")}; + let zero_point_input = ${y.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${y.getByIndices("scale_indices")};`:`let zero_point_value = ${l?o?"i32":"u32":$.type.value}(0);`}; + // Compute and write output + ${T.setByOffset("global_idx",`${T.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getShaderSource:L,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(a/g/64),y:1,z:1},programUniforms:O})}},Af=(e,r)=>{kf(e.inputs,r),e.compute(If(e.inputs,r))},Ff=e=>Nt({axis:e.axis,blockSize:e.blockSize})}),Of,Df,Lf,Ox=Ve(()=>{gs(),gt(),Pt(),Of=(e,r,t)=>{let s=e===r,o=er&&t>0;if(s||o||n)throw new Error("Range these inputs' contents are invalid.")},Df=(e,r,t,s)=>{let o=Math.abs(Math.ceil((r-e)/t)),n=[o],i=o,a=[{type:12,data:i},{type:s,data:e},{type:s,data:t},...ct(n)],l=c=>{let p=it("output",s,n.length),d=p.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:d},{name:"delta",type:d}];return` + ${c.registerUniforms(u).declareVariables(p)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${d}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:a})}},Lf=e=>{let r=0,t=0,s=0;e.inputs[0].dataType===6?(r=e.inputs[0].getInt32Array()[0],t=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(r=e.inputs[0].getFloat32Array()[0],t=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),Yt.webgpu.validateInputContent&&Of(r,t,s),e.compute(Df(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),zf,Hl,ql,Bf,Rf,jf,Dx=Ve(()=>{gt(),Et(),cr(),Pt(),zf=(e,r,t,s)=>{if(e!=="none"&&s!=="i32"&&s!=="u32"&&s!=="f32")throw new Error(`Input ${s} is not supported with reduction ${e}.`);let o=`{ + var oldValue = 0; + loop { + let newValueF32 =`,n=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${r}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${r}=${t};`;case"add":return s==="i32"||s==="u32"?`atomicAdd(&${r}, bitcast<${s}>(${t}));`:` + ${o}bitcast<${s}>(oldValue) + (${t})${n}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` + ${o}max(bitcast(oldValue), (${t}))${n}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${o}min(bitcast<${s}>(oldValue), (${t}))${n}`;case"mul":return`${o}(bitcast<${s}>(oldValue) * (${t}))${n}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Hl=(e,r)=>`${e===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[${r?"i - indices_start":"i"}]; + let dim_value = uniforms.output_shape[${r?"i - indices_start":"i"} + uniforms.last_index_dimension];`} + + if (index >= 0) { + if (index >= i32(dim_value)) { + index = i32(dim_value - 1); + } + } else { + if (index < -i32(dim_value)) { + index = 0; + } else { + index += i32(dim_value); + } + } + data_offset += u32((u32(index) * element_count_dim));`,ql=(e,r,t)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * ${t?"global_idx":"idx"} + i]; + ${zf(e.reduction,"output[data_offset + i]","value",r)} + }`,Bf=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t,n=1,i=Math.ceil(ye.size(s)/n),a=s[s.length-1],l=ye.sizeFromDimension(t,a),c=ye.sizeFromDimension(s,0)/a,p=[{type:12,data:i},{type:12,data:a},{type:12,data:l},...ct(e[1].dims,e[2].dims,o)],d=u=>{let f=$e("indices",e[1].dataType,e[1].dims.length),_=$e("updates",e[2].dataType,e[2].dims.length,n),b=r.reduction!=="none"&&r.reduction!==""?Gd("output",e[0].dataType,o.length):it("output",e[0].dataType,o.length,n);return` + ${u.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(f,_,b)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var hasDuplicates = false; + if (${r.reduction==="none"}) { + for (var i = 0; i < ${c}; i = i + 1) { + for (var j = i + 1; j < ${c}; j = j + 1) { + var index_i = i32(indices[i].x); + var index_j = i32(indices[j].x); + if (index_i == index_j) { + hasDuplicates = true; + break; + } + } + if (hasDuplicates) { + break; + } + } + } + + if (${r.reduction==="none"} && hasDuplicates) { + if (global_idx != 0u) { + return; + } + // Process each index-update pair individually when duplicates exist + for (var idx = 0u; idx < ${c}u; idx++) { + var data_offset = 0u; + for (var i = 0u; i < uniforms.last_index_dimension; i++) { + var index = i32(indices[idx * uniforms.last_index_dimension + i].x); + ${Hl(t.length,!1)} + } + ${ql(r,b.type.value,!1)} + } + return; + } + + var data_offset = 0u; + var indices_start = uniforms.last_index_dimension * global_idx; + var indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${Hl(t.length,!0)} + } + ${ql(r,b.type.value,!0)} + }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:d}},Rf=e=>Nt({reduction:e.reduction}),jf=(e,r)=>{e.compute(Bf(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Nf,Vf,Uf,Ql,Wf,Gf,Kf,Hf,qf,Qf,Xf,Jf,Xl,Yf,Zf,eg,tg,rg,sg,ng,Lx=Ve(()=>{gt(),Et(),cr(),Pt(),Nf=(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 + 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")}},Vf=(e,r,t)=>{r.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(t).fill(1);return r.forEach((o,n)=>s[o]=e[n]),s},Uf=(e,r,t,s,o,n)=>{let[i,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(p=>n.push(p));else if(r.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(a>0&&e.length>a&&e[a].dims.length===1&&e[a].dims[0]>0){if(e[a].getFloat32Array().forEach(p=>s.push(p)),s.length!==0&&s.length!==c&&t>=18&&s.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");Nf(s,r),r.axes.length>0&&Vf(s,r.axes,c).forEach((p,d)=>s[d]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>o.push(Number(p))),o.length!==0&&o.length!==c&&t>=18&&o.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(s.length!==0&&s.length!==r.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.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 s<"u"&&typeof o<"u"&&s.length>0&&o.length>c)throw new Error("Resize requires only of scales or sizes to be specified")},Ql=(e,r,t,s)=>` + // 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 big = (${e}) * (${r}); + let whole = ${s}(big / (${t})); + let fract = ${s}(big % (${t})) / ${s}(${t}); + return whole + fract; +`,Wf=(e,r)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${r} { `+(()=>{switch(e){case"asymmetric":return` + if (xScale < 1.0 || floor(xScale) != xScale) { + return ${r}(xResized) / ${r}(xScale); + } else { + ${Ql("xResized","lengthOriginal","lengthResized",r)} + } + `;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${r}(xResized) + 0.5) / ${r}(xScale);`;case"align_corners":return`if (lengthResized == 1) { + return 0.0; + } else { + ${Ql("xResized","lengthOriginal - 1","lengthResized - 1",r)} + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${r}(roiStart) * ${r}(lengthOriginal - 1) + + (${r}(xResized) * ${r}(roiEnd - roiStart) * ${r}(lengthOriginal - 1)) / + ${r}(lengthResized - 1); + } else { + return 0.5 * ${r}(roiStart + roiEnd) * ${r}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${r}xScale * ${r}(lengthResized); + const adjustment = ${r}(lengthResized) / outputWidth; + const center = ${r}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + 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`)}})()+"}",Gf=(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`)}})()+"}",Kf=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),o=e.length===0?s:e.slice();return r.length>0?(r.forEach((n,i)=>{s[n]=o[i],s[i+t]=o[r.length+i]}),s):o},Hf=(e,r,t,s)=>{let o=[];if(t.length>0)if(s.length>0){if(e.forEach(n=>o.push(n)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((n,i)=>o[n]=t[i])}else t.forEach(n=>o.push(n));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((n,i)=>Math.round(n*r[i]))}return o},qf=(e,r,t)=>{let s=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(n=>r[n]),Number.MAX_VALUE):Math.min(...r,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(n=>r[n]),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 o=e.slice();return t.axes.length>0?(t.axes.forEach(n=>r[n]=s),t.axes.forEach(n=>o[n]=Math.round(e[n]*r[n]))):(r.fill(s,0,r.length),o.forEach((n,i)=>o[i]=Math.round(n*r[i]))),o},Qf=(e,r,t,s,o)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${t.length}> { + var original_indices: array<${e.type.value}, ${t.length}>; + for (var i:u32 = 0; i < ${t.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${lt("uniforms.scales","i",s)}; + var roi_low = ${lt("uniforms.roi","i",o)}; + var roi_hi = ${lt("uniforms.roi",`i + ${r.length}`,o)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${lt("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${lt("uniforms.output_shape","i",t.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,Xf=(e,r,t,s,o,n,i)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${r.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${lt("uniforms.scales","i",o)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${lt("uniforms.roi","i",n)}; + var roi_hi = ${lt("uniforms.roi",`i + ${t.length}`,n)}; + var input_shape_i = ${lt("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${lt("uniforms.output_shape","i",s.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${i} || (original_idx >= 0 && original_idx < ${r.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${r.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; + }`,Jf=(e,r)=>` + fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { + for (var i:u32 = 0; i < ${r.length}; i++) { + var input_index = ${e.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${lt("uniforms.input_shape","i",r.length)}) { + return false; + } + } + return true; + }`,Xl=(e,r,t,s)=>e.rank>s?` + ${e.indicesSet("input_indices",r,"channel")}; + ${e.indicesSet("input_indices",t,"batch")}; +`:"",Yf=(e,r,t,s,o)=>{let[n,i,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],c=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${c} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(row, ${t[i]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; + ${Xl(e,l,n,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${c} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${c} = originalIndices[${i}]; + var col:${c} = originalIndices[${a}]; + ${s?`if (row < 0 || row > (${t[i]} - 1) || col < 0 || col > (${t[a]} - 1)) { + return ${o}; + }`:""}; + row = max(0, min(row, ${t[i]} - 1)); + col = max(0, min(col, ${t[a]} - 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 = ${t.length>2?`u32(originalIndices[${l}])`:"0"}; + var batch: u32 = ${t.length>2?`u32(originalIndices[${n}])`:"0"}; + var x11: ${c} = getInputValue(batch, channel, row1, col1); + var x12: ${c} = getInputValue(batch, channel, row1, col2); + var x21: ${c} = getInputValue(batch, channel, row2, col1); + var x22: ${c} = getInputValue(batch, channel, row2, col2); + var dx1: ${c} = abs(row - ${c}(row1)); + var dx2: ${c} = abs(${c}(row2) - row); + var dy1: ${c} = abs(col - ${c}(col1)); + var dy2: ${c} = abs(${c}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},Zf=(e,r,t,s,o,n,i,a,l,c)=>{let p=t.length===2,[d,u]=p?[0,1]:[2,3],f=e.type.value,_=b=>{let k=b===d?"row":"col";return` + fn ${k}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${f} { + var output_index = ${r.indicesGet("output_indices",b)}; + var originalIdx: ${f} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[b]}, + ${s[b]}, ${t[b]}, ${n[b]}, ${n[b]} + ${t.length}); + var fractOriginalIdx: ${f} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${a} && (originalIdx < 0 || originalIdx > (${t[b]} - 1))) { + return ${l}; + } + var data: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${k}: ${f} = originalIdx + ${f}(i); + if (${k} < 0 || ${k} >= ${t[b]}) { + ${c?`coefs[i + 1] = 0.0; + continue;`:a?`return ${l};`:`${k} = max(0, min(${k}, ${t[b]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",b,`u32(${k})`)}; + data[i + 1] = ${b===d?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${_(d)}; + ${_(u)}; + fn getCubicInterpolationCoefs(s: ${f}) -> array<${f}, 4> { + var absS = abs(s); + var coeffs: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${f} = 1.0 - absS; + var twoMinusAbsS: ${f} = 2.0 - absS; + var onePlusAbsS: ${f} = 1.0 + absS; + coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; + coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; + coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${f}, 4>, coefs: array<${f}, 4>) -> ${f} { + var coefsSum: ${f} = 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: ${r.type.indices}) -> ${f} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},eg=(e,r,t,s,o)=>{let[n,i,a,l,c]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${p} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(depth, ${t[i]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(height, ${t[a]} - 1))`)}; + ${e.indicesSet("input_indices",l,`max(0, min(width, ${t[l]} - 1))`)}; + ${Xl(e,c,n,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${r.type.indices}) -> ${p} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${p} = originalIndices[${i}]; + var height:${p} = originalIndices[${a}]; + var width:${p} = originalIndices[${l}]; + ${s?`if (depth < 0 || depth > (${t[i]} - 1) || height < 0 || height > (${t[a]} - 1) || width < 0 || (width > ${t[l]} - 1)) { + return ${o}; + }`:""}; + + depth = max(0, min(depth, ${t[i]} - 1)); + height = max(0, min(height, ${t[a]} - 1)); + width = max(0, min(width, ${t[l]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${t.length>3?`u32(originalIndices[${c}])`:"0"}; + var batch: u32 = ${t.length>3?`u32(originalIndices[${n}])`:"0"}; + + var x111: ${p} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${p} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${p} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${p} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${p} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${p} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${p} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${p} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${p} = abs(depth - ${p}(depth1)); + var dx2: ${p} = abs(${p}(depth2) - depth); + var dy1: ${p} = abs(height - ${p}(height1)); + var dy2: ${p} = abs(${p}(height2) - height); + var dz1: ${p} = abs(width - ${p}(width1)); + var dz2: ${p} = abs(${p}(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); + }`},tg=(e,r,t,s,o,n)=>{let i=e.dims,a=Kf(n,r.axes,i.length),l=Hf(i,s,o,r.axes),c=s.slice();s.length===0&&(c=i.map((M,$)=>M===0?1:l[$]/M),r.keepAspectRatioPolicy!=="stretch"&&(l=qf(i,c,r)));let p=it("output",e.dataType,l.length),d=$e("input",e.dataType,i.length),u=ye.size(l),f=i.length===l.length&&i.every((M,$)=>M===l[$]),_=r.coordinateTransformMode==="tf_crop_and_resize",b=r.extrapolationValue,k=d.type.value,g=M=>` + ${f?"":` + ${Wf(r.coordinateTransformMode,k)}; + ${(()=>{switch(r.mode){case"nearest":return` + ${Jf(d,i)}; + ${Gf(r.nearestMode,t,k)}; + ${Xf(d,p,i,l,c.length,a.length,_)}; + `;case"linear":return` + ${Qf(p,i,l,c.length,a.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${Yf(d,p,i,_,b)}`;if(i.length===3||i.length===5)return`${eg(d,p,i,_,b)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(i.length===2||i.length===4)return`${Zf(d,p,i,l,c,a,r.cubicCoeffA,_,r.extrapolationValue,r.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${M.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",a.length).declareVariables(d,p)} + ${M.mainStart()} + ${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${f?"output[global_idx] = input[global_idx];":` + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${d.type.indices}; + ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${d.getByIndices("input_indices")}; + } else { + output[global_idx] = ${r.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${r.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${r.cacheKey}|${t}|${c.length>0?r.mode==="cubic"?c:c.length:""}|${o.length>0?o:""}|${a.length>0?a:""}|${f}|${r.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:1,data:c},{type:1,data:a},...ct(i,l)]})}},rg=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},sg=(e,r)=>{let t=[],s=[],o=[],n=rg(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Uf(e.inputs,r,n,t,s,o),e.compute(tg(e.inputs[0],r,n,t,s,o),{inputs:[0]})},ng=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,o=e.cubicCoeffA,n=e.excludeOutside!==0,i=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return Nt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:o,excludeOutside:n,extrapolationValue:i,keepAspectRatioPolicy:a,mode:l,nearestMode:c})}}),og,ig,ag,zx=Ve(()=>{gt(),Et(),Pt(),og=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let r=e[0],t=e[1],s=e[2];if(r.dataType!==t.dataType||r.dataType!==s.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 o=r.dims[r.dims.length-1],n=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==n)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 i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},ig=(e,r,t,s)=>{let o=r.simplified,n=e[0].dims,i=ye.size(n),a=n,l=i,c=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],d=!o&&e.length>3,u=e.length>4,f=s&&t>1,_=s&&t>2,b=t>3,k=64,g=or(c),M=[{type:12,data:l},{type:12,data:g},{type:12,data:c},{type:1,data:r.epsilon}],$=y=>{let T=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],x=[$e("x",e[0].dataType,e[0].dims,g),$e("skip",e[1].dataType,e[1].dims,g),$e("gamma",e[2].dataType,e[2].dims,g)];d&&x.push($e("beta",e[3].dataType,e[3].dims,g)),u&&x.push($e("bias",e[4].dataType,e[4].dims,g)),x.push(it("output",e[0].dataType,a,g)),f&&x.push(it("mean_output",1,p)),_&&x.push(it("inv_std_output",1,p)),b&&x.push(it("input_skip_bias_sum",e[0].dataType,a,g));let P=Er(e[0].dataType),O=Er(1,g);return` + + ${y.registerUniforms(T).declareVariables(...x)} + var sum_shared : array<${O}, ${k}>; + var sum_squared_shared : array<${O}, ${k}>; + + ${y.mainStart([k,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${k}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${k}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${k-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${u?"bias[offset1d + i]":P+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${b?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Gn(P,g,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${k}; + for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { + reduce_size = curr_size + (reduce_size & 1); + if (ix < curr_size) { + sum_shared[ix] += sum_shared[ix + reduce_size]; + sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; + } + workgroupBarrier(); + } + + let sum = sum_shared[0]; + let square_sum = sum_squared_shared[0]; + let mean = ${Ks("sum",g)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Ks("square_sum",g)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); + ${f?"mean_output[global_idx] = mean;":""} + ${_?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${o?"":`- ${P}(mean)`}) * + ${P}(inv_std_dev) * gamma[offset1d + i] + ${d?"+ beta[offset1d + i]":""}; + } + }`},v=[{dims:a,dataType:e[0].dataType}];return t>1&&v.push({dims:p,dataType:1}),t>2&&v.push({dims:p,dataType:1}),t>3&&v.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${g};${f};${_};${b}`,inputDependencies:e.map((y,T)=>"type")},getShaderSource:$,getRunData:()=>({outputs:v,dispatchGroup:{x:Math.ceil(l/c)},programUniforms:M})}},ag=(e,r)=>{og(e.inputs);let t=[0];e.outputCount>1&&t.push(-3),e.outputCount>2&&t.push(-3),e.outputCount>3&&t.push(3),e.compute(ig(e.inputs,r,e.outputCount,!1),{outputs:t})}}),lg,xo,cg,Jl,ug,dg,pg,hg,Bx=Ve(()=>{gt(),Et(),cr(),Pt(),lg=(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,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`)})},xo=(e,r)=>{let t=[];if(e.length>r)if(e[r].dataType===7)e[r].getBigInt64Array().forEach(s=>t.push(Number(s)));else if(e[r].dataType===6)e[r].getInt32Array().forEach(s=>t.push(Number(s)));else throw new Error(`Input ${r} must be an array of int32 or int64`);return t},cg=(e,r)=>{if(e.length>1){let t=xo(e,1),s=xo(e,2),o=xo(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),Nt({starts:t,ends:s,axes:o})}else return r},Jl=(e,r,t,s,o)=>{let n=e;return e<0&&(n+=t[s[r]]),o[r]<0?Math.max(0,Math.min(n,t[s[r]]-1)):Math.max(0,Math.min(n,t[s[r]]))},ug=(e,r,t)=>`fn calculateInputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${t.length}; i >= 0; i--) { + let input_shape_i = ${lt("uniforms.input_shape","i",t.length)}; + let steps_i = ${lt("uniforms.steps","i",t.length)}; + let signs_i = ${lt("uniforms.signs","i",t.length)}; + let starts_i = ${lt("uniforms.starts","i",t.length)}; + var output_index = ${r.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; + }`,dg=(e,r)=>{let t=e[0].dims,s=ye.size(t),o=r.axes.length>0?ye.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=xo(e,4);n.forEach(g=>g!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(o.length).fill(1));let i=r.starts.map((g,M)=>Jl(g,M,t,o,n)),a=r.ends.map((g,M)=>Jl(g,M,t,o,n));if(o.length!==i.length||o.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==t.length)for(let g=0;gMath.sign(g));n.forEach((g,M,$)=>{if(g<0){let v=(a[M]-i[M])/g,y=i[M],T=y+v*n[M];i[M]=T,a[M]=y,$[M]=-g}});let c=t.slice(0);o.forEach((g,M)=>{c[g]=Math.ceil((a[g]-i[g])/n[g])});let p={dims:c,dataType:e[0].dataType},d=it("output",e[0].dataType,c.length),u=$e("input",e[0].dataType,e[0].dims.length),f=ye.size(c),_=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:n.length}],b=[{type:12,data:f},{type:12,data:i},{type:6,data:l},{type:12,data:n},...ct(e[0].dims,c)],k=g=>` + ${g.registerUniforms(_).declareVariables(u,d)} + ${ug(u,d,t)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${d.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${d.setByOffset("global_idx",u.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:b})}},pg=(e,r)=>{lg(e.inputs,r);let t=cg(e.inputs,r);e.compute(dg(e.inputs,t),{inputs:[0]})},hg=e=>{let r=e.starts,t=e.ends,s=e.axes;return Nt({starts:r,ends:t,axes:s})}}),mg,_g,fg,gg,Rx=Ve(()=>{gt(),Et(),cr(),Hs(),Pt(),mg=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},_g=(e,r)=>{let t=e.inputs[0],s=t.dims,o=ye.size(s),n=s.length,i=ye.normalizeAxis(r.axis,n),a=iP),c[i]=n-1,c[n-1]=i,l=e.compute(os(t,c),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,d=p[n-1],u=o/d,f=or(d),_=d/f,b=64;u===1&&(b=256);let k=(x,P)=>P===4?`max(max(${x}.x, ${x}.y), max(${x}.z, ${x}.w))`:P===2?`max(${x}.x, ${x}.y)`:P===3?`max(max(${x}.x, ${x}.y), ${x}.z)`:x,g=$e("x",l.dataType,l.dims,f),M=it("result",l.dataType,l.dims,f),$=g.type.value,v=Er(l.dataType)==="f32"?`var threadMax = ${$}(-3.402823e+38f);`:`var threadMax = ${$}(-65504.0h);`,y=x=>` + var rowMaxShared : ${$}; + var rowSumShared : ${$}; + var threadShared : array<${$}, ${b}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${$} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${$}) { + let index = row * row_stride + col; + result[index] = value; + } + ${x.registerUniform("packedCols","i32").declareVariables(g,M)} + ${x.mainStart(b)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${b}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${v} + 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 = ${$}(${k("threadShared[0]",f)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${$}(0.0); + for (var col = lindex; col < cols; col += wg) { + let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); + threadSum += subExp; + } + threadShared[lindex] = threadSum; + workgroupBarrier(); + + for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { + if (lindex < currSize) { + threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; + } + workgroupBarrier(); + } + if (lindex == 0) { + rowSumShared = ${$}(${Ks("threadShared[0]",f)}); + } + 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); + } + }`,T=e.compute({name:"Softmax",shaderCache:{hint:`${f};${b}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:_}]}),getShaderSource:y},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(os(T,c),{inputs:[T]})},fg=(e,r)=>{mg(e.inputs),_g(e,r)},gg=e=>Nt({axis:e.axis})}),Yl,wg,Mg,bg,yg,jx=Ve(()=>{gt(),Et(),Pt(),Yl=e=>Array.from(e.getBigInt64Array(),Number),wg=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, 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(Yl(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")},Mg=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Yl(e[1]),o=Mg(t,s),n=ye.size(o),i=e[0].dataType,a=$e("input",i,t.length),l=it("output",i,o.length),c=p=>` + const inputShape = ${a.indices(...t)}; + ${p.registerUniform("output_size","u32").declareVariables(a,l)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${l.offsetToIndices("global_idx")}; + var input_indices: ${a.type.indices}; + for (var i = 0; i < ${t.length}; i++) { + let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i; + + ${a.indicesSet("input_indices","i","input_dim_value")} + } + ${l.setByOffset("global_idx",a.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...ct(e[0].dims,o)]}),getShaderSource:c}},yg=e=>{wg(e.inputs),e.compute(bg(e.inputs),{inputs:[0]})}}),vg,xg,Tg,Nx=Ve(()=>{gt(),Et(),Pt(),vg=(e,r,t,s,o)=>{let n=it("output_data",o,t.length,4),i=$e("a_data",r[1].dataType,r[1].dims.length,4),a=$e("b_data",r[2].dataType,r[2].dims.length,4),l=$e("c_data",r[0].dataType,r[0].dims.length,4),c,p=(d,u,f)=>`select(${u}, ${d}, ${f})`;if(!s)c=n.setByOffset("global_idx",p(i.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let d=(u,f,_="")=>{let b=`a_data[index_a${f}][component_a${f}]`,k=`b_data[index_b${f}][component_b${f}]`,g=`bool(c_data[index_c${f}] & (0xffu << (component_c${f} * 8)))`;return` + let output_indices${f} = ${n.offsetToIndices(`global_idx * 4u + ${f}u`)}; + let offset_a${f} = ${i.broadcastedIndicesToOffset(`output_indices${f}`,n)}; + let offset_b${f} = ${a.broadcastedIndicesToOffset(`output_indices${f}`,n)}; + let offset_c${f} = ${l.broadcastedIndicesToOffset(`output_indices${f}`,n)}; + let index_a${f} = offset_a${f} / 4u; + let index_b${f} = offset_b${f} / 4u; + let index_c${f} = offset_c${f} / 4u; + let component_a${f} = offset_a${f} % 4u; + let component_b${f} = offset_b${f} % 4u; + let component_c${f} = offset_c${f} % 4u; + ${u}[${f}] = ${_}(${p(b,k,g)}); + `};o===9?c=` + var data = vec4(0); + ${d("data",0,"u32")} + ${d("data",1,"u32")} + ${d("data",2,"u32")} + ${d("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=` + ${d("output_data[global_idx]",0)} + ${d("output_data[global_idx]",1)} + ${d("output_data[global_idx]",2)} + ${d("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(l,i,a,n)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${c} + }`},xg=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,o=e[1].dataType,n=!(ye.areEqual(r,t)&&ye.areEqual(t,s)),i=r,a=ye.size(r);if(n){let c=Un.calcShape(Un.calcShape(r,t,!1),s,!1);if(!c)throw new Error("Can't perform where op on the given tensors");i=c,a=ye.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>vg(c,e,i,n,o),getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...ct(s,r,t,i)]})}},Tg=e=>{e.compute(xg(e.inputs))}}),Eg,Vx=Ve(()=>{rx(),pl(),sx(),nx(),ox(),ix(),ax(),px(),mx(),_x(),fx(),gx(),wx(),Mx(),bx(),yx(),vx(),xx(),Tx(),Ex(),Px(),Cx(),Sx(),$x(),kx(),L_(),Ix(),Ax(),Fx(),Ox(),Dx(),cl(),Lx(),K_(),zx(),Bx(),Rx(),U_(),jx(),Hs(),fl(),Nx(),Eg=new Map([["Abs",[nh]],["Acos",[oh]],["Acosh",[ih]],["Add",[Hh]],["ArgMax",[Up,dl]],["ArgMin",[Vp,dl]],["Asin",[ah]],["Asinh",[lh]],["Atan",[ch]],["Atanh",[uh]],["Attention",[Qp]],["AveragePool",[xf,vf]],["BatchNormalization",[Zp]],["BiasAdd",[rh]],["BiasSplitGelu",[Wh]],["Cast",[ph,dh]],["Ceil",[_h]],["Clip",[mh]],["Concat",[am,lm]],["Conv",[$l,Cl]],["ConvTranspose",[Dm,Am]],["Cos",[fh]],["Cosh",[gh]],["CumSum",[zm,Bm]],["DepthToSpace",[Vm,Um]],["DequantizeLinear",[Af,Ff]],["Div",[qh]],["Einsum",[Qm,Xm]],["Elu",[wh,go]],["Equal",[Qh]],["Erf",[Mh]],["Exp",[bh]],["Expand",[e_]],["FastGelu",[r_]],["Floor",[yh]],["FusedConv",[$l,Cl]],["Gather",[i_,o_]],["GatherElements",[g_,f_]],["GatherBlockQuantized",[p_,h_]],["GatherND",[l_,c_]],["Gelu",[vh]],["Gemm",[y_,b_]],["GlobalAveragePool",[Ef,Tf]],["GlobalMaxPool",[$f,Sf]],["Greater",[Zh]],["GreaterOrEqual",[tm]],["GridSample",[k_,I_]],["GroupQueryAttention",[X_]],["HardSigmoid",[kh,$h]],["InstanceNormalization",[Z_]],["LayerNormalization",[rf]],["LeakyRelu",[xh,go]],["Less",[em]],["LessOrEqual",[rm]],["Log",[Bh]],["MatMul",[nf]],["MatMulNBits",[cf,uf]],["MaxPool",[Pf,Cf]],["Mul",[Xh]],["MultiHeadAttention",[D_,F_]],["Neg",[Eh]],["Not",[Th]],["Pad",[Mf]],["Pow",[Jh]],["QuickGelu",[Nh,go]],["Range",[Lf]],["Reciprocal",[Ph]],["ReduceMin",[zp]],["ReduceMean",[Ap]],["ReduceMax",[Lp]],["ReduceSum",[Rp]],["ReduceProd",[Bp]],["ReduceL1",[Fp]],["ReduceL2",[Op]],["ReduceLogSum",[Np]],["ReduceLogSumExp",[Dp]],["ReduceSumSquare",[jp]],["Relu",[Ch]],["Resize",[sg,ng]],["RotaryEmbedding",[G_]],["ScatterND",[jf,Rf]],["Sigmoid",[Sh]],["Sin",[Ih]],["Sinh",[Ah]],["Slice",[pg,hg]],["SkipLayerNormalization",[ag]],["Split",[N_,V_]],["Sqrt",[Fh]],["Softmax",[fg,gg]],["Sub",[Yh]],["Tan",[Oh]],["Tanh",[Dh]],["ThresholdedRelu",[zh,go]],["Tile",[yg]],["Transpose",[Zd,ep]],["Where",[Tg]]])}),Pg,Ux=Ve(()=>{gs(),Bs(),Pt(),Pg=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t,s,o){fs(e.programInfo.name);let n=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let c of r)a.push({binding:a.length,resource:{buffer:c.buffer}});for(let c of t)a.push({binding:a.length,resource:{buffer:c.buffer}});o&&a.push({binding:a.length,resource:o});let l=n.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}i.setPipeline(e.computePipeline),i.setBindGroup(0,l),i.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(),cs(e.programInfo.name)}dispose(){}build(e,r){fs(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(c=>{t.features.has(c.feature)&&s.push(`enable ${c.extension};`)});let o=Hd(r,this.backend.device.limits),n=e.getShaderSource(o),i=`${s.join(` +`)} +${o.additionalImplementations} +${n}`,a=t.createShaderModule({code:i,label:e.name});Dt("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return cs(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let r=typeof e=="number"?e:e.x,t=typeof e=="number"?1:e.y||1,s=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=o&&t<=o&&s<=o)return[r,t,s];let n=r*t*s,i=Math.ceil(Math.sqrt(n));if(i>o){if(i=Math.ceil(Math.cbrt(n)),i>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),Cg={};Nn(Cg,{WebGpuBackend:()=>Ig});var Sg,$g,kg,Ig,Wx=Ve(()=>{gs(),gt(),Bs(),Fd(),ex(),Vx(),Ux(),Sg=(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 s=0;s{var o,n;let s=e.name;return(o=e.shaderCache)!=null&&o.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${Sg(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},kg=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Ig=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,r){this.env=e;let t=[],s={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},o=n=>r.features.has(n)&&t.push(n)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new kg(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Ud(this),this.programManager=new Pg(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ha(e.logLevel,!!e.debug),this.device.onuncapturederror=n=>{n.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${n.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;fs(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var s;let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let o=0;o"u"&&(this.queryTimeBase=f);let b=Number(f-this.queryTimeBase),k=Number(_-this.queryTimeBase);if(!Number.isSafeInteger(b)||!Number.isSafeInteger(k))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(g=>({dims:g.dims,dataType:zs(g.dataType)})),outputsMetadata:u.map(g=>({dims:g.dims,dataType:zs(g.dataType)})),kernelId:i,kernelType:l,kernelName:c,programName:p,startTime:b,endTime:k});else{let g="";d.forEach(($,v)=>{g+=`input[${v}]: [${$.dims}] | ${zs($.dataType)}, `});let M="";u.forEach(($,v)=>{M+=`output[${v}]: [${$.dims}] | ${zs($.dataType)}, `}),console.log(`[profiling] kernel "${i}|${l}|${c}|${p}" ${g}${M}execution time: ${k-b} ns`)}po("GPU",`${p}::${f}::${_}`)}e.unmap(),this.pendingQueries.delete(e)}),cs()}run(e,r,t,s,o,n){fs(e.name);let i=[];for(let M=0;M$):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let d=[],u=[];for(let M=0;M=n)throw new Error(`Invalid output index: ${p[M]}`);if(p[M]===-3)continue;let $=p[M]===-1,v=p[M]===-2,y=$||v?o(a[M].dataType,a[M].dims):s(p[M],a[M].dataType,a[M].dims);if(d.push(y),y.data===0)continue;let T=this.gpuDataManager.get(y.data);if(!T)throw new Error(`no GPU data for output: ${y.data}`);if($&&this.temporaryData.push(T),v){let x=this.kernelPersistentData.get(this.currentKernelId);x||(x=[],this.kernelPersistentData.set(this.currentKernelId,x)),x.push(T)}u.push(T)}if(i.length!==r.length||u.length!==d.length){if(u.length===0)return cs(e.name),d;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let f;if(c){let M=0,$=[];c.forEach(x=>{let P=typeof x.data=="number"?[x.data]:x.data;if(P.length===0)return;let O=x.type===10?2:4,L,G;x.type===10?(G=P.length>4?16:P.length>2?8:P.length*O,L=P.length>4?16:O*P.length):(G=P.length<=2?P.length*O:16,L=16),M=Math.ceil(M/G)*G,$.push(M);let K=x.type===10?8:4;M+=P.length>4?Math.ceil(P.length/K)*L:P.length*O});let v=16;M=Math.ceil(M/v)*v;let y=new ArrayBuffer(M);c.forEach((x,P)=>{let O=$[P],L=typeof x.data=="number"?[x.data]:x.data;if(x.type===6)new Int32Array(y,O,L.length).set(L);else if(x.type===12)new Uint32Array(y,O,L.length).set(L);else if(x.type===10)new Uint16Array(y,O,L.length).set(L);else if(x.type===1)new Float32Array(y,O,L.length).set(L);else throw new Error(`Unsupported uniform type: ${zs(x.type)}`)});let T=this.gpuDataManager.create(M,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(T.buffer,0,y,0,M),this.gpuDataManager.release(T.id),f={offset:0,size:M,buffer:T.buffer}}let _=this.programManager.normalizeDispatchGroupSize(l),b=_[1]===1&&_[2]===1,k=$g(e,r,b),g=this.programManager.getArtifact(k);if(g||(g=this.programManager.build(e,_),this.programManager.setArtifact(k,g),Dt("info",()=>`[artifact] key: ${k}, programName: ${e.name}`)),c&&g.uniformVariablesInfo){if(c.length!==g.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${g.uniformVariablesInfo.length}, got ${c.length} in program "${g.programInfo.name}".`);for(let M=0;M`[ProgramManager] run "${e.name}" (key=${k}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let M={kernelId:this.currentKernelId,programName:g.programInfo.name,inputTensorViews:r,outputTensorViews:d};this.pendingKernels.push(M),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(M)}return this.programManager.run(g,i,u,_,f),cs(e.name),d}upload(e,r){this.gpuDataManager.upload(e,r)}memcpy(e,r){this.gpuDataManager.memcpy(e,r)}async download(e,r){await this.gpuDataManager.download(e,r)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,r,t,s){let o=Eg.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:s,kernelEntry:o[0],attributes:[o[1],t]};this.kernels.set(r,n)}releaseKernel(e){let r=this.kernelPersistentData.get(e);if(r){for(let t of r)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,r,t){let s=this.kernels.get(e);if(!s)throw new Error(`kernel not created: ${e}`);let o=s.kernelType,n=s.kernelName,i=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),Dt("info",()=>`[WebGPU] Start to run kernel "[${o}] ${n}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(r,a[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${n}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${o}] ${n}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let n=o.get(r),i=this.gpuDataManager.registerExternalBuffer(t,s,n);return o.set(r,[i,t]),i}unregisterBuffers(e){let r=this.sessionExternalDataMapping.get(e);r&&(r.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let r=this.gpuDataManager.get(e);if(!r)throw new Error(`no GPU data for buffer: ${e}`);return r.buffer}createDownloader(e,r,t){return async()=>{let s=await nl(this,e,r);return qa(s.buffer,t)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.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(){Dt("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(){Dt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Dt("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),t=e.length;this.pendingKernels=[];for(let s=0;s=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Ag={};Nn(Ag,{init:()=>Og});var Mi,Fg,Og,Gx=Ve(()=>{gt(),Bs(),Et(),Zv(),Mi=class mv{constructor(r,t,s,o){this.module=r,this.dataType=t,this.data=s,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=ye.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=ye.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=ye.size(this.dims);return r===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,r)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let r=ye.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(ye.size(r)!==ye.size(this.dims))throw new Error("Invalid new shape");return new mv(this.module,this.dataType,this.data,r)}},Fg=class{constructor(e,r,t){this.module=e,this.backend=r,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=r.adapterInfo;let s=e.PTR_SIZE,o=t/e.PTR_SIZE,n=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*o++,n));let i=Number(e.getValue(s*o++,n));this.outputCount=Number(e.getValue(s*o++,n)),this.customDataOffset=Number(e.getValue(s*o++,"*")),this.customDataSize=Number(e.getValue(s*o++,n));let a=[];for(let l=0;ltypeof a=="number"?this.inputs[a]:a))??this.inputs,s=(r==null?void 0:r.outputs)??[],o=(a,l,c)=>new Mi(this.module,l,this.output(a,c),c),n=(a,l)=>{let c=pn(a,l);if(!c)throw new Error(`Unsupported data type: ${a}`);let p=c>0?this.backend.gpuDataManager.create(c).id:0;return new Mi(this.module,a,p,l)};return this.backend.run(e,t,s,o,n,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,o=s===4?"i32":"i64",n=this.module.stackAlloc((1+r.length)*s);this.module.setValue(n,r.length,o);for(let i=0;i{let o=r.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let n=(Wx(),lo(Cg)).WebGpuBackend,i=new n;await i.initialize(t,s),o("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,c,p=!1)=>{if(p)Dt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(c)}`),i.memcpy(Number(a),Number(l));else{Dt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(c)}`);let d=r.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(c));i.upload(Number(l),d)}},async(a,l,c)=>{Dt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${c}`),await i.download(Number(a),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+c)>>>0))},(a,l,c)=>i.createKernel(a,Number(l),c,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,c,p)=>{Dt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${a}, contextDataOffset=${l}`);let d=new Fg(r,i,Number(l));return i.computeKernel(Number(a),d,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let n=new Rd(t);o("webnn",[n,()=>n.reserveTensorId(),i=>n.releaseTensorId(i),async(i,a,l,c,p)=>n.ensureTensor(i,a,l,c,p),(i,a)=>{n.uploadTensor(i,a)},async(i,a)=>n.downloadTensor(i,a)])}}}),Dg,Zl,ec,qs,Lg,tc,bi,rc,sc,nc,oc,ic,ac,zg=Ve(()=>{Xv(),Jv(),gt(),dn(),Na(),xd(),Dg=(e,r)=>{Jt()._OrtInit(e,r)!==0&&Kt("Can't initialize onnxruntime.")},Zl=async e=>{Dg(e.wasm.numThreads,oi(e.logLevel))},ec=async(e,r)=>{var t,s;(s=(t=Jt()).asyncInit)==null||s.call(t);{let o=(Gx(),lo(Ag)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await o("webgpu",Jt(),e,n)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await o("webnn",Jt(),e)}}},qs=new Map,Lg=e=>{let r=Jt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,o,o+s)!==0&&Kt("Can't get session input/output count.");let n=s===4?"i32":"i64";return[Number(r.getValue(o,n)),Number(r.getValue(o+s,n))]}finally{r.stackRestore(t)}},tc=(e,r)=>{let t=Jt(),s=t.stackSave(),o=0;try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputMetadata(e,r,i,i+n)!==0&&Kt("Can't get session input/output metadata.");let a=Number(t.getValue(i,"*"));o=Number(t.getValue(i+n,"*"));let l=t.HEAP32[o/4];if(l===0)return[a,0];let c=t.HEAPU32[o/4+1],p=[];for(let d=0;d{let r=Jt(),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]},rc=async(e,r)=>{var d,u,f,_;let t,s,o=Jt();Array.isArray(e)?[t,s]=e:e.buffer===o.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=bi(e);let n=0,i=0,a=0,l=[],c=[],p=[];try{if([i,l]=await vd(r),(r==null?void 0:r.externalData)&&o.mountExternalData){let P=[];for(let O of r.externalData){let L=typeof O=="string"?O:O.path;P.push(Ka(typeof O=="string"?O:O.data).then(G=>{o.mountExternalData(L,G)}))}await Promise.all(P)}for(let P of(r==null?void 0:r.executionProviders)??[])if((typeof P=="string"?P:P.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof P!="string"){let O=P,L=O==null?void 0:O.context,G=O==null?void 0:O.gpuDevice,K=O==null?void 0:O.deviceType,R=O==null?void 0:O.powerPreference;L?o.currentContext=L:G?o.currentContext=await o.webnnCreateMLContext(G):o.currentContext=await o.webnnCreateMLContext({deviceType:K,powerPreference:R})}else o.currentContext=await o.webnnCreateMLContext();break}n=await o._OrtCreateSession(t,s,i),(d=o.webgpuOnCreateSession)==null||d.call(o,n),n===0&&Kt("Can't create a session."),(u=o.jsepOnCreateSession)==null||u.call(o),o.currentContext&&(o.webnnRegisterMLContext(n,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[b,k]=Lg(n),g=!!(r!=null&&r.enableGraphCapture),M=[],$=[],v=[],y=[],T=[];for(let P=0;PP==="gpu-buffer"||P==="ml-tensor")&&(a=o._OrtCreateBinding(n),a===0&&Kt("Can't create IO binding."),x={handle:a,outputPreferredLocations:T,outputPreferredLocationsEncoded:T.map(P=>Ga(P))}),qs.set(n,[n,c,p,x,g,!1]),[n,M,$,v,y]}catch(b){throw c.forEach(k=>o._OrtFree(k)),p.forEach(k=>o._OrtFree(k)),a!==0&&o._OrtReleaseBinding(a)!==0&&Kt("Can't release IO binding."),n!==0&&o._OrtReleaseSession(n)!==0&&Kt("Can't release session."),b}finally{o._free(t),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&Kt("Can't release session options."),l.forEach(b=>o._free(b)),(_=o.unmountExternalData)==null||_.call(o)}},sc=e=>{var l,c,p;let r=Jt(),t=qs.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,o,n,i,a]=t;i&&(a&&r._OrtClearBoundOutputs(i.handle)!==0&&Kt("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&Kt("Can't release IO binding.")),(l=r.jsepOnReleaseSession)==null||l.call(r,e),(c=r.webnnOnReleaseSession)==null||c.call(r,e),(p=r.webgpuOnReleaseSession)==null||p.call(r,e),o.forEach(d=>r._OrtFree(d)),n.forEach(d=>r._OrtFree(d)),r._OrtReleaseSession(s)!==0&&Kt("Can't release session."),qs.delete(e)},nc=async(e,r,t,s,o,n,i=!1)=>{if(!e){r.push(0);return}let a=Jt(),l=a.PTR_SIZE,c=e[0],p=e[1],d=e[3],u=d,f,_;if(c==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${n} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let g=e[2].gpuBuffer;_=pn(Vn(c),p);{let M=a.jsepRegisterBuffer;if(!M)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');f=M(s,n,g,_)}}else if(d==="ml-tensor"){let g=e[2].mlTensor;_=pn(Vn(c),p);let M=a.webnnRegisterMLTensor;if(!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');f=M(s,g,Vn(c),p)}else{let g=e[2];if(Array.isArray(g)){_=l*g.length,f=a._malloc(_),t.push(f);for(let M=0;Ma.setValue(k+$*l,M,l===4?"i32":"i64"));let g=a._OrtCreateTensor(Vn(c),f,_,k,p.length,Ga(u));g===0&&Kt(`Can't create tensor for input/output. session=${s}, index=${n}.`),r.push(g)}finally{a.stackRestore(b)}},oc=async(e,r,t,s,o,n)=>{var G,K,R,te;let i=Jt(),a=i.PTR_SIZE,l=qs.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],p=l[1],d=l[2],u=l[3],f=l[4],_=l[5],b=r.length,k=s.length,g=0,M=[],$=[],v=[],y=[],T=i.stackSave(),x=i.stackAlloc(b*a),P=i.stackAlloc(b*a),O=i.stackAlloc(k*a),L=i.stackAlloc(k*a);try{[g,M]=gd(n);for(let Z=0;ZX*ae,1);F=zs(_e);let Ie=u==null?void 0:u.outputPreferredLocations[s[Z]];if(F==="string"){if(Ie==="gpu-buffer"||Ie==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let X=[];for(let ae=0;ae0){let X=i.jsepGetBuffer;if(!X)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ae=X(U),W=pn(_e,Ge);if(W===void 0||!Ua(F))throw new Error(`Unsupported data type: ${F}`);j=!0,ee.push([F,ze,{gpuBuffer:ae,download:i.jsepCreateDownloader(ae,W,F),dispose:()=>{i._OrtReleaseTensor(ne)!==0&&Kt("Can't release tensor.")}},"gpu-buffer"])}else if(Ie==="ml-tensor"&&Ge>0){let X=i.webnnEnsureTensor,ae=i.webnnIsInt64Supported;if(!X||!ae)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(pn(_e,Ge)===void 0||!Wa(F))throw new Error(`Unsupported data type: ${F}`);if(F==="int64"&&!ae(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let W=await X(e,U,_e,ze,!1);j=!0,ee.push([F,ze,{mlTensor:W,download:i.webnnCreateMLTensorDownloader(U,F),dispose:()=>{i.webnnReleaseTensorId(U),i._OrtReleaseTensor(ne)}},"ml-tensor"])}else{let X=Va(F),ae=new X(Ge);new Uint8Array(ae.buffer,ae.byteOffset,ae.byteLength).set(i.HEAPU8.subarray(U,U+ae.byteLength)),ee.push([F,ze,ae,"cpu"])}}finally{i.stackRestore(me),F==="string"&&U&&i._free(U),j||i._OrtReleaseTensor(ne),(te=i.webnnOnRunEnd)==null||te.call(i,c)}}return u&&!f&&(i._OrtClearBoundOutputs(u.handle)!==0&&Kt("Can't clear bound outputs."),qs.set(e,[c,p,d,u,f,!1])),ee}finally{i.stackRestore(T),$.forEach(H=>i._OrtReleaseTensor(H)),v.forEach(H=>i._OrtReleaseTensor(H)),y.forEach(H=>i._free(H)),g!==0&&i._OrtReleaseRunOptions(g),M.forEach(H=>i._free(H))}},ic=e=>{let r=Jt(),t=qs.get(e);if(!t)throw new Error("invalid session id");let s=t[0],o=r._OrtEndProfiling(s);o===0&&Kt("Can't get an profile file name."),r._OrtFree(o)},ac=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),Qs,es,Kn,To,Eo,yi,lc,vi,Mn,bn,Bg,Rg,jg,Ng,Vg,Ug,Wg,Gg,Kg=Ve(()=>{gs(),zg(),dn(),za(),Qs=()=>!!Yt.wasm.proxy&&typeof document<"u",Kn=!1,To=!1,Eo=!1,vi=new Map,Mn=(e,r)=>{let t=vi.get(e);t?t.push(r):vi.set(e,[r])},bn=()=>{if(Kn||!To||Eo||!es)throw new Error("worker not ready")},Bg=e=>{switch(e.data.type){case"init-wasm":Kn=!1,e.data.err?(Eo=!0,lc[1](e.data.err)):(To=!0,lc[0]()),yi&&(URL.revokeObjectURL(yi),yi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=vi.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},Rg=async()=>{if(!To){if(Kn)throw new Error("multiple calls to 'initWasm()' detected.");if(Eo)throw new Error("previous call to 'initWasm()' failed.");if(Kn=!0,Qs())return new Promise((e,r)=>{es==null||es.terminate(),pd().then(([t,s])=>{try{es=s,es.onerror=n=>r(n),es.onmessage=Bg,lc=[e,r];let o={type:"init-wasm",in:Yt};!o.in.wasm.wasmPaths&&(t||Fa)&&(o.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href}),es.postMessage(o),yi=t}catch(o){r(o)}},r)});try{await ja(Yt.wasm),await Zl(Yt),To=!0}catch(e){throw Eo=!0,e}finally{Kn=!1}}},jg=async e=>{if(Qs())return bn(),new Promise((r,t)=>{Mn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Yt}};es.postMessage(s)});await ec(Yt,e)},Ng=async e=>Qs()?(bn(),new Promise((r,t)=>{Mn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};es.postMessage(s,[e.buffer])})):bi(e),Vg=async(e,r)=>{if(Qs()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return bn(),new Promise((t,s)=>{Mn("create",[t,s]);let o={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),es.postMessage(o,n)})}else return rc(e,r)},Ug=async e=>{if(Qs())return bn(),new Promise((r,t)=>{Mn("release",[r,t]);let s={type:"release",in:e};es.postMessage(s)});sc(e)},Wg=async(e,r,t,s,o,n)=>{if(Qs()){if(t.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return bn(),new Promise((i,a)=>{Mn("run",[i,a]);let l=t,c={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};es.postMessage(c,ac(l))})}else return oc(e,r,t,s,o,n)},Gg=async e=>{if(Qs())return bn(),new Promise((r,t)=>{Mn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};es.postMessage(s)});ic(e)}}),cc,Hg,qg,Kx=Ve(()=>{gs(),Kg(),gt(),Ca(),xd(),cc=(e,r)=>{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"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${r()}`)}},Hg=e=>{switch(e[3]){case"cpu":return new _s(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!Ua(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:o}=e[2];return _s.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:o})}case"ml-tensor":{let r=e[0];if(!Wa(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:o}=e[2];return _s.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},qg=class{async fetchModelAndCopyToWasmMemory(e){return Ng(await Ka(e))}async loadModel(e,r){fs();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Vg(t,r),cs()}async dispose(){return Ug(this.sessionId)}async run(e,r,t){fs();let s=[],o=[];Object.entries(e).forEach(d=>{let u=d[0],f=d[1],_=this.inputNames.indexOf(u);if(_===-1)throw new Error(`invalid input '${u}'`);s.push(f),o.push(_)});let n=[],i=[];Object.entries(r).forEach(d=>{let u=d[0],f=d[1],_=this.outputNames.indexOf(u);if(_===-1)throw new Error(`invalid output '${u}'`);n.push(f),i.push(_)});let a=s.map((d,u)=>cc(d,()=>`input "${this.inputNames[o[u]]}"`)),l=n.map((d,u)=>d?cc(d,()=>`output "${this.outputNames[i[u]]}"`):null),c=await Wg(this.sessionId,o,a,i,l,t),p={};for(let d=0;ddc,initializeFlags:()=>uc,wasmBackend:()=>Xg});var uc,dc,Xg,Hx=Ve(()=>{gs(),Kg(),Kx(),uc=()=>{(typeof Yt.wasm.initTimeout!="number"||Yt.wasm.initTimeout<0)&&(Yt.wasm.initTimeout=0);let e=Yt.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Yt.wasm.simd=!1),typeof Yt.wasm.proxy!="boolean"&&(Yt.wasm.proxy=!1),typeof Yt.wasm.trace!="boolean"&&(Yt.wasm.trace=!1),typeof Yt.wasm.numThreads!="number"||!Number.isInteger(Yt.wasm.numThreads)||Yt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Yt.wasm.numThreads=1;else{let r=typeof navigator>"u"?Fv("node:os").cpus().length:navigator.hardwareConcurrency;Yt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},dc=class{async init(e){uc(),await Rg(),await jg(e)}async createInferenceSessionHandler(e,r){let t=new qg;return await t.loadModel(e,r),t}},Xg=new dc});gs(),gs(),gs();var qx="1.22.0-dev.20250409-89f8206ba4",Qx=td;{let e=(Hx(),lo(Qg)).wasmBackend;cn("webgpu",e,5),cn("webnn",e,5),cn("cpu",e,10),cn("wasm",e,10)}Object.defineProperty(Yt.versions,"web",{value:qx,enumerable:!0});/** +* @license +* Copyright 2021 Google LLC. All Rights Reserved. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============================================================================= +*//** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Xx=Object.freeze({__proto__:null,get InferenceSession(){return Pa},get TRACE(){return po},get TRACE_FUNC_BEGIN(){return fs},get TRACE_FUNC_END(){return cs},get Tensor(){return _s},default:Qx,get env(){return Yt},get registerBackend(){return cn}}),js={},Jx={"onnxruntime-common":e=>{e.exports=$v},"onnxruntime-web":e=>{e.exports=Xx},"?2ce3":()=>{},"?7992":()=>{},"?5af5":()=>{},"?2b25":()=>{},"?db59":()=>{},"?383f":()=>{},"?fa4b":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,r,t)=>{t.r(r),t.d(r,{Environment:()=>Oe,Interpreter:()=>ot,Template:()=>Qt,parse:()=>ie,tokenize:()=>p});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),o=class{constructor(S,Q){this.value=S,this.type=Q}};function n(S){return/\w/.test(S)}function i(S){return/[0-9]/.test(S)}var a=[["{%",s.OpenStatement],["%}",s.CloseStatement],["{{",s.OpenExpression],["}}",s.CloseExpression],["(",s.OpenParen],[")",s.CloseParen],["{",s.OpenCurlyBracket],["}",s.CloseCurlyBracket],["[",s.OpenSquareBracket],["]",s.CloseSquareBracket],[",",s.Comma],[".",s.Dot],[":",s.Colon],["|",s.Pipe],["<=",s.ComparisonBinaryOperator],[">=",s.ComparisonBinaryOperator],["==",s.ComparisonBinaryOperator],["!=",s.ComparisonBinaryOperator],["<",s.ComparisonBinaryOperator],[">",s.ComparisonBinaryOperator],["+",s.AdditiveBinaryOperator],["-",s.AdditiveBinaryOperator],["~",s.AdditiveBinaryOperator],["*",s.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],l=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function c(S,Q={}){return S.endsWith(` +`)&&(S=S.slice(0,-1)),Q.lstrip_blocks&&(S=S.replace(/^[ \t]*({[#%-])/gm,"$1")),Q.trim_blocks&&(S=S.replace(/([#%-]})\n/g,"$1")),S.replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{").replace(/-#}\s*/g,"#}").replace(/\s*{#-/g,"{#").replace(/{%\s*(end)?generation\s*%}/gs,"")}function p(S,Q={}){var rt,ft;const B=[],q=c(S,Q);let re=0,ge=0;const Fe=ht=>{let vt="";for(;ht(q[re]);){if(q[re]==="\\"){if(++re,re>=q.length)throw new SyntaxError("Unexpected end of input");const st=q[re++],zt=l.get(st);if(zt===void 0)throw new SyntaxError(`Unexpected escaped character: ${st}`);vt+=zt;continue}if(vt+=q[re++],re>=q.length)throw new SyntaxError("Unexpected end of input")}return vt};e:for(;re0){B.push(new o(st,s.Text));continue}}if(q[re]==="{"&&q[re+1]==="#"){re+=2;let st="";for(;q[re]!=="#"||q[re+1]!=="}";){if(re+2>=q.length)throw new SyntaxError("Missing end of comment tag");st+=q[re++]}B.push(new o(st,s.Comment)),re+=2;continue}Fe(st=>/\s/.test(st));const vt=q[re];if(vt==="-"||vt==="+"){const st=(ft=B.at(-1))==null?void 0:ft.type;if(st===s.Text||st===void 0)throw new SyntaxError(`Unexpected character: ${vt}`);switch(st){case s.Identifier:case s.NumericLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++re;const zt=Fe(i);B.push(new o(`${vt}${zt}`,zt.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[st,zt]of a){if(st==="}}"&&ge>0)continue;if(q.slice(re,re+st.length)===st){B.push(new o(st,zt)),zt===s.OpenExpression?ge=0:zt===s.OpenCurlyBracket?++ge:zt===s.CloseCurlyBracket&&--ge,re+=st.length;continue e}}if(vt==="'"||vt==='"'){++re;const st=Fe(zt=>zt!==vt);B.push(new o(st,s.StringLiteral)),++re;continue}if(i(vt)){let st=Fe(i);if(q[re]==="."&&i(q[re+1])){++re;const zt=Fe(i);st=`${st}.${zt}`}B.push(new o(st,s.NumericLiteral));continue}if(n(vt)){const st=Fe(n);B.push(new o(st,s.Identifier));continue}throw new SyntaxError(`Unexpected character: ${vt}`)}return B}var d=class{constructor(){J(this,"type","Statement")}},u=class extends d{constructor(Q){super();J(this,"type","Program");this.body=Q}},f=class extends d{constructor(Q,B,q){super();J(this,"type","If");this.test=Q,this.body=B,this.alternate=q}},_=class extends d{constructor(Q,B,q,re){super();J(this,"type","For");this.loopvar=Q,this.iterable=B,this.body=q,this.defaultBlock=re}},b=class extends d{constructor(){super(...arguments);J(this,"type","Break")}},k=class extends d{constructor(){super(...arguments);J(this,"type","Continue")}},g=class extends d{constructor(Q,B,q){super();J(this,"type","Set");this.assignee=Q,this.value=B,this.body=q}},M=class extends d{constructor(Q,B,q){super();J(this,"type","Macro");this.name=Q,this.args=B,this.body=q}},$=class extends d{constructor(Q){super();J(this,"type","Comment");this.value=Q}},v=class extends d{constructor(){super(...arguments);J(this,"type","Expression")}},y=class extends v{constructor(Q,B,q){super();J(this,"type","MemberExpression");this.object=Q,this.property=B,this.computed=q}},T=class extends v{constructor(Q,B){super();J(this,"type","CallExpression");this.callee=Q,this.args=B}},x=class extends v{constructor(Q){super();J(this,"type","Identifier");this.value=Q}},P=class extends v{constructor(Q){super();J(this,"type","Literal");this.value=Q}},O=class extends P{constructor(){super(...arguments);J(this,"type","IntegerLiteral")}},L=class extends P{constructor(){super(...arguments);J(this,"type","FloatLiteral")}},G=class extends P{constructor(){super(...arguments);J(this,"type","StringLiteral")}},K=class extends P{constructor(){super(...arguments);J(this,"type","ArrayLiteral")}},R=class extends P{constructor(){super(...arguments);J(this,"type","TupleLiteral")}},te=class extends P{constructor(){super(...arguments);J(this,"type","ObjectLiteral")}},H=class extends v{constructor(Q,B,q){super();J(this,"type","BinaryExpression");this.operator=Q,this.left=B,this.right=q}},ee=class extends v{constructor(Q,B){super();J(this,"type","FilterExpression");this.operand=Q,this.filter=B}},Z=class extends d{constructor(Q,B){super();J(this,"type","FilterStatement");this.filter=Q,this.body=B}},ne=class extends v{constructor(Q,B){super();J(this,"type","SelectExpression");this.lhs=Q,this.test=B}},me=class extends v{constructor(Q,B,q){super();J(this,"type","TestExpression");this.operand=Q,this.negate=B,this.test=q}},ue=class extends v{constructor(Q,B){super();J(this,"type","UnaryExpression");this.operator=Q,this.argument=B}},j=class extends v{constructor(Q=void 0,B=void 0,q=void 0){super();J(this,"type","SliceExpression");this.start=Q,this.stop=B,this.step=q}},F=class extends v{constructor(Q,B){super();J(this,"type","KeywordArgumentExpression");this.key=Q,this.value=B}},U=class extends v{constructor(Q){super();J(this,"type","SpreadExpression");this.argument=Q}},se=class extends d{constructor(Q,B,q){super();J(this,"type","CallStatement");this.call=Q,this.callerArgs=B,this.body=q}},_e=class extends v{constructor(Q,B,q){super();J(this,"type","Ternary");this.condition=Q,this.trueExpr=B,this.falseExpr=q}};function ie(S){const Q=new u([]);let B=0;function q(Re,je){const et=S[B++];if(!et||et.type!==Re)throw new Error(`Parser Error: ${je}. ${et.type} !== ${Re}.`);return et}function re(Re){if(!ft(Re))throw new SyntaxError(`Expected ${Re}`);++B}function ge(){switch(S[B].type){case s.Comment:return new $(S[B++].value);case s.Text:return ht();case s.OpenStatement:return vt();case s.OpenExpression:return st();default:throw new SyntaxError(`Unexpected token type: ${S[B].type}`)}}function Fe(...Re){return B+Re.length<=S.length&&Re.every((je,et)=>je===S[B+et].type)}function rt(...Re){var je,et,Xt;return((je=S[B])==null?void 0:je.type)===s.OpenStatement&&((et=S[B+1])==null?void 0:et.type)===s.Identifier&&Re.includes((Xt=S[B+1])==null?void 0:Xt.value)}function ft(...Re){return B+Re.length<=S.length&&Re.every((je,et)=>S[B+et].type==="Identifier"&&je===S[B+et].value)}function ht(){return new G(q(s.Text,"Expected text token").value)}function vt(){if(q(s.OpenStatement,"Expected opening statement token"),S[B].type!==s.Identifier)throw new SyntaxError(`Unknown statement, got ${S[B].type}`);const Re=S[B].value;let je;switch(Re){case"set":++B,je=zt();break;case"if":++B,je=Ut(),q(s.OpenStatement,"Expected {% token"),re("endif"),q(s.CloseStatement,"Expected %} token");break;case"macro":++B,je=Nr(),q(s.OpenStatement,"Expected {% token"),re("endmacro"),q(s.CloseStatement,"Expected %} token");break;case"for":++B,je=rr(),q(s.OpenStatement,"Expected {% token"),re("endfor"),q(s.CloseStatement,"Expected %} token");break;case"call":{++B;let et=null;Fe(s.OpenParen)&&(et=ts());const Xt=Gr();if(Xt.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const Vs=ts();q(s.CloseStatement,"Expected closing statement token");const Es=[];for(;!rt("endcall");)Es.push(ge());q(s.OpenStatement,"Expected '{%'"),re("endcall"),q(s.CloseStatement,"Expected closing statement token");const Us=new T(Xt,Vs);je=new se(Us,et,Es);break}case"break":++B,q(s.CloseStatement,"Expected closing statement token"),je=new b;break;case"continue":++B,q(s.CloseStatement,"Expected closing statement token"),je=new k;break;case"filter":{++B;let et=Gr();et instanceof x&&Fe(s.OpenParen)&&(et=Wr(et)),q(s.CloseStatement,"Expected closing statement token");const Xt=[];for(;!rt("endfilter");)Xt.push(ge());q(s.OpenStatement,"Expected '{%'"),re("endfilter"),q(s.CloseStatement,"Expected '%}'"),je=new Z(et,Xt);break}default:throw new SyntaxError(`Unknown statement type: ${Re}`)}return je}function st(){q(s.OpenExpression,"Expected opening expression token");const Re=Sr();return q(s.CloseExpression,"Expected closing expression token"),Re}function zt(){const Re=Xr();let je=null;const et=[];if(Fe(s.Equals))++B,je=Xr();else{for(q(s.CloseStatement,"Expected %} token");!rt("endset");)et.push(ge());q(s.OpenStatement,"Expected {% token"),re("endset")}return q(s.CloseStatement,"Expected closing statement token"),new g(Re,je,et)}function Ut(){const Re=Sr();q(s.CloseStatement,"Expected closing statement token");const je=[],et=[];for(;!rt("elif","else","endif");)je.push(ge());if(rt("elif")){++B,++B;const Xt=Ut();et.push(Xt)}else if(rt("else"))for(++B,++B,q(s.CloseStatement,"Expected closing statement token");!rt("endif");)et.push(ge());return new f(Re,je,et)}function Nr(){const Re=Gr();if(Re.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const je=ts();q(s.CloseStatement,"Expected closing statement token");const et=[];for(;!rt("endmacro");)et.push(ge());return new M(Re,je,et)}function Xr(Re=!1){const je=Re?Gr:Sr,et=[je()],Xt=Fe(s.Comma);for(;Xt&&(++B,et.push(je()),!!Fe(s.Comma)););return Xt?new R(et):et[0]}function rr(){const Re=Xr(!0);if(!(Re instanceof x||Re instanceof R))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Re.type} instead`);if(!ft("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++B;const je=Sr();q(s.CloseStatement,"Expected closing statement token");const et=[];for(;!rt("endfor","else");)et.push(ge());const Xt=[];if(rt("else"))for(++B,++B,q(s.CloseStatement,"Expected closing statement token");!rt("endfor");)Xt.push(ge());return new _(Re,je,et,Xt)}function Sr(){return $r()}function $r(){const Re=Vr();if(ft("if")){++B;const je=Vr();if(ft("else")){++B;const et=$r();return new _e(je,Re,et)}else return new ne(Re,je)}return Re}function Vr(){let Re=ds();for(;ft("or");){const je=S[B];++B;const et=ds();Re=new H(je,Re,et)}return Re}function ds(){let Re=kr();for(;ft("and");){const je=S[B];++B;const et=kr();Re=new H(je,Re,et)}return Re}function kr(){let Re;for(;ft("not");){const je=S[B];++B;const et=kr();Re=new ue(je,et)}return Re??Os()}function Os(){let Re=Ds();for(;;){let je;if(ft("not","in"))je=new o("not in",s.Identifier),B+=2;else if(ft("in"))je=S[B++];else if(Fe(s.ComparisonBinaryOperator))je=S[B++];else break;const et=Ds();Re=new H(je,Re,et)}return Re}function Ds(){let Re=mr();for(;Fe(s.AdditiveBinaryOperator);){const je=S[B];++B;const et=mr();Re=new H(je,Re,et)}return Re}function Ur(){const Re=pr(Gr());return Fe(s.OpenParen)?Wr(Re):Re}function Wr(Re){let je=new T(Re,ts());return je=pr(je),Fe(s.OpenParen)&&(je=Wr(je)),je}function ts(){q(s.OpenParen,"Expected opening parenthesis for arguments list");const Re=Dr();return q(s.CloseParen,"Expected closing parenthesis for arguments list"),Re}function Dr(){const Re=[];for(;!Fe(s.CloseParen);){let je;if(S[B].type===s.MultiplicativeBinaryOperator&&S[B].value==="*"){++B;const et=Sr();je=new U(et)}else if(je=Sr(),Fe(s.Equals)){if(++B,!(je instanceof x))throw new SyntaxError("Expected identifier for keyword argument");const et=Sr();je=new F(je,et)}Re.push(je),Fe(s.Comma)&&++B}return Re}function Ts(){const Re=[];let je=!1;for(;!Fe(s.CloseSquareBracket);)Fe(s.Colon)?(Re.push(void 0),++B,je=!0):(Re.push(Sr()),Fe(s.Colon)&&(++B,je=!0));if(Re.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(je){if(Re.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new j(...Re)}return Re[0]}function pr(Re){for(;Fe(s.Dot)||Fe(s.OpenSquareBracket);){const je=S[B];++B;let et;const Xt=je.type===s.OpenSquareBracket;if(Xt)et=Ts(),q(s.CloseSquareBracket,"Expected closing square bracket");else if(et=Gr(),et.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Re=new y(Re,et,Xt)}return Re}function mr(){let Re=Jr();for(;Fe(s.MultiplicativeBinaryOperator);){const je=S[B++],et=Jr();Re=new H(je,Re,et)}return Re}function Jr(){let Re=Ns();for(;ft("is");){++B;const je=ft("not");je&&++B;const et=Gr();if(!(et instanceof x))throw new SyntaxError("Expected identifier for the test");Re=new me(Re,je,et)}return Re}function Ns(){let Re=Ur();for(;Fe(s.Pipe);){++B;let je=Gr();if(!(je instanceof x))throw new SyntaxError("Expected identifier for the filter");Fe(s.OpenParen)&&(je=Wr(je)),Re=new ee(Re,je)}return Re}function Gr(){const Re=S[B++];switch(Re.type){case s.NumericLiteral:{const je=Re.value;return je.includes(".")?new L(Number(je)):new O(Number(je))}case s.StringLiteral:{let je=Re.value;for(;Fe(s.StringLiteral);)je+=S[B++].value;return new G(je)}case s.Identifier:return new x(Re.value);case s.OpenParen:{const je=Xr();return q(s.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),je}case s.OpenSquareBracket:{const je=[];for(;!Fe(s.CloseSquareBracket);)je.push(Sr()),Fe(s.Comma)&&++B;return++B,new K(je)}case s.OpenCurlyBracket:{const je=new Map;for(;!Fe(s.CloseCurlyBracket);){const et=Sr();q(s.Colon,"Expected colon between key and value in object literal");const Xt=Sr();je.set(et,Xt),Fe(s.Comma)&&++B}return++B,new te(je)}default:throw new SyntaxError(`Unexpected token: ${Re.type}`)}}for(;B=0?(Q=(Q??(Q=0))<0?Math.max(S.length+Q,0):Math.min(Q,S.length),B=(B??(B=S.length))<0?Math.max(S.length+B,0):Math.min(B,S.length)):(Q=(Q??(Q=S.length-1))<0?Math.max(S.length+Q,-1):Math.min(Q,S.length-1),B=(B??(B=-1))<-1?Math.max(S.length+B,-1):Math.min(B,S.length-1));const ge=[];for(let Fe=Q;re*FeQ.toUpperCase())}function Ie(S){return X(new Date,S)}function X(S,Q){const B=new Intl.DateTimeFormat(void 0,{month:"long"}),q=new Intl.DateTimeFormat(void 0,{month:"short"}),re=ge=>ge<10?"0"+ge:ge.toString();return Q.replace(/%[YmdbBHM%]/g,ge=>{switch(ge){case"%Y":return S.getFullYear().toString();case"%m":return re(S.getMonth()+1);case"%d":return re(S.getDate());case"%b":return q.format(S);case"%B":return B.format(S);case"%H":return re(S.getHours());case"%M":return re(S.getMinutes());case"%%":return"%";default:return ge}})}function ae(S){return S.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function W(S,Q,B,q){if(q===0)return S;let re=q==null||q<0?1/0:q;const ge=Q.length===0?new RegExp("(?=)","gu"):new RegExp(ae(Q),"gu");return S.replaceAll(ge,Fe=>re>0?(--re,B):Fe)}var be=class extends Error{},ke=class extends Error{},Ee=class{constructor(S=void 0){J(this,"type","RuntimeValue");J(this,"value");J(this,"builtins",new Map);this.value=S}__bool__(){return new Ae(!!this.value)}toString(){return String(this.value)}},Me=class extends Ee{constructor(){super(...arguments);J(this,"type","IntegerValue")}},Se=class extends Ee{constructor(){super(...arguments);J(this,"type","FloatValue")}toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},we=class extends Ee{constructor(){super(...arguments);J(this,"type","StringValue");J(this,"builtins",new Map([["upper",new Ke(()=>new we(this.value.toUpperCase()))],["lower",new Ke(()=>new we(this.value.toLowerCase()))],["strip",new Ke(()=>new we(this.value.trim()))],["title",new Ke(()=>new we(Ge(this.value)))],["capitalize",new Ke(()=>new we(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new Me(this.value.length)],["rstrip",new Ke(()=>new we(this.value.trimEnd()))],["lstrip",new Ke(()=>new we(this.value.trimStart()))],["startswith",new Ke(Q=>{if(Q.length===0)throw new Error("startswith() requires at least one argument");const B=Q[0];if(B instanceof we)return new Ae(this.value.startsWith(B.value));if(B instanceof xe){for(const q of B.value){if(!(q instanceof we))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(q.value))return new Ae(!0)}return new Ae(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Ke(Q=>{if(Q.length===0)throw new Error("endswith() requires at least one argument");const B=Q[0];if(B instanceof we)return new Ae(this.value.endsWith(B.value));if(B instanceof xe){for(const q of B.value){if(!(q instanceof we))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(q.value))return new Ae(!0)}return new Ae(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Ke(Q=>{const B=Q[0]??new nt;if(!(B instanceof we||B instanceof nt))throw new Error("sep argument must be a string or null");const q=Q[1]??new Me(-1);if(!(q instanceof Me))throw new Error("maxsplit argument must be a number");let re=[];if(B instanceof nt){const ge=this.value.trimStart();for(const{0:Fe,index:rt}of ge.matchAll(/\S+/g)){if(q.value!==-1&&re.length>=q.value&&rt!==void 0){re.push(Fe+ge.slice(rt+Fe.length));break}re.push(Fe)}}else{if(B.value==="")throw new Error("empty separator");re=this.value.split(B.value),q.value!==-1&&re.length>q.value&&re.push(re.splice(q.value).join(B.value))}return new xe(re.map(ge=>new we(ge)))})],["replace",new Ke(Q=>{if(Q.length<2)throw new Error("replace() requires at least two arguments");const B=Q[0],q=Q[1];if(!(B instanceof we&&q instanceof we))throw new Error("replace() arguments must be strings");let re;if(Q.length>2?Q[2].type==="KeywordArgumentsValue"?re=Q[2].value.get("count")??new nt:re=Q[2]:re=new nt,!(re instanceof Me||re instanceof nt))throw new Error("replace() count argument must be a number or null");return new we(W(this.value,B.value,q.value,re.value))})]]))}},Ae=class extends Ee{constructor(){super(...arguments);J(this,"type","BooleanValue")}},Be=class extends Ee{constructor(){super(...arguments);J(this,"type","ObjectValue");J(this,"builtins",new Map([["get",new Ke(([Q,B])=>{if(!(Q instanceof we))throw new Error(`Object key must be a string: got ${Q.type}`);return this.value.get(Q.value)??B??new nt})],["items",new Ke(()=>this.items())],["keys",new Ke(()=>this.keys())],["values",new Ke(()=>this.values())]]))}__bool__(){return new Ae(this.value.size>0)}items(){return new xe(Array.from(this.value.entries()).map(([Q,B])=>new xe([new we(Q),B])))}keys(){return new xe(Array.from(this.value.keys()).map(Q=>new we(Q)))}values(){return new xe(Array.from(this.value.values()))}},Qe=class extends Be{constructor(){super(...arguments);J(this,"type","KeywordArgumentsValue")}},xe=class extends Ee{constructor(){super(...arguments);J(this,"type","ArrayValue");J(this,"builtins",new Map([["length",new Me(this.value.length)]]))}__bool__(){return new Ae(this.value.length>0)}},Ze=class extends xe{constructor(){super(...arguments);J(this,"type","TupleValue")}},Ke=class extends Ee{constructor(){super(...arguments);J(this,"type","FunctionValue")}},nt=class extends Ee{constructor(){super(...arguments);J(this,"type","NullValue")}},Je=class extends Ee{constructor(){super(...arguments);J(this,"type","UndefinedValue")}},Oe=class{constructor(S){J(this,"variables",new Map([["namespace",new Ke(S=>{if(S.length===0)return new Be(new Map);if(S.length!==1||!(S[0]instanceof Be))throw new Error("`namespace` expects either zero arguments or a single object argument");return S[0]})]]));J(this,"tests",new Map([["boolean",S=>S.type==="BooleanValue"],["callable",S=>S instanceof Ke],["odd",S=>{if(!(S instanceof Me))throw new Error(`cannot odd on ${S.type}`);return S.value%2!==0}],["even",S=>{if(!(S instanceof Me))throw new Error(`cannot even on ${S.type}`);return S.value%2===0}],["false",S=>S.type==="BooleanValue"&&!S.value],["true",S=>S.type==="BooleanValue"&&S.value],["none",S=>S.type==="NullValue"],["string",S=>S.type==="StringValue"],["number",S=>S instanceof Me||S instanceof Se],["integer",S=>S instanceof Me],["iterable",S=>S.type==="ArrayValue"||S.type==="StringValue"],["mapping",S=>S.type==="ObjectValue"],["lower",S=>{const Q=S.value;return S.type==="StringValue"&&Q===Q.toLowerCase()}],["upper",S=>{const Q=S.value;return S.type==="StringValue"&&Q===Q.toUpperCase()}],["none",S=>S.type==="NullValue"],["defined",S=>S.type!=="UndefinedValue"],["undefined",S=>S.type==="UndefinedValue"],["equalto",(S,Q)=>S.value===Q.value],["eq",(S,Q)=>S.value===Q.value]]));this.parent=S}set(S,Q){return this.declareVariable(S,It(Q))}declareVariable(S,Q){if(this.variables.has(S))throw new SyntaxError(`Variable already declared: ${S}`);return this.variables.set(S,Q),Q}setVariable(S,Q){return this.variables.set(S,Q),Q}resolve(S){if(this.variables.has(S))return this;if(this.parent)return this.parent.resolve(S);throw new Error(`Unknown variable: ${S}`)}lookupVariable(S){try{return this.resolve(S).variables.get(S)??new Je}catch{return new Je}}};function Ye(S){S.set("false",!1),S.set("true",!0),S.set("none",null),S.set("raise_exception",Q=>{throw new Error(Q)}),S.set("range",ve),S.set("strftime_now",Ie),S.set("True",!0),S.set("False",!1),S.set("None",null)}var ot=class{constructor(S){J(this,"global");this.global=S??new Oe}run(S){return this.evaluate(S,this.global)}evaluateBinaryExpression(S,Q){const B=this.evaluate(S.left,Q);switch(S.operator.value){case"and":return B.__bool__().value?this.evaluate(S.right,Q):B;case"or":return B.__bool__().value?B:this.evaluate(S.right,Q)}const q=this.evaluate(S.right,Q);switch(S.operator.value){case"==":return new Ae(B.value==q.value);case"!=":return new Ae(B.value!=q.value)}if(B instanceof Je||q instanceof Je){if(q instanceof Je&&["in","not in"].includes(S.operator.value))return new Ae(S.operator.value==="not in");throw new Error(`Cannot perform operation ${S.operator.value} on undefined values`)}else{if(B instanceof nt||q instanceof nt)throw new Error("Cannot perform operation on null values");if(S.operator.value==="~")return new we(B.value.toString()+q.value.toString());if((B instanceof Me||B instanceof Se)&&(q instanceof Me||q instanceof Se)){const re=B.value,ge=q.value;switch(S.operator.value){case"+":case"-":case"*":{const Fe=S.operator.value==="+"?re+ge:S.operator.value==="-"?re-ge:re*ge;return B instanceof Se||q instanceof Se?new Se(Fe):new Me(Fe)}case"/":return new Se(re/ge);case"%":{const Fe=re%ge;return B instanceof Se||q instanceof Se?new Se(Fe):new Me(Fe)}case"<":return new Ae(re":return new Ae(re>ge);case">=":return new Ae(re>=ge);case"<=":return new Ae(re<=ge)}}else if(B instanceof xe&&q instanceof xe)switch(S.operator.value){case"+":return new xe(B.value.concat(q.value))}else if(q instanceof xe){const re=q.value.find(ge=>ge.value===B.value)!==void 0;switch(S.operator.value){case"in":return new Ae(re);case"not in":return new Ae(!re)}}}if(B instanceof we||q instanceof we)switch(S.operator.value){case"+":return new we(B.value.toString()+q.value.toString())}if(B instanceof we&&q instanceof we)switch(S.operator.value){case"in":return new Ae(q.value.includes(B.value));case"not in":return new Ae(!q.value.includes(B.value))}if(B instanceof we&&q instanceof Be)switch(S.operator.value){case"in":return new Ae(q.value.has(B.value));case"not in":return new Ae(!q.value.has(B.value))}throw new SyntaxError(`Unknown operator "${S.operator.value}" between ${B.type} and ${q.type}`)}evaluateArguments(S,Q){const B=[],q=new Map;for(const re of S)if(re.type==="SpreadExpression"){const ge=re,Fe=this.evaluate(ge.argument,Q);if(!(Fe instanceof xe))throw new Error(`Cannot unpack non-iterable type: ${Fe.type}`);for(const rt of Fe.value)B.push(rt)}else if(re.type==="KeywordArgumentExpression"){const ge=re;q.set(ge.key.value,this.evaluate(ge.value,Q))}else{if(q.size>0)throw new Error("Positional arguments must come before keyword arguments");B.push(this.evaluate(re,Q))}return[B,q]}applyFilter(S,Q,B){if(Q.type==="Identifier"){const q=Q;if(q.value==="tojson")return new we(St(S));if(S instanceof xe)switch(q.value){case"list":return S;case"first":return S.value[0];case"last":return S.value[S.value.length-1];case"length":return new Me(S.value.length);case"reverse":return new xe(S.value.reverse());case"sort":return new xe(S.value.sort((re,ge)=>{if(re.type!==ge.type)throw new Error(`Cannot compare different types: ${re.type} and ${ge.type}`);switch(re.type){case"IntegerValue":case"FloatValue":return re.value-ge.value;case"StringValue":return re.value.localeCompare(ge.value);default:throw new Error(`Cannot compare type: ${re.type}`)}}));case"join":return new we(S.value.map(re=>re.value).join(""));case"string":return new we(St(S));case"unique":{const re=new Set,ge=[];for(const Fe of S.value)re.has(Fe.value)||(re.add(Fe.value),ge.push(Fe));return new xe(ge)}default:throw new Error(`Unknown ArrayValue filter: ${q.value}`)}else if(S instanceof we)switch(q.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const re=S.builtins.get(q.value);if(re instanceof Ke)return re.value([],B);if(re instanceof Me)return re;throw new Error(`Unknown StringValue filter: ${q.value}`)}case"trim":return new we(S.value.trim());case"indent":return new we(S.value.split(` +`).map((re,ge)=>ge===0||re.length===0?re:" "+re).join(` +`));case"join":case"string":return S;case"int":{const re=parseInt(S.value,10);return new Me(isNaN(re)?0:re)}case"float":{const re=parseFloat(S.value);return new Se(isNaN(re)?0:re)}default:throw new Error(`Unknown StringValue filter: ${q.value}`)}else if(S instanceof Me||S instanceof Se)switch(q.value){case"abs":return S instanceof Me?new Me(Math.abs(S.value)):new Se(Math.abs(S.value));case"int":return new Me(Math.floor(S.value));case"float":return new Se(S.value);default:throw new Error(`Unknown NumericValue filter: ${q.value}`)}else if(S instanceof Be)switch(q.value){case"items":return new xe(Array.from(S.value.entries()).map(([re,ge])=>new xe([new we(re),ge])));case"length":return new Me(S.value.size);default:throw new Error(`Unknown ObjectValue filter: ${q.value}`)}else if(S instanceof Ae)switch(q.value){case"bool":return new Ae(S.value);case"int":return new Me(S.value?1:0);case"float":return new Se(S.value?1:0);case"string":return new we(S.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${q.value}`)}throw new Error(`Cannot apply filter "${q.value}" to type: ${S.type}`)}else if(Q.type==="CallExpression"){const q=Q;if(q.callee.type!=="Identifier")throw new Error(`Unknown filter: ${q.callee.type}`);const re=q.callee.value;if(re==="tojson"){const[,ge]=this.evaluateArguments(q.args,B),Fe=ge.get("indent")??new nt;if(!(Fe instanceof Me||Fe instanceof nt))throw new Error("If set, indent must be a number");return new we(St(S,Fe.value))}else if(re==="join"){let ge;if(S instanceof we)ge=Array.from(S.value);else if(S instanceof xe)ge=S.value.map(ht=>ht.value);else throw new Error(`Cannot apply filter "${re}" to type: ${S.type}`);const[Fe,rt]=this.evaluateArguments(q.args,B),ft=Fe.at(0)??rt.get("separator")??new we("");if(!(ft instanceof we))throw new Error("separator must be a string");return new we(ge.join(ft.value))}else if(re==="int"||re==="float"){const[ge,Fe]=this.evaluateArguments(q.args,B),rt=ge.at(0)??Fe.get("default")??(re==="int"?new Me(0):new Se(0));if(S instanceof we){const ft=re==="int"?parseInt(S.value,10):parseFloat(S.value);return isNaN(ft)?rt:re==="int"?new Me(ft):new Se(ft)}else{if(S instanceof Me||S instanceof Se)return S;if(S instanceof Ae)return re==="int"?new Me(S.value?1:0):new Se(S.value?1:0);throw new Error(`Cannot apply filter "${re}" to type: ${S.type}`)}}else if(re==="default"){const[ge,Fe]=this.evaluateArguments(q.args,B),rt=ge[0]??new we(""),ft=ge[1]??Fe.get("boolean")??new Ae(!1);if(!(ft instanceof Ae))throw new Error("`default` filter flag must be a boolean");return S instanceof Je||ft.value&&!S.__bool__().value?rt:S}if(S instanceof xe){switch(re){case"selectattr":case"rejectattr":{const ge=re==="selectattr";if(S.value.some(st=>!(st instanceof Be)))throw new Error(`\`${re}\` can only be applied to array of objects`);if(q.args.some(st=>st.type!=="StringLiteral"))throw new Error(`arguments of \`${re}\` must be strings`);const[Fe,rt,ft]=q.args.map(st=>this.evaluate(st,B));let ht;if(rt){const st=B.tests.get(rt.value);if(!st)throw new Error(`Unknown test: ${rt.value}`);ht=st}else ht=(...st)=>st[0].__bool__().value;const vt=S.value.filter(st=>{const zt=st.value.get(Fe.value),Ut=zt?ht(zt,ft):!1;return ge?Ut:!Ut});return new xe(vt)}case"map":{const[,ge]=this.evaluateArguments(q.args,B);if(ge.has("attribute")){const Fe=ge.get("attribute");if(!(Fe instanceof we))throw new Error("attribute must be a string");const rt=ge.get("default"),ft=S.value.map(ht=>{if(!(ht instanceof Be))throw new Error("items in map must be an object");return ht.value.get(Fe.value)??rt??new Je});return new xe(ft)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${re}`)}else if(S instanceof we){switch(re){case"indent":{const[ge,Fe]=this.evaluateArguments(q.args,B),rt=ge.at(0)??Fe.get("width")??new Me(4);if(!(rt instanceof Me))throw new Error("width must be a number");const ft=ge.at(1)??Fe.get("first")??new Ae(!1),ht=ge.at(2)??Fe.get("blank")??new Ae(!1),vt=S.value.split(` +`),st=" ".repeat(rt.value),zt=vt.map((Ut,Nr)=>!ft.value&&Nr===0||!ht.value&&Ut.length===0?Ut:st+Ut);return new we(zt.join(` +`))}case"replace":{const ge=S.builtins.get("replace");if(!(ge instanceof Ke))throw new Error("replace filter not available");const[Fe,rt]=this.evaluateArguments(q.args,B);return ge.value([...Fe,new Qe(rt)],B)}}throw new Error(`Unknown StringValue filter: ${re}`)}else throw new Error(`Cannot apply filter "${re}" to type: ${S.type}`)}throw new Error(`Unknown filter: ${Q.type}`)}evaluateFilterExpression(S,Q){const B=this.evaluate(S.operand,Q);return this.applyFilter(B,S.filter,Q)}evaluateTestExpression(S,Q){const B=this.evaluate(S.operand,Q),q=Q.tests.get(S.test.value);if(!q)throw new Error(`Unknown test: ${S.test.value}`);const re=q(B);return new Ae(S.negate?!re:re)}evaluateSelectExpression(S,Q){return this.evaluate(S.test,Q).__bool__().value?this.evaluate(S.lhs,Q):new Je}evaluateUnaryExpression(S,Q){const B=this.evaluate(S.argument,Q);switch(S.operator.value){case"not":return new Ae(!B.value);default:throw new SyntaxError(`Unknown operator: ${S.operator.value}`)}}evaluateTernaryExpression(S,Q){return this.evaluate(S.condition,Q).__bool__().value?this.evaluate(S.trueExpr,Q):this.evaluate(S.falseExpr,Q)}evalProgram(S,Q){return this.evaluateBlock(S.body,Q)}evaluateBlock(S,Q){let B="";for(const q of S){const re=this.evaluate(q,Q);re.type!=="NullValue"&&re.type!=="UndefinedValue"&&(B+=re.toString())}return new we(B)}evaluateIdentifier(S,Q){return Q.lookupVariable(S.value)}evaluateCallExpression(S,Q){const[B,q]=this.evaluateArguments(S.args,Q);q.size>0&&B.push(new Qe(q));const re=this.evaluate(S.callee,Q);if(re.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${re.type}`);return re.value(B,Q)}evaluateSliceExpression(S,Q,B){if(!(S instanceof xe||S instanceof we))throw new Error("Slice object must be an array or string");const q=this.evaluate(Q.start,B),re=this.evaluate(Q.stop,B),ge=this.evaluate(Q.step,B);if(!(q instanceof Me||q instanceof Je))throw new Error("Slice start must be numeric or undefined");if(!(re instanceof Me||re instanceof Je))throw new Error("Slice stop must be numeric or undefined");if(!(ge instanceof Me||ge instanceof Je))throw new Error("Slice step must be numeric or undefined");return S instanceof xe?new xe(ze(S.value,q.value,re.value,ge.value)):new we(ze(Array.from(S.value),q.value,re.value,ge.value).join(""))}evaluateMemberExpression(S,Q){const B=this.evaluate(S.object,Q);let q;if(S.computed){if(S.property.type==="SliceExpression")return this.evaluateSliceExpression(B,S.property,Q);q=this.evaluate(S.property,Q)}else q=new we(S.property.value);let re;if(B instanceof Be){if(!(q instanceof we))throw new Error(`Cannot access property with non-string: got ${q.type}`);re=B.value.get(q.value)??B.builtins.get(q.value)}else if(B instanceof xe||B instanceof we)if(q instanceof Me)re=B.value.at(q.value),B instanceof we&&(re=new we(B.value.at(q.value)));else if(q instanceof we)re=B.builtins.get(q.value);else throw new Error(`Cannot access property with non-string/non-number: got ${q.type}`);else{if(!(q instanceof we))throw new Error(`Cannot access property with non-string: got ${q.type}`);re=B.builtins.get(q.value)}return re instanceof Ee?re:new Je}evaluateSet(S,Q){const B=S.value?this.evaluate(S.value,Q):this.evaluateBlock(S.body,Q);if(S.assignee.type==="Identifier"){const q=S.assignee.value;Q.setVariable(q,B)}else if(S.assignee.type==="TupleLiteral"){const q=S.assignee;if(!(B instanceof xe))throw new Error(`Cannot unpack non-iterable type in set: ${B.type}`);const re=B.value;if(re.length!==q.value.length)throw new Error(`Too ${q.value.length>re.length?"few":"many"} items to unpack in set`);for(let ge=0;geUt.setVariable(S.loopvar.value,st);else if(S.loopvar.type==="TupleLiteral"){const Ut=S.loopvar;if(st.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${st.type}`);const Nr=st;if(Ut.value.length!==Nr.value.length)throw new Error(`Too ${Ut.value.length>Nr.value.length?"few":"many"} items to unpack`);zt=Xr=>{for(let rr=0;rr0?ge[ht-1]:new Je],["nextitem",ht{var Fe;const re=new Oe(q);B=B.slice();let ge;((Fe=B.at(-1))==null?void 0:Fe.type)==="KeywordArgumentsValue"&&(ge=B.pop());for(let rt=0;rt{const ht=new Oe(ft);if(S.callerArgs)for(let vt=0;vtthis.evaluate(B,Q)));case"TupleLiteral":return new Ze(S.value.map(B=>this.evaluate(B,Q)));case"ObjectLiteral":{const B=new Map;for(const[q,re]of S.value){const ge=this.evaluate(q,Q);if(!(ge instanceof we))throw new Error(`Object keys must be strings: got ${ge.type}`);B.set(ge.value,this.evaluate(re,Q))}return new Be(B)}case"Identifier":return this.evaluateIdentifier(S,Q);case"CallExpression":return this.evaluateCallExpression(S,Q);case"MemberExpression":return this.evaluateMemberExpression(S,Q);case"UnaryExpression":return this.evaluateUnaryExpression(S,Q);case"BinaryExpression":return this.evaluateBinaryExpression(S,Q);case"FilterExpression":return this.evaluateFilterExpression(S,Q);case"FilterStatement":return this.evaluateFilterStatement(S,Q);case"TestExpression":return this.evaluateTestExpression(S,Q);case"SelectExpression":return this.evaluateSelectExpression(S,Q);case"Ternary":return this.evaluateTernaryExpression(S,Q);case"Comment":return new nt;default:throw new SyntaxError(`Unknown node type: ${S.type}`)}}};function It(S){switch(typeof S){case"number":return Number.isInteger(S)?new Me(S):new Se(S);case"string":return new we(S);case"boolean":return new Ae(S);case"undefined":return new Je;case"object":return S===null?new nt:Array.isArray(S)?new xe(S.map(It)):new Be(new Map(Object.entries(S).map(([Q,B])=>[Q,It(B)])));case"function":return new Ke((Q,B)=>{const q=S(...Q.map(re=>re.value))??null;return It(q)});default:throw new Error(`Cannot convert to runtime value: ${S}`)}}function St(S,Q,B){const q=B??0;switch(S.type){case"NullValue":case"UndefinedValue":return"null";case"IntegerValue":case"FloatValue":case"StringValue":case"BooleanValue":return JSON.stringify(S.value);case"ArrayValue":case"ObjectValue":{const re=Q?" ".repeat(Q):"",ge=` +`+re.repeat(q),Fe=ge+re;if(S.type==="ArrayValue"){const rt=S.value.map(ft=>St(ft,Q,q+1));return Q?`[${Fe}${rt.join(`,${Fe}`)}${ge}]`:`[${rt.join(", ")}]`}else{const rt=Array.from(S.value.entries()).map(([ft,ht])=>{const vt=`"${ft}": ${St(ht,Q,q+1)}`;return Q?`${Fe}${vt}`:vt});return Q?`{${rt.join(",")}${ge}}`:`{${rt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${S.type}`)}}var wt=` +`,Mr="{%- ",Pr=" -%}";function jr(S){switch(S.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return S.operator.value==="and"?1:S.operator.value==="in"||S.operator.value==="not in"?2:0}return 0}function us(S,Q=" "){const B=typeof Q=="number"?" ".repeat(Q):Q;return Cr(S.body,0,B).replace(/\n$/,"")}function qt(...S){return Mr+S.join(" ")+Pr}function Cr(S,Q,B){return S.map(q=>Xs(q,Q,B)).join(wt)}function Xs(S,Q,B){const q=B.repeat(Q);switch(S.type){case"Program":return Cr(S.body,Q,B);case"If":return Js(S,Q,B);case"For":return Ys(S,Q,B);case"Set":return Zs(S,Q,B);case"Macro":return pt(S,Q,B);case"Break":return q+qt("break");case"Continue":return q+qt("continue");case"CallStatement":return As(S,Q,B);case"FilterStatement":return Fs(S,Q,B);case"Comment":return q+"{# "+S.value+" #}";default:return q+"{{- "+Ct(S)+" -}}"}}function Js(S,Q,B){const q=B.repeat(Q),re=[];let ge=S;for(;ge&&(re.push({test:ge.test,body:ge.body}),ge.alternate.length===1&&ge.alternate[0].type==="If");)ge=ge.alternate[0];let Fe=q+qt("if",Ct(re[0].test))+wt+Cr(re[0].body,Q+1,B);for(let rt=1;rt0&&(Fe+=wt+q+qt("else")+wt+Cr(ge.alternate,Q+1,B)),Fe+=wt+q+qt("endif"),Fe}function Ys(S,Q,B){const q=B.repeat(Q);let re="";if(S.iterable.type==="SelectExpression"){const Fe=S.iterable;re=`${Ct(Fe.lhs)} if ${Ct(Fe.test)}`}else re=Ct(S.iterable);let ge=q+qt("for",Ct(S.loopvar),"in",re)+wt+Cr(S.body,Q+1,B);return S.defaultBlock.length>0&&(ge+=wt+q+qt("else")+wt+Cr(S.defaultBlock,Q+1,B)),ge+=wt+q+qt("endfor"),ge}function Zs(S,Q,B){const q=B.repeat(Q),re=Ct(S.assignee),ge=S.value?Ct(S.value):"",Fe=q+qt("set",`${re}${S.value?" = "+ge:""}`);return S.body.length===0?Fe:Fe+wt+Cr(S.body,Q+1,B)+wt+q+qt("endset")}function pt(S,Q,B){const q=B.repeat(Q),re=S.args.map(Ct).join(", ");return q+qt("macro",`${S.name.value}(${re})`)+wt+Cr(S.body,Q+1,B)+wt+q+qt("endmacro")}function As(S,Q,B){const q=B.repeat(Q),re=S.callerArgs&&S.callerArgs.length>0?`(${S.callerArgs.map(Ct).join(", ")})`:"",ge=Ct(S.call);let Fe=q+qt(`call${re}`,ge)+wt;return Fe+=Cr(S.body,Q+1,B)+wt,Fe+=q+qt("endcall"),Fe}function Fs(S,Q,B){const q=B.repeat(Q),re=S.filter.type==="Identifier"?S.filter.value:Ct(S.filter);let ge=q+qt("filter",re)+wt;return ge+=Cr(S.body,Q+1,B)+wt,ge+=q+qt("endfilter"),ge}function Ct(S,Q=-1){switch(S.type){case"SpreadExpression":return`*${Ct(S.argument)}`;case"Identifier":return S.value;case"IntegerLiteral":return`${S.value}`;case"FloatLiteral":return`${S.value}`;case"StringLiteral":return JSON.stringify(S.value);case"BinaryExpression":{const B=S,q=jr(B),re=Ct(B.left,q),ge=Ct(B.right,q+1),Fe=`${re} ${B.operator.value} ${ge}`;return q`${Ct(q)}: ${Ct(re)}`).join(", ")}}`;case"SliceExpression":{const B=S,q=B.start?Ct(B.start):"",re=B.stop?Ct(B.stop):"",ge=B.step?`:${Ct(B.step)}`:"";return`${q}:${re}${ge}`}case"KeywordArgumentExpression":{const B=S;return`${B.key.value}=${Ct(B.value)}`}case"Ternary":{const B=S,q=`${Ct(B.trueExpr)} if ${Ct(B.condition,0)} else ${Ct(B.falseExpr)}`;return Q>-1?`(${q})`:q}default:throw new Error(`Unknown expression type: ${S.type}`)}}var Qt=class{constructor(S){J(this,"parsed");const Q=p(S,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=ie(Q)}render(S){const Q=new Oe;if(Ye(Q),S)for(const[re,ge]of Object.entries(S))Q.set(re,ge);return new ot(Q).run(this.parsed).value}format(S){return us(this.parsed,(S==null?void 0:S.indent)||" ")}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>k,deviceToExecutionProviders:()=>_,isONNXProxy:()=>$,isONNXTensor:()=>g});var o=t("./src/env.js"),n=t("?2ce3"),i=t("onnxruntime-web"),a=t("onnxruntime-common");const l=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),c=[];let p,d;const u=Symbol.for("onnxruntime");if(u in globalThis)d=globalThis[u];else if(o.apis.IS_NODE_ENV){switch(d=n??(s||(s=t.t(n,2))),process.platform){case"win32":c.push("dml");break;case"linux":process.arch==="x64"&&c.push("cuda");break}c.push("cpu"),p=["cpu"]}else d=i,o.apis.IS_WEBNN_AVAILABLE&&c.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&c.push("webgpu"),c.push("wasm"),p=["wasm"];const f=d.InferenceSession;function _(v=null){if(!v)return p;switch(v){case"auto":return c;case"gpu":return c.filter(y=>["webgpu","cuda","dml","webnn-gpu"].includes(y))}if(c.includes(v))return[l[v]??v];throw new Error(`Unsupported device: "${v}". Should be one of: ${c.join(", ")}.`)}let b=null;async function k(v,y,T){b&&await b;const x=f.create(v,y);b??(b=x);const P=await x;return P.config=T,P}function g(v){return v instanceof d.Tensor}const M=d==null?void 0:d.env;M!=null&&M.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!M.wasm.wasmPaths&&(M.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`),M.wasm.proxy=!1),M!=null&&M.webgpu&&(M.webgpu.powerPreference="high-performance");function $(){var v;return(v=M==null?void 0:M.wasm)==null?void 0:v.proxy}o.env.backends.onnx=M},"./src/base/feature_extraction_utils.js":(e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>i,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(c){super(),this.config=c}static async from_pretrained(c,p={}){const d=await(0,n.getModelJSON)(c,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(d)}}function a(l,c){var p;if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${c} expects input to be a Float32Array or a Float64Array, but got ${((p=l==null?void 0:l.constructor)==null?void 0:p.name)??typeof l} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(e,r,t)=>{t.r(r),t.d(r,{ImageProcessor:()=>v,center_to_corners_format:()=>d,post_process_instance_segmentation:()=>$,post_process_object_detection:()=>u,post_process_panoptic_segmentation:()=>M,post_process_semantic_segmentation:()=>f});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/utils/image.js");var i=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function c(y,T,x=0,P=null){const O=y/T;let L=(0,n.bankers_round)(O)*T;return P!==null&&L>P&&(L=Math.floor(O)*T),LT&&F.push(se)}else{let se=(0,n.max)(j.data)[1];if(se===R-1||(U=(0,n.softmax)(j.data),U[se]ie*ee[(ve+1)%2])),Z.boxes.push(_e),Z.classes.push(se),Z.scores.push(U[se])}}te.push(Z)}return te}function f(y,T=null){const x=y.logits,P=x.dims[0];if(T!==null&&T.length!==P)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const O=[];for(let L=0;Lee[F]&&(ee[F]=j[F],Z[F]=ue)}const ne=new Array(K.dims[0]);for(let ue=0;ueue!==void 0);O.push({segmentation:H,labels:me})}return O}function _(y,T,x,P){const O=[],L=[],G=[];for(let K=0;Kx&&(O.push(te),L.push(Z),G.push(H))}return[O,L,G]}function b(y,T,x,P=.5,O=.8){const L=[];let G=0,K=0;const R=T[x].data;for(let H=0;H=P&&++K;let te=G>0&&K>0;return te&&(te=G/K>O),[te,L]}function k(y,T,x,P,O,L=null,G=null){const[K,R]=G??y[0].dims,te=new o.Tensor("int32",new Int32Array(K*R),[K,R]),H=[];if(G!==null)for(let ue=0;ueZ[U]&&(ee[U]=ue,Z[U]=F[U])}let ne=0;const me=te.data;for(let ue=0;ue200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(y,T)/Math.min(y,T)}`);let L=Math.round(y/x)*x,G=Math.round(T/x)*x;if(L*G>O){const K=Math.sqrt(y*T/O);L=Math.floor(y/K/x)*x,G=Math.floor(T/K/x)*x}else if(L*GL?te=Math.floor(L*R/O):L>O&&(R=Math.floor(O*te/L)),await T.resize(te,R,{resample:P}))}async crop_margin(T,x=200){const P=T.clone().grayscale(),O=(0,n.min)(P.data)[0],G=(0,n.max)(P.data)[0]-O;if(G===0)return T;const K=x/255;let R=P.width,te=P.height,H=0,ee=0;const Z=P.data;for(let ne=0;nethis.preprocess(L)));return{pixel_values:(0,o.stack)(P.map(L=>L.pixel_values),0),original_sizes:P.map(L=>L.original_size),reshaped_input_sizes:P.map(L=>L.reshaped_input_size)}}static async from_pretrained(T,x={}){const P=await(0,a.getModelJSON)(T,l.IMAGE_PROCESSOR_NAME,!0,x);return new this(P)}}},"./src/base/processing_utils.js":(e,r,t)=>{t.r(r),t.d(r,{Processor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(l,c,p){super(),this.config=l,this.components=c,this.chat_template=p}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(l,c={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,chat_template:this.chat_template??void 0,...c})}batch_decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...l)}decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...l)}async _call(l,...c){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...c);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,c={}){const[p,d,u]=await Promise.all([this.uses_processor_config?(0,n.getModelJSON)(l,s.PROCESSOR_NAME,!0,c):{},Promise.all(this.classes.filter(f=>f in this).map(async f=>{const _=await this[f].from_pretrained(l,c);return[f.replace(/_class$/,""),_]})).then(Object.fromEntries),this.uses_chat_template_file?(0,n.getModelText)(l,s.CHAT_TEMPLATE_NAME,!0,c):null]);return new this(p,d,u)}}J(i,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),J(i,"uses_processor_config",!1),J(i,"uses_chat_template_file",!1)},"./src/configs.js":(e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>p,PretrainedConfig:()=>c,getCacheShapes:()=>a});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js");async function n(d,u){return await(0,o.getModelJSON)(d,"config.json",!0,u)}function i(d){const u={};let f={};switch(d.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"voxtral":case"smolvlm":case"gemma3n":f=i(d.text_config);break;case"moondream1":f=i(d.phi_config);break;case"musicgen":f=i(d.decoder);break;case"multi_modality":f=i(d.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":u.num_heads="num_attention_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size";break;case"llama":case"arcee":case"lfm2":case"smollm3":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size",u.num_attention_heads="num_attention_heads",u.dim_kv="head_dim";break;case"qwen3":case"gemma":case"gemma2":case"gemma3_text":case"gemma3n_text":case"glm":case"helium":case"ernie4_5":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.dim_kv="head_dim";break;case"openelm":u.num_heads="num_kv_heads",u.num_layers="num_transformer_layers",u.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":u.num_heads="num_heads",u.num_layers="num_layers",u.hidden_size="hidden_size";break;case"bloom":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="hidden_size";break;case"mpt":u.num_heads="n_heads",u.num_layers="n_layers",u.hidden_size="d_model";break;case"exaone":u.num_heads="num_key_value_heads",u.num_layers="num_layers",u.dim_kv="head_dim",u.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":u.num_decoder_layers="num_decoder_layers",u.num_decoder_heads="num_heads",u.decoder_dim_kv="d_kv",u.num_encoder_layers="num_layers",u.num_encoder_heads="num_heads",u.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="d_model",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="d_model";break;case"speecht5":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="hidden_size",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="hidden_size";break;case"trocr":u.num_encoder_layers=u.num_decoder_layers="decoder_layers",u.num_encoder_heads=u.num_decoder_heads="decoder_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="d_model";break;case"musicgen_decoder":u.num_encoder_layers=u.num_decoder_layers="num_hidden_layers",u.num_encoder_heads=u.num_decoder_heads="num_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"moonshine":u.num_decoder_layers="decoder_num_hidden_layers",u.num_decoder_heads="decoder_num_key_value_heads",u.num_encoder_layers="encoder_num_hidden_layers",u.num_encoder_heads="encoder_num_key_value_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const b=i(d.decoder),k="num_decoder_layers"in b,g=(0,s.pick)(d,["model_type","is_encoder_decoder"]);return k?(g.num_decoder_layers=b.num_decoder_layers,g.num_decoder_heads=b.num_decoder_heads,g.decoder_hidden_size=b.decoder_hidden_size,g.num_encoder_layers=b.num_encoder_layers,g.num_encoder_heads=b.num_encoder_heads,g.encoder_hidden_size=b.encoder_hidden_size):(g.num_layers=b.num_layers,g.num_heads=b.num_heads,g.hidden_size=b.hidden_size),g}const _={...f,...(0,s.pick)(d,["model_type","multi_query","is_encoder_decoder"])};for(const b in u)_[b]=d[u[b]];return _}function a(d,u){if(d.model_type==="lfm2"){const f=(u==null?void 0:u.prefix)??"past_key_values",_=f==="present"?"present":"past",b={},{layer_types:k,num_attention_heads:g,num_key_value_heads:M,hidden_size:$,conv_L_cache:v}=d,y=$/g,T=(u==null?void 0:u.batch_size)??1;for(let x=0;x{var O,L;t.r(r),t.d(r,{apis:()=>g,env:()=>x});var s=t("?db59"),o=t("?383f"),n=t("?fa4b");const i="3.7.1",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes((O=self.constructor)==null?void 0:O.name),c=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,d=typeof navigator<"u"&&"ml"in navigator,u=typeof process<"u",f=u&&((L=process==null?void 0:process.release)==null?void 0:L.name)==="node",_=!P(s),b=!P(o),k=typeof globalThis.Deno<"u",g=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:c,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:d,IS_PROCESS_AVAILABLE:u,IS_NODE_ENV:f,IS_FS_AVAILABLE:_,IS_PATH_AVAILABLE:b}),M=_&&b;let $="./";if(M){const G=Object({url:self.location.href}).url;G?$=o.dirname(o.dirname(n.fileURLToPath(G))):typeof __dirname<"u"&&($=o.dirname(__dirname))}const v=M?o.join($,"/.cache/"):null,y="/models/",T=M?o.join($,y):y,x={version:i,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:T,useFS:_,useBrowserCache:c&&!k,useFSCache:_,cacheDir:v,useCustomCache:!1,customCache:null};function P(G){return Object.keys(G).length===0}},"./src/generation/configuration_utils.js":(e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>o});var s=t("./src/utils/core.js");class o{constructor(i){J(this,"max_length",20);J(this,"max_new_tokens",null);J(this,"min_length",0);J(this,"min_new_tokens",null);J(this,"early_stopping",!1);J(this,"max_time",null);J(this,"do_sample",!1);J(this,"num_beams",1);J(this,"num_beam_groups",1);J(this,"penalty_alpha",null);J(this,"use_cache",!0);J(this,"temperature",1);J(this,"top_k",50);J(this,"top_p",1);J(this,"typical_p",1);J(this,"epsilon_cutoff",0);J(this,"eta_cutoff",0);J(this,"diversity_penalty",0);J(this,"repetition_penalty",1);J(this,"encoder_repetition_penalty",1);J(this,"length_penalty",1);J(this,"no_repeat_ngram_size",0);J(this,"bad_words_ids",null);J(this,"force_words_ids",null);J(this,"renormalize_logits",!1);J(this,"constraints",null);J(this,"forced_bos_token_id",null);J(this,"forced_eos_token_id",null);J(this,"remove_invalid_values",!1);J(this,"exponential_decay_length_penalty",null);J(this,"suppress_tokens",null);J(this,"streamer",null);J(this,"begin_suppress_tokens",null);J(this,"forced_decoder_ids",null);J(this,"guidance_scale",null);J(this,"num_return_sequences",1);J(this,"output_attentions",!1);J(this,"output_hidden_states",!1);J(this,"output_scores",!1);J(this,"return_dict_in_generate",!1);J(this,"pad_token_id",null);J(this,"bos_token_id",null);J(this,"eos_token_id",null);J(this,"encoder_no_repeat_ngram_size",0);J(this,"decoder_start_token_id",null);J(this,"generation_kwargs",{});Object.assign(this,(0,s.pick)(i,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>g,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>c,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>_,MinNewTokensLengthLogitsProcessor:()=>b,NoBadWordsLogitsProcessor:()=>k,NoRepeatNGramLogitsProcessor:()=>u,RepetitionPenaltyLogitsProcessor:()=>f,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>M,TopKLogitsWarper:()=>v,TopPLogitsWarper:()=>$,WhisperTimeStampLogitsProcessor:()=>d});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var o=t("./src/utils/maths.js");class n extends s.Callable{_call(T,x){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(T,x){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(T){this.processors.push(T)}extend(T){this.processors.push(...T)}_call(T,x){let P=x;for(const O of this.processors)P=O(T,P);return P}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(T){super(),this.bos_token_id=T}_call(T,x){for(let P=0;P=1&&L[L.length-1]>=this.timestamp_begin,K=L.length<2||L[L.length-2]>=this.timestamp_begin;if(G&&(K?O.subarray(this.timestamp_begin).fill(-1/0):O.subarray(0,this.eos_token_id).fill(-1/0)),T[P].length===this.begin_index&&this.max_initial_timestamp_index!==null){const ee=this.timestamp_begin+this.max_initial_timestamp_index;O.subarray(ee+1).fill(-1/0)}const R=(0,o.log_softmax)(O),te=Math.log(R.subarray(this.timestamp_begin).map(Math.exp).reduce((ee,Z)=>ee+Z)),H=(0,o.max)(R.subarray(0,this.timestamp_begin))[0];te>H&&O.subarray(0,this.timestamp_begin).fill(-1/0)}return x}}class u extends n{constructor(T){super(),this.no_repeat_ngram_size=T}getNgrams(T){const x=T.length,P=[];for(let L=0;L1 to use the classifier free guidance processor, got guidance scale ${T}.`);this.guidance_scale=T}_call(T,x){if(x.dims[0]!==2*T.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${x.dims[0]} for the logits and ${T.length} for the input ids.`);const P=T.length,O=x.slice([0,P],null),L=x.slice([P,x.dims[0]],null);for(let G=0;G1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${T}`);if(!Number.isInteger(P)||P<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${P}`);this.top_p=T,this.filter_value=x,this.min_tokens_to_keep=P}}class v extends i{constructor(T,{filter_value:x=-1/0,min_tokens_to_keep:P=1}={}){if(super(),!Number.isInteger(T)||T<0)throw new Error(`\`top_k\` must be a positive integer, but is ${T}`);this.top_k=Math.max(T,P),this.filter_value=x}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>i});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class i extends s.Callable{constructor(d){super(),this.generation_config=d}async _call(d){return this.sample(d)}async sample(d){throw Error("sample should be implemented in subclasses.")}getLogits(d,u){let f=d.dims.at(-1),_=d.data;if(u===-1)_=_.slice(-f);else{let b=u*f;_=_.slice(b,b+f)}return _}randomSelect(d){let u=0;for(let _=0;_1)return new c(d);if(d.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${d.num_return_sequences}.`);return new a(d)}}class a extends i{async sample(d){const u=(0,n.max)(d.data)[1];return[[BigInt(u),0]]}}class l extends i{async sample(d){let u=d.dims.at(-1);this.generation_config.top_k>0&&(u=Math.min(this.generation_config.top_k,u));const[f,_]=await(0,o.topk)(d,u),b=(0,n.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},()=>{const k=this.randomSelect(b);return[_.data[k],Math.log(b[k])]})}}class c extends i{async sample(d){let u=d.dims.at(-1);this.generation_config.top_k>0&&(u=Math.min(this.generation_config.top_k,u));const[f,_]=await(0,o.topk)(d,u),b=(0,n.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},(k,g)=>[_.data[g],Math.log(b[g])])}}},"./src/generation/stopping_criteria.js":(e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>i,StoppingCriteria:()=>o,StoppingCriteriaList:()=>n});var s=t("./src/utils/generic.js");class o extends s.Callable{_call(p,d){throw Error("StoppingCriteria needs to be subclassed")}}class n extends s.Callable{constructor(){super(),this.criteria=[]}push(p){this.criteria.push(p)}extend(p){p instanceof n?p=p.criteria:p instanceof o&&(p=[p]),this.criteria.push(...p)}_call(p,d){const u=new Array(p.length).fill(!1);for(const f of this.criteria){const _=f(p,d);for(let b=0;bd.length>=this.max_length)}}class a extends o{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,d){return p.map(u=>{const f=u.at(-1);return this.eos_token_id.some(_=>f==_)})}}class l extends o{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,d){return new Array(p.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>i,TextStreamer:()=>l,WhisperTextStreamer:()=>c});var s=t("./src/utils/core.js"),o=t("./src/tokenizers.js"),n=t("./src/env.js");class i{put(d){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const a=n.apis.IS_PROCESS_AVAILABLE?p=>process.stdout.write(p):p=>console.log(p);class l extends i{constructor(d,{skip_prompt:u=!1,callback_function:f=null,token_callback_function:_=null,skip_special_tokens:b=!0,decode_kwargs:k={},...g}={}){super(),this.tokenizer=d,this.skip_prompt=u,this.callback_function=f??a,this.token_callback_function=_,this.decode_kwargs={skip_special_tokens:b,...k,...g},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(d){var k;if(d.length>1)throw Error("TextStreamer only supports batch size of 1");const u=this.next_tokens_are_prompt;if(u&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const f=d[0];(k=this.token_callback_function)==null||k.call(this,f),this.token_cache=(0,s.mergeArrays)(this.token_cache,f);const _=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let b;u||_.endsWith(` +`)?(b=_.slice(this.print_len),this.token_cache=[],this.print_len=0):_.length>0&&(0,o.is_chinese_char)(_.charCodeAt(_.length-1))?(b=_.slice(this.print_len),this.print_len+=b.length):(b=_.slice(this.print_len,_.lastIndexOf(" ")+1),this.print_len+=b.length),this.on_finalized_text(b,!1)}end(){let d;this.token_cache.length>0?(d=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):d="",this.next_tokens_are_prompt=!0,this.on_finalized_text(d,!0)}on_finalized_text(d,u){var f,_;d.length>0&&((f=this.callback_function)==null||f.call(this,d)),u&&this.callback_function===a&&n.apis.IS_PROCESS_AVAILABLE&&((_=this.callback_function)==null||_.call(this,` +`))}}class c extends l{constructor(d,{skip_prompt:u=!1,callback_function:f=null,token_callback_function:_=null,on_chunk_start:b=null,on_chunk_end:k=null,on_finalize:g=null,time_precision:M=.02,skip_special_tokens:$=!0,decode_kwargs:v={}}={}){super(d,{skip_prompt:u,skip_special_tokens:$,callback_function:f,token_callback_function:_,decode_kwargs:v}),this.timestamp_begin=d.timestamp_begin,this.on_chunk_start=b,this.on_chunk_end=k,this.on_finalize=g,this.time_precision=M,this.waiting_for_timestamp=!1}put(d){var f,_,b;if(d.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const u=d[0];if(u.length===1){const k=Number(u[0])-this.timestamp_begin;if(k>=0){const g=k*this.time_precision;this.waiting_for_timestamp?(f=this.on_chunk_end)==null||f.call(this,g):(_=this.on_chunk_start)==null||_.call(this,g),this.waiting_for_timestamp=!this.waiting_for_timestamp,(b=this.token_callback_function)==null||b.call(this,u);return}}return super.put(d)}end(){var d;super.end(),(d=this.on_finalize)==null||d.call(this)}}},"./src/models.js":(e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>Io,ASTModel:()=>Di,ASTPreTrainedModel:()=>ko,AlbertForMaskedLM:()=>Mt,AlbertForQuestionAnswering:()=>tt,AlbertForSequenceClassification:()=>We,AlbertModel:()=>qe,AlbertPreTrainedModel:()=>Ne,ArceeForCausalLM:()=>xt,ArceeModel:()=>at,ArceePreTrainedModel:()=>He,AutoModel:()=>Pu,AutoModelForAudioClassification:()=>X0,AutoModelForAudioFrameClassification:()=>Y0,AutoModelForAudioTextToText:()=>av,AutoModelForCTC:()=>Q0,AutoModelForCausalLM:()=>B0,AutoModelForDepthEstimation:()=>rv,AutoModelForDocumentQuestionAnswering:()=>Z0,AutoModelForImageClassification:()=>V0,AutoModelForImageFeatureExtraction:()=>ov,AutoModelForImageMatting:()=>ev,AutoModelForImageSegmentation:()=>U0,AutoModelForImageTextToText:()=>iv,AutoModelForImageToImage:()=>tv,AutoModelForMaskGeneration:()=>q0,AutoModelForMaskedLM:()=>R0,AutoModelForNormalEstimation:()=>sv,AutoModelForObjectDetection:()=>K0,AutoModelForPoseEstimation:()=>nv,AutoModelForQuestionAnswering:()=>j0,AutoModelForSemanticSegmentation:()=>W0,AutoModelForSeq2SeqLM:()=>O0,AutoModelForSequenceClassification:()=>A0,AutoModelForSpeechSeq2Seq:()=>D0,AutoModelForTextToSpectrogram:()=>L0,AutoModelForTextToWaveform:()=>z0,AutoModelForTokenClassification:()=>F0,AutoModelForUniversalSegmentation:()=>G0,AutoModelForVision2Seq:()=>N0,AutoModelForXVector:()=>J0,AutoModelForZeroShotObjectDetection:()=>H0,BartForConditionalGeneration:()=>gr,BartForSequenceClassification:()=>Kr,BartModel:()=>Zt,BartPretrainedModel:()=>Yr,BaseModelOutput:()=>ke,BeitForImageClassification:()=>pM,BeitModel:()=>dM,BeitPreTrainedModel:()=>Nc,BertForMaskedLM:()=>Se,BertForQuestionAnswering:()=>Be,BertForSequenceClassification:()=>we,BertForTokenClassification:()=>Ae,BertModel:()=>Me,BertPreTrainedModel:()=>Ee,BlenderbotForConditionalGeneration:()=>nr,BlenderbotModel:()=>hr,BlenderbotPreTrainedModel:()=>ar,BlenderbotSmallForConditionalGeneration:()=>Hn,BlenderbotSmallModel:()=>Ws,BlenderbotSmallPreTrainedModel:()=>Hr,BloomForCausalLM:()=>Ow,BloomModel:()=>Fw,BloomPreTrainedModel:()=>$c,CLIPModel:()=>Lo,CLIPPreTrainedModel:()=>Ss,CLIPSegForImageSegmentation:()=>Zn,CLIPSegModel:()=>$n,CLIPSegPreTrainedModel:()=>rs,CLIPTextModel:()=>Ki,CLIPTextModelWithProjection:()=>zo,CLIPVisionModel:()=>Hi,CLIPVisionModelWithProjection:()=>Bo,CamembertForMaskedLM:()=>ht,CamembertForQuestionAnswering:()=>zt,CamembertForSequenceClassification:()=>vt,CamembertForTokenClassification:()=>st,CamembertModel:()=>ft,CamembertPreTrainedModel:()=>rt,CausalLMOutput:()=>Fn,CausalLMOutputWithPast:()=>hT,ChineseCLIPModel:()=>dt,ChineseCLIPPreTrainedModel:()=>Cn,ClapAudioModelWithProjection:()=>my,ClapModel:()=>py,ClapPreTrainedModel:()=>ra,ClapTextModelWithProjection:()=>hy,CodeGenForCausalLM:()=>V,CodeGenModel:()=>z,CodeGenPreTrainedModel:()=>A,CohereForCausalLM:()=>mw,CohereModel:()=>hw,CoherePreTrainedModel:()=>bc,ConvBertForMaskedLM:()=>Fs,ConvBertForQuestionAnswering:()=>S,ConvBertForSequenceClassification:()=>Ct,ConvBertForTokenClassification:()=>Qt,ConvBertModel:()=>As,ConvBertPreTrainedModel:()=>pt,ConvNextForImageClassification:()=>ib,ConvNextModel:()=>ob,ConvNextPreTrainedModel:()=>ru,ConvNextV2ForImageClassification:()=>lb,ConvNextV2Model:()=>ab,ConvNextV2PreTrainedModel:()=>su,DFineForObjectDetection:()=>EM,DFineModel:()=>TM,DFinePreTrainedModel:()=>Hc,DPTForDepthEstimation:()=>NM,DPTModel:()=>jM,DPTPreTrainedModel:()=>Zc,DacDecoderModel:()=>r0,DacDecoderOutput:()=>Zy,DacEncoderModel:()=>t0,DacEncoderOutput:()=>Yy,DacModel:()=>e0,DacPreTrainedModel:()=>ca,DebertaForMaskedLM:()=>Xr,DebertaForQuestionAnswering:()=>$r,DebertaForSequenceClassification:()=>rr,DebertaForTokenClassification:()=>Sr,DebertaModel:()=>Nr,DebertaPreTrainedModel:()=>Ut,DebertaV2ForMaskedLM:()=>kr,DebertaV2ForQuestionAnswering:()=>Ur,DebertaV2ForSequenceClassification:()=>Os,DebertaV2ForTokenClassification:()=>Ds,DebertaV2Model:()=>ds,DebertaV2PreTrainedModel:()=>Vr,DecisionTransformerModel:()=>Dy,DecisionTransformerPreTrainedModel:()=>Oy,DeiTForImageClassification:()=>kM,DeiTModel:()=>$M,DeiTPreTrainedModel:()=>Qc,DepthAnythingForDepthEstimation:()=>UM,DepthAnythingPreTrainedModel:()=>VM,DepthProForDepthEstimation:()=>qM,DepthProPreTrainedModel:()=>HM,DetrForObjectDetection:()=>mM,DetrForSegmentation:()=>Vc,DetrModel:()=>hM,DetrObjectDetectionOutput:()=>Uc,DetrPreTrainedModel:()=>Xi,DetrSegmentationOutput:()=>_M,Dinov2ForImageClassification:()=>ub,Dinov2Model:()=>cb,Dinov2PreTrainedModel:()=>nu,Dinov2WithRegistersForImageClassification:()=>pb,Dinov2WithRegistersModel:()=>db,Dinov2WithRegistersPreTrainedModel:()=>ou,DistilBertForMaskedLM:()=>mr,DistilBertForQuestionAnswering:()=>pr,DistilBertForSequenceClassification:()=>Dr,DistilBertForTokenClassification:()=>Ts,DistilBertModel:()=>ts,DistilBertPreTrainedModel:()=>Wr,DonutSwinModel:()=>nb,DonutSwinPreTrainedModel:()=>sb,EfficientNetForImageClassification:()=>yy,EfficientNetModel:()=>by,EfficientNetPreTrainedModel:()=>fu,ElectraForMaskedLM:()=>q,ElectraForQuestionAnswering:()=>Fe,ElectraForSequenceClassification:()=>re,ElectraForTokenClassification:()=>ge,ElectraModel:()=>B,ElectraPreTrainedModel:()=>Q,Ernie4_5_ForCausalLM:()=>ay,Ernie4_5_Model:()=>iy,Ernie4_5_PretrainedModel:()=>du,EsmForMaskedLM:()=>Gr,EsmForSequenceClassification:()=>Re,EsmForTokenClassification:()=>je,EsmModel:()=>Ns,EsmPreTrainedModel:()=>Jr,ExaoneForCausalLM:()=>nw,ExaoneModel:()=>sw,ExaonePreTrainedModel:()=>_c,FalconForCausalLM:()=>dy,FalconModel:()=>uy,FalconPreTrainedModel:()=>hu,FastViTForImageClassification:()=>eM,FastViTModel:()=>Zw,FastViTPreTrainedModel:()=>Lc,Florence2ForConditionalGeneration:()=>ji,Florence2PreTrainedModel:()=>Ri,GLPNForDepthEstimation:()=>rb,GLPNModel:()=>tb,GLPNPreTrainedModel:()=>tu,GPT2LMHeadModel:()=>Wo,GPT2Model:()=>Uo,GPT2PreTrainedModel:()=>eo,GPTBigCodeForCausalLM:()=>E,GPTBigCodeModel:()=>h,GPTBigCodePreTrainedModel:()=>no,GPTJForCausalLM:()=>Xo,GPTJModel:()=>Qo,GPTJPreTrainedModel:()=>so,GPTNeoForCausalLM:()=>ro,GPTNeoModel:()=>In,GPTNeoPreTrainedModel:()=>to,GPTNeoXForCausalLM:()=>qo,GPTNeoXModel:()=>Ho,GPTNeoXPreTrainedModel:()=>An,Gemma2ForCausalLM:()=>ww,Gemma2Model:()=>gw,Gemma2PreTrainedModel:()=>vc,Gemma3ForCausalLM:()=>bw,Gemma3Model:()=>Mw,Gemma3PreTrainedModel:()=>xc,Gemma3nForConditionalGeneration:()=>nn,Gemma3nPreTrainedModel:()=>Wi,GemmaForCausalLM:()=>fw,GemmaModel:()=>_w,GemmaPreTrainedModel:()=>yc,GlmForCausalLM:()=>rw,GlmModel:()=>tw,GlmPreTrainedModel:()=>mc,GraniteForCausalLM:()=>pw,GraniteModel:()=>dw,GranitePreTrainedModel:()=>Mc,GroundingDinoForObjectDetection:()=>mb,GroundingDinoPreTrainedModel:()=>hb,GroupViTModel:()=>Yw,GroupViTPreTrainedModel:()=>Jw,HeliumForCausalLM:()=>ew,HeliumModel:()=>Zg,HeliumPreTrainedModel:()=>hc,HieraForImageClassification:()=>AM,HieraModel:()=>IM,HieraPreTrainedModel:()=>Xc,HubertForCTC:()=>Wb,HubertForSequenceClassification:()=>Gb,HubertModel:()=>Ub,HubertPreTrainedModel:()=>Zx,IJepaForImageClassification:()=>Vw,IJepaModel:()=>Nw,IJepaPreTrainedModel:()=>Fc,Idefics3ForConditionalGeneration:()=>En,Idefics3PreTrainedModel:()=>on,ImageMattingOutput:()=>cv,JAISLMHeadModel:()=>Ko,JAISModel:()=>Go,JAISPreTrainedModel:()=>kn,JinaCLIPModel:()=>No,JinaCLIPPreTrainedModel:()=>Yn,JinaCLIPTextModel:()=>Vo,JinaCLIPVisionModel:()=>Sn,Lfm2ForCausalLM:()=>yr,Lfm2Model:()=>Gt,Lfm2PreTrainedModel:()=>Ot,LiteWhisperForConditionalGeneration:()=>Fo,LlamaForCausalLM:()=>De,LlamaModel:()=>Pe,LlamaPreTrainedModel:()=>ce,LlavaForConditionalGeneration:()=>Xn,LlavaOnevisionForConditionalGeneration:()=>zi,LlavaPreTrainedModel:()=>Qn,LlavaQwen2ForCausalLM:()=>Ui,LongT5ForConditionalGeneration:()=>br,LongT5Model:()=>_r,LongT5PreTrainedModel:()=>Wt,M2M100ForConditionalGeneration:()=>Tb,M2M100Model:()=>xb,M2M100PreTrainedModel:()=>lu,MBartForCausalLM:()=>ur,MBartForConditionalGeneration:()=>Ir,MBartForSequenceClassification:()=>ps,MBartModel:()=>Cs,MBartPreTrainedModel:()=>zr,MPNetForMaskedLM:()=>vn,MPNetForQuestionAnswering:()=>I,MPNetForSequenceClassification:()=>xn,MPNetForTokenClassification:()=>pe,MPNetModel:()=>yn,MPNetPreTrainedModel:()=>Ps,MT5ForConditionalGeneration:()=>Lr,MT5Model:()=>fr,MT5PreTrainedModel:()=>ir,MarianMTModel:()=>vb,MarianModel:()=>yb,MarianPreTrainedModel:()=>au,MaskFormerForInstanceSegmentation:()=>eb,MaskFormerModel:()=>ZM,MaskFormerPreTrainedModel:()=>eu,MaskedLMOutput:()=>Ar,Metric3DForDepthEstimation:()=>XM,Metric3DPreTrainedModel:()=>QM,Metric3Dv2ForDepthEstimation:()=>YM,Metric3Dv2PreTrainedModel:()=>JM,MgpstrForSceneTextRecognition:()=>jy,MgpstrModelOutput:()=>By,MgpstrPreTrainedModel:()=>Ry,MimiDecoderModel:()=>Jy,MimiDecoderOutput:()=>qy,MimiEncoderModel:()=>Xy,MimiEncoderOutput:()=>Hy,MimiModel:()=>Qy,MimiPreTrainedModel:()=>la,MistralForCausalLM:()=>oy,MistralModel:()=>ny,MistralPreTrainedModel:()=>uu,MobileBertForMaskedLM:()=>Vs,MobileBertForQuestionAnswering:()=>Us,MobileBertForSequenceClassification:()=>Es,MobileBertModel:()=>Xt,MobileBertPreTrainedModel:()=>et,MobileLLMForCausalLM:()=>iw,MobileLLMModel:()=>ow,MobileLLMPreTrainedModel:()=>fc,MobileNetV1ForImageClassification:()=>xy,MobileNetV1ForSemanticSegmentation:()=>Ty,MobileNetV1Model:()=>vy,MobileNetV1PreTrainedModel:()=>na,MobileNetV2ForImageClassification:()=>Py,MobileNetV2ForSemanticSegmentation:()=>Cy,MobileNetV2Model:()=>Ey,MobileNetV2PreTrainedModel:()=>oa,MobileNetV3ForImageClassification:()=>$y,MobileNetV3ForSemanticSegmentation:()=>ky,MobileNetV3Model:()=>Sy,MobileNetV3PreTrainedModel:()=>ia,MobileNetV4ForImageClassification:()=>Ay,MobileNetV4ForSemanticSegmentation:()=>Fy,MobileNetV4Model:()=>Iy,MobileNetV4PreTrainedModel:()=>aa,MobileViTForImageClassification:()=>nM,MobileViTModel:()=>sM,MobileViTPreTrainedModel:()=>zc,MobileViTV2ForImageClassification:()=>iM,MobileViTV2Model:()=>oM,MobileViTV2PreTrainedModel:()=>Bc,ModelOutput:()=>be,ModernBertDecoderForCausalLM:()=>Pr,ModernBertDecoderModel:()=>Mr,ModernBertDecoderPreTrainedModel:()=>wt,ModernBertForMaskedLM:()=>ot,ModernBertForSequenceClassification:()=>It,ModernBertForTokenClassification:()=>St,ModernBertModel:()=>Ye,ModernBertPreTrainedModel:()=>Oe,Moondream1ForConditionalGeneration:()=>Bi,MoonshineForConditionalGeneration:()=>Li,MoonshineModel:()=>pc,MoonshinePreTrainedModel:()=>Oo,MptForCausalLM:()=>Lw,MptModel:()=>Dw,MptPreTrainedModel:()=>kc,MultiModalityCausalLM:()=>zy,MultiModalityPreTrainedModel:()=>Ly,MusicgenForCausalLM:()=>sT,MusicgenForConditionalGeneration:()=>wu,MusicgenModel:()=>rT,MusicgenPreTrainedModel:()=>gu,NeoBertForMaskedLM:()=>Ze,NeoBertForQuestionAnswering:()=>Je,NeoBertForSequenceClassification:()=>Ke,NeoBertForTokenClassification:()=>nt,NeoBertModel:()=>xe,NeoBertPreTrainedModel:()=>Qe,NomicBertModel:()=>us,NomicBertPreTrainedModel:()=>jr,OPTForCausalLM:()=>Bw,OPTModel:()=>zw,OPTPreTrainedModel:()=>Ic,Olmo2ForCausalLM:()=>uw,Olmo2Model:()=>cw,Olmo2PreTrainedModel:()=>wc,OlmoForCausalLM:()=>lw,OlmoModel:()=>aw,OlmoPreTrainedModel:()=>gc,OpenELMForCausalLM:()=>vw,OpenELMModel:()=>yw,OpenELMPreTrainedModel:()=>Tc,OwlViTForObjectDetection:()=>lM,OwlViTModel:()=>aM,OwlViTPreTrainedModel:()=>Rc,Owlv2ForObjectDetection:()=>uM,Owlv2Model:()=>cM,Owlv2PreTrainedModel:()=>jc,PaliGemmaForConditionalGeneration:()=>Vi,PaliGemmaPreTrainedModel:()=>Ni,PatchTSMixerForPrediction:()=>Wy,PatchTSMixerModel:()=>Uy,PatchTSMixerPreTrainedModel:()=>bu,PatchTSTForPrediction:()=>Vy,PatchTSTModel:()=>Ny,PatchTSTPreTrainedModel:()=>Mu,Phi3ForCausalLM:()=>Aw,Phi3Model:()=>Iw,Phi3PreTrainedModel:()=>Sc,Phi3VForCausalLM:()=>Pn,Phi3VPreTrainedModel:()=>Gi,PhiForCausalLM:()=>kw,PhiModel:()=>$w,PhiPreTrainedModel:()=>Cc,PreTrainedModel:()=>W,PretrainedMixin:()=>jt,PvtForImageClassification:()=>Kw,PvtModel:()=>Gw,PvtPreTrainedModel:()=>Oc,PyAnnoteForAudioFrameClassification:()=>kb,PyAnnoteModel:()=>$b,PyAnnotePreTrainedModel:()=>cu,QuestionAnsweringModelOutput:()=>Br,Qwen2ForCausalLM:()=>Tw,Qwen2Model:()=>xw,Qwen2PreTrainedModel:()=>Ec,Qwen2VLForConditionalGeneration:()=>Sw,Qwen2VLPreTrainedModel:()=>Cw,Qwen3ForCausalLM:()=>Pw,Qwen3Model:()=>Ew,Qwen3PreTrainedModel:()=>Pc,RFDetrForObjectDetection:()=>vM,RFDetrModel:()=>yM,RFDetrObjectDetectionOutput:()=>xM,RFDetrPreTrainedModel:()=>Kc,RTDetrForObjectDetection:()=>gM,RTDetrModel:()=>fM,RTDetrObjectDetectionOutput:()=>Jo,RTDetrPreTrainedModel:()=>Wc,RTDetrV2ForObjectDetection:()=>MM,RTDetrV2Model:()=>wM,RTDetrV2ObjectDetectionOutput:()=>bM,RTDetrV2PreTrainedModel:()=>Gc,ResNetForImageClassification:()=>OM,ResNetModel:()=>FM,ResNetPreTrainedModel:()=>Jc,RoFormerForMaskedLM:()=>Xs,RoFormerForQuestionAnswering:()=>Zs,RoFormerForSequenceClassification:()=>Js,RoFormerForTokenClassification:()=>Ys,RoFormerModel:()=>Cr,RoFormerPreTrainedModel:()=>qt,RobertaForMaskedLM:()=>Po,RobertaForQuestionAnswering:()=>Ci,RobertaForSequenceClassification:()=>Ei,RobertaForTokenClassification:()=>Pi,RobertaModel:()=>Ti,RobertaPreTrainedModel:()=>en,SamImageSegmentationOutput:()=>bb,SamModel:()=>Mb,SamPreTrainedModel:()=>wb,SapiensForDepthEstimation:()=>GM,SapiensForNormalEstimation:()=>KM,SapiensForSemanticSegmentation:()=>WM,SapiensPreTrainedModel:()=>Yi,SegformerForImageClassification:()=>fy,SegformerForSemanticSegmentation:()=>gy,SegformerModel:()=>tT,SegformerPreTrainedModel:()=>sa,Seq2SeqLMOutput:()=>pT,SequenceClassifierOutput:()=>Tt,SiglipModel:()=>qi,SiglipPreTrainedModel:()=>Jn,SiglipTextModel:()=>Ro,SiglipVisionModel:()=>jo,SmolLM3ForCausalLM:()=>Yg,SmolLM3Model:()=>Qi,SmolLM3PreTrainedModel:()=>Ls,SmolVLMForConditionalGeneration:()=>Do,SnacDecoderModel:()=>o0,SnacEncoderModel:()=>n0,SnacModel:()=>s0,SnacPreTrainedModel:()=>ua,SpeechT5ForSpeechToText:()=>Zb,SpeechT5ForTextToSpeech:()=>ey,SpeechT5HifiGan:()=>ty,SpeechT5Model:()=>eT,SpeechT5PreTrainedModel:()=>ta,SqueezeBertForMaskedLM:()=>le,SqueezeBertForQuestionAnswering:()=>Te,SqueezeBertForSequenceClassification:()=>de,SqueezeBertModel:()=>Y,SqueezeBertPreTrainedModel:()=>N,StableLmForCausalLM:()=>My,StableLmModel:()=>wy,StableLmPreTrainedModel:()=>_u,Starcoder2ForCausalLM:()=>cy,Starcoder2Model:()=>ly,Starcoder2PreTrainedModel:()=>pu,StyleTextToSpeech2Model:()=>Yb,StyleTextToSpeech2PreTrainedModel:()=>Jb,Swin2SRForImageSuperResolution:()=>RM,Swin2SRModel:()=>BM,Swin2SRPreTrainedModel:()=>Yc,SwinForImageClassification:()=>LM,SwinForSemanticSegmentation:()=>zM,SwinModel:()=>DM,SwinPreTrainedModel:()=>Ji,T5ForConditionalGeneration:()=>sr,T5Model:()=>Lt,T5PreTrainedModel:()=>Bt,TableTransformerForObjectDetection:()=>CM,TableTransformerModel:()=>PM,TableTransformerObjectDetectionOutput:()=>SM,TableTransformerPreTrainedModel:()=>qc,TokenClassifierOutput:()=>vr,TrOCRForCausalLM:()=>sy,TrOCRPreTrainedModel:()=>ry,UltravoxModel:()=>yu,UltravoxPreTrainedModel:()=>Gy,UniSpeechForCTC:()=>Ob,UniSpeechForSequenceClassification:()=>Db,UniSpeechModel:()=>Fb,UniSpeechPreTrainedModel:()=>Zi,UniSpeechSatForAudioFrameClassification:()=>Rb,UniSpeechSatForCTC:()=>zb,UniSpeechSatForSequenceClassification:()=>Bb,UniSpeechSatModel:()=>Lb,UniSpeechSatPreTrainedModel:()=>Yo,ViTForImageClassification:()=>jw,ViTMAEModel:()=>qw,ViTMAEPreTrainedModel:()=>Hw,ViTMSNForImageClassification:()=>Xw,ViTMSNModel:()=>Qw,ViTMSNPreTrainedModel:()=>Dc,ViTModel:()=>Rw,ViTPreTrainedModel:()=>Ac,VisionEncoderDecoderModel:()=>Tn,VitMatteForImageMatting:()=>rM,VitMattePreTrainedModel:()=>tM,VitPoseForPoseEstimation:()=>Ww,VitPosePreTrainedModel:()=>Uw,VitsModel:()=>mu,VitsModelOutput:()=>uv,VitsPreTrainedModel:()=>_y,VoxtralForConditionalGeneration:()=>Ky,Wav2Vec2BertForCTC:()=>Nb,Wav2Vec2BertForSequenceClassification:()=>Vb,Wav2Vec2BertModel:()=>jb,Wav2Vec2BertPreTrainedModel:()=>ea,Wav2Vec2ForAudioFrameClassification:()=>Sb,Wav2Vec2ForCTC:()=>Pb,Wav2Vec2ForSequenceClassification:()=>Cb,Wav2Vec2Model:()=>Eb,Wav2Vec2PreTrainedModel:()=>an,WavLMForAudioFrameClassification:()=>Xb,WavLMForCTC:()=>Hb,WavLMForSequenceClassification:()=>qb,WavLMForXVector:()=>Qb,WavLMModel:()=>Kb,WavLMPreTrainedModel:()=>oo,WeSpeakerResNetModel:()=>Ab,WeSpeakerResNetPreTrainedModel:()=>Ib,WhisperForConditionalGeneration:()=>Ao,WhisperModel:()=>sn,WhisperPreTrainedModel:()=>qn,XLMForQuestionAnswering:()=>Ai,XLMForSequenceClassification:()=>ki,XLMForTokenClassification:()=>Ii,XLMModel:()=>Si,XLMPreTrainedModel:()=>tn,XLMRobertaForMaskedLM:()=>Oi,XLMRobertaForQuestionAnswering:()=>$o,XLMRobertaForSequenceClassification:()=>Co,XLMRobertaForTokenClassification:()=>So,XLMRobertaModel:()=>Fi,XLMRobertaPreTrainedModel:()=>rn,XLMWithLMHeadModel:()=>$i,XVectorOutput:()=>lv,YolosForObjectDetection:()=>fb,YolosModel:()=>_b,YolosObjectDetectionOutput:()=>gb,YolosPreTrainedModel:()=>iu});var s=t("./src/configs.js"),o=t("./src/backends/onnx.js"),n=t("./src/utils/dtypes.js"),i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),c=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),d=t("./src/generation/configuration_utils.js"),u=t("./src/utils/tensor.js"),f=t("./src/utils/image.js"),_=t("./src/utils/maths.js"),b=t("./src/generation/stopping_criteria.js"),k=t("./src/generation/logits_sampler.js"),g=t("./src/env.js"),M=t("./src/models/whisper/generation_whisper.js"),$=t("./src/models/whisper/common_whisper.js");const v={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11,ImageAudioTextToText:12},y=new Map,T=new Map,x=new Map;async function P(w,C,D){var Fr;let oe=((Fr=D.config)==null?void 0:Fr["transformers.js_config"])??{},fe=D.device??oe.device;fe&&typeof fe!="string"&&(fe.hasOwnProperty(C)?fe=fe[C]:(console.warn(`device not specified for "${C}". Using the default device.`),fe=null));const he=fe??(g.apis.IS_NODE_ENV?"cpu":"wasm"),Ce=(0,o.deviceToExecutionProviders)(he),Le=oe.device_config??{};Le.hasOwnProperty(he)&&(oe={...oe,...Le[he]});let Ue=D.dtype??oe.dtype;if(typeof Ue!="string"&&(Ue&&Ue.hasOwnProperty(C)?Ue=Ue[C]:(Ue=n.DEFAULT_DEVICE_DTYPE_MAPPING[he]??n.DATA_TYPES.fp32,console.warn(`dtype not specified for "${C}". Using the default dtype (${Ue}) for this device (${he}).`))),Ue===n.DATA_TYPES.auto){let kt=oe.dtype;typeof kt!="string"&&(kt=kt==null?void 0:kt[C]),kt&&kt!==n.DATA_TYPES.auto&&n.DATA_TYPES.hasOwnProperty(kt)?Ue=kt:Ue=n.DEFAULT_DEVICE_DTYPE_MAPPING[he]??n.DATA_TYPES.fp32}const Xe=Ue;if(n.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Xe)){if(Xe===n.DATA_TYPES.fp16&&he==="webgpu"&&!await(0,n.isWebGpuFp16Supported)())throw new Error(`The device (${he}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Xe}. Should be one of: ${Object.keys(n.DATA_TYPES).join(", ")}`);const mt=oe.kv_cache_dtype,bt=mt?typeof mt=="string"?mt:mt[Xe]??"float32":void 0;if(bt&&!["float32","float16"].includes(bt))throw new Error(`Invalid kv_cache_dtype: ${bt}. Should be one of: float32, float16`);const yt={dtype:Xe,kv_cache_dtype:bt,device:he},Ft=n.DEFAULT_DTYPE_SUFFIX_MAPPING[Xe],_t=`${C}${Ft}.onnx`,$t=`${D.subfolder??""}/${_t}`,ut={...D.session_options};ut.executionProviders??(ut.executionProviders=Ce);const At=oe.free_dimension_overrides;At?ut.freeDimensionOverrides??(ut.freeDimensionOverrides=At):he.startsWith("webnn")&&!ut.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${he}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const Ht=g.apis.IS_NODE_ENV&&g.env.useFSCache,er=(0,l.getModelFile)(w,$t,!0,D,Ht),dr=D.use_external_data_format??oe.use_external_data_format;let lr=[];if(dr){let kt;typeof dr=="object"?dr.hasOwnProperty(_t)?kt=dr[_t]:dr.hasOwnProperty(C)?kt=dr[C]:kt=!1:kt=dr;const xr=+kt;if(xr>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${xr}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let is=0;is{const Dn=await(0,l.getModelFile)(w,Zr,!0,D,Ht);hs(Dn instanceof Uint8Array?{path:On,data:Dn}:On)}))}}else ut.externalData!==void 0&&(lr=ut.externalData.map(async kt=>{if(typeof kt.data=="string"){const xr=await(0,l.getModelFile)(w,kt.data,!0,D);return{...kt,data:xr}}return kt}));if(lr.length>0){const kt=await Promise.all(lr);g.apis.IS_NODE_ENV||(ut.externalData=kt)}if(he==="webgpu"){const kt=(0,s.getCacheShapes)(D.config,{prefix:"present"});if(Object.keys(kt).length>0&&!(0,o.isONNXProxy)()){const xr={};for(const is in kt)xr[is]="gpu-buffer";ut.preferredOutputLocation=xr}}return{buffer_or_path:await er,session_options:ut,session_config:yt}}async function O(w,C,D){return Object.fromEntries(await Promise.all(Object.keys(C).map(async oe=>{const{buffer_or_path:fe,session_options:he,session_config:Ce}=await P(w,C[oe],D),Le=await(0,o.createInferenceSession)(fe,he,Ce);return[oe,Le]})))}async function L(w,C,D){return Object.fromEntries(await Promise.all(Object.keys(C).map(async oe=>{const fe=await(0,l.getModelJSON)(w,C[oe],!1,D);return[oe,fe]})))}function G(w,C){const D=Object.create(null),oe=[];for(const Ce of w.inputNames){const Le=C[Ce];if(!(Le instanceof u.Tensor)){oe.push(Ce);continue}D[Ce]=(0,o.isONNXProxy)()?Le.clone():Le}if(oe.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${oe.join(", ")}.`);const fe=Object.keys(C).length,he=w.inputNames.length;if(fe>he){let Ce=Object.keys(C).filter(Le=>!w.inputNames.includes(Le));console.warn(`WARNING: Too many inputs were provided (${fe} > ${he}). The following inputs will be ignored: "${Ce.join(", ")}".`)}return D}let K=Promise.resolve();async function R(w,C){const D=G(w,C);try{const oe=Object.fromEntries(Object.entries(D).map(([Ce,Le])=>[Ce,Le.ort_tensor])),fe=()=>w.run(oe),he=await(g.apis.IS_BROWSER_ENV||g.apis.IS_WEBWORKER_ENV?K=K.then(fe):fe());return te(he)}catch(oe){const fe=Object.fromEntries(Object.entries(D).map(([he,Ce])=>{const Le={type:Ce.type,dims:Ce.dims,location:Ce.location};return Le.location!=="gpu-buffer"&&(Le.data=Ce.data),[he,Le]}));throw console.error(`An error occurred during model execution: "${oe}".`),console.error("Inputs given to model:",fe),oe}}function te(w){for(let C in w)(0,o.isONNXTensor)(w[C])?w[C]=new u.Tensor(w[C]):typeof w[C]=="object"&&te(w[C]);return w}function H(w){if(w instanceof u.Tensor)return w;if(w.length===0)throw Error("items must be non-empty");if(Array.isArray(w[0])){if(w.some(C=>C.length!==w[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new u.Tensor("int64",BigInt64Array.from(w.flat().map(C=>BigInt(C))),[w.length,w[0].length])}else return new u.Tensor("int64",BigInt64Array.from(w.map(C=>BigInt(C))),[1,w.length])}function ee(w){return new u.Tensor("bool",[w],[1])}async function Z(w,C){let{encoder_outputs:D,input_ids:oe,decoder_input_ids:fe,...he}=C;if(!D){const Le=(0,a.pick)(C,w.sessions.model.inputNames);D=(await ne(w,Le)).last_hidden_state}return he.input_ids=fe,he.encoder_hidden_states=D,w.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(he.encoder_attention_mask=C.attention_mask),await ue(w,he,!0)}async function ne(w,C){const D=w.sessions.model,oe=(0,a.pick)(C,D.inputNames);if(D.inputNames.includes("inputs_embeds")&&!oe.inputs_embeds){if(!C.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");oe.inputs_embeds=await w.encode_text({input_ids:C.input_ids})}if(D.inputNames.includes("token_type_ids")&&!oe.token_type_ids){if(!oe.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");oe.token_type_ids=(0,u.zeros_like)(oe.input_ids)}if(D.inputNames.includes("pixel_mask")&&!oe.pixel_mask){if(!oe.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const fe=oe.pixel_values.dims;oe.pixel_mask=(0,u.ones)([fe[0],fe[2],fe[3]])}return await R(D,oe)}async function me(w,C){const D=await w.encode(C);return await w.decode(D)}async function ue(w,C,D=!1){const oe=w.sessions[D?"decoder_model_merged":"model"],{past_key_values:fe,...he}=C;if(oe.inputNames.includes("use_cache_branch")&&(he.use_cache_branch=ee(!!fe)),oe.inputNames.includes("position_ids")&&he.attention_mask&&!he.position_ids){const Le=["paligemma","gemma3_text","gemma3"].includes(w.config.model_type)?1:0;he.position_ids=ze(he,fe,Le)}w.addPastKeyValues(he,fe);const Ce=(0,a.pick)(he,oe.inputNames);return await R(oe,Ce)}function j({modality_token_id:w,inputs_embeds:C,modality_features:D,input_ids:oe,attention_mask:fe}){const he=oe.tolist().map(Xe=>Xe.reduce((mt,bt,yt)=>(bt==w&&mt.push(yt),mt),[])),Ce=he.reduce((Xe,mt)=>Xe+mt.length,0),Le=D.dims[0];if(Ce!==Le)throw new Error(`Number of tokens and features do not match: tokens: ${Ce}, features ${Le}`);let Ue=0;for(let Xe=0;Xehe.dims[1]||fe[fe.at(-1)])),{...D,decoder_input_ids:H(C)}}function X(w,...C){return w.config.is_encoder_decoder?Ie(w,...C):Ge(w,...C)}function ae(w,C,D,oe){const fe=!!D.past_key_values;return oe.guidance_scale!==null&&oe.guidance_scale>1&&(fe?D.input_ids=(0,u.cat)([D.input_ids,D.input_ids],0):(D.input_ids=(0,u.cat)([D.input_ids,(0,u.full_like)(D.input_ids,BigInt(oe.pad_token_id))],0),D.attention_mask=(0,u.cat)([D.attention_mask,(0,u.full_like)(D.attention_mask,0n)],0))),(fe||!D.pixel_values)&&(D.pixel_values=(0,u.full)([0,0,3,384,384],1)),fe&&(D.images_seq_mask=new u.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),D.images_emb_mask=new u.Tensor("bool",new Array(0).fill(!1),[1,1,0])),D}class W extends i.Callable{constructor(D,oe,fe){super();J(this,"main_input_name","input_ids");J(this,"forward_params",["input_ids","attention_mask"]);this.config=D,this.sessions=oe,this.configs=fe;const he=x.get(this.constructor),Ce=y.get(he);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ce){case v.DecoderOnly:this.can_generate=!0,this._forward=ue,this._prepare_inputs_for_generation=Ge;break;case v.Seq2Seq:case v.Vision2Seq:case v.Musicgen:this.can_generate=!0,this._forward=Z,this._prepare_inputs_for_generation=Ie;break;case v.EncoderDecoder:this._forward=Z;break;case v.ImageTextToText:this.can_generate=!0,this._forward=ie,this._prepare_inputs_for_generation=X;break;case v.AudioTextToText:this.can_generate=!0,this._forward=_e,this._prepare_inputs_for_generation=X;break;case v.Phi3V:case v.ImageAudioTextToText:this.can_generate=!0,this._prepare_inputs_for_generation=X;break;case v.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=ae;break;case v.AutoEncoder:this._forward=me;break;default:this._forward=ne;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var oe;const D=[];for(const fe of Object.values(this.sessions))(oe=fe==null?void 0:fe.handler)!=null&&oe.dispose&&D.push(fe.handler.dispose());return await Promise.all(D)}static async from_pretrained(D,{progress_callback:oe=null,config:fe=null,cache_dir:he=null,local_files_only:Ce=!1,revision:Le="main",model_file_name:Ue=null,subfolder:Xe="onnx",device:mt=null,dtype:bt=null,use_external_data_format:yt=null,session_options:Ft={}}={}){let _t={progress_callback:oe,config:fe,cache_dir:he,local_files_only:Ce,revision:Le,model_file_name:Ue,subfolder:Xe,device:mt,dtype:bt,use_external_data_format:yt,session_options:Ft};const $t=x.get(this),ut=y.get($t);fe=_t.config=await s.AutoConfig.from_pretrained(D,_t);let At;if(ut===v.DecoderOnly)At=await Promise.all([O(D,{model:_t.model_file_name??"model"},_t),L(D,{generation_config:"generation_config.json"},_t)]);else if(ut===v.Seq2Seq||ut===v.Vision2Seq)At=await Promise.all([O(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},_t),L(D,{generation_config:"generation_config.json"},_t)]);else if(ut===v.MaskGeneration)At=await Promise.all([O(D,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},_t)]);else if(ut===v.EncoderDecoder)At=await Promise.all([O(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},_t)]);else if(ut===v.ImageTextToText){const Ht={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};fe.is_encoder_decoder&&(Ht.model="encoder_model"),At=await Promise.all([O(D,Ht,_t),L(D,{generation_config:"generation_config.json"},_t)])}else if(ut===v.AudioTextToText){const Ht={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};At=await Promise.all([O(D,Ht,_t),L(D,{generation_config:"generation_config.json"},_t)])}else if(ut===v.ImageAudioTextToText){const Ht={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};At=await Promise.all([O(D,Ht,_t),L(D,{generation_config:"generation_config.json"},_t)])}else if(ut===v.Musicgen)At=await Promise.all([O(D,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},_t),L(D,{generation_config:"generation_config.json"},_t)]);else if(ut===v.MultiModality)At=await Promise.all([O(D,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},_t),L(D,{generation_config:"generation_config.json"},_t)]);else if(ut===v.Phi3V)At=await Promise.all([O(D,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},_t),L(D,{generation_config:"generation_config.json"},_t)]);else if(ut===v.AutoEncoder)At=await Promise.all([O(D,{encoder_model:"encoder_model",decoder_model:"decoder_model"},_t)]);else{if(ut!==v.EncoderOnly){const Ht=$t??(fe==null?void 0:fe.model_type);Ht!=="custom"&&console.warn(`Model type for '${Ht}' not found, assuming encoder-only architecture. Please report this at ${c.GITHUB_ISSUE_URL}.`)}At=await Promise.all([O(D,{model:_t.model_file_name??"model"},_t)])}return new this(fe,...At)}async _call(D){return await this.forward(D)}async forward(D){return await this._forward(this,D)}get generation_config(){var D;return((D=this.configs)==null?void 0:D.generation_config)??null}_get_logits_warper(D){const oe=new p.LogitsProcessorList;return D.temperature!==null&&D.temperature!==1&&oe.push(new p.TemperatureLogitsWarper(D.temperature)),D.top_k!==null&&D.top_k!==0&&oe.push(new p.TopKLogitsWarper(D.top_k)),D.top_p!==null&&D.top_p<1&&oe.push(new p.TopPLogitsWarper(D.top_p)),oe}_get_logits_processor(D,oe,fe=null){const he=new p.LogitsProcessorList;if(D.repetition_penalty!==null&&D.repetition_penalty!==1&&he.push(new p.RepetitionPenaltyLogitsProcessor(D.repetition_penalty)),D.no_repeat_ngram_size!==null&&D.no_repeat_ngram_size>0&&he.push(new p.NoRepeatNGramLogitsProcessor(D.no_repeat_ngram_size)),D.bad_words_ids!==null&&he.push(new p.NoBadWordsLogitsProcessor(D.bad_words_ids,D.eos_token_id)),D.min_length!==null&&D.eos_token_id!==null&&D.min_length>0&&he.push(new p.MinLengthLogitsProcessor(D.min_length,D.eos_token_id)),D.min_new_tokens!==null&&D.eos_token_id!==null&&D.min_new_tokens>0&&he.push(new p.MinNewTokensLengthLogitsProcessor(oe,D.min_new_tokens,D.eos_token_id)),D.forced_bos_token_id!==null&&he.push(new p.ForcedBOSTokenLogitsProcessor(D.forced_bos_token_id)),D.forced_eos_token_id!==null&&he.push(new p.ForcedEOSTokenLogitsProcessor(D.max_length,D.forced_eos_token_id)),D.begin_suppress_tokens!==null){const Ce=oe>1||D.forced_bos_token_id===null?oe:oe+1;he.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ce))}return D.guidance_scale!==null&&D.guidance_scale>1&&he.push(new p.ClassifierFreeGuidanceLogitsProcessor(D.guidance_scale)),fe!==null&&he.extend(fe),he}_prepare_generation_config(D,oe,fe=d.GenerationConfig){const he={...this.config};for(const Le of["decoder","generator","text_config"])Le in he&&Object.assign(he,he[Le]);const Ce=new fe(he);return Object.assign(Ce,this.generation_config??{}),D&&Object.assign(Ce,D),oe&&Object.assign(Ce,(0,a.pick)(oe,Object.getOwnPropertyNames(Ce))),Ce}_get_stopping_criteria(D,oe=null){const fe=new b.StoppingCriteriaList;return D.max_length!==null&&fe.push(new b.MaxLengthCriteria(D.max_length,this.config.max_position_embeddings??null)),D.eos_token_id!==null&&fe.push(new b.EosTokenCriteria(D.eos_token_id)),oe&&fe.extend(oe),fe}_validate_model_class(){if(!this.can_generate){const D=[Tu,Eu,xu,vu],oe=x.get(this.constructor),fe=new Set,he=this.config.model_type;for(const Le of D){const Ue=Le.get(he);Ue&&fe.add(Ue[0])}let Ce=`The current model class (${oe}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw fe.size>0&&(Ce+=` Please use the following class instead: ${[...fe].join(", ")}`),Error(Ce)}}prepare_inputs_for_generation(...D){return this._prepare_inputs_for_generation(this,...D)}_update_model_kwargs_for_generation({generated_input_ids:D,outputs:oe,model_inputs:fe,is_encoder_decoder:he}){return fe.past_key_values=this.getPastKeyValues(oe,fe.past_key_values),fe.input_ids=new u.Tensor("int64",D.flat(),[D.length,1]),he||(fe.attention_mask=(0,u.cat)([fe.attention_mask,(0,u.ones)([fe.attention_mask.dims[0],1])],1)),fe.position_ids=null,fe}_prepare_model_inputs({inputs:D,bos_token_id:oe,model_kwargs:fe}){const he=(0,a.pick)(fe,this.forward_params),Ce=this.main_input_name;if(Ce in he){if(D)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else he[Ce]=D;return{inputs_tensor:he[Ce],model_inputs:he,model_input_name:Ce}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:D,model_inputs:oe,model_input_name:fe,generation_config:he}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!oe.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Le,pixel_values:Ue,attention_mask:Xe,...mt}=oe,bt=await this._prepare_inputs_embeds(oe);oe={...mt,...(0,a.pick)(bt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ce}=await ne(this,oe);if(he.guidance_scale!==null&&he.guidance_scale>1)Ce=(0,u.cat)([Ce,(0,u.full_like)(Ce,0)],0),"attention_mask"in oe&&(oe.attention_mask=(0,u.cat)([oe.attention_mask,(0,u.zeros_like)(oe.attention_mask)],0));else if(oe.decoder_input_ids){const Le=H(oe.decoder_input_ids).dims[0];if(Le!==Ce.dims[0]){if(Ce.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ce.dims[0]}) than the decoder inputs (${Le}).`);Ce=(0,u.cat)(Array.from({length:Le},()=>Ce),0)}}return oe.encoder_outputs=Ce,oe}_prepare_decoder_input_ids_for_generation({batch_size:D,model_input_name:oe,model_kwargs:fe,decoder_start_token_id:he,bos_token_id:Ce,generation_config:Le}){let{decoder_input_ids:Ue,...Xe}=fe;if(!(Ue instanceof u.Tensor)){if(Ue)Array.isArray(Ue[0])||(Ue=Array.from({length:D},()=>Ue));else if(he??(he=Ce),this.config.model_type==="musicgen")Ue=Array.from({length:D*this.config.decoder.num_codebooks},()=>[he]);else if(Array.isArray(he)){if(he.length!==D)throw new Error(`\`decoder_start_token_id\` expcted to have length ${D} but got ${he.length}`);Ue=he}else Ue=Array.from({length:D},()=>[he]);Ue=H(Ue)}return fe.decoder_attention_mask=(0,u.ones_like)(Ue),{input_ids:Ue,model_inputs:Xe}}async generate({inputs:D=null,generation_config:oe=null,logits_processor:fe=null,stopping_criteria:he=null,streamer:Ce=null,...Le}){this._validate_model_class(),oe=this._prepare_generation_config(oe,Le);let{inputs_tensor:Ue,model_inputs:Xe,model_input_name:mt}=this._prepare_model_inputs({inputs:D,model_kwargs:Le});const bt=this.config.is_encoder_decoder;bt&&("encoder_outputs"in Xe||(Xe=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Ue,model_inputs:Xe,model_input_name:mt,generation_config:oe})));let yt;bt?{input_ids:yt,model_inputs:Xe}=this._prepare_decoder_input_ids_for_generation({batch_size:Xe[mt].dims.at(0),model_input_name:mt,model_kwargs:Xe,decoder_start_token_id:oe.decoder_start_token_id,bos_token_id:oe.bos_token_id,generation_config:oe}):yt=Xe[mt];let Ft=yt.dims.at(-1);oe.max_new_tokens!==null&&(oe.max_length=Ft+oe.max_new_tokens);const _t=this._get_logits_processor(oe,Ft,fe),$t=this._get_stopping_criteria(oe,he),ut=Xe[mt].dims.at(0),At=k.LogitsSampler.getSampler(oe),Ht=new Array(ut).fill(0),er=yt.tolist();Ce&&Ce.put(er);let dr,lr={};for(;;){if(Xe=this.prepare_inputs_for_generation(er,Xe,oe),dr=await this.forward(Xe),oe.output_attentions&&oe.return_dict_in_generate){const Zr=this.getAttentions(dr);for(const hs in Zr)hs in lr||(lr[hs]=[]),lr[hs].push(Zr[hs])}const kt=dr.logits.slice(null,-1,null),xr=_t(er,kt),is=[];for(let Zr=0;ZrZr))break;Xe=this._update_model_kwargs_for_generation({generated_input_ids:is,outputs:dr,model_inputs:Xe,is_encoder_decoder:bt})}Ce&&Ce.end();const wr=this.getPastKeyValues(dr,Xe.past_key_values,!0),Fr=new u.Tensor("int64",er.flat(),[er.length,er[0].length]);if(oe.return_dict_in_generate)return{sequences:Fr,past_key_values:wr,...lr};for(const kt of Object.values(dr))kt.location==="gpu-buffer"&&kt.dispose();return Fr}getPastKeyValues(D,oe,fe=!1){const he=Object.create(null);for(const Ce in D)if(Ce.startsWith("present")){const Le=Ce.replace("present_conv","past_conv").replace("present","past_key_values"),Ue=Ce.includes("encoder");if(Ue&&oe?he[Le]=oe[Le]:he[Le]=D[Ce],oe&&(!Ue||fe)){const Xe=oe[Le];Xe.location==="gpu-buffer"&&Xe.dispose()}}return he}getAttentions(D){const oe={};for(const fe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const he in D)he.startsWith(fe)&&(fe in oe||(oe[fe]=[]),oe[fe].push(D[he]));return oe}addPastKeyValues(D,oe){var fe,he,Ce;if(oe)Object.assign(D,oe);else{const Le=this.sessions.decoder_model_merged??this.sessions.model,Ue=((he=(fe=D[this.main_input_name]??D.attention_mask)==null?void 0:fe.dims)==null?void 0:he[0])??1,Xe=((Ce=Le==null?void 0:Le.config)==null?void 0:Ce.kv_cache_dtype)??"float32",mt=Xe==="float16"?u.DataTypeMap.float16:u.DataTypeMap.float32,bt=(0,s.getCacheShapes)(this.config,{batch_size:Ue});for(const yt in bt){const Ft=bt[yt].reduce((_t,$t)=>_t*$t,1);D[yt]=new u.Tensor(Xe,new mt(Ft),bt[yt])}}}async encode_image({pixel_values:D}){return(await R(this.sessions.vision_encoder,{pixel_values:D})).image_features}async encode_text({input_ids:D}){return(await R(this.sessions.embed_tokens,{input_ids:D})).inputs_embeds}async encode_audio({audio_values:D}){return(await R(this.sessions.audio_encoder,{audio_values:D})).audio_features}}class be{}class ke extends be{constructor({last_hidden_state:C,hidden_states:D=null,attentions:oe=null}){super(),this.last_hidden_state=C,this.hidden_states=D,this.attentions=oe}}class Ee extends W{}class Me extends Ee{}class Se extends Ee{async _call(C){return new Ar(await super._call(C))}}class we extends Ee{async _call(C){return new Tt(await super._call(C))}}class Ae extends Ee{async _call(C){return new vr(await super._call(C))}}class Be extends Ee{async _call(C){return new Br(await super._call(C))}}class Qe extends W{}class xe extends Qe{}class Ze extends Qe{async _call(C){return new Ar(await super._call(C))}}class Ke extends Qe{async _call(C){return new Tt(await super._call(C))}}class nt extends Qe{async _call(C){return new vr(await super._call(C))}}class Je extends Qe{async _call(C){return new Br(await super._call(C))}}class Oe extends W{}class Ye extends Oe{}class ot extends Oe{async _call(C){return new Ar(await super._call(C))}}class It extends Oe{async _call(C){return new Tt(await super._call(C))}}class St extends Oe{async _call(C){return new vr(await super._call(C))}}class wt extends W{}class Mr extends wt{}class Pr extends wt{}class jr extends W{}class us extends jr{}class qt extends W{}class Cr extends qt{}class Xs extends qt{async _call(C){return new Ar(await super._call(C))}}class Js extends qt{async _call(C){return new Tt(await super._call(C))}}class Ys extends qt{async _call(C){return new vr(await super._call(C))}}class Zs extends qt{async _call(C){return new Br(await super._call(C))}}class pt extends W{}class As extends pt{}class Fs extends pt{async _call(C){return new Ar(await super._call(C))}}class Ct extends pt{async _call(C){return new Tt(await super._call(C))}}class Qt extends pt{async _call(C){return new vr(await super._call(C))}}class S extends pt{async _call(C){return new Br(await super._call(C))}}class Q extends W{}class B extends Q{}class q extends Q{async _call(C){return new Ar(await super._call(C))}}class re extends Q{async _call(C){return new Tt(await super._call(C))}}class ge extends Q{async _call(C){return new vr(await super._call(C))}}class Fe extends Q{async _call(C){return new Br(await super._call(C))}}class rt extends W{}class ft extends rt{}class ht extends rt{async _call(C){return new Ar(await super._call(C))}}class vt extends rt{async _call(C){return new Tt(await super._call(C))}}class st extends rt{async _call(C){return new vr(await super._call(C))}}class zt extends rt{async _call(C){return new Br(await super._call(C))}}class Ut extends W{}class Nr extends Ut{}class Xr extends Ut{async _call(C){return new Ar(await super._call(C))}}class rr extends Ut{async _call(C){return new Tt(await super._call(C))}}class Sr extends Ut{async _call(C){return new vr(await super._call(C))}}class $r extends Ut{async _call(C){return new Br(await super._call(C))}}class Vr extends W{}class ds extends Vr{}class kr extends Vr{async _call(C){return new Ar(await super._call(C))}}class Os extends Vr{async _call(C){return new Tt(await super._call(C))}}class Ds extends Vr{async _call(C){return new vr(await super._call(C))}}class Ur extends Vr{async _call(C){return new Br(await super._call(C))}}class Wr extends W{}class ts extends Wr{}class Dr extends Wr{async _call(C){return new Tt(await super._call(C))}}class Ts extends Wr{async _call(C){return new vr(await super._call(C))}}class pr extends Wr{async _call(C){return new Br(await super._call(C))}}class mr extends Wr{async _call(C){return new Ar(await super._call(C))}}class Jr extends W{}class Ns extends Jr{}class Gr extends Jr{async _call(C){return new Ar(await super._call(C))}}class Re extends Jr{async _call(C){return new Tt(await super._call(C))}}class je extends Jr{async _call(C){return new vr(await super._call(C))}}class et extends W{}class Xt extends et{}class Vs extends et{async _call(C){return new Ar(await super._call(C))}}class Es extends et{async _call(C){return new Tt(await super._call(C))}}class Us extends et{async _call(C){return new Br(await super._call(C))}}class Ps extends W{}class yn extends Ps{}class vn extends Ps{async _call(C){return new Ar(await super._call(C))}}class xn extends Ps{async _call(C){return new Tt(await super._call(C))}}class pe extends Ps{async _call(C){return new vr(await super._call(C))}}class I extends Ps{async _call(C){return new Br(await super._call(C))}}class N extends W{}class Y extends N{}class le extends N{async _call(C){return new Ar(await super._call(C))}}class de extends N{async _call(C){return new Tt(await super._call(C))}}class Te extends N{async _call(C){return new Br(await super._call(C))}}class Ne extends W{}class qe extends Ne{}class We extends Ne{async _call(C){return new Tt(await super._call(C))}}class tt extends Ne{async _call(C){return new Br(await super._call(C))}}class Mt extends Ne{async _call(C){return new Ar(await super._call(C))}}class Bt extends W{constructor(){super(...arguments);J(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Lt extends Bt{}class sr extends Bt{}class Wt extends W{}class _r extends Wt{}class br extends Wt{}class ir extends W{}class fr extends ir{}class Lr extends ir{}class Yr extends W{}class Zt extends Yr{}class gr extends Yr{}class Kr extends Yr{async _call(C){return new Tt(await super._call(C))}}class zr extends W{}class Cs extends zr{}class Ir extends zr{}class ps extends zr{async _call(C){return new Tt(await super._call(C))}}class ur extends zr{}class ar extends W{}class hr extends ar{}class nr extends ar{}class Hr extends W{}class Ws extends Hr{}class Hn extends Hr{}class en extends W{}class Ti extends en{}class Po extends en{async _call(C){return new Ar(await super._call(C))}}class Ei extends en{async _call(C){return new Tt(await super._call(C))}}class Pi extends en{async _call(C){return new vr(await super._call(C))}}class Ci extends en{async _call(C){return new Br(await super._call(C))}}class tn extends W{}class Si extends tn{}class $i extends tn{async _call(C){return new Ar(await super._call(C))}}class ki extends tn{async _call(C){return new Tt(await super._call(C))}}class Ii extends tn{async _call(C){return new vr(await super._call(C))}}class Ai extends tn{async _call(C){return new Br(await super._call(C))}}class rn extends W{}class Fi extends rn{}class Oi extends rn{async _call(C){return new Ar(await super._call(C))}}class Co extends rn{async _call(C){return new Tt(await super._call(C))}}class So extends rn{async _call(C){return new vr(await super._call(C))}}class $o extends rn{async _call(C){return new Br(await super._call(C))}}class ko extends W{}class Di extends ko{}class Io extends ko{}class qn extends W{constructor(){super(...arguments);J(this,"requires_attention_mask",!1);J(this,"main_input_name","input_features");J(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class sn extends qn{}class Ao extends qn{_prepare_generation_config(C,D){return super._prepare_generation_config(C,D,M.WhisperGenerationConfig)}_retrieve_init_tokens(C){const D=[C.decoder_start_token_id];let oe=C.language;const fe=C.task;if(C.is_multilingual){oe||(console.warn("No language specified - defaulting to English (en)."),oe="en");const Ce=`<|${(0,$.whisper_language_to_code)(oe)}|>`;D.push(C.lang_to_id[Ce]),D.push(C.task_to_id[fe??"transcribe"])}else if(oe||fe)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!C.return_timestamps&&C.no_timestamps_token_id&&D.at(-1)!==C.no_timestamps_token_id?D.push(C.no_timestamps_token_id):C.return_timestamps&&D.at(-1)===C.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),D.pop()),D.filter(he=>he!=null)}async generate({inputs:C=null,generation_config:D=null,logits_processor:oe=null,stopping_criteria:fe=null,...he}){D=this._prepare_generation_config(D,he);const Ce=he.decoder_input_ids??this._retrieve_init_tokens(D);if(D.return_timestamps&&(oe??(oe=new p.LogitsProcessorList),oe.push(new p.WhisperTimeStampLogitsProcessor(D,Ce))),D.begin_suppress_tokens&&(oe??(oe=new p.LogitsProcessorList),oe.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ce.length))),D.return_token_timestamps){if(!D.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");D.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),D.output_attentions=!0,D.return_dict_in_generate=!0}const Le=await super.generate({inputs:C,generation_config:D,logits_processor:oe,decoder_input_ids:Ce,...he});return D.return_token_timestamps&&(Le.token_timestamps=this._extract_token_timestamps(Le,D.alignment_heads,D.num_frames)),Le}_extract_token_timestamps(C,D,oe=null,fe=.02){if(!C.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");oe==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let he=this.config.median_filter_width;he===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),he=7);const Ce=C.cross_attentions,Le=Array.from({length:this.config.decoder_layers},($t,ut)=>(0,u.cat)(Ce.map(At=>At[ut]),2)),Ue=(0,u.stack)(D.map(([$t,ut])=>{if($t>=Le.length)throw new Error(`Layer index ${$t} is out of bounds for cross attentions (length ${Le.length}).`);return oe?Le[$t].slice(null,ut,null,[0,oe]):Le[$t].slice(null,ut)})).transpose(1,0,2,3),[Xe,mt]=(0,u.std_mean)(Ue,-2,0,!0),bt=Ue.clone();for(let $t=0;$tAt[Fr+1]-At[Fr]),dr=(0,a.mergeArrays)([1],er).map(wr=>!!wr),lr=[];for(let wr=0;wrArray.from({length:C.dims[0]},er=>Array.from({length:C.dims[1]},dr=>1))),_t=D?D.tolist():[],$t=oe?oe.tolist():[];let ut=0,At=0;for(let Ht=0;Htyt[Ht][Tr]==1),lr=er.reduce((tr,Tr,ln)=>(Tr==Ue&&tr.push(ln),tr),[]).map(tr=>er[tr+1]),wr=lr.filter(tr=>tr==Ce).length,Fr=lr.filter(tr=>tr==Le).length;let kt=[],xr=0,is=wr,On=Fr;for(let tr=0;tr$s>xr&&zn==Ce),ln=er.findIndex((zn,$s)=>$s>xr&&zn==Le),Ln=is>0&&Tr!==-1?Tr:er.length+1,ao=On>0&&ln!==-1?ln:er.length+1;let ma,Cu,Su,$u;Ln0?(0,_.max)(kt.at(-1))[0]+1:0;kt.push(Array.from({length:3*Iu},(zn,$s)=>dv+$s%Iu));const Au=Iu+dv,fa=mT*ku*_a,_T=Array.from({length:fa},(zn,$s)=>Au+Math.floor($s/(ku*_a))),fT=Array.from({length:fa},(zn,$s)=>Au+Math.floor($s/_a)%ku),gT=Array.from({length:fa},(zn,$s)=>Au+$s%_a);kt.push([_T,fT,gT].flat()),xr=ma+fa}if(xr0?(0,_.max)(kt.at(-1))[0]+1:0,Tr=er.length-xr;kt.push(Array.from({length:3*Tr},(ln,Ln)=>tr+Ln%Tr))}const Zr=kt.reduce((tr,Tr)=>tr+Tr.length,0),hs=new Array(Zr);let da=0;for(let tr=0;tr<3;++tr)for(let Tr=0;Trbt[ut%bt.length]),_t=Array.from({length:yt[0]},($t,ut)=>(0,_.max)(bt.subarray(yt[1]*ut,yt[1]*(ut+1)))[0]+1n+BigInt(yt[1]));return[new u.Tensor("int64",Ft,[3,...yt]),new u.Tensor("int64",_t,[_t.length,1])]}else{const[bt,yt]=C.dims,Ft=BigInt64Array.from({length:3*bt*yt},(_t,$t)=>BigInt(Math.floor($t%yt/bt)));return[new u.Tensor("int64",Ft,[3,...C.dims]),(0,u.zeros)([bt,1])]}}async encode_image({pixel_values:C,image_grid_thw:D}){return(await R(this.sessions.vision_encoder,{pixel_values:C,grid_thw:D})).image_features}_merge_input_ids_with_image_features(C){return F({image_token_id:this.config.image_token_id,...C})}prepare_inputs_for_generation(C,D,oe){if(D.attention_mask&&!D.position_ids)if(!D.past_key_values)[D.position_ids,D.rope_deltas]=this.get_rope_index(D.input_ids,D.image_grid_thw,D.video_grid_thw,D.attention_mask);else{D.pixel_values=null;const fe=BigInt(Object.values(D.past_key_values)[0].dims.at(-2)),he=D.rope_deltas.map(Ce=>fe+Ce);D.position_ids=(0,u.stack)([he,he,he],0)}return D}}class Cc extends W{}class $w extends Cc{}class kw extends Cc{}class Sc extends W{}class Iw extends Sc{}class Aw extends Sc{}class $c extends W{}class Fw extends $c{}class Ow extends $c{}class kc extends W{}class Dw extends kc{}class Lw extends kc{}class Ic extends W{}class zw extends Ic{}class Bw extends Ic{}class Ac extends W{}class Rw extends Ac{}class jw extends Ac{async _call(C){return new Tt(await super._call(C))}}class Fc extends W{}class Nw extends Fc{}class Vw extends Fc{async _call(C){return new Tt(await super._call(C))}}class Uw extends W{}class Ww extends Uw{}class Oc extends W{}class Gw extends Oc{}class Kw extends Oc{async _call(C){return new Tt(await super._call(C))}}class Hw extends W{}class qw extends Hw{}class Dc extends W{}class Qw extends Dc{}class Xw extends Dc{async _call(C){return new Tt(await super._call(C))}}class Jw extends W{}class Yw extends Jw{}class Lc extends W{}class Zw extends Lc{}class eM extends Lc{async _call(C){return new Tt(await super._call(C))}}class tM extends W{}class rM extends tM{async _call(C){return new cv(await super._call(C))}}class zc extends W{}class sM extends zc{}class nM extends zc{async _call(C){return new Tt(await super._call(C))}}class Bc extends W{}class oM extends Bc{}class iM extends Bc{async _call(C){return new Tt(await super._call(C))}}class Rc extends W{}class aM extends Rc{}class lM extends Rc{}class jc extends W{}class cM extends jc{}class uM extends jc{}class Nc extends W{}class dM extends Nc{}class pM extends Nc{async _call(C){return new Tt(await super._call(C))}}class Xi extends W{}class hM extends Xi{}class mM extends Xi{async _call(C){return new Uc(await super._call(C))}}class Vc extends Xi{async _call(C){return new _M(await super._call(C))}}class Uc extends be{constructor({logits:C,pred_boxes:D}){super(),this.logits=C,this.pred_boxes=D}}class _M extends be{constructor({logits:C,pred_boxes:D,pred_masks:oe}){super(),this.logits=C,this.pred_boxes=D,this.pred_masks=oe}}class Wc extends W{}class fM extends Wc{}class gM extends Wc{async _call(C){return new Jo(await super._call(C))}}class Jo extends be{constructor({logits:C,pred_boxes:D}){super(),this.logits=C,this.pred_boxes=D}}class Gc extends W{}class wM extends Gc{}class MM extends Gc{async _call(C){return new bM(await super._call(C))}}class bM extends Jo{}class Kc extends W{}class yM extends Kc{}class vM extends Kc{async _call(C){return new xM(await super._call(C))}}class xM extends Jo{}class Hc extends W{}class TM extends Hc{}class EM extends Hc{async _call(C){return new Jo(await super._call(C))}}class qc extends W{}class PM extends qc{}class CM extends qc{async _call(C){return new SM(await super._call(C))}}class SM extends Uc{}class Qc extends W{}class $M extends Qc{}class kM extends Qc{async _call(C){return new Tt(await super._call(C))}}class Xc extends W{}class IM extends Xc{}class AM extends Xc{async _call(C){return new Tt(await super._call(C))}}class Jc extends W{}class FM extends Jc{}class OM extends Jc{async _call(C){return new Tt(await super._call(C))}}class Ji extends W{}class DM extends Ji{}class LM extends Ji{async _call(C){return new Tt(await super._call(C))}}class zM extends Ji{}class Yc extends W{}class BM extends Yc{}class RM extends Yc{}class Zc extends W{}class jM extends Zc{}class NM extends Zc{}class VM extends W{}class UM extends VM{}class Yi extends W{}class WM extends Yi{}class GM extends Yi{}class KM extends Yi{}class HM extends W{}class qM extends HM{}class QM extends W{}class XM extends QM{}class JM extends W{}class YM extends JM{}class eu extends W{}class ZM extends eu{}class eb extends eu{}class tu extends W{}class tb extends tu{}class rb extends tu{}class sb extends W{}class nb extends sb{}class ru extends W{}class ob extends ru{}class ib extends ru{async _call(C){return new Tt(await super._call(C))}}class su extends W{}class ab extends su{}class lb extends su{async _call(C){return new Tt(await super._call(C))}}class nu extends W{}class cb extends nu{}class ub extends nu{async _call(C){return new Tt(await super._call(C))}}class ou extends W{}class db extends ou{}class pb extends ou{async _call(C){return new Tt(await super._call(C))}}class hb extends W{}class mb extends hb{}class iu extends W{}class _b extends iu{}class fb extends iu{async _call(C){return new gb(await super._call(C))}}class gb extends be{constructor({logits:C,pred_boxes:D}){super(),this.logits=C,this.pred_boxes=D}}class wb extends W{}class Mb extends wb{async get_image_embeddings({pixel_values:C}){return await ne(this,{pixel_values:C})}async forward(C){if((!C.image_embeddings||!C.image_positional_embeddings)&&(C={...C,...await this.get_image_embeddings(C)}),!C.input_labels&&C.input_points){const oe=C.input_points.dims.slice(0,-1),fe=oe.reduce((he,Ce)=>he*Ce,1);C.input_labels=new u.Tensor("int64",new BigInt64Array(fe).fill(1n),oe)}const D={image_embeddings:C.image_embeddings,image_positional_embeddings:C.image_positional_embeddings};return C.input_points&&(D.input_points=C.input_points),C.input_labels&&(D.input_labels=C.input_labels),C.input_boxes&&(D.input_boxes=C.input_boxes),await R(this.sessions.prompt_encoder_mask_decoder,D)}async _call(C){return new bb(await super._call(C))}}class bb extends be{constructor({iou_scores:C,pred_masks:D}){super(),this.iou_scores=C,this.pred_masks=D}}class au extends W{}class yb extends au{}class vb extends au{}class lu extends W{}class xb extends lu{}class Tb extends lu{}class an extends W{}class Eb extends an{}class Pb extends an{async _call(C){return new Fn(await super._call(C))}}class Cb extends an{async _call(C){return new Tt(await super._call(C))}}class Sb extends an{async _call(C){return new vr(await super._call(C))}}class cu extends W{}class $b extends cu{}class kb extends cu{async _call(C){return new vr(await super._call(C))}}class Ib extends W{}class Ab extends Ib{}class Zi extends W{}class Fb extends Zi{}class Ob extends Zi{async _call(C){return new Fn(await super._call(C))}}class Db extends Zi{async _call(C){return new Tt(await super._call(C))}}class Yo extends W{}class Lb extends Yo{}class zb extends Yo{async _call(C){return new Fn(await super._call(C))}}class Bb extends Yo{async _call(C){return new Tt(await super._call(C))}}class Rb extends Yo{async _call(C){return new vr(await super._call(C))}}class ea extends W{}class jb extends ea{}class Nb extends ea{async _call(C){return new Fn(await super._call(C))}}class Vb extends ea{async _call(C){return new Tt(await super._call(C))}}class Zx extends W{}class Ub extends an{}class Wb extends an{async _call(C){return new Fn(await super._call(C))}}class Gb extends an{async _call(C){return new Tt(await super._call(C))}}class oo extends W{}class Kb extends oo{}class Hb extends oo{async _call(C){return new Fn(await super._call(C))}}class qb extends oo{async _call(C){return new Tt(await super._call(C))}}class Qb extends oo{async _call(C){return new lv(await super._call(C))}}class Xb extends oo{async _call(C){return new vr(await super._call(C))}}class Jb extends W{}class Yb extends Jb{}class ta extends W{}class eT extends ta{}class Zb extends ta{}class ey extends ta{async generate_speech(C,D,{threshold:oe=.5,minlenratio:fe=0,maxlenratio:he=20,vocoder:Ce=null}={}){const Le={input_ids:C},{encoder_outputs:Ue,encoder_attention_mask:Xe}=await ne(this,Le),mt=Ue.dims[1]/this.config.reduction_factor,bt=Math.floor(mt*he),yt=Math.floor(mt*fe),Ft=this.config.num_mel_bins;let _t=[],$t=null,ut=null,At=0;for(;;){++At;const dr=ee(!!ut);let lr;ut?lr=ut.output_sequence_out:lr=new u.Tensor("float32",new Float32Array(Ft),[1,1,Ft]);let wr={use_cache_branch:dr,output_sequence:lr,encoder_attention_mask:Xe,speaker_embeddings:D,encoder_hidden_states:Ue};this.addPastKeyValues(wr,$t),ut=await R(this.sessions.decoder_model_merged,wr),$t=this.getPastKeyValues(ut,$t);const{prob:Fr,spectrum:kt}=ut;if(_t.push(kt),At>=yt&&(Array.from(Fr.data).filter(xr=>xr>=oe).length>0||At>=bt))break}const Ht=(0,u.cat)(_t),{waveform:er}=await R(Ce.sessions.model,{spectrogram:Ht});return{spectrogram:Ht,waveform:er}}}class ty extends W{constructor(){super(...arguments);J(this,"main_input_name","spectrogram")}}class ry extends W{}class sy extends ry{}class uu extends W{}class ny extends uu{}class oy extends uu{}class du extends W{}class iy extends du{}class ay extends du{}class pu extends W{}class ly extends pu{}class cy extends pu{}class hu extends W{}class uy extends hu{}class dy extends hu{}class ra extends W{}class py extends ra{}class hy extends ra{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"text_model"})}}class my extends ra{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"audio_model"})}}class _y extends W{}class mu extends _y{async _call(C){return new uv(await super._call(C))}}class sa extends W{}class tT extends sa{}class fy extends sa{}class gy extends sa{}class _u extends W{}class wy extends _u{}class My extends _u{}class fu extends W{}class by extends fu{}class yy extends fu{async _call(C){return new Tt(await super._call(C))}}class gu extends W{}class rT extends gu{}class sT extends gu{}class wu extends W{constructor(){super(...arguments);J(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(D){const[oe,fe]=D.dims,he=this.config.decoder.num_codebooks,Ce=fe-he;let Le=0;for(let mt=0;mt0&&Ft<=Ce&&(D.data[Le++]=D.data[mt])}const Ue=Math.floor(oe/he),Xe=Le/(Ue*he);return new u.Tensor(D.type,D.data.slice(0,Le),[Ue,he,Xe])}prepare_inputs_for_generation(D,oe,fe){let he=structuredClone(D);for(let Le=0;Le=Ue&&(he[Le][Ue]=BigInt(this.config.decoder.pad_token_id));return fe.guidance_scale!==null&&fe.guidance_scale>1&&(he=he.concat(he)),super.prepare_inputs_for_generation(he,oe,fe)}async generate(D){const oe=await super.generate(D),fe=this._apply_and_filter_by_delay_pattern_mask(oe).unsqueeze_(0),{audio_values:he}=await R(this.sessions.encodec_decode,{audio_codes:fe});return he}}class na extends W{}class vy extends na{}class xy extends na{async _call(C){return new Tt(await super._call(C))}}class Ty extends na{}class oa extends W{}class Ey extends oa{}class Py extends oa{async _call(C){return new Tt(await super._call(C))}}class Cy extends oa{}class ia extends W{}class Sy extends ia{}class $y extends ia{async _call(C){return new Tt(await super._call(C))}}class ky extends ia{}class aa extends W{}class Iy extends aa{}class Ay extends aa{async _call(C){return new Tt(await super._call(C))}}class Fy extends aa{}class Oy extends W{}class Dy extends Oy{}class Ly extends W{}class zy extends Ly{constructor(...D){super(...D);J(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(D){const oe=this._generation_mode??"text";let fe;if(oe==="text"||!D.past_key_values){const Xe=this.sessions.prepare_inputs_embeds,mt=(0,a.pick)(D,Xe.inputNames);fe=await R(Xe,mt)}else{const Xe=this.sessions.gen_img_embeds,mt=(0,a.pick)({image_ids:D.input_ids},Xe.inputNames);fe=await R(Xe,mt)}const he={...D,...fe},Ce=await ue(this,he),Le=this.sessions[oe==="text"?"lm_head":"gen_head"];if(!Le)throw new Error(`Unable to find "${Le}" generation head`);const Ue=await R(Le,(0,a.pick)(Ce,Le.inputNames));return{...fe,...Ce,...Ue}}async generate(D){return this._generation_mode="text",super.generate(D)}async generate_images(D){this._generation_mode="image";const oe=(D.inputs??D[this.main_input_name]).dims[1],he=(await super.generate(D)).slice(null,[oe,null]),Ce=this.sessions.image_decode,{decoded_image:Le}=await R(Ce,{generated_tokens:he}),Ue=Le.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Xe=[];for(const mt of Ue){const bt=f.RawImage.fromTensor(mt);Xe.push(bt)}return Xe}}class By extends be{constructor({char_logits:C,bpe_logits:D,wp_logits:oe}){super(),this.char_logits=C,this.bpe_logits=D,this.wp_logits=oe}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Ry extends W{}class jy extends Ry{async _call(C){return new By(await super._call(C))}}class Mu extends W{}class Ny extends Mu{}class Vy extends Mu{}class bu extends W{}class Uy extends bu{}class Wy extends bu{}class Gy extends W{constructor(){super(...arguments);J(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class yu extends Gy{_merge_input_ids_with_audio_features(C){const D=C.audio_features.dims.at(-1),oe=C.audio_features.view(-1,D);return U({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...C,audio_features:oe})}}class Ky extends yu{}class la extends W{constructor(){super(...arguments);J(this,"main_input_name","input_values");J(this,"forward_params",["input_values"])}}class Hy extends be{constructor({audio_codes:C}){super(),this.audio_codes=C}}class qy extends be{constructor({audio_values:C}){super(),this.audio_values=C}}class Qy extends la{async encode(C){return new Hy(await R(this.sessions.encoder_model,C))}async decode(C){return new qy(await R(this.sessions.decoder_model,C))}}class Xy extends la{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class Jy extends la{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class ca extends W{constructor(){super(...arguments);J(this,"main_input_name","input_values");J(this,"forward_params",["input_values"])}}class Yy extends be{constructor({audio_codes:C}){super(),this.audio_codes=C}}class Zy extends be{constructor({audio_values:C}){super(),this.audio_values=C}}class e0 extends ca{async encode(C){return new Yy(await R(this.sessions.encoder_model,C))}async decode(C){return new Zy(await R(this.sessions.decoder_model,C))}}class t0 extends ca{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class r0 extends ca{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class ua extends W{constructor(){super(...arguments);J(this,"main_input_name","input_values");J(this,"forward_params",["input_values"])}}class s0 extends ua{async encode(C){return await R(this.sessions.encoder_model,C)}async decode(C){return await R(this.sessions.decoder_model,C)}}class n0 extends ua{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class o0 extends ua{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class jt{static async from_pretrained(C,{progress_callback:D=null,config:oe=null,cache_dir:fe=null,local_files_only:he=!1,revision:Ce="main",model_file_name:Le=null,subfolder:Ue="onnx",device:Xe=null,dtype:mt=null,use_external_data_format:bt=null,session_options:yt={}}={}){const Ft={progress_callback:D,config:oe,cache_dir:fe,local_files_only:he,revision:Ce,model_file_name:Le,subfolder:Ue,device:Xe,dtype:mt,use_external_data_format:bt,session_options:yt};if(Ft.config=await s.AutoConfig.from_pretrained(C,Ft),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const _t=Ft.config.model_type;for(const $t of this.MODEL_CLASS_MAPPINGS){let ut=$t.get(_t);if(!ut){for(const At of $t.values())if(At[0]===_t){ut=At;break}if(!ut)continue}return await ut[1].from_pretrained(C,Ft)}if(this.BASE_IF_FAIL)return I0.has(_t)||console.warn(`Unknown model class "${_t}", attempting to construct from base class.`),await W.from_pretrained(C,Ft);throw Error(`Unsupported model type: ${_t}`)}}J(jt,"MODEL_CLASS_MAPPINGS",null),J(jt,"BASE_IF_FAIL",!1);const nT=new Map([["bert",["BertModel",Me]],["neobert",["NeoBertModel",xe]],["modernbert",["ModernBertModel",Ye]],["nomic_bert",["NomicBertModel",us]],["roformer",["RoFormerModel",Cr]],["electra",["ElectraModel",B]],["esm",["EsmModel",Ns]],["convbert",["ConvBertModel",As]],["camembert",["CamembertModel",ft]],["deberta",["DebertaModel",Nr]],["deberta-v2",["DebertaV2Model",ds]],["mpnet",["MPNetModel",yn]],["albert",["AlbertModel",qe]],["distilbert",["DistilBertModel",ts]],["roberta",["RobertaModel",Ti]],["xlm",["XLMModel",Si]],["xlm-roberta",["XLMRobertaModel",Fi]],["clap",["ClapModel",py]],["clip",["CLIPModel",Lo]],["clipseg",["CLIPSegModel",$n]],["chinese_clip",["ChineseCLIPModel",dt]],["siglip",["SiglipModel",qi]],["jina_clip",["JinaCLIPModel",No]],["mobilebert",["MobileBertModel",Xt]],["squeezebert",["SqueezeBertModel",Y]],["wav2vec2",["Wav2Vec2Model",Eb]],["wav2vec2-bert",["Wav2Vec2BertModel",jb]],["unispeech",["UniSpeechModel",Fb]],["unispeech-sat",["UniSpeechSatModel",Lb]],["hubert",["HubertModel",Ub]],["wavlm",["WavLMModel",Kb]],["audio-spectrogram-transformer",["ASTModel",Di]],["vits",["VitsModel",mu]],["pyannote",["PyAnnoteModel",$b]],["wespeaker-resnet",["WeSpeakerResNetModel",Ab]],["detr",["DetrModel",hM]],["rt_detr",["RTDetrModel",fM]],["rt_detr_v2",["RTDetrV2Model",wM]],["rf_detr",["RFDetrModel",yM]],["d_fine",["DFineModel",TM]],["table-transformer",["TableTransformerModel",PM]],["vit",["ViTModel",Rw]],["ijepa",["IJepaModel",Nw]],["pvt",["PvtModel",Gw]],["vit_msn",["ViTMSNModel",Qw]],["vit_mae",["ViTMAEModel",qw]],["groupvit",["GroupViTModel",Yw]],["fastvit",["FastViTModel",Zw]],["mobilevit",["MobileViTModel",sM]],["mobilevitv2",["MobileViTV2Model",oM]],["owlvit",["OwlViTModel",aM]],["owlv2",["Owlv2Model",cM]],["beit",["BeitModel",dM]],["deit",["DeiTModel",$M]],["hiera",["HieraModel",IM]],["convnext",["ConvNextModel",ob]],["convnextv2",["ConvNextV2Model",ab]],["dinov2",["Dinov2Model",cb]],["dinov2_with_registers",["Dinov2WithRegistersModel",db]],["resnet",["ResNetModel",FM]],["swin",["SwinModel",DM]],["swin2sr",["Swin2SRModel",BM]],["donut-swin",["DonutSwinModel",nb]],["yolos",["YolosModel",_b]],["dpt",["DPTModel",jM]],["glpn",["GLPNModel",tb]],["hifigan",["SpeechT5HifiGan",ty]],["efficientnet",["EfficientNetModel",by]],["decision_transformer",["DecisionTransformerModel",Dy]],["patchtst",["PatchTSTForPrediction",Ny]],["patchtsmixer",["PatchTSMixerForPrediction",Uy]],["mobilenet_v1",["MobileNetV1Model",vy]],["mobilenet_v2",["MobileNetV2Model",Ey]],["mobilenet_v3",["MobileNetV3Model",Sy]],["mobilenet_v4",["MobileNetV4Model",Iy]],["maskformer",["MaskFormerModel",ZM]],["mgp-str",["MgpstrForSceneTextRecognition",jy]],["style_text_to_speech_2",["StyleTextToSpeech2Model",Yb]]]),oT=new Map([["t5",["T5Model",Lt]],["longt5",["LongT5Model",_r]],["mt5",["MT5Model",fr]],["bart",["BartModel",Zt]],["mbart",["MBartModel",Cs]],["marian",["MarianModel",yb]],["whisper",["WhisperModel",sn]],["m2m_100",["M2M100Model",xb]],["blenderbot",["BlenderbotModel",hr]],["blenderbot-small",["BlenderbotSmallModel",Ws]]]),iT=new Map([["mimi",["MimiModel",Qy]],["dac",["DacModel",e0]],["snac",["SnacModel",s0]]]),aT=new Map([["bloom",["BloomModel",Fw]],["jais",["JAISModel",Go]],["gpt2",["GPT2Model",Uo]],["gptj",["GPTJModel",Qo]],["gpt_bigcode",["GPTBigCodeModel",h]],["gpt_neo",["GPTNeoModel",In]],["gpt_neox",["GPTNeoXModel",Ho]],["codegen",["CodeGenModel",z]],["llama",["LlamaModel",Pe]],["arcee",["ArceeModel",at]],["lfm2",["Lfm2Model",Gt]],["smollm3",["SmolLM3Model",Qi]],["exaone",["ExaoneModel",sw]],["olmo",["OlmoModel",aw]],["olmo2",["Olmo2Model",cw]],["mobilellm",["MobileLLMModel",ow]],["granite",["GraniteModel",dw]],["cohere",["CohereModel",hw]],["gemma",["GemmaModel",_w]],["gemma2",["Gemma2Model",gw]],["gemma3_text",["Gemma3Model",Mw]],["helium",["HeliumModel",Zg]],["glm",["GlmModel",tw]],["openelm",["OpenELMModel",yw]],["qwen2",["Qwen2Model",xw]],["qwen3",["Qwen3Model",Ew]],["phi",["PhiModel",$w]],["phi3",["Phi3Model",Iw]],["mpt",["MptModel",Dw]],["opt",["OPTModel",zw]],["mistral",["MistralModel",ny]],["ernie4_5",["Ernie4_5_Model",iy]],["starcoder2",["Starcoder2Model",ly]],["falcon",["FalconModel",uy]],["stablelm",["StableLmModel",wy]],["modernbert-decoder",["ModernBertDecoderModel",Mr]]]),vu=new Map([["speecht5",["SpeechT5ForSpeechToText",Zb]],["whisper",["WhisperForConditionalGeneration",Ao]],["lite-whisper",["LiteWhisperForConditionalGeneration",Fo]],["moonshine",["MoonshineForConditionalGeneration",Li]]]),i0=new Map([["speecht5",["SpeechT5ForTextToSpeech",ey]]]),a0=new Map([["vits",["VitsModel",mu]],["musicgen",["MusicgenForConditionalGeneration",wu]]]),l0=new Map([["bert",["BertForSequenceClassification",we]],["neobert",["NeoBertForSequenceClassification",Ke]],["modernbert",["ModernBertForSequenceClassification",It]],["roformer",["RoFormerForSequenceClassification",Js]],["electra",["ElectraForSequenceClassification",re]],["esm",["EsmForSequenceClassification",Re]],["convbert",["ConvBertForSequenceClassification",Ct]],["camembert",["CamembertForSequenceClassification",vt]],["deberta",["DebertaForSequenceClassification",rr]],["deberta-v2",["DebertaV2ForSequenceClassification",Os]],["mpnet",["MPNetForSequenceClassification",xn]],["albert",["AlbertForSequenceClassification",We]],["distilbert",["DistilBertForSequenceClassification",Dr]],["roberta",["RobertaForSequenceClassification",Ei]],["xlm",["XLMForSequenceClassification",ki]],["xlm-roberta",["XLMRobertaForSequenceClassification",Co]],["bart",["BartForSequenceClassification",Kr]],["mbart",["MBartForSequenceClassification",ps]],["mobilebert",["MobileBertForSequenceClassification",Es]],["squeezebert",["SqueezeBertForSequenceClassification",de]]]),c0=new Map([["bert",["BertForTokenClassification",Ae]],["neobert",["NeoBertForTokenClassification",nt]],["modernbert",["ModernBertForTokenClassification",St]],["roformer",["RoFormerForTokenClassification",Ys]],["electra",["ElectraForTokenClassification",ge]],["esm",["EsmForTokenClassification",je]],["convbert",["ConvBertForTokenClassification",Qt]],["camembert",["CamembertForTokenClassification",st]],["deberta",["DebertaForTokenClassification",Sr]],["deberta-v2",["DebertaV2ForTokenClassification",Ds]],["mpnet",["MPNetForTokenClassification",pe]],["distilbert",["DistilBertForTokenClassification",Ts]],["roberta",["RobertaForTokenClassification",Pi]],["xlm",["XLMForTokenClassification",Ii]],["xlm-roberta",["XLMRobertaForTokenClassification",So]]]),xu=new Map([["t5",["T5ForConditionalGeneration",sr]],["longt5",["LongT5ForConditionalGeneration",br]],["mt5",["MT5ForConditionalGeneration",Lr]],["bart",["BartForConditionalGeneration",gr]],["mbart",["MBartForConditionalGeneration",Ir]],["marian",["MarianMTModel",vb]],["m2m_100",["M2M100ForConditionalGeneration",Tb]],["blenderbot",["BlenderbotForConditionalGeneration",nr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Hn]]]),Tu=new Map([["bloom",["BloomForCausalLM",Ow]],["gpt2",["GPT2LMHeadModel",Wo]],["jais",["JAISLMHeadModel",Ko]],["gptj",["GPTJForCausalLM",Xo]],["gpt_bigcode",["GPTBigCodeForCausalLM",E]],["gpt_neo",["GPTNeoForCausalLM",ro]],["gpt_neox",["GPTNeoXForCausalLM",qo]],["codegen",["CodeGenForCausalLM",V]],["llama",["LlamaForCausalLM",De]],["arcee",["ArceeForCausalLM",xt]],["lfm2",["Lfm2ForCausalLM",yr]],["smollm3",["SmolLM3ForCausalLM",Yg]],["exaone",["ExaoneForCausalLM",nw]],["olmo",["OlmoForCausalLM",lw]],["olmo2",["Olmo2ForCausalLM",uw]],["mobilellm",["MobileLLMForCausalLM",iw]],["granite",["GraniteForCausalLM",pw]],["cohere",["CohereForCausalLM",mw]],["gemma",["GemmaForCausalLM",fw]],["gemma2",["Gemma2ForCausalLM",ww]],["gemma3_text",["Gemma3ForCausalLM",bw]],["helium",["HeliumForCausalLM",ew]],["glm",["GlmForCausalLM",rw]],["openelm",["OpenELMForCausalLM",vw]],["qwen2",["Qwen2ForCausalLM",Tw]],["qwen3",["Qwen3ForCausalLM",Pw]],["phi",["PhiForCausalLM",kw]],["phi3",["Phi3ForCausalLM",Aw]],["mpt",["MptForCausalLM",Lw]],["opt",["OPTForCausalLM",Bw]],["mbart",["MBartForCausalLM",ur]],["mistral",["MistralForCausalLM",oy]],["ernie4_5",["Ernie4_5_ForCausalLM",ay]],["starcoder2",["Starcoder2ForCausalLM",cy]],["falcon",["FalconForCausalLM",dy]],["trocr",["TrOCRForCausalLM",sy]],["stablelm",["StableLmForCausalLM",My]],["modernbert-decoder",["ModernBertDecoderForCausalLM",Pr]],["phi3_v",["Phi3VForCausalLM",Pn]]]),lT=new Map([["multi_modality",["MultiModalityCausalLM",zy]]]),u0=new Map([["bert",["BertForMaskedLM",Se]],["neobert",["NeoBertForMaskedLM",Ze]],["modernbert",["ModernBertForMaskedLM",ot]],["roformer",["RoFormerForMaskedLM",Xs]],["electra",["ElectraForMaskedLM",q]],["esm",["EsmForMaskedLM",Gr]],["convbert",["ConvBertForMaskedLM",Fs]],["camembert",["CamembertForMaskedLM",ht]],["deberta",["DebertaForMaskedLM",Xr]],["deberta-v2",["DebertaV2ForMaskedLM",kr]],["mpnet",["MPNetForMaskedLM",vn]],["albert",["AlbertForMaskedLM",Mt]],["distilbert",["DistilBertForMaskedLM",mr]],["roberta",["RobertaForMaskedLM",Po]],["xlm",["XLMWithLMHeadModel",$i]],["xlm-roberta",["XLMRobertaForMaskedLM",Oi]],["mobilebert",["MobileBertForMaskedLM",Vs]],["squeezebert",["SqueezeBertForMaskedLM",le]]]),d0=new Map([["bert",["BertForQuestionAnswering",Be]],["neobert",["NeoBertForQuestionAnswering",Je]],["roformer",["RoFormerForQuestionAnswering",Zs]],["electra",["ElectraForQuestionAnswering",Fe]],["convbert",["ConvBertForQuestionAnswering",S]],["camembert",["CamembertForQuestionAnswering",zt]],["deberta",["DebertaForQuestionAnswering",$r]],["deberta-v2",["DebertaV2ForQuestionAnswering",Ur]],["mpnet",["MPNetForQuestionAnswering",I]],["albert",["AlbertForQuestionAnswering",tt]],["distilbert",["DistilBertForQuestionAnswering",pr]],["roberta",["RobertaForQuestionAnswering",Ci]],["xlm",["XLMForQuestionAnswering",Ai]],["xlm-roberta",["XLMRobertaForQuestionAnswering",$o]],["mobilebert",["MobileBertForQuestionAnswering",Us]],["squeezebert",["SqueezeBertForQuestionAnswering",Te]]]),Eu=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Tn]],["idefics3",["Idefics3ForConditionalGeneration",En]],["smolvlm",["SmolVLMForConditionalGeneration",Do]]]),p0=new Map([["llava",["LlavaForConditionalGeneration",Xn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",zi]],["moondream1",["Moondream1ForConditionalGeneration",Bi]],["florence2",["Florence2ForConditionalGeneration",ji]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Sw]],["idefics3",["Idefics3ForConditionalGeneration",En]],["smolvlm",["SmolVLMForConditionalGeneration",Do]],["paligemma",["PaliGemmaForConditionalGeneration",Vi]],["llava_qwen2",["LlavaQwen2ForCausalLM",Ui]],["gemma3n",["Gemma3nForConditionalGeneration",nn]]]),h0=new Map([["ultravox",["UltravoxModel",yu]],["voxtral",["VoxtralForConditionalGeneration",Ky]]]),cT=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Tn]]]),m0=new Map([["vit",["ViTForImageClassification",jw]],["ijepa",["IJepaForImageClassification",Vw]],["pvt",["PvtForImageClassification",Kw]],["vit_msn",["ViTMSNForImageClassification",Xw]],["fastvit",["FastViTForImageClassification",eM]],["mobilevit",["MobileViTForImageClassification",nM]],["mobilevitv2",["MobileViTV2ForImageClassification",iM]],["beit",["BeitForImageClassification",pM]],["deit",["DeiTForImageClassification",kM]],["hiera",["HieraForImageClassification",AM]],["convnext",["ConvNextForImageClassification",ib]],["convnextv2",["ConvNextV2ForImageClassification",lb]],["dinov2",["Dinov2ForImageClassification",ub]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",pb]],["resnet",["ResNetForImageClassification",OM]],["swin",["SwinForImageClassification",LM]],["segformer",["SegformerForImageClassification",fy]],["efficientnet",["EfficientNetForImageClassification",yy]],["mobilenet_v1",["MobileNetV1ForImageClassification",xy]],["mobilenet_v2",["MobileNetV2ForImageClassification",Py]],["mobilenet_v3",["MobileNetV3ForImageClassification",$y]],["mobilenet_v4",["MobileNetV4ForImageClassification",Ay]]]),_0=new Map([["detr",["DetrForObjectDetection",mM]],["rt_detr",["RTDetrForObjectDetection",gM]],["rt_detr_v2",["RTDetrV2ForObjectDetection",MM]],["rf_detr",["RFDetrForObjectDetection",vM]],["d_fine",["DFineForObjectDetection",EM]],["table-transformer",["TableTransformerForObjectDetection",CM]],["yolos",["YolosForObjectDetection",fb]]]),f0=new Map([["owlvit",["OwlViTForObjectDetection",lM]],["owlv2",["Owlv2ForObjectDetection",uM]],["grounding-dino",["GroundingDinoForObjectDetection",mb]]]),io=new Map([["detr",["DetrForSegmentation",Vc]],["clipseg",["CLIPSegForImageSegmentation",Zn]]]),g0=new Map([["segformer",["SegformerForSemanticSegmentation",gy]],["sapiens",["SapiensForSemanticSegmentation",WM]],["swin",["SwinForSemanticSegmentation",zM]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",Ty]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",Cy]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",ky]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Fy]]]),w0=new Map([["detr",["DetrForSegmentation",Vc]],["maskformer",["MaskFormerForInstanceSegmentation",eb]]]),M0=new Map([["sam",["SamModel",Mb]]]),b0=new Map([["wav2vec2",["Wav2Vec2ForCTC",Pb]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Nb]],["unispeech",["UniSpeechForCTC",Ob]],["unispeech-sat",["UniSpeechSatForCTC",zb]],["wavlm",["WavLMForCTC",Hb]],["hubert",["HubertForCTC",Wb]]]),y0=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Cb]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Vb]],["unispeech",["UniSpeechForSequenceClassification",Db]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Bb]],["wavlm",["WavLMForSequenceClassification",qb]],["hubert",["HubertForSequenceClassification",Gb]],["audio-spectrogram-transformer",["ASTForAudioClassification",Io]]]),v0=new Map([["wavlm",["WavLMForXVector",Qb]]]),x0=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Rb]],["wavlm",["WavLMForAudioFrameClassification",Xb]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Sb]],["pyannote",["PyAnnoteForAudioFrameClassification",kb]]]),T0=new Map([["vitmatte",["VitMatteForImageMatting",rM]]]),uT=new Map([["patchtst",["PatchTSTForPrediction",Vy]],["patchtsmixer",["PatchTSMixerForPrediction",Wy]]]),E0=new Map([["swin2sr",["Swin2SRForImageSuperResolution",RM]]]),P0=new Map([["dpt",["DPTForDepthEstimation",NM]],["depth_anything",["DepthAnythingForDepthEstimation",UM]],["glpn",["GLPNForDepthEstimation",rb]],["sapiens",["SapiensForDepthEstimation",GM]],["depth_pro",["DepthProForDepthEstimation",qM]],["metric3d",["Metric3DForDepthEstimation",XM]],["metric3dv2",["Metric3Dv2ForDepthEstimation",YM]]]),C0=new Map([["sapiens",["SapiensForNormalEstimation",KM]]]),S0=new Map([["vitpose",["VitPoseForPoseEstimation",Ww]]]),$0=new Map([["clip",["CLIPVisionModelWithProjection",Bo]],["siglip",["SiglipVisionModel",jo]],["jina_clip",["JinaCLIPVisionModel",Sn]]]),k0=[[nT,v.EncoderOnly],[oT,v.EncoderDecoder],[aT,v.DecoderOnly],[iT,v.AutoEncoder],[l0,v.EncoderOnly],[c0,v.EncoderOnly],[xu,v.Seq2Seq],[vu,v.Seq2Seq],[Tu,v.DecoderOnly],[lT,v.MultiModality],[u0,v.EncoderOnly],[d0,v.EncoderOnly],[Eu,v.Vision2Seq],[p0,v.ImageTextToText],[h0,v.AudioTextToText],[m0,v.EncoderOnly],[io,v.EncoderOnly],[w0,v.EncoderOnly],[g0,v.EncoderOnly],[T0,v.EncoderOnly],[uT,v.EncoderOnly],[E0,v.EncoderOnly],[P0,v.EncoderOnly],[C0,v.EncoderOnly],[S0,v.EncoderOnly],[_0,v.EncoderOnly],[f0,v.EncoderOnly],[M0,v.MaskGeneration],[b0,v.EncoderOnly],[y0,v.EncoderOnly],[i0,v.Seq2Seq],[a0,v.EncoderOnly],[v0,v.EncoderOnly],[x0,v.EncoderOnly],[$0,v.EncoderOnly]];for(const[w,C]of k0)for(const[D,oe]of w.values())y.set(D,C),x.set(oe,D),T.set(D,oe);const dT=[["MusicgenForConditionalGeneration",wu,v.Musicgen],["Phi3VForCausalLM",Pn,v.Phi3V],["CLIPTextModelWithProjection",zo,v.EncoderOnly],["SiglipTextModel",Ro,v.EncoderOnly],["JinaCLIPTextModel",Vo,v.EncoderOnly],["ClapTextModelWithProjection",hy,v.EncoderOnly],["ClapAudioModelWithProjection",my,v.EncoderOnly],["DacEncoderModel",t0,v.EncoderOnly],["DacDecoderModel",r0,v.EncoderOnly],["MimiEncoderModel",Xy,v.EncoderOnly],["MimiDecoderModel",Jy,v.EncoderOnly],["SnacEncoderModel",n0,v.EncoderOnly],["SnacDecoderModel",o0,v.EncoderOnly],["Gemma3nForConditionalGeneration",nn,v.ImageAudioTextToText]];for(const[w,C,D]of dT)y.set(w,D),x.set(C,w),T.set(w,C);const I0=new Map([["modnet",io],["birefnet",io],["isnet",io],["ben",io]]);for(const[w,C]of I0.entries())C.set(w,["PreTrainedModel",W]),y.set(w,v.EncoderOnly),x.set(W,w),T.set(w,W);class Pu extends jt{}J(Pu,"MODEL_CLASS_MAPPINGS",k0.map(C=>C[0])),J(Pu,"BASE_IF_FAIL",!0);class A0 extends jt{}J(A0,"MODEL_CLASS_MAPPINGS",[l0]);class F0 extends jt{}J(F0,"MODEL_CLASS_MAPPINGS",[c0]);class O0 extends jt{}J(O0,"MODEL_CLASS_MAPPINGS",[xu]);class D0 extends jt{}J(D0,"MODEL_CLASS_MAPPINGS",[vu]);class L0 extends jt{}J(L0,"MODEL_CLASS_MAPPINGS",[i0]);class z0 extends jt{}J(z0,"MODEL_CLASS_MAPPINGS",[a0]);class B0 extends jt{}J(B0,"MODEL_CLASS_MAPPINGS",[Tu]);class R0 extends jt{}J(R0,"MODEL_CLASS_MAPPINGS",[u0]);class j0 extends jt{}J(j0,"MODEL_CLASS_MAPPINGS",[d0]);class N0 extends jt{}J(N0,"MODEL_CLASS_MAPPINGS",[Eu]);class V0 extends jt{}J(V0,"MODEL_CLASS_MAPPINGS",[m0]);class U0 extends jt{}J(U0,"MODEL_CLASS_MAPPINGS",[io]);class W0 extends jt{}J(W0,"MODEL_CLASS_MAPPINGS",[g0]);class G0 extends jt{}J(G0,"MODEL_CLASS_MAPPINGS",[w0]);class K0 extends jt{}J(K0,"MODEL_CLASS_MAPPINGS",[_0]);class H0 extends jt{}J(H0,"MODEL_CLASS_MAPPINGS",[f0]);class q0 extends jt{}J(q0,"MODEL_CLASS_MAPPINGS",[M0]);class Q0 extends jt{}J(Q0,"MODEL_CLASS_MAPPINGS",[b0]);class X0 extends jt{}J(X0,"MODEL_CLASS_MAPPINGS",[y0]);class J0 extends jt{}J(J0,"MODEL_CLASS_MAPPINGS",[v0]);class Y0 extends jt{}J(Y0,"MODEL_CLASS_MAPPINGS",[x0]);class Z0 extends jt{}J(Z0,"MODEL_CLASS_MAPPINGS",[cT]);class ev extends jt{}J(ev,"MODEL_CLASS_MAPPINGS",[T0]);class tv extends jt{}J(tv,"MODEL_CLASS_MAPPINGS",[E0]);class rv extends jt{}J(rv,"MODEL_CLASS_MAPPINGS",[P0]);class sv extends jt{}J(sv,"MODEL_CLASS_MAPPINGS",[C0]);class nv extends jt{}J(nv,"MODEL_CLASS_MAPPINGS",[S0]);class ov extends jt{}J(ov,"MODEL_CLASS_MAPPINGS",[$0]);class iv extends jt{}J(iv,"MODEL_CLASS_MAPPINGS",[p0]);class av extends jt{}J(av,"MODEL_CLASS_MAPPINGS",[h0]);class pT extends be{constructor({logits:C,past_key_values:D,encoder_outputs:oe,decoder_attentions:fe=null,cross_attentions:he=null}){super(),this.logits=C,this.past_key_values=D,this.encoder_outputs=oe,this.decoder_attentions=fe,this.cross_attentions=he}}class Tt extends be{constructor({logits:C,...D}){super(),this.logits=C;const oe=Object.values(D);oe.length>0&&(this.attentions=oe)}}class lv extends be{constructor({logits:C,embeddings:D}){super(),this.logits=C,this.embeddings=D}}class vr extends be{constructor({logits:C}){super(),this.logits=C}}class Ar extends be{constructor({logits:C}){super(),this.logits=C}}class Br extends be{constructor({start_logits:C,end_logits:D}){super(),this.start_logits=C,this.end_logits=D}}class Fn extends be{constructor({logits:C}){super(),this.logits=C}}class hT extends be{constructor({logits:C,past_key_values:D}){super(),this.logits=C,this.past_key_values=D}}class cv extends be{constructor({alphas:C}){super(),this.alphas=C}}class uv extends be{constructor({waveform:C,spectrogram:D}){super(),this.waveform=C,this.spectrogram=D}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,c=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=c,this.window=(0,o.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(a,l){return(0,o.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:l,transpose:!0})}async _call(a){(0,s.validate_audio_inputs)(a,"ASTFeatureExtractor");const l=await this._extract_fbank_features(a,this.config.max_length);if(this.config.do_normalize){const c=this.std*2,p=l.data;for(let d=0;d{t.r(r),t.d(r,{AutoFeatureExtractor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var n=t("./src/models/feature_extractors.js");class i{static async from_pretrained(l,c={}){const p=await(0,o.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,c),d=p.feature_extractor_type,u=n[d];if(!u)throw new Error(`Unknown feature_extractor_type: '${d}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new u(p)}}},"./src/models/auto/image_processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoImageProcessor:()=>a});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js"),n=t("./src/base/image_processors_utils.js"),i=t("./src/models/image_processors.js");class a{static async from_pretrained(c,p={}){const d=await(0,o.getModelJSON)(c,s.IMAGE_PROCESSOR_NAME,!0,p),u=d.image_processor_type??d.feature_extractor_type;let f=i[u==null?void 0:u.replace(/Fast$/,"")];return f||(u!==void 0&&console.warn(`Image processor type '${u}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),f=n.ImageProcessor),new f(d)}}},"./src/models/auto/processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>c});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js"),n=t("./src/base/processing_utils.js"),i=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class c{static async from_pretrained(d,u={}){const f=await(0,o.getModelJSON)(d,s.IMAGE_PROCESSOR_NAME,!0,u),{image_processor_type:_,feature_extractor_type:b,processor_class:k}=f;if(k&&i[k])return i[k].from_pretrained(d,u);if(!_&&!b)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const g={};if(_){const $=a[_.replace(/Fast$/,"")];if(!$)throw new Error(`Unknown image_processor_type: '${_}'.`);g.image_processor=new $(f)}if(b){const $=a[b];if($)g.image_processor=new $(f);else{const v=l[b];if(!v)throw new Error(`Unknown feature_extractor_type: '${b}'.`);g.feature_extractor=new v(f)}}const M={};return new n.Processor(M,g,null)}}},"./src/models/beit/image_processing_beit.js":(e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(e,r,t)=>{t.r(r),t.d(r,{ClapFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,o.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,o.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,o.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,c,p){let d;const u=a.length-l;if(u>0)if(c==="rand_trunc"){const f=Math.floor(Math.random()*(u+1));a=a.subarray(f,f+l),d=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${c}" not implemented`);else{if(u<0){let f=new Float64Array(l);if(f.set(a),p==="repeat")for(let _=a.length;_{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>n,CLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/convnext/image_processing_convnext.js":(e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>n,ConvNextImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){var c;const l=(c=this.size)==null?void 0:c.shortest_edge;if(l===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(l<384){const p=Math.floor(l/this.crop_pct),[d,u]=this.get_resize_output_image_size(a,{shortest_edge:p});a=await a.resize(d,u,{resample:this.resample}),a=await a.center_crop(l,l)}else a=await a.resize(l,l,{resample:this.resample});return a}}class n extends o{}},"./src/models/dac/feature_extraction_dac.js":(e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>o});var s=t("./src/models/encodec/feature_extraction_encodec.js");class o extends s.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>n,DeiTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/detr/image_processing_detr.js":(e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(l){const c=await super._call(l),p=[c.pixel_values.dims[0],64,64],d=(0,o.full)(p,1n);return{...c,pixel_mask:d}}post_process_object_detection(...l){return(0,s.post_process_object_detection)(...l)}post_process_panoptic_segmentation(...l){return(0,s.post_process_panoptic_segmentation)(...l)}post_process_instance_segmentation(...l){return(0,s.post_process_instance_segmentation)(...l)}}class i extends n{}},"./src/models/donut/image_processing_donut.js":(e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>n,DonutImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(a,l,c,p={}){const[d,u,f]=l;let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(f).fill(_));let b=this.image_std;Array.isArray(b)||(b=new Array(f).fill(_));const k=_.map((g,M)=>-g/b[M]);return super.pad_image(a,l,c,{center:!0,constant_values:k,...p})}}class n extends o{}},"./src/models/dpt/image_processing_dpt.js":(e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>n,DPTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/efficientnet/image_processing_efficientnet.js":(e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super(i),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(a=>a*a))}}},"./src/models/encodec/feature_extraction_encodec.js":(e,r,t)=>{t.r(r),t.d(r,{EncodecFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"EncodecFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=this.config.feature_size;if(a.length%l!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${l}).`);const c=[1,l,a.length/l];return{input_values:new o.Tensor("float32",a,c)}}}},"./src/models/feature_extractors.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>n.ClapFeatureExtractor,DacFeatureExtractor:()=>i.DacFeatureExtractor,EncodecFeatureExtractor:()=>o.EncodecFeatureExtractor,Gemma3nAudioFeatureExtractor:()=>a.Gemma3nAudioFeatureExtractor,ImageFeatureExtractor:()=>k.ImageProcessor,MoonshineFeatureExtractor:()=>l.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>c.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>p.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>d.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>u.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>f.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>_.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>b.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),o=t("./src/models/encodec/feature_extraction_encodec.js"),n=t("./src/models/clap/feature_extraction_clap.js"),i=t("./src/models/dac/feature_extraction_dac.js"),a=t("./src/models/gemma3n/feature_extraction_gemma3n.js"),l=t("./src/models/moonshine/feature_extraction_moonshine.js"),c=t("./src/models/pyannote/feature_extraction_pyannote.js"),p=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),d=t("./src/models/snac/feature_extraction_snac.js"),u=t("./src/models/speecht5/feature_extraction_speecht5.js"),f=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),_=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),b=t("./src/models/whisper/feature_extraction_whisper.js"),k=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{constructor(l,c,p){super(l,c,p);const{tasks_answer_post_processing_type:d,task_prompts_without_inputs:u,task_prompts_with_input:f}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(d??{})),this.task_prompts_without_inputs=new Map(Object.entries(u??{})),this.task_prompts_with_input=new Map(Object.entries(f??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const c=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))c.push(this.task_prompts_without_inputs.get(p));else{for(const[d,u]of this.task_prompts_with_input)if(p.includes(d)){c.push(u.replaceAll("{input}",p).replaceAll(d,""));break}c.length!==l.length&&c.push(p)}return c}post_process_generation(l,c,p){const d=this.tasks_answer_post_processing_type.get(c)??"pure_text";l=l.replaceAll("","").replaceAll("","");let u;switch(d){case"pure_text":u=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const f=d==="ocr"?"quad_boxes":"bboxes",_=l.matchAll(this.regexes[f]),b=[],k=[];for(const[g,M,...$]of _)b.push(M?M.trim():b.at(-1)??""),k.push($.map((v,y)=>(Number(v)+.5)/this.size_per_bin*p[y%2]));u={labels:b,[f]:k};break;default:throw new Error(`Task "${c}" (of type "${d}") not yet implemented.`)}return{[c]:u}}async _call(l,c=null,p={}){if(!l&&!c)throw new Error("Either text or images must be provided");const d=await this.image_processor(l,p),u=c?this.tokenizer(this.construct_prompts(c),p):{};return{...d,...u}}}J(i,"tokenizer_class",n.AutoTokenizer),J(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/gemma3n/feature_extraction_gemma3n.js":(e,r,t)=>{t.r(r),t.d(r,{Gemma3nAudioFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const{fft_length:c,feature_size:p,min_frequency:d,max_frequency:u,sampling_rate:f,frame_length:_}=this.config,b=(0,n.mel_filter_bank)(Math.floor(1+c/2),p,d,u,f,null,"htk",!1);this.mel_filters=b,this.window=(0,n.window_function)(_,"hann")}async _extract_fbank_features(l,c){return(0,n.spectrogram)(l,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(l,{max_length:c=48e4,truncation:p=!0,padding:d=!0,pad_to_multiple_of:u=128}={}){if((0,s.validate_audio_inputs)(l,"Gemma3nAudioFeatureExtractor"),p&&l.length>c&&(l=l.slice(0,c)),d&&l.length%u!==0){const b=u-l.length%u,k=new Float64Array(l.length+b);k.set(l),this.config.padding_value!==0&&k.fill(this.config.padding_value,l.length),l=k}const f=await this._extract_fbank_features(l,this.config.max_length),_=(0,o.full)([1,f.dims[0]],!0);return{input_features:f.unsqueeze_(0),input_features_mask:_}}}},"./src/models/gemma3n/processing_gemma3n.js":(e,r,t)=>{t.r(r),t.d(r,{Gemma3nProcessor:()=>a});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js");t("./src/utils/image.js"),t("./src/utils/audio.js");class a extends s.Processor{constructor(c,p,d){super(c,p,d),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:u,boa_token:f,audio_token:_,eoa_token:b,image_token_id:k,boi_token:g,image_token:M,eoi_token:$}=this.tokenizer.config;this.audio_token_id=u,this.boa_token=f,this.audio_token=_;const v=_.repeat(this.audio_seq_length);this.full_audio_sequence=` + +${f}${v}${b} + +`,this.image_token_id=k,this.boi_token=g,this.image_token=M;const y=M.repeat(this.image_seq_length);this.full_image_sequence=` + +${g}${y}${$} + +`}async _call(c,p=null,d=null,u={}){typeof c=="string"&&(c=[c]);let f;d&&(f=await this.feature_extractor(d,u),c=c.map(k=>k.replaceAll(this.audio_token,this.full_audio_sequence)));let _;return p&&(_=await this.image_processor(p,u),c=c.map(k=>k.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(c,u),..._,...f}}}J(a,"image_processor_class",o.AutoImageProcessor),J(a,"feature_extractor_class",n.AutoFeatureExtractor),J(a,"tokenizer_class",i.AutoTokenizer),J(a,"uses_processor_config",!0),J(a,"uses_chat_template_file",!0)},"./src/models/glpn/image_processing_glpn.js":(e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a){const l=await super._call(a),c=l.pixel_values.dims,p=(0,o.ones)([c[0],c[2],c[3]]);return{...l,pixel_mask:p}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/base/image_processors_utils.js");function a(c,p){const u=c.dims.at(-1)-1,f=c.tolist();f.fill(!1,0,1),f.fill(!1,u);const _=p.tolist();return f.map((b,k)=>b?k:null).filter(b=>b!==null).map(b=>_[b])}class l extends s.Processor{async _call(p,d,u={}){const f=p?await this.image_processor(p,u):{};return{...d?this.tokenizer(d,u):{},...f}}post_process_grounded_object_detection(p,d,{box_threshold:u=.25,text_threshold:f=.25,target_sizes:_=null}={}){const{logits:b,pred_boxes:k}=p,g=b.dims[0];if(_!==null&&_.length!==g)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const M=b.dims.at(1),$=b.sigmoid(),v=$.max(-1).tolist(),y=k.tolist().map(x=>x.map(P=>(0,i.center_to_corners_format)(P))),T=[];for(let x=0;xR.map((te,H)=>te*P[(H+1)%2])));const O=v[x],L=[],G=[],K=[];for(let R=0;R{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{constructor(a){super(a),this.do_image_splitting=a.do_image_splitting??!0,this.max_image_size=a.max_image_size}get_resize_for_vision_encoder(a,l){let[c,p]=a.dims.slice(-2);const d=p/c;return p>=c?(p=Math.ceil(p/l)*l,c=Math.floor(p/d),c=Math.ceil(c/l)*l):(c=Math.ceil(c/l)*l,p=Math.floor(c*d),p=Math.ceil(p/l)*l),{height:c,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:c=!1}={}){let p;if(!Array.isArray(a))p=[[a]];else{if(a.length===0||!a[0])throw new Error("No images provided.");Array.isArray(a[0])?p=a:p=[a]}let d=[],u=[],f=[];const _=[],b=[];for(const x of p){let P=await Promise.all(x.map(G=>this.preprocess(G)));_.push(...P.map(G=>G.original_size)),b.push(...P.map(G=>G.reshaped_input_size)),P.forEach(G=>G.pixel_values.unsqueeze_(0));const{longest_edge:O}=this.max_image_size;let L;if(l??this.do_image_splitting){let G=new Array(P.length),K=new Array(P.length);L=await Promise.all(P.map(async(R,te)=>{const H=this.get_resize_for_vision_encoder(R.pixel_values,O),ee=await(0,o.interpolate_4d)(R.pixel_values,{size:[H.height,H.width]}),{frames:Z,num_splits_h:ne,num_splits_w:me}=await this.split_image(ee,this.max_image_size);return G[te]=ne,K[te]=me,(0,o.cat)(Z,0)})),u.push(G),f.push(K)}else{const G=[O,O];L=await Promise.all(P.map(K=>(0,o.interpolate_4d)(K.pixel_values,{size:G}))),u.push(new Array(P.length).fill(0)),f.push(new Array(P.length).fill(0))}d.push((0,o.cat)(L,0))}const k=d.length,[g,M,$,v]=d[0].dims;let y,T;if(k===1)y=d[0].unsqueeze_(0),T=(0,o.full)([k,g,$,v],!0);else{const x=Math.max(...d.map(L=>L.dims.at(0)));T=(0,o.full)([k,x,$,v],!0);const P=T.data,O=x*$*v;for(let L=0;Lc||f>p){_=Math.ceil(u/c),b=Math.ceil(f/p);const k=Math.ceil(u/_),g=Math.ceil(f/b);for(let v=0;v<_;++v)for(let y=0;y{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");var i=t("./src/utils/core.js");function a(d,u,f,_,b,k){let g="";for(let M=0;M`+b.repeat(d);g+=` +`}return g+=` +${_}${k}`+b.repeat(d)+`${_}`,g}function l(d,u,f,_){return`${u}${_}`+f.repeat(d)+`${u}`}function c(d,u,f,_,b,k){return d===0&&u===0?l(f,_,b,k):a(f,d,u,_,b,k)}class p extends s.Processor{constructor(){super(...arguments);J(this,"fake_image_token","");J(this,"image_token","");J(this,"global_img_token","")}async _call(f,_=null,b={}){b.return_row_col_info??(b.return_row_col_info=!0);let k;_&&(k=await this.image_processor(_,b)),Array.isArray(f)||(f=[f]);const g=k.rows??[new Array(f.length).fill(0)],M=k.cols??[new Array(f.length).fill(0)],$=this.config.image_seq_len,v=[],y=[];for(let x=0;xc(te,L[H],$,this.fake_image_token,this.image_token,this.global_img_token)),K=P.split(this.image_token);if(K.length===0)throw new Error("The image token should be present in the text.");let R=K[0];for(let te=0;te{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>o.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>n.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>d.DPTFeatureExtractor,DPTImageProcessor:()=>d.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>c.DetrFeatureExtractor,DetrImageProcessor:()=>c.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>u.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>f.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>b.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>g.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>M.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>$.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>v.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>v.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>y.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>y.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>T.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>T.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>x.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>x.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>P.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>P.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>O.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>O.MobileViTImageProcessor,NougatImageProcessor:()=>L.NougatImageProcessor,OwlViTFeatureExtractor:()=>K.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>K.OwlViTImageProcessor,Owlv2ImageProcessor:()=>G.Owlv2ImageProcessor,Phi3VImageProcessor:()=>R.Phi3VImageProcessor,PvtImageProcessor:()=>te.PvtImageProcessor,Qwen2VLImageProcessor:()=>H.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>ee.RTDetrImageProcessor,SamImageProcessor:()=>Z.SamImageProcessor,SegformerFeatureExtractor:()=>ne.SegformerFeatureExtractor,SegformerImageProcessor:()=>ne.SegformerImageProcessor,SiglipImageProcessor:()=>me.SiglipImageProcessor,SmolVLMImageProcessor:()=>ue.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>j.Swin2SRImageProcessor,VLMImageProcessor:()=>k.VLMImageProcessor,ViTFeatureExtractor:()=>F.ViTFeatureExtractor,ViTImageProcessor:()=>F.ViTImageProcessor,VitMatteImageProcessor:()=>U.VitMatteImageProcessor,VitPoseImageProcessor:()=>se.VitPoseImageProcessor,YolosFeatureExtractor:()=>_e.YolosFeatureExtractor,YolosImageProcessor:()=>_e.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),o=t("./src/models/bit/image_processing_bit.js"),n=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),i=t("./src/models/clip/image_processing_clip.js"),a=t("./src/models/convnext/image_processing_convnext.js"),l=t("./src/models/deit/image_processing_deit.js"),c=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/donut/image_processing_donut.js"),d=t("./src/models/dpt/image_processing_dpt.js"),u=t("./src/models/efficientnet/image_processing_efficientnet.js"),f=t("./src/models/glpn/image_processing_glpn.js"),_=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),b=t("./src/models/idefics3/image_processing_idefics3.js"),k=t("./src/models/janus/image_processing_janus.js"),g=t("./src/models/jina_clip/image_processing_jina_clip.js"),M=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),$=t("./src/models/mask2former/image_processing_mask2former.js"),v=t("./src/models/maskformer/image_processing_maskformer.js"),y=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),T=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),x=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),P=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),O=t("./src/models/mobilevit/image_processing_mobilevit.js"),L=t("./src/models/nougat/image_processing_nougat.js"),G=t("./src/models/owlv2/image_processing_owlv2.js"),K=t("./src/models/owlvit/image_processing_owlvit.js"),R=t("./src/models/phi3_v/image_processing_phi3_v.js"),te=t("./src/models/pvt/image_processing_pvt.js"),H=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),ee=t("./src/models/rt_detr/image_processing_rt_detr.js"),Z=t("./src/models/sam/image_processing_sam.js"),ne=t("./src/models/segformer/image_processing_segformer.js"),me=t("./src/models/siglip/image_processing_siglip.js"),ue=t("./src/models/smolvlm/image_processing_smolvlm.js"),j=t("./src/models/swin2sr/image_processing_swin2sr.js"),F=t("./src/models/vit/image_processing_vit.js"),U=t("./src/models/vitmatte/image_processing_vitmatte.js"),se=t("./src/models/vitpose/image_processing_vitpose.js"),_e=t("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLMImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super({do_pad:!0,pad_size:{width:i.image_size,height:i.image_size},...i}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(i,a,l,c){return super.pad_image(i,a,l,{constant_values:this.constant_values,center:!0,...c})}}},"./src/models/janus/processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>c});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class c extends s.Processor{constructor(d,u,f){super(d,u,f),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(d,{images:u=null,chat_template:f="default"}={}){u?Array.isArray(u)||(u=[u]):u=await Promise.all(d.filter(L=>L.images).flatMap(L=>L.images).map(L=>l.RawImage.read(L)));const _=this.tokenizer,b=_.apply_chat_template(d,{tokenize:!1,add_generation_prompt:!0,chat_template:f}),k=L=>_.encode(L,{add_special_tokens:!1}),g=b.split(this.image_tag),M=g.length-1;if(u.length!==M)throw new Error(`Number of images provided (${u.length}) does not match number of "${this.image_tag}" image tags (${M})`);const[$,v,y]=_.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let T=k(g[0]),x=new Array(T.length).fill(!1);for(let L=1;L0){const L=await this.image_processor(u);return L.pixel_values.unsqueeze_(0),{...O,...L}}return O}}J(c,"image_processor_class",o.AutoImageProcessor),J(c,"tokenizer_class",n.AutoTokenizer),J(c,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){const{resize_mode:a,fill_color:l,interpolation:c,size:p,...d}=i,u=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},f=c==="bicubic"?3:2;super({...d,size:u,resample:f,do_center_crop:!0,crop_size:p,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{async _call(l=null,c=null,p={}){if(!l&&!c)throw new Error("Either text or images must be provided");const d=l?this.tokenizer(l,p):{},u=c?await this.image_processor(c,p):{};return{...d,...u}}}J(i,"tokenizer_class",n.AutoTokenizer),J(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/llava/processing_llava.js":(e,r,t)=>{t.r(r),t.d(r,{LlavaProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{async _call(l,c=null,p={}){const d=await this.image_processor(l,p);if(c){const[f,_]=d.pixel_values.dims.slice(-2),{image_token:b,patch_size:k,num_additional_image_tokens:g}=this.config,M=Math.floor(f/k)*Math.floor(_/k)+g;c=structuredClone(c),Array.isArray(c)||(c=[c]);for(let $=0;${t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>o});var s=t("./src/models/maskformer/image_processing_maskformer.js");class o extends s.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>n,MaskFormerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_panoptic_segmentation(...a){return(0,s.post_process_panoptic_segmentation)(...a)}post_process_instance_segmentation(...a){return(0,s.post_process_instance_segmentation)(...a)}}class n extends o{}},"./src/models/mgp_str/processing_mgp_str.js":(e,r,t)=>{t.r(r),t.d(r,{MgpstrProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/utils/maths.js");const a={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class l extends s.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(p,d){if(!a.hasOwnProperty(d))throw new Error(`Format ${d} is not supported.`);const[u,f]=a[d],_=this[u].bind(this),[b,k]=p.dims,g=[],M=[],$=p.tolist();for(let y=0;y0?P.reduce((L,G)=>L*G,1):0;M.push(x),g.push(O)}return[_(M),g]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}batch_decode([p,d,u]){const[f,_]=this._decode_helper(p,"char"),[b,k]=this._decode_helper(d,"bpe"),[g,M]=this._decode_helper(u,"wp"),$=[],v=[];for(let y=0;y{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>n,MobileNetV1ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>n,MobileNetV2ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>n,MobileNetV3ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>n,MobileNetV4ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilevit/image_processing_mobilevit.js":(e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>n,MobileViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/moonshine/feature_extraction_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"MoonshineFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=[1,a.length];return{input_values:new o.Tensor("float32",a,l)}}}},"./src/models/moonshine/processing_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}J(i,"tokenizer_class",o.AutoTokenizer),J(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>o});var s=t("./src/models/donut/image_processing_donut.js");class o extends s.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>o});var s=t("./src/models/owlvit/image_processing_owlvit.js");class o extends s.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>n,OwlViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/models/owlvit/processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{}J(i,"tokenizer_class",n.AutoTokenizer),J(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(e,r,t)=>{t.r(r),t.d(r,{PaliGemmaProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");const i="";function a(c,p,d,u,f){return`${u.repeat(d*f)}${p}${c} +`}class l extends s.Processor{async _call(p,d=null,u={}){d||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),d=""),Array.isArray(p)||(p=[p]),Array.isArray(d)||(d=[d]);const f=this.tokenizer.bos_token,_=this.image_processor.config.image_seq_length;let b;d.some(M=>M.includes(i))?b=d.map(M=>{const $=M.replaceAll(i,i.repeat(_)),v=$.lastIndexOf(i),y=v===-1?0:v+i.length;return $.slice(0,y)+f+$.slice(y)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),b=d.map(M=>a(M,f,_,i,p.length)));const k=this.tokenizer(b,u);return{...await this.image_processor(p,u),...k}}}J(l,"tokenizer_class",n.AutoTokenizer),J(l,"image_processor_class",o.AutoImageProcessor),J(l,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VImageProcessor:()=>p});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");const n=336,i=[2,3],{ceil:a,floor:l,sqrt:c}=Math;class p extends s.ImageProcessor{constructor(u){super({...u,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=u.num_crops}calc_num_image_tokens_from_image_size(u,f){const{num_img_tokens:_}=this.config;return l((l(f/n)*l(u/n)+1)*_+1+(l(f/n)+1)*c(_))}get_resize_output_image_size(u,f){const _=this._num_crops,[b,k]=u.size;let g=b/k,M=1;for(;M*Math.ceil(M/g)<=_;)M+=1;M-=1;const $=Math.floor(M*336),v=Math.floor($/g);return[$,v]}pad_image(u,f,_,b={}){const[k,g]=f,M=n*a(k/n),$=n*a(g/n),v=[1,1,1].map((y,T)=>(y-this.image_mean[T])/this.image_std[T]);return super.pad_image(u,f,{width:$,height:M},{center:!0,constant_values:v,...b})}async _call(u,{num_crops:f=null}={}){if(this._num_crops=f??(f=this.config.num_crops),f<4||c(f)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(u)||(u=[u]);const _=u.length,b=await Promise.all(u.map(x=>this.preprocess(x))),k=b.map(x=>x.original_size),g=b.map(x=>x.reshaped_input_size),M=[];for(const{pixel_values:x}of b){x.unsqueeze_(0);const[P,O]=x.dims.slice(-2),L=await(0,o.interpolate_4d)(x,{size:[n,n],mode:"bicubic"});if(f>0){const G=[],K=c(f),R=l(O/K),te=l(P/K);for(let ee=0;eex.map(P=>n*a(P/n))),y=new o.Tensor("int64",v.flat(),[_,2]),T=v.map(([x,P])=>this.calc_num_image_tokens_from_image_size(P,x));return{pixel_values:$,original_sizes:k,reshaped_input_sizes:g,image_sizes:y,num_img_tokens:T}}}},"./src/models/phi3_v/processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");const i="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{async _call(p,d=null,{padding:u=!0,truncation:f=!0,num_crops:_=null}={}){Array.isArray(p)||(p=[p]);let b,k;if(d){k=await this.image_processor(d,{num_crops:_});const{num_img_tokens:g}=k,M=p.map((v,y)=>v.split(a).join(i.repeat(g[y])));b=this.tokenizer(M,{padding:u,truncation:f});const $=this.tokenizer.model.convert_tokens_to_ids([i])[0];b.input_ids.map_(v=>v==$?-v:v)}else b=this.tokenizer(p);return{...b,...k}}}J(l,"image_processor_class",o.AutoImageProcessor),J(l,"tokenizer_class",n.AutoTokenizer)},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,Gemma3nProcessor:()=>o.Gemma3nProcessor,GroundingDinoProcessor:()=>n.GroundingDinoProcessor,Idefics3Processor:()=>i.Idefics3Processor,JinaCLIPProcessor:()=>l.JinaCLIPProcessor,LlavaProcessor:()=>c.LlavaProcessor,MgpstrProcessor:()=>p.MgpstrProcessor,MoonshineProcessor:()=>d.MoonshineProcessor,OwlViTProcessor:()=>u.OwlViTProcessor,PaliGemmaProcessor:()=>_.PaliGemmaProcessor,Phi3VProcessor:()=>f.Phi3VProcessor,PyAnnoteProcessor:()=>b.PyAnnoteProcessor,Qwen2VLProcessor:()=>k.Qwen2VLProcessor,SamProcessor:()=>g.SamProcessor,SmolVLMProcessor:()=>M.SmolVLMProcessor,SpeechT5Processor:()=>$.SpeechT5Processor,UltravoxProcessor:()=>v.UltravoxProcessor,VLChatProcessor:()=>a.VLChatProcessor,VoxtralProcessor:()=>y.VoxtralProcessor,Wav2Vec2Processor:()=>T.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>x.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>P.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),o=t("./src/models/gemma3n/processing_gemma3n.js"),n=t("./src/models/grounding_dino/processing_grounding_dino.js"),i=t("./src/models/idefics3/processing_idefics3.js"),a=t("./src/models/janus/processing_janus.js"),l=t("./src/models/jina_clip/processing_jina_clip.js"),c=t("./src/models/llava/processing_llava.js"),p=t("./src/models/mgp_str/processing_mgp_str.js"),d=t("./src/models/moonshine/processing_moonshine.js"),u=t("./src/models/owlvit/processing_owlvit.js"),f=t("./src/models/phi3_v/processing_phi3_v.js"),_=t("./src/models/paligemma/processing_paligemma.js"),b=t("./src/models/pyannote/processing_pyannote.js"),k=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),g=t("./src/models/sam/processing_sam.js"),M=t("./src/models/smolvlm/processing_smolvlm.js"),$=t("./src/models/speecht5/processing_speecht5.js"),v=t("./src/models/ultravox/processing_ultravox.js"),y=t("./src/models/voxtral/processing_voxtral.js"),T=t("./src/models/wav2vec2/processing_wav2vec2.js"),x=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),P=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const c=[1,1,l.length];return{input_values:new o.Tensor("float32",l,c)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,c){const p=c/this.samples_to_frames(c)/this.config.sampling_rate,d=[];for(const u of l.tolist()){const f=[];let _=-1;for(let b=0;b({id:b,start:k*p,end:g*p,confidence:M/(g-k)})))}return d}}},"./src/models/pyannote/processing_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteProcessor:()=>n});var s=t("./src/base/processing_utils.js"),o=t("./src/models/pyannote/feature_extraction_pyannote.js");class n extends s.Processor{async _call(a){return await this.feature_extractor(a)}post_process_speaker_diarization(...a){return this.feature_extractor.post_process_speaker_diarization(...a)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}J(n,"feature_extractor_class",o.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,...l){const{pixel_values:c,original_sizes:p,reshaped_input_sizes:d}=await super._call(a,...l);let u=c;const{temporal_patch_size:f,merge_size:_,patch_size:b}=this.config;u.dims[0]===1&&(u=(0,o.cat)(Array.from({length:f},()=>u),0));const k=u.dims[0]/f,g=u.dims[1],M=Math.floor(u.dims[2]/b),$=Math.floor(u.dims[3]/b),v=u.view(k,f,g,Math.floor(M/_),_,b,Math.floor($/_),_,b).permute(0,3,6,4,7,2,1,5,8).view(k*M*$,g*f*b*b),y=new o.Tensor("int64",[k,M,$],[1,3]);return{pixel_values:v,image_grid_thw:y,original_sizes:p,reshaped_input_sizes:d}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");class i extends s.Processor{async _call(l,c=null,...p){Array.isArray(l)||(l=[l]);let d,u;if(c&&(d=await this.image_processor(c),u=d.image_grid_thw),u){let _=this.image_processor.config.merge_size**2,b=0;const k=u.tolist();l=l.map(g=>{for(;g.includes("<|image_pad|>");){const M=Number(k[b++].reduce(($,v)=>$*v,1n));g=g.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(M/_)))}return g.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...d}}}J(i,"image_processor_class",o.AutoImageProcessor),J(i,"tokenizer_class",n.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...i){return(0,s.post_process_object_detection)(...i)}}},"./src/models/sam/image_processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/core.js"),n=t("./src/utils/tensor.js");class i extends s.ImageProcessor{reshape_input_points(l,c,p,d=!1){l=structuredClone(l);let u=(0,o.calculateDimensions)(l);if(u.length===3)d||(u=[1,...u]),l=[l];else if(u.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let f=0;fd!==c.dims[u]))throw Error(`The first ${p.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new n.Tensor("int64",l.flat(1/0).map(BigInt),p)}async _call(l,{input_points:c=null,input_labels:p=null,input_boxes:d=null}={}){const u=await super._call(l);if(c&&(u.input_points=this.reshape_input_points(c,u.original_sizes,u.reshaped_input_sizes)),p){if(!u.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");u.input_labels=this.add_input_labels(p,u.input_points)}return d&&(u.input_boxes=this.reshape_input_points(d,u.original_sizes,u.reshaped_input_sizes,!0)),u}async post_process_masks(l,c,p,{mask_threshold:d=0,binarize:u=!0,pad_size:f=null}={}){const _=[];f=f??this.pad_size;const b=[f.height,f.width];for(let k=0;kd&&(y[T]=1);$=new n.Tensor("bool",y,$.dims)}_.push($)}return _}generate_crop_boxes(l,c,{crop_n_layers:p=0,overlap_ratio:d=512/1500,points_per_crop:u=32,crop_n_points_downscale_factor:f=1}={}){}}},"./src/models/sam/processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamProcessor:()=>n});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js");class n extends s.Processor{async _call(...a){return await this.image_processor(...a)}post_process_masks(...a){return this.image_processor.post_process_masks(...a)}reshape_input_points(...a){return this.image_processor.reshape_input_points(...a)}}J(n,"image_processor_class",o.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const c=this.config.sampling_rate,p=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(c/2),c,null,"kaldi",!0);this.mel_filters=p,this.window=(0,n.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(l,c){return l=l.map(p=>p*32768),(0,n.spectrogram)(l,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:c,transpose:!0})}async _call(l,{padding:c=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:d=!0,return_attention_mask:u=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let f=await this._extract_fbank_features(l,this.config.max_length);if(d){const[y,T]=f.dims,x=f.data;for(let P=0;P0){const O=new Float32Array(T*(y+P));O.set(x),O.fill(this.config.padding_value,x.length);const L=y+P;f=new o.Tensor(f.type,O,[L,T]),u&&(_=new o.Tensor("int64",new BigInt64Array(L),[1,L]),_.data.fill(1n,0,y))}}const[b,k]=f.dims,g=this.config.stride;if(b%g!==0)throw new Error(`The number of frames (${b}) must be a multiple of the stride (${g}).`);const $=f.view(1,Math.floor(b/g),k*g),v={input_features:$};if(u){const y=$.dims[1],T=new BigInt64Array(y);if(_){const x=_.data;for(let P=1,O=0;P{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>n,SegformerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class n extends o{}},"./src/models/siglip/image_processing_siglip.js":(e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/smolvlm/image_processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMImageProcessor:()=>s.Idefics3ImageProcessor});var s=t("./src/models/idefics3/image_processing_idefics3.js")},"./src/models/smolvlm/processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMProcessor:()=>s.Idefics3Processor});var s=t("./src/models/idefics3/processing_idefics3.js")},"./src/models/snac/feature_extraction_snac.js":(e,r,t)=>{t.r(r),t.d(r,{SnacFeatureExtractor:()=>o});var s=t("./src/models/dac/feature_extraction_dac.js");class o extends s.DacFeatureExtractor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");class o extends s.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js");class i extends s.Processor{async _call(l){return await this.feature_extractor(l)}}J(i,"tokenizer_class",o.AutoTokenizer),J(i,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(i,a,l,c={}){const[p,d,u]=a;return super.pad_image(i,a,{width:d+(l-d%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...c})}}},"./src/models/ultravox/processing_ultravox.js":(e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l,c=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let d={};if(c){const f=c.length,{input_features:_}=await this.feature_extractor(c,{...p,max_length:f}),b=Math.round(f/this.config.encoder_ds_factor+1e-4),k=1+Math.ceil(b/this.config.stack_factor);d.audio_token_len=[k],d.audio_values=_;const g=this.config.audio_placeholder;if(!l.includes(g))throw new Error(`The input text does not contain the image token ${g}.`);l=l.replaceAll(g,g.repeat(k))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...d}}}J(i,"tokenizer_class",o.AutoTokenizer),J(i,"feature_extractor_class",s.AutoFeatureExtractor),J(i,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>n,ViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/vitmatte/image_processing_vitmatte.js":(e,r,t)=>{t.r(r),t.d(r,{VitMatteImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,l){Array.isArray(a)||(a=[a]),Array.isArray(l)||(l=[l]);const c=await Promise.all(a.map(u=>this.preprocess(u))),p=await Promise.all(l.map(u=>this.preprocess(u,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,o.stack)(c.map((u,f)=>(0,o.cat)([u.pixel_values,p[f].pixel_values],0)),0),original_sizes:c.map(u=>u.original_size),reshaped_input_sizes:c.map(u=>u.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_pose_estimation(i,a,{threshold:l=null}={}){const c=i.tolist(),[p,d,u,f]=i.dims,_=[];for(let b=0;b{t.r(r),t.d(r,{VoxtralProcessor:()=>d});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js"),i=t("./src/utils/tensor.js");const a="[AUDIO]",l="[BEGIN_AUDIO]",c=375;function p(u,f){const _=[];for(let b=0;bp(L,v)),T=y.map(L=>L.length),x=y.flat(),P=(await Promise.all(x.map(L=>this.feature_extractor(L,b)))).map(L=>L.input_features);k.audio_values=P.length>1?(0,i.cat)(P,0):P[0];let O=M[0];for(let L=0;L{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const c=a.reduce((d,u)=>d+u,0)/a.length,p=a.reduce((d,u)=>d+(u-c)**2,0)/a.length;return a.map(d=>(d-c)/Math.sqrt(p+1e-7))}async _call(a){(0,s.validate_audio_inputs)(a,"Wav2Vec2FeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));let l=a;this.config.do_normalize&&(l=this._zero_mean_unit_var_norm(l));const c=[1,l.length];return{input_values:new o.Tensor("float32",l,c),attention_mask:new o.Tensor("int64",new BigInt64Array(l.length).fill(1n),c)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}J(i,"tokenizer_class",s.AutoTokenizer),J(i,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}J(i,"tokenizer_class",s.AutoTokenizer),J(i,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(e,r,t)=>{t.r(r),t.d(r,{WeSpeakerFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,c=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=c,this.window=(0,o.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(a){return a=a.map(l=>l*32768),(0,o.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(a){(0,s.validate_audio_inputs)(a,"WeSpeakerFeatureExtractor");const l=(await this._extract_fbank_features(a)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const c=l.mean(1).data,p=l.data,[d,u,f]=l.dims;for(let _=0;_{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>o,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>n,whisper_language_to_code:()=>i});const s=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],o=new Map(s),n=new Map([...s.map(([a,l])=>[l,a]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function i(a){a=a.toLowerCase();let l=n.get(a);if(l===void 0){const c=a.match(/^<\|([a-z]{2})\|>$/);if(c&&(a=c[1]),o.has(a))l=a;else{const d=a.length===2?o.keys():o.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(d))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{constructor(l){var c;super(l),(c=this.config).mel_filters??(c.mel_filters=(0,o.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,o.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const c=await(0,o.spectrogram)(l,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(l.length/this.config.hop_length),this.config.nb_max_frames)}),p=c.data,d=(0,n.max)(p)[0];for(let u=0;ud?(l.length>this.config.n_samples&&console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),p=l.slice(0,d)):(p=new Float32Array(d),p.set(l)),{input_features:(await this._extract_fbank_features(p)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperGenerationConfig:()=>o});var s=t("./src/generation/configuration_utils.js");class o extends s.GenerationConfig{constructor(){super(...arguments);J(this,"return_timestamps",null);J(this,"return_token_timestamps",null);J(this,"num_frames",null);J(this,"alignment_heads",null);J(this,"task",null);J(this,"language",null);J(this,"no_timestamps_token_id",null);J(this,"prompt_ids",null);J(this,"is_multilingual",null);J(this,"lang_to_id",null);J(this,"task_to_id",null);J(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}J(i,"tokenizer_class",o.AutoTokenizer),J(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>n,YolosImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),o=t("./src/utils/tensor.js"),n=t("./src/env.js");const i=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV,a=async(c,p,d)=>{const u=await(0,s.createInferenceSession)(new Uint8Array(c),p);let f=Promise.resolve();return async _=>{const b=(0,s.isONNXProxy)(),k=Object.fromEntries(Object.entries(_).map(([M,$])=>[M,(b?$.clone():$).ort_tensor])),g=await(f=i?f.then(()=>u.run(k)):u.run(k));return Array.isArray(d)?d.map(M=>new o.Tensor(g[M])):new o.Tensor(g[d])}};class l{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=a([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=a([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=a([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=a([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=a([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=a([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=a([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=a([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}J(l,"session_options",{})},"./src/pipelines.js":(e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>K,AutomaticSpeechRecognitionPipeline:()=>te,BackgroundRemovalPipeline:()=>ne,DepthEstimationPipeline:()=>_e,DocumentQuestionAnsweringPipeline:()=>F,FeatureExtractionPipeline:()=>L,FillMaskPipeline:()=>$,ImageClassificationPipeline:()=>ee,ImageFeatureExtractionPipeline:()=>G,ImageSegmentationPipeline:()=>Z,ImageToImagePipeline:()=>se,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>ue,Pipeline:()=>b,QuestionAnsweringPipeline:()=>M,SummarizationPipeline:()=>y,Text2TextGenerationPipeline:()=>v,TextClassificationPipeline:()=>k,TextGenerationPipeline:()=>P,TextToAudioPipeline:()=>U,TokenClassificationPipeline:()=>g,TranslationPipeline:()=>T,ZeroShotAudioClassificationPipeline:()=>R,ZeroShotClassificationPipeline:()=>O,ZeroShotImageClassificationPipeline:()=>me,ZeroShotObjectDetectionPipeline:()=>j,pipeline:()=>ze});var s=t("./src/tokenizers.js"),o=t("./src/models.js"),n=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),c=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),d=t("./src/utils/image.js");async function u(Ie){return Array.isArray(Ie)||(Ie=[Ie]),await Promise.all(Ie.map(X=>d.RawImage.read(X)))}async function f(Ie,X){return Array.isArray(Ie)||(Ie=[Ie]),await Promise.all(Ie.map(ae=>typeof ae=="string"||ae instanceof URL?(0,c.read_audio)(ae,X):ae instanceof Float64Array?new Float32Array(ae):ae))}function _(Ie,X){X&&(Ie=Ie.map(Ee=>Ee|0));const[ae,W,be,ke]=Ie;return{xmin:ae,ymin:W,xmax:be,ymax:ke}}class b extends i.Callable{constructor({task:X,model:ae,tokenizer:W=null,processor:be=null}){super(),this.task=X,this.model=ae,this.tokenizer=W,this.processor=be}async dispose(){await this.model.dispose()}}class k extends b{constructor(X){super(X)}async _call(X,{top_k:ae=1}={}){const W=this.tokenizer(X,{padding:!0,truncation:!0}),be=await this.model(W),ke=this.model.config.problem_type==="multi_label_classification"?Se=>Se.sigmoid():Se=>new p.Tensor("float32",(0,l.softmax)(Se.data),Se.dims),Ee=this.model.config.id2label,Me=[];for(const Se of be.logits){const we=ke(Se),Ae=await(0,p.topk)(we,ae),Be=Ae[0].tolist(),xe=Ae[1].tolist().map((Ze,Ke)=>({label:Ee?Ee[Ze]:`LABEL_${Ze}`,score:Be[Ke]}));ae===1?Me.push(...xe):Me.push(xe)}return Array.isArray(X)||ae===1?Me:Me[0]}}class g extends b{constructor(X){super(X)}async _call(X,{ignore_labels:ae=["O"]}={}){const W=Array.isArray(X),be=this.tokenizer(W?X:[X],{padding:!0,truncation:!0}),Ee=(await this.model(be)).logits,Me=this.model.config.id2label,Se=[];for(let we=0;weYe==this.tokenizer.sep_token_id);Se[Be].map((Ye,ot)=>Ye==1&&(ot===0||ot>xe&&we.findIndex(It=>It==Qe[ot])===-1));const Ze=ke[Be].tolist(),Ke=Ee[Be].tolist();for(let Ye=1;Yeot==Qe[Ye])!==-1)&&(Ze[Ye]=-1/0,Ke[Ye]=-1/0);const nt=(0,l.softmax)(Ze).map((Ye,ot)=>[Ye,ot]),Je=(0,l.softmax)(Ke).map((Ye,ot)=>[Ye,ot]);nt[0][0]=0,Je[0][0]=0;const Oe=(0,a.product)(nt,Je).filter(Ye=>Ye[0][1]<=Ye[1][1]).map(Ye=>[Ye[0][1],Ye[1][1],Ye[0][0]*Ye[1][0]]).sort((Ye,ot)=>ot[2]-Ye[2]);for(let Ye=0;YeZe==this.tokenizer.mask_token_id);if(we===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ae=be[Me][we],Be=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ae.data),Ae.dims),ae),Qe=Be[0].tolist(),xe=Be[1].tolist();ke.push(xe.map((Ze,Ke)=>{const nt=Se.slice();return nt[we]=Ze,{score:Qe[Ke],token:Number(Ze),token_str:this.tokenizer.decode([Ze]),sequence:this.tokenizer.decode(nt,{skip_special_tokens:!0})}}))}return Array.isArray(X)?ke:ke[0]}}class v extends b{constructor(ae){super(ae);J(this,"_key","generated_text")}async _call(ae,W={}){Array.isArray(ae)||(ae=[ae]),this.model.config.prefix&&(ae=ae.map(we=>this.model.config.prefix+we));const be=this.model.config.task_specific_params;be&&be[this.task]&&be[this.task].prefix&&(ae=ae.map(we=>be[this.task].prefix+we));const ke=this.tokenizer,Ee={padding:!0,truncation:!0};let Me;this instanceof T&&"_build_translation_inputs"in ke?Me=ke._build_translation_inputs(ae,Ee,W):Me=ke(ae,Ee);const Se=await this.model.generate({...Me,...W});return ke.batch_decode(Se,{skip_special_tokens:!0}).map(we=>({[this._key]:we}))}}class y extends v{constructor(ae){super(ae);J(this,"_key","summary_text")}}class T extends v{constructor(ae){super(ae);J(this,"_key","translation_text")}}function x(Ie){return Array.isArray(Ie)&&Ie.every(X=>"role"in X&&"content"in X)}class P extends b{constructor(X){super(X)}async _call(X,ae={}){let W=!1,be=!1,ke=ae.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,Ee;if(typeof X=="string")Ee=X=[X];else if(Array.isArray(X)&&X.every(xe=>typeof xe=="string"))W=!0,Ee=X;else{if(x(X))X=[X];else if(Array.isArray(X)&&X.every(x))W=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");be=!0,Ee=X.map(xe=>this.tokenizer.apply_chat_template(xe,{tokenize:!1,add_generation_prompt:!0})),ke=!1}const Me=be?!1:ae.return_full_text??!0;this.tokenizer.padding_side="left";const Se=this.tokenizer(Ee,{add_special_tokens:ke,padding:!0,truncation:!0}),we=await this.model.generate({...Se,...ae}),Ae=this.tokenizer.batch_decode(we,{skip_special_tokens:!0});let Be;!Me&&Se.input_ids.dims.at(-1)>0&&(Be=this.tokenizer.batch_decode(Se.input_ids,{skip_special_tokens:!0}).map(xe=>xe.length));const Qe=Array.from({length:X.length},xe=>[]);for(let xe=0;xe[ae.toLowerCase(),W])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(X,ae,{hypothesis_template:W="This example is {}.",multi_label:be=!1}={}){const ke=Array.isArray(X);ke||(X=[X]),Array.isArray(ae)||(ae=[ae]);const Ee=ae.map(we=>W.replace("{}",we)),Me=be||ae.length===1,Se=[];for(const we of X){const Ae=[];for(const xe of Ee){const Ze=this.tokenizer(we,{text_pair:xe,padding:!0,truncation:!0}),Ke=await this.model(Ze);Me?Ae.push([Ke.logits.data[this.contradiction_id],Ke.logits.data[this.entailment_id]]):Ae.push(Ke.logits.data[this.entailment_id])}const Qe=(Me?Ae.map(xe=>(0,l.softmax)(xe)[1]):(0,l.softmax)(Ae)).map((xe,Ze)=>[xe,Ze]).sort((xe,Ze)=>Ze[0]-xe[0]);Se.push({sequence:we,labels:Qe.map(xe=>ae[xe[1]]),scores:Qe.map(xe=>xe[0])})}return ke?Se:Se[0]}}class L extends b{constructor(X){super(X)}async _call(X,{pooling:ae="none",normalize:W=!1,quantize:be=!1,precision:ke="binary"}={}){const Ee=this.tokenizer(X,{padding:!0,truncation:!0}),Me=await this.model(Ee);let Se=Me.last_hidden_state??Me.logits??Me.token_embeddings;switch(ae){case"none":break;case"mean":Se=(0,p.mean_pooling)(Se,Ee.attention_mask);break;case"first_token":case"cls":Se=Se.slice(null,0);break;case"last_token":case"eos":Se=Se.slice(null,-1);break;default:throw Error(`Pooling method '${ae}' not supported.`)}return W&&(Se=Se.normalize(2,-1)),be&&(Se=(0,p.quantize_embeddings)(Se,ke)),Se}}class G extends b{constructor(X){super(X)}async _call(X,{pool:ae=null}={}){const W=await u(X),{pixel_values:be}=await this.processor(W),ke=await this.model({pixel_values:be});let Ee;if(ae){if(!("pooler_output"in ke))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ee=ke.pooler_output}else Ee=ke.last_hidden_state??ke.logits??ke.image_embeds;return Ee}}class K extends b{constructor(X){super(X)}async _call(X,{top_k:ae=5}={}){const W=this.processor.feature_extractor.config.sampling_rate,be=await f(X,W),ke=this.model.config.id2label,Ee=[];for(const Me of be){const Se=await this.processor(Me),Ae=(await this.model(Se)).logits[0],Be=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ae.data),Ae.dims),ae),Qe=Be[0].tolist(),Ze=Be[1].tolist().map((Ke,nt)=>({label:ke?ke[Ke]:`LABEL_${Ke}`,score:Qe[nt]}));Ee.push(Ze)}return Array.isArray(X)?Ee:Ee[0]}}class R extends b{constructor(X){super(X)}async _call(X,ae,{hypothesis_template:W="This is a sound of {}."}={}){const be=!Array.isArray(X);be&&(X=[X]);const ke=ae.map(Ae=>W.replace("{}",Ae)),Ee=this.tokenizer(ke,{padding:!0,truncation:!0}),Me=this.processor.feature_extractor.config.sampling_rate,Se=await f(X,Me),we=[];for(const Ae of Se){const Be=await this.processor(Ae),Qe=await this.model({...Ee,...Be}),xe=(0,l.softmax)(Qe.logits_per_audio.data);we.push([...xe].map((Ze,Ke)=>({score:Ze,label:ae[Ke]})))}return be?we[0]:we}}class te extends b{constructor(X){super(X)}async _call(X,ae={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(X,ae);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(X,ae);case"moonshine":return this._call_moonshine(X,ae);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(X,ae){ae.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),ae.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const W=!Array.isArray(X);W&&(X=[X]);const be=this.processor.feature_extractor.config.sampling_rate,ke=await f(X,be),Ee=[];for(const Me of ke){const Se=await this.processor(Me),Ae=(await this.model(Se)).logits[0],Be=[];for(const xe of Ae)Be.push((0,l.max)(xe.data)[1]);const Qe=this.tokenizer.decode(Be);Ee.push({text:Qe})}return W?Ee[0]:Ee}async _call_whisper(X,ae){const W=ae.return_timestamps??!1,be=ae.chunk_length_s??0,ke=ae.force_full_sequences??!1;let Ee=ae.stride_length_s??null;const Me={...ae};W==="word"&&(Me.return_token_timestamps=!0,Me.return_timestamps=!1);const Se=!Array.isArray(X);Se&&(X=[X]);const we=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ae=this.processor.feature_extractor.config.hop_length,Be=this.processor.feature_extractor.config.sampling_rate,Qe=await f(X,Be),xe=[];for(const Ze of Qe){let Ke=[];if(be>0){if(Ee===null)Ee=be/6;else if(be<=Ee)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Oe=Be*be,Ye=Be*Ee,ot=Oe-2*Ye;let It=0;for(;;){const St=It+Oe,wt=Ze.subarray(It,St),Mr=await this.processor(wt),Pr=It===0,jr=St>=Ze.length;if(Ke.push({stride:[wt.length,Pr?0:Ye,jr?0:Ye],input_features:Mr.input_features,is_last:jr}),jr)break;It+=ot}}else Ke=[{stride:[Ze.length,0,0],input_features:(await this.processor(Ze)).input_features,is_last:!0}];for(const Oe of Ke){Me.num_frames=Math.floor(Oe.stride[0]/Ae);const Ye=await this.model.generate({inputs:Oe.input_features,...Me});W==="word"?(Oe.tokens=Ye.sequences.tolist()[0],Oe.token_timestamps=Ye.token_timestamps.tolist()[0].map(ot=>(0,l.round)(ot,2))):Oe.tokens=Ye[0].tolist(),Oe.stride=Oe.stride.map(ot=>ot/Be)}const[nt,Je]=this.tokenizer._decode_asr(Ke,{time_precision:we,return_timestamps:W,force_full_sequences:ke});xe.push({text:nt,...Je})}return Se?xe[0]:xe}async _call_moonshine(X,ae){const W=!Array.isArray(X);W&&(X=[X]);const be=this.processor.feature_extractor.config.sampling_rate,ke=await f(X,be),Ee=[];for(const Me of ke){const Se=await this.processor(Me),we=Math.floor(Me.length/be)*6,Ae=await this.model.generate({max_new_tokens:we,...ae,...Se}),Be=this.processor.batch_decode(Ae,{skip_special_tokens:!0})[0];Ee.push({text:Be})}return W?Ee[0]:Ee}}class H extends b{constructor(X){super(X)}async _call(X,ae={}){const W=Array.isArray(X),be=await u(X),{pixel_values:ke}=await this.processor(be),Ee=[];for(const Me of ke){Me.dims=[1,...Me.dims];const Se=await this.model.generate({inputs:Me,...ae}),we=this.tokenizer.batch_decode(Se,{skip_special_tokens:!0}).map(Ae=>({generated_text:Ae.trim()}));Ee.push(we)}return W?Ee:Ee[0]}}class ee extends b{constructor(X){super(X)}async _call(X,{top_k:ae=5}={}){const W=await u(X),{pixel_values:be}=await this.processor(W),ke=await this.model({pixel_values:be}),Ee=this.model.config.id2label,Me=[];for(const Se of ke.logits){const we=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Se.data),Se.dims),ae),Ae=we[0].tolist(),Qe=we[1].tolist().map((xe,Ze)=>({label:Ee?Ee[xe]:`LABEL_${xe}`,score:Ae[Ze]}));Me.push(Qe)}return Array.isArray(X)?Me:Me[0]}}class Z extends b{constructor(X){super(X),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(X,{threshold:ae=.5,mask_threshold:W=.5,overlap_mask_area_threshold:be=.8,label_ids_to_fuse:ke=null,target_sizes:Ee=null,subtask:Me=null}={}){if(Array.isArray(X)&&X.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const we=await u(X),Ae=we.map(Oe=>[Oe.height,Oe.width]),Be=await this.processor(we),{inputNames:Qe,outputNames:xe}=this.model.sessions.model;if(!Qe.includes("pixel_values")){if(Qe.length!==1)throw Error(`Expected a single input name, but got ${Qe.length} inputs: ${Qe}.`);const Oe=Qe[0];if(Oe in Be)throw Error(`Input name ${Oe} already exists in the inputs.`);Be[Oe]=Be.pixel_values}const Ze=await this.model(Be);let Ke=null;if(Me!==null)Ke=this.subtasks_mapping[Me];else if(this.processor.image_processor){for(const[Oe,Ye]of Object.entries(this.subtasks_mapping))if(Ye in this.processor.image_processor){Ke=this.processor.image_processor[Ye].bind(this.processor.image_processor),Me=Oe;break}}const nt=this.model.config.id2label,Je=[];if(Me)if(Me==="panoptic"||Me==="instance"){const Oe=Ke(Ze,ae,W,be,ke,Ee??Ae)[0],Ye=Oe.segmentation;for(const ot of Oe.segments_info){const It=new Uint8ClampedArray(Ye.data.length);for(let wt=0;wtMr<-1e-5||Mr>1+1e-5)&&St.sigmoid_();const wt=await d.RawImage.fromTensor(St.mul_(255).to("uint8")).resize(It[1],It[0]);Je.push({label:null,score:null,mask:wt})}}return Je}}class ne extends Z{constructor(X){super(X)}async _call(X,ae={}){if(Array.isArray(X)&&X.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const be=await u(X),ke=await super._call(X,ae);return be.map((Me,Se)=>{const we=Me.clone();return we.putAlpha(ke[Se].mask),we})}}class me extends b{constructor(X){super(X)}async _call(X,ae,{hypothesis_template:W="This is a photo of {}"}={}){const be=Array.isArray(X),ke=await u(X),Ee=ae.map(Qe=>W.replace("{}",Qe)),Me=this.tokenizer(Ee,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:Se}=await this.processor(ke),we=await this.model({...Me,pixel_values:Se}),Ae=this.model.config.model_type==="siglip"?Qe=>Qe.sigmoid().data:Qe=>(0,l.softmax)(Qe.data),Be=[];for(const Qe of we.logits_per_image){const Ze=[...Ae(Qe)].map((Ke,nt)=>({score:Ke,label:ae[nt]}));Ze.sort((Ke,nt)=>nt.score-Ke.score),Be.push(Ze)}return be?Be:Be[0]}}class ue extends b{constructor(X){super(X)}async _call(X,{threshold:ae=.9,percentage:W=!1}={}){const be=Array.isArray(X);if(be&&X.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const ke=await u(X),Ee=W?null:ke.map(xe=>[xe.height,xe.width]),{pixel_values:Me,pixel_mask:Se}=await this.processor(ke),we=await this.model({pixel_values:Me,pixel_mask:Se}),Ae=this.processor.image_processor.post_process_object_detection(we,ae,Ee),Be=this.model.config.id2label,Qe=Ae.map(xe=>xe.boxes.map((Ze,Ke)=>({score:xe.scores[Ke],label:Be[xe.classes[Ke]],box:_(Ze,!W)})));return be?Qe:Qe[0]}}class j extends b{constructor(X){super(X)}async _call(X,ae,{threshold:W=.1,top_k:be=null,percentage:ke=!1}={}){const Ee=Array.isArray(X),Me=await u(X),Se=this.tokenizer(ae,{padding:!0,truncation:!0}),we=await this.processor(Me),Ae=[];for(let Be=0;Be({score:Je.scores[Ye],label:Je.labels[Ye],box:_(Oe,!ke)}))}else{const Je=this.processor.image_processor.post_process_object_detection(Ke,W,xe,!0)[0];nt=Je.boxes.map((Oe,Ye)=>({score:Je.scores[Ye],label:ae[Je.classes[Ye]],box:_(Oe,!ke)}))}nt.sort((Je,Oe)=>Oe.score-Je.score),be!==null&&(nt=nt.slice(0,be)),Ae.push(nt)}return Ee?Ae:Ae[0]}}class F extends b{constructor(X){super(X)}async _call(X,ae,W={}){const be=(await u(X))[0],{pixel_values:ke}=await this.processor(be),Ee=`${ae}`,Me=this.tokenizer(Ee,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,Se=await this.model.generate({inputs:ke,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Me,...W}),Ae=this.tokenizer.batch_decode(Se)[0].match(/(.*?)<\/s_answer>/);let Be=null;return Ae&&Ae.length>=2&&(Be=Ae[1].trim()),[{answer:Be}]}}class U extends b{constructor(ae){super(ae);J(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=ae.vocoder??null}async _call(ae,{speaker_embeddings:W=null}={}){return this.processor?this._call_text_to_spectrogram(ae,{speaker_embeddings:W}):this._call_text_to_waveform(ae)}async _call_text_to_waveform(ae){const W=this.tokenizer(ae,{padding:!0,truncation:!0}),{waveform:be}=await this.model(W),ke=this.model.config.sampling_rate;return new c.RawAudio(be.data,ke)}async _call_text_to_spectrogram(ae,{speaker_embeddings:W}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await o.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof W=="string"||W instanceof URL)&&(W=new Float32Array(await(await fetch(W)).arrayBuffer())),W instanceof Float32Array)W=new p.Tensor("float32",W,[1,W.length]);else if(!(W instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:be}=this.tokenizer(ae,{padding:!0,truncation:!0}),{waveform:ke}=await this.model.generate_speech(be,W,{vocoder:this.vocoder}),Ee=this.processor.feature_extractor.config.sampling_rate;return new c.RawAudio(ke.data,Ee)}}class se extends b{constructor(X){super(X)}async _call(X){const ae=await u(X),W=await this.processor(ae),be=await this.model(W),ke=[];for(const Ee of be.reconstruction){const Me=Ee.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");ke.push(d.RawImage.fromTensor(Me))}return ke.length>1?ke:ke[0]}}class _e extends b{constructor(X){super(X)}async _call(X){const ae=await u(X),W=await this.processor(ae),{predicted_depth:be}=await this.model(W),ke=[];for(let Ee=0;Ee1?ke:ke[0]}}const ie=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:k,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:g,model:o.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:M,model:o.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:$,model:o.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:y,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:T,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:v,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:P,model:o.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:O,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:K,model:o.AutoModelForAudioClassification,processor:n.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:R,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:te,model:[o.AutoModelForSpeechSeq2Seq,o.AutoModelForCTC],processor:n.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:U,model:[o.AutoModelForTextToWaveform,o.AutoModelForTextToSpectrogram],processor:[n.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:H,model:o.AutoModelForVision2Seq,processor:n.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ee,model:o.AutoModelForImageClassification,processor:n.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Z,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:ne,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:me,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ue,model:o.AutoModelForObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:j,model:o.AutoModelForZeroShotObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:F,model:o.AutoModelForDocumentQuestionAnswering,processor:n.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:se,model:o.AutoModelForImageToImage,processor:n.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:_e,model:o.AutoModelForDepthEstimation,processor:n.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:L,model:o.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:n.AutoProcessor,pipeline:G,model:[o.AutoModelForImageFeatureExtraction,o.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),ve=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ze(Ie,X=null,{progress_callback:ae=null,config:W=null,cache_dir:be=null,local_files_only:ke=!1,revision:Ee="main",device:Me=null,dtype:Se=null,subfolder:we="onnx",use_external_data_format:Ae=null,model_file_name:Be=null,session_options:Qe={}}={}){Ie=ve[Ie]??Ie;const xe=ie[Ie.split("_",1)[0]];if(!xe)throw Error(`Unsupported pipeline: ${Ie}. Must be one of [${Object.keys(ie)}]`);X||(X=xe.default.model,console.log(`No model specified. Using default model: "${X}".`));const Ze={progress_callback:ae,config:W,cache_dir:be,local_files_only:ke,revision:Ee,device:Me,dtype:Se,subfolder:we,use_external_data_format:Ae,model_file_name:Be,session_options:Qe},Ke=new Map([["tokenizer",xe.tokenizer],["model",xe.model],["processor",xe.processor]]),nt=await Ge(Ke,X,Ze);nt.task=Ie,(0,a.dispatchCallback)(ae,{status:"ready",task:Ie,model:X});const Je=xe.pipeline;return new Je(nt)}async function Ge(Ie,X,ae){const W=Object.create(null),be=[];for(const[ke,Ee]of Ie.entries()){if(!Ee)continue;let Me;Array.isArray(Ee)?Me=new Promise(async(Se,we)=>{var Be,Qe;let Ae;for(const xe of Ee){if(xe===null){Se(null);return}try{Se(await xe.from_pretrained(X,ae));return}catch(Ze){if((Be=Ze.message)!=null&&Be.includes("Unsupported model type"))Ae=Ze;else if((Qe=Ze.message)!=null&&Qe.includes("Could not locate file"))Ae=Ze;else{we(Ze);return}}}we(Ae)}):Me=Ee.from_pretrained(X,ae),W[ke]=Me,be.push(Me)}await Promise.all(be);for(const[ke,Ee]of Object.entries(W))W[ke]=await Ee;return W}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Fs,AutoTokenizer:()=>xn,BartTokenizer:()=>st,BertTokenizer:()=>As,BlenderbotSmallTokenizer:()=>Xt,BlenderbotTokenizer:()=>et,BloomTokenizer:()=>Xr,CLIPTokenizer:()=>Ns,CamembertTokenizer:()=>Fe,CodeGenTokenizer:()=>Jr,CodeLlamaTokenizer:()=>$r,CohereTokenizer:()=>Ps,ConvBertTokenizer:()=>q,DebertaTokenizer:()=>S,DebertaV2Tokenizer:()=>Q,DistilBertTokenizer:()=>ge,ElectraTokenizer:()=>ft,Ernie4_5_Tokenizer:()=>vn,EsmTokenizer:()=>Ds,FalconTokenizer:()=>kr,GPT2Tokenizer:()=>vt,GPTNeoXTokenizer:()=>Os,GemmaTokenizer:()=>Wr,Grok1Tokenizer:()=>ts,HerbertTokenizer:()=>B,LlamaTokenizer:()=>Sr,M2M100Tokenizer:()=>pr,MBart50Tokenizer:()=>Ut,MBartTokenizer:()=>zt,MPNetTokenizer:()=>ds,MarianTokenizer:()=>Re,MgpstrTokenizer:()=>yn,MobileBertTokenizer:()=>Ct,NllbTokenizer:()=>Ts,NougatTokenizer:()=>Es,PreTrainedTokenizer:()=>pt,Qwen2Tokenizer:()=>Ur,RoFormerTokenizer:()=>re,RobertaTokenizer:()=>Nr,SiglipTokenizer:()=>Gr,SpeechT5Tokenizer:()=>Vs,SqueezeBertTokenizer:()=>Qt,T5Tokenizer:()=>ht,TokenizerModel:()=>G,VitsTokenizer:()=>Us,Wav2Vec2CTCTokenizer:()=>je,WhisperTokenizer:()=>mr,XLMRobertaTokenizer:()=>Vr,XLMTokenizer:()=>rt,is_chinese_char:()=>$});var s=t("./src/utils/generic.js"),o=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),c=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function d(pe,I){const N=await Promise.all([(0,n.getModelJSON)(pe,"tokenizer.json",!0,I),(0,n.getModelJSON)(pe,"tokenizer_config.json",!0,I)]);return I.legacy!==null&&(N[1].legacy=I.legacy),N}function u(pe,I){const N=[];let Y=0;for(const le of pe.matchAll(I)){const de=le[0];Y0&&N.push(de),Y=le.index+de.length}return Y=19968&&pe<=40959||pe>=13312&&pe<=19903||pe>=131072&&pe<=173791||pe>=173824&&pe<=177983||pe>=177984&&pe<=178207||pe>=178208&&pe<=183983||pe>=63744&&pe<=64255||pe>=194560&&pe<=195103}function v(pe,I,N){const Y=[];let le=0;for(;lethis.tokens_to_ids.get(N)??this.unk_token_id)}convert_ids_to_tokens(I){return I.map(N=>this.vocab[N]??this.unk_token)}}class K extends G{constructor(I){super(I),this.tokens_to_ids=_(I.vocab),this.unk_token_id=this.tokens_to_ids.get(I.unk_token),this.unk_token=I.unk_token,this.max_input_chars_per_word=I.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[N,Y]of this.tokens_to_ids)this.vocab[Y]=N}encode(I){const N=[];for(const Y of I){const le=[...Y];if(le.length>this.max_input_chars_per_word){N.push(this.unk_token);continue}let de=!1,Te=0;const Ne=[];for(;Te0&&(tt=this.config.continuing_subword_prefix+tt),this.tokens_to_ids.has(tt)){We=tt;break}--qe}if(We===null){de=!0;break}Ne.push(We),Te=qe}de?N.push(this.unk_token):N.push(...Ne)}return N}}class R extends G{constructor(I,N){super(I);const Y=I.vocab.length;this.vocab=new Array(Y),this.scores=new Array(Y);for(let le=0;le[le,de])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,i.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(I){const N=I.chars,Y=1;let le=0;for(;le{const pe=[...Array.from({length:94},(le,de)=>de+33),...Array.from({length:12},(le,de)=>de+161),...Array.from({length:82},(le,de)=>de+174)],I=pe.slice();let N=0;for(let le=0;le<256;++le)pe.includes(le)||(pe.push(le),I.push(256+N),N+=1);const Y=I.map(le=>String.fromCharCode(le));return Object.fromEntries(pe.map((le,de)=>[le,Y[de]]))})(),H=(0,o.reverseDictionary)(te);class ee extends G{constructor(I){super(I),this.tokens_to_ids=_(I.vocab),this.unk_token_id=this.tokens_to_ids.get(I.unk_token),this.unk_token=I.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[Y,le]of this.tokens_to_ids)this.vocab[le]=Y;const N=Array.isArray(I.merges[0]);this.merges=N?I.merges:I.merges.map(Y=>Y.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((Y,le)=>[JSON.stringify(Y),le])),this.end_of_word_suffix=I.end_of_word_suffix,this.continuing_subword_suffix=I.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new l.LRUCache(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(I){if(I.length===0)return[];const N=this.cache.get(I);if(N!==void 0)return N;const Y=Array.from(I);this.end_of_word_suffix&&(Y[Y.length-1]+=this.end_of_word_suffix);let le=[];if(Y.length>1){const de=new l.PriorityQueue((qe,We)=>qe.score`<0x${Ne.toString(16).toUpperCase().padStart(2,"0")}>`);Te.every(Ne=>this.tokens_to_ids.has(Ne))?N.push(...Te):N.push(this.unk_token)}else N.push(this.unk_token)}return N}}class Z extends G{constructor(I,N){super(I),this.tokens_to_ids=_(N.target_lang?I.vocab[N.target_lang]:I.vocab),this.bos_token=N.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=N.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=N.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[Y,le]of this.tokens_to_ids)this.vocab[le]=Y}encode(I){return I}}class ne extends s.Callable{constructor(I){super(),this.config=I}static fromConfig(I){if(I===null)return null;switch(I.type){case"BertNormalizer":return new Ie(I);case"Precompiled":return new jr(I);case"Sequence":return new Ge(I);case"Replace":return new me(I);case"NFC":return new j(I);case"NFD":return new F(I);case"NFKC":return new U(I);case"NFKD":return new se(I);case"Strip":return new _e(I);case"StripAccents":return new ie(I);case"Lowercase":return new ve(I);case"Prepend":return new ze(I);default:throw new Error(`Unknown Normalizer type: ${I.type}`)}}normalize(I){throw Error("normalize should be implemented in subclass.")}_call(I){return this.normalize(I)}}class me extends ne{normalize(I){const N=f(this.config.pattern);return N===null?I:I.replaceAll(N,this.config.content)}}class ue extends ne{constructor(){super(...arguments);J(this,"form")}normalize(N){return N=N.normalize(this.form),N}}class j extends ue{constructor(){super(...arguments);J(this,"form","NFC")}}class F extends ue{constructor(){super(...arguments);J(this,"form","NFD")}}class U extends ue{constructor(){super(...arguments);J(this,"form","NFKC")}}class se extends ue{constructor(){super(...arguments);J(this,"form","NFKD")}}class _e extends ne{normalize(I){return this.config.strip_left&&this.config.strip_right?I=I.trim():(this.config.strip_left&&(I=I.trimStart()),this.config.strip_right&&(I=I.trimEnd())),I}}class ie extends ne{normalize(I){return I=g(I),I}}class ve extends ne{normalize(I){return I=I.toLowerCase(),I}}class ze extends ne{normalize(I){return I=this.config.prepend+I,I}}class Ge extends ne{constructor(I){super(I),this.normalizers=I.normalizers.map(N=>ne.fromConfig(N))}normalize(I){return this.normalizers.reduce((N,Y)=>Y.normalize(N),I)}}class Ie extends ne{_tokenize_chinese_chars(I){const N=[];for(let Y=0;Ythis.pre_tokenize_text(Y,N)):this.pre_tokenize_text(I,N)).flat()}_call(I,N){return this.pre_tokenize(I,N)}}class ae extends X{constructor(I){super(),this.pattern=new RegExp(`[^\\s${T}]+|[${T}]`,"gu")}pre_tokenize_text(I,N){return I.trim().match(this.pattern)||[]}}class W extends X{constructor(I){super(),this.config=I,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=te,this.text_encoder=new TextEncoder}pre_tokenize_text(I,N){return this.add_prefix_space&&!I.startsWith(" ")&&(I=" "+I),(this.use_regex?I.match(this.pattern)||[]:[I]).map(le=>Array.from(this.text_encoder.encode(le),de=>this.byte_encoder[de]).join(""))}}class be extends X{constructor(I){super(),this.config=I,this.pattern=f(this.config.pattern,this.config.invert)}pre_tokenize_text(I,N){var Y;return this.pattern===null?[]:this.config.invert?I.match(this.pattern)||[]:((Y=this.config.behavior)==null?void 0:Y.toLowerCase())==="removed"?I.split(this.pattern).filter(le=>le):u(I,this.pattern)}}class ke extends X{constructor(I){super(),this.config=I,this.pattern=new RegExp(`[^${T}]+|[${T}]+`,"gu")}pre_tokenize_text(I,N){return I.match(this.pattern)||[]}}class Ee extends X{constructor(I){super(),this.config=I;const N=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(N,"gu")}pre_tokenize_text(I,N){return I.match(this.pattern)||[]}}class Me extends s.Callable{constructor(I){super(),this.config=I}static fromConfig(I){if(I===null)return null;switch(I.type){case"TemplateProcessing":return new Ae(I);case"ByteLevel":return new Be(I);case"RobertaProcessing":return new we(I);case"BertProcessing":return new Se(I);case"Sequence":return new Qe(I);default:throw new Error(`Unknown PostProcessor type: ${I.type}`)}}post_process(I,...N){throw Error("post_process should be implemented in subclass.")}_call(I,...N){return this.post_process(I,...N)}}class Se extends Me{constructor(I){super(I),this.cls=I.cls[0],this.sep=I.sep[0]}post_process(I,N=null,{add_special_tokens:Y=!0}={}){Y&&(I=(0,o.mergeArrays)([this.cls],I,[this.sep]));let le=new Array(I.length).fill(0);if(N!==null){const de=Y&&this instanceof we?[this.sep]:[],Te=Y?[this.sep]:[];I=(0,o.mergeArrays)(I,de,N,Te),le=(0,o.mergeArrays)(le,new Array(N.length+de.length+Te.length).fill(1))}return{tokens:I,token_type_ids:le}}}class we extends Se{}class Ae extends Me{constructor(I){super(I),this.single=I.single,this.pair=I.pair}post_process(I,N=null,{add_special_tokens:Y=!0}={}){const le=N===null?this.single:this.pair;let de=[],Te=[];for(const Ne of le)"SpecialToken"in Ne?Y&&(de.push(Ne.SpecialToken.id),Te.push(Ne.SpecialToken.type_id)):"Sequence"in Ne&&(Ne.Sequence.id==="A"?(de=(0,o.mergeArrays)(de,I),Te=(0,o.mergeArrays)(Te,new Array(I.length).fill(Ne.Sequence.type_id))):Ne.Sequence.id==="B"&&(de=(0,o.mergeArrays)(de,N),Te=(0,o.mergeArrays)(Te,new Array(N.length).fill(Ne.Sequence.type_id))));return{tokens:de,token_type_ids:Te}}}class Be extends Me{post_process(I,N=null){return N&&(I=(0,o.mergeArrays)(I,N)),{tokens:I}}}class Qe extends Me{constructor(I){super(I),this.processors=I.processors.map(N=>Me.fromConfig(N))}post_process(I,N=null,Y={}){let le;for(const de of this.processors)if(de instanceof Be)I=de.post_process(I).tokens,N&&(N=de.post_process(N).tokens);else{const Te=de.post_process(I,N,Y);I=Te.tokens,le=Te.token_type_ids}return{tokens:I,token_type_ids:le}}}class xe extends s.Callable{constructor(I){super(),this.config=I,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=I.trim_offsets}static fromConfig(I){if(I===null)return null;switch(I.type){case"WordPiece":return new Oe(I);case"Metaspace":return new Pr(I);case"ByteLevel":return new Ye(I);case"Replace":return new Ze(I);case"ByteFallback":return new Ke(I);case"Fuse":return new nt(I);case"Strip":return new Je(I);case"Sequence":return new It(I);case"CTC":return new ot(I);case"BPEDecoder":return new St(I);default:throw new Error(`Unknown Decoder type: ${I.type}`)}}_call(I){return this.decode(I)}decode(I){return this.decode_chain(I).join("")}decode_chain(I){throw Error("`decode_chain` should be implemented in subclass.")}}class Ze extends xe{decode_chain(I){const N=f(this.config.pattern);return N===null?I:I.map(Y=>Y.replaceAll(N,this.config.content))}}class Ke extends xe{constructor(I){super(I),this.text_decoder=new TextDecoder}decode_chain(I){const N=[];let Y=[];for(const le of I){let de=null;if(le.length===6&&le.startsWith("<0x")&&le.endsWith(">")){const Te=parseInt(le.slice(3,5),16);isNaN(Te)||(de=Te)}if(de!==null)Y.push(de);else{if(Y.length>0){const Te=this.text_decoder.decode(Uint8Array.from(Y));N.push(Te),Y=[]}N.push(le)}}if(Y.length>0){const le=this.text_decoder.decode(Uint8Array.from(Y));N.push(le),Y=[]}return N}}class nt extends xe{decode_chain(I){return[I.join("")]}}class Je extends xe{constructor(I){super(I),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(I){return I.map(N=>{let Y=0;for(let de=0;de(Y!==0&&(N.startsWith(this.config.prefix)?N=N.replace(this.config.prefix,""):N=" "+N),this.cleanup&&(N=k(N)),N))}}class Ye extends xe{constructor(I){super(I),this.byte_decoder=H,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(I){const N=I.join(""),Y=new Uint8Array([...N].map(de=>this.byte_decoder[de]));return this.text_decoder.decode(Y)}decode_chain(I){const N=[];let Y=[];for(const le of I)this.added_tokens.find(de=>de.content===le)!==void 0?(Y.length>0&&(N.push(this.convert_tokens_to_string(Y)),Y=[]),N.push(le)):Y.push(le);return Y.length>0&&N.push(this.convert_tokens_to_string(Y)),N}}class ot extends xe{constructor(I){super(I),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(I){if(I.length===0)return"";const N=[I[0]];for(let de=1;dede!==this.pad_token).join("");return this.cleanup&&(le=k(le).replaceAll(this.word_delimiter_token," ").trim()),le}decode_chain(I){return[this.convert_tokens_to_string(I)]}}class It extends xe{constructor(I){super(I),this.decoders=I.decoders.map(N=>xe.fromConfig(N))}decode_chain(I){return this.decoders.reduce((N,Y)=>Y.decode_chain(N),I)}}class St extends xe{constructor(I){super(I),this.suffix=this.config.suffix}decode_chain(I){return I.map((N,Y)=>N.replaceAll(this.suffix,Y===I.length-1?"":" "))}}class wt extends xe{decode_chain(I){let N="";for(let Y=1;YY.normalize("NFKC")).join("~"):I=I.normalize("NFKC"),I}}class us extends X{constructor(I){super(),this.tokenizers=I.pretokenizers.map(N=>X.fromConfig(N))}pre_tokenize_text(I,N){return this.tokenizers.reduce((Y,le)=>le.pre_tokenize(Y,N),[I])}}class qt extends X{constructor(I){super()}pre_tokenize_text(I,N){return I.match(/\w+|[^\w\s]+/g)||[]}}class Cr extends X{constructor(I){super()}pre_tokenize_text(I,N){return y(I)}}class Xs extends X{constructor(I){super(),this.config=I,this.pattern=f(this.config.pattern),this.content=this.config.content}pre_tokenize_text(I,N){return this.pattern===null?[I]:[I.replaceAll(this.pattern,this.config.content)]}}const Js=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Ys(pe,I,N,Y){for(const le of Object.keys(pe)){const de=I-pe[le].length,Te=N(le),Ne=new Array(de).fill(Te);pe[le]=Y==="right"?(0,o.mergeArrays)(pe[le],Ne):(0,o.mergeArrays)(Ne,pe[le])}}function Zs(pe,I){for(const N of Object.keys(pe))pe[N].length=I}class pt extends s.Callable{constructor(N,Y){super();J(this,"return_token_type_ids",!1);J(this,"padding_side","right");this.config=Y,this.normalizer=ne.fromConfig(N.normalizer),this.pre_tokenizer=X.fromConfig(N.pre_tokenizer),this.model=G.fromConfig(N.model,Y),this.post_processor=Me.fromConfig(N.post_processor),this.decoder=xe.fromConfig(N.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const le of N.added_tokens){const de=new L(le);this.added_tokens.push(de),this.model.tokens_to_ids.set(de.content,de.id),this.model.vocab[de.id]=de.content,de.special&&(this.special_tokens.push(de.content),this.all_special_ids.push(de.id))}if(this.additional_special_tokens=Y.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new l.DictionarySplitter(this.added_tokens.map(le=>le.content)),this.added_tokens_map=new Map(this.added_tokens.map(le=>[le.content,le])),this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=Y.model_max_length,this.remove_space=Y.remove_space,this.clean_up_tokenization_spaces=Y.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Y.do_lowercase_and_remove_accent??!1,Y.padding_side&&(this.padding_side=Y.padding_side),this.add_bos_token=Y.add_bos_token,this.add_eos_token=Y.add_eos_token,this.legacy=!1,this.chat_template=Y.chat_template??null,Array.isArray(this.chat_template)){const le=Object.create(null);for(const{name:de,template:Te}of this.chat_template){if(typeof de!="string"||typeof Te!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');le[de]=Te}this.chat_template=le}this._compiled_template_cache=new Map}getToken(...N){for(const Y of N){const le=this.config[Y];if(le)if(typeof le=="object"){if(le.__type==="AddedToken")return le.content;throw Error(`Unknown token: ${le}`)}else return le}return null}static async from_pretrained(N,{progress_callback:Y=null,config:le=null,cache_dir:de=null,local_files_only:Te=!1,revision:Ne="main",legacy:qe=null}={}){const We=await d(N,{progress_callback:Y,config:le,cache_dir:de,local_files_only:Te,revision:Ne,legacy:qe});return new this(...We)}_call(N,{text_pair:Y=null,add_special_tokens:le=!0,padding:de=!1,truncation:Te=null,max_length:Ne=null,return_tensor:qe=!0,return_token_type_ids:We=null}={}){const tt=Array.isArray(N);let Mt;if(tt){if(N.length===0)throw Error("text array must be non-empty");if(Y!==null){if(Array.isArray(Y)){if(N.length!==Y.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Mt=N.map((Lt,sr)=>this._encode_plus(Lt,{text_pair:Y[sr],add_special_tokens:le,return_token_type_ids:We}))}else Mt=N.map(Lt=>this._encode_plus(Lt,{add_special_tokens:le,return_token_type_ids:We}))}else{if(N==null)throw Error("text may not be null or undefined");if(Array.isArray(Y))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Mt=[this._encode_plus(N,{text_pair:Y,add_special_tokens:le,return_token_type_ids:We})]}if(Ne===null?Ne=this.model_max_length:Te===null&&(de===!0?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),Ne=this.model_max_length):de===!1&&(console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),Te=!0)),de===!0&&(Ne=Math.min((0,i.max)(Mt.map(Lt=>Lt.input_ids.length))[0],Ne??1/0)),Ne=Math.min(Ne,this.model_max_length??1/0),de||Te)for(let Lt=0;LtNe?Te&&Zs(Mt[Lt],Ne):de&&Ys(Mt[Lt],Ne,sr=>sr==="input_ids"?this.pad_token_id:0,this.padding_side));const Bt={};if(qe){if(!(de&&Te)&&Mt.some(sr=>{var Wt;for(const _r of Object.keys(sr))if(sr[_r].length!==((Wt=Mt[0][_r])==null?void 0:Wt.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const Lt=[Mt.length,Mt[0].input_ids.length];for(const sr of Object.keys(Mt[0]))Bt[sr]=new a.Tensor("int64",BigInt64Array.from(Mt.flatMap(Wt=>Wt[sr]).map(BigInt)),Lt)}else{for(const Lt of Object.keys(Mt[0]))Bt[Lt]=Mt.map(sr=>sr[Lt]);if(!tt)for(const Lt of Object.keys(Bt))Bt[Lt]=Bt[Lt][0]}return Bt}_encode_text(N){if(N===null)return null;const Y=this.added_tokens_splitter.split(N);for(let de=0;de0&&(Y[de-1]=Y[de-1].trimEnd()),Te.rstrip&&de{if(de.length===0)return[];if(this.added_tokens_map.has(de))return[de];if(this.remove_space===!0&&(de=de.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(de=M(de)),this.normalizer!==null&&(de=this.normalizer(de)),de.length===0)return[];const Ne=this.pre_tokenizer!==null?this.pre_tokenizer(de,{section_index:Te}):[de];return this.model(Ne)})}_encode_plus(N,{text_pair:Y=null,add_special_tokens:le=!0,return_token_type_ids:de=null}={}){const{tokens:Te,token_type_ids:Ne}=this._tokenize_helper(N,{pair:Y,add_special_tokens:le}),qe=this.model.convert_tokens_to_ids(Te),We={input_ids:qe,attention_mask:new Array(qe.length).fill(1)};return(de??this.return_token_type_ids)&&Ne&&(We.token_type_ids=Ne),We}_tokenize_helper(N,{pair:Y=null,add_special_tokens:le=!1}={}){const de=this._encode_text(N),Te=this._encode_text(Y);return this.post_processor?this.post_processor(de,Te,{add_special_tokens:le}):{tokens:(0,o.mergeArrays)(de??[],Te??[])}}tokenize(N,{pair:Y=null,add_special_tokens:le=!1}={}){return this._tokenize_helper(N,{pair:Y,add_special_tokens:le}).tokens}encode(N,{text_pair:Y=null,add_special_tokens:le=!0,return_token_type_ids:de=null}={}){return this._encode_plus(N,{text_pair:Y,add_special_tokens:le,return_token_type_ids:de}).input_ids}batch_decode(N,Y={}){return N instanceof a.Tensor&&(N=N.tolist()),N.map(le=>this.decode(le,Y))}decode(N,Y={}){if(N instanceof a.Tensor&&(N=b(N)),!Array.isArray(N)||N.length===0||!(0,o.isIntegralNumber)(N[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(N,Y)}decode_single(N,{skip_special_tokens:Y=!1,clean_up_tokenization_spaces:le=null}){let de=this.model.convert_ids_to_tokens(N);Y&&(de=de.filter(Ne=>!this.special_tokens.includes(Ne)));let Te=this.decoder?this.decoder(de):de.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Te=Te.replaceAll(this.decoder.end_of_word_suffix," "),Y&&(Te=Te.trim())),(le??this.clean_up_tokenization_spaces)&&(Te=k(Te)),Te}get_chat_template({chat_template:N=null,tools:Y=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const le=this.chat_template;if(N!==null&&Object.hasOwn(le,N))N=le[N];else if(N===null)if(Y!==null&&"tool_use"in le)N=le.tool_use;else if("default"in le)N=le.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(le).sort()}.`)}else if(N===null)if(this.chat_template)N=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return N}apply_chat_template(N,{tools:Y=null,documents:le=null,chat_template:de=null,add_generation_prompt:Te=!1,tokenize:Ne=!0,padding:qe=!1,truncation:We=!1,max_length:tt=null,return_tensor:Mt=!0,return_dict:Bt=!1,tokenizer_kwargs:Lt={},...sr}={}){if(de=this.get_chat_template({chat_template:de,tools:Y}),typeof de!="string")throw Error(`chat_template must be a string, but got ${typeof de}`);let Wt=this._compiled_template_cache.get(de);Wt===void 0&&(Wt=new c.Template(de),this._compiled_template_cache.set(de,Wt));const _r=Object.create(null);for(const ir of Js){const fr=this.getToken(ir);fr&&(_r[ir]=fr)}const br=Wt.render({messages:N,add_generation_prompt:Te,tools:Y,documents:le,..._r,...sr});if(Ne){const ir=this._call(br,{add_special_tokens:!1,padding:qe,truncation:We,max_length:tt,return_tensor:Mt,...Lt});return Bt?ir:ir.input_ids}return br}}class As extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class Fs extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class Ct extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class Qt extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class S extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class Q extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class B extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class q extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class re extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class ge extends pt{}class Fe extends pt{}class rt extends pt{constructor(N,Y){super(N,Y);J(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class ft extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class ht extends pt{}class vt extends pt{}class st extends pt{}class zt extends pt{constructor(I,N){super(I,N),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)),this.lang_to_token=Y=>Y}_build_translation_inputs(I,N,Y){return Dr(this,I,N,Y)}}class Ut extends zt{}class Nr extends pt{}class Xr extends pt{}const rr="▁";class Sr extends pt{constructor(N,Y){super(N,Y);J(this,"padding_side","left");this.legacy=Y.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Mr({replacement:rr,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(N){if(N===null)return null;if(this.legacy||N.length===0)return super._encode_text(N);let Y=super._encode_text(rr+N.replaceAll(rr," "));return Y.length>1&&Y[0]===rr&&this.special_tokens.includes(Y[1])&&(Y=Y.slice(1)),Y}}class $r extends pt{}class Vr extends pt{}class ds extends pt{}class kr extends pt{}class Os extends pt{}class Ds extends pt{}class Ur extends pt{}class Wr extends pt{}class ts extends pt{}function Dr(pe,I,N,Y){if(!("language_codes"in pe)||!Array.isArray(pe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in pe)||!(pe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in pe)||typeof pe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const le=Y.src_lang,de=Y.tgt_lang;if(!pe.language_codes.includes(de))throw new Error(`Target language code "${de}" is not valid. Must be one of: {${pe.language_codes.join(", ")}}`);if(le!==void 0){if(!pe.language_codes.includes(le))throw new Error(`Source language code "${le}" is not valid. Must be one of: {${pe.language_codes.join(", ")}}`);for(const Te of pe.post_processor.config.single)if("SpecialToken"in Te&&pe.languageRegex.test(Te.SpecialToken.id)){Te.SpecialToken.id=pe.lang_to_token(le);break}}return Y.forced_bos_token_id=pe.model.convert_tokens_to_ids([pe.lang_to_token(de)])[0],pe._call(I,N)}class Ts extends pt{constructor(I,N){super(I,N),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)),this.lang_to_token=Y=>Y}_build_translation_inputs(I,N,Y){return Dr(this,I,N,Y)}}class pr extends pt{constructor(I,N){super(I,N),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)).map(Y=>Y.slice(2,-2)),this.lang_to_token=Y=>`__${Y}__`}_build_translation_inputs(I,N,Y){return Dr(this,I,N,Y)}}class mr extends pt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(I,{return_timestamps:N=!1,return_language:Y=!1,time_precision:le=null,force_full_sequences:de=!0}={}){if(le===null)throw Error("Must specify time_precision");let Te=null;const Ne=N==="word";function qe(){return{language:Te,timestamp:[null,null],text:""}}const We=[];let tt=qe(),Mt=0;const Bt=this.timestamp_begin,sr=Bt+1500;let Wt=[],_r=[],br=!1,ir=null;const fr=new Set(this.all_special_ids);for(const Zt of I){const gr=Zt.tokens,Kr=Ne?Zt.token_timestamps:null;let zr=null,Cs=Bt;if("stride"in Zt){const[ur,ar,hr]=Zt.stride;if(Mt-=ar,ir=ur-hr,ar&&(Cs=ar/le+Bt),hr)for(let nr=gr.length-1;nr>=0;--nr){const Hr=Number(gr[nr]);if(Hr>=Bt){if(zr!==null&&(Hr-Bt)*le=Bt&&ar<=sr){const hr=(ar-Bt)*le+Mt,nr=(0,i.round)(hr,2);if(zr!==null&&ar>=zr)br=!0;else if(br||Wt.length>0&&ar0?(Wt.push(Ir),Ne&&_r.push(ps)):Wt.every(ur=>ur.length===0)&&(tt=qe(),Wt=[],Ir=[],_r=[],ps=[])}if(Wt.length>0){if(de&&N)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Zt,gr]=this.findLongestCommonSequence(Wt,_r),Kr=this.decode(Zt);tt.text=Kr,Ne&&(tt.words=this.collateWordTimestamps(Zt,gr,Te)),We.push(tt)}let Lr=Object.create(null);const Yr=We.map(Zt=>Zt.text).join("");if(N||Y){for(let Zt=0;Zt0;let Ne=Te?[]:null,qe=Te?N[0]:null;for(let We=1;Wear===Cs[hr]&&qe[Yr+hr]<=N[We][Kr+hr]).length:Ir=gr.filter((ar,hr)=>ar===Cs[hr]).length;const ps=Lr/1e4,ur=Ir/Lr+ps;Ir>1&&ur>Mt&&(Mt=ur,Bt=[Yr,Zt,Kr,zr])}const[sr,Wt,_r,br]=Bt,ir=Math.floor((Wt+sr)/2),fr=Math.floor((br+_r)/2);de.push(...Y.slice(0,ir)),Y=tt.slice(fr),le=Y.length,Te&&(Ne.push(...qe.slice(0,ir)),qe=N[We].slice(fr))}return de.push(...Y),Te?(Ne.push(...qe),[de,Ne]):[de,[]]}collateWordTimestamps(I,N,Y){const[le,de,Te]=this.combineTokensIntoWords(I,Y),Ne=[];for(let qe=0;qe=le){const Ne=((Te-le)*Y).toFixed(2);de.push(`<|${Ne}|>`),de.push([])}else de[de.length-1].push(Te);return de=de.map(Te=>typeof Te=="string"?Te:super.decode(Te,N)),de.join("")}splitTokensOnUnicode(I){const N=this.decode(I,{decode_with_timestamps:!0}),Y="�",le=[],de=[],Te=[];let Ne=[],qe=[],We=0;for(let tt=0;tt=this.model.tokens_to_ids.get("<|endoftext|>"),sr=tt.startsWith(" "),Wt=tt.trim(),_r=qe.test(Wt);if(Lt||sr||_r||de.length===0)de.push(tt),Te.push(Mt),Ne.push(Bt);else{const br=de.length-1;de[br]+=tt,Te[br].push(...Mt),Ne[br].push(...Bt)}}return[de,Te,Ne]}mergePunctuations(I,N,Y,le,de){const Te=structuredClone(I),Ne=structuredClone(N),qe=structuredClone(Y);let We=Te.length-2,tt=Te.length-1;for(;We>=0;)Te[We].startsWith(" ")&&le.includes(Te[We].trim())?(Te[tt]=Te[We]+Te[tt],Ne[tt]=(0,o.mergeArrays)(Ne[We],Ne[tt]),qe[tt]=(0,o.mergeArrays)(qe[We],qe[tt]),Te[We]="",Ne[We]=[],qe[We]=[]):tt=We,--We;for(We=0,tt=1;ttMt),Ne.filter(Mt=>Mt.length>0),qe.filter(Mt=>Mt.length>0)]}}class Jr extends pt{}class Ns extends pt{}class Gr extends pt{}class Re extends pt{constructor(I,N){super(I,N),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Y=>this.languageRegex.test(Y)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(I){if(I===null)return null;const[N,...Y]=I.trim().split(this.languageRegex);if(Y.length===0)return super._encode_text(N);if(Y.length===2){const[le,de]=Y;return this.supported_language_codes.includes(le)||console.warn(`Unsupported language code "${le}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,o.mergeArrays)([le],super._encode_text(de))}}}class je extends pt{}class et extends pt{}class Xt extends pt{}class Vs extends pt{}class Es extends pt{}class Us extends pt{constructor(I,N){super(I,N),this.decoder=new wt({})}}class Ps extends pt{}class yn extends pt{}class vn extends pt{}class xn{static async from_pretrained(I,{progress_callback:N=null,config:Y=null,cache_dir:le=null,local_files_only:de=!1,revision:Te="main",legacy:Ne=null}={}){var Bt;const[qe,We]=await d(I,{progress_callback:N,config:Y,cache_dir:le,local_files_only:de,revision:Te,legacy:Ne}),tt=((Bt=We.tokenizer_class)==null?void 0:Bt.replace(/Fast$/,""))??"PreTrainedTokenizer";let Mt=this.TOKENIZER_CLASS_MAPPING[tt];return Mt||(console.warn(`Unknown tokenizer class "${tt}", attempting to construct from base class.`),Mt=pt),new Mt(qe,We)}}J(xn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:ht,DistilBertTokenizer:ge,CamembertTokenizer:Fe,DebertaTokenizer:S,DebertaV2Tokenizer:Q,BertTokenizer:As,HerbertTokenizer:B,ConvBertTokenizer:q,RoFormerTokenizer:re,XLMTokenizer:rt,ElectraTokenizer:ft,MobileBertTokenizer:Ct,SqueezeBertTokenizer:Qt,AlbertTokenizer:Fs,GPT2Tokenizer:vt,BartTokenizer:st,MBartTokenizer:zt,MBart50Tokenizer:Ut,RobertaTokenizer:Nr,WhisperTokenizer:mr,CodeGenTokenizer:Jr,CLIPTokenizer:Ns,SiglipTokenizer:Gr,MarianTokenizer:Re,BloomTokenizer:Xr,NllbTokenizer:Ts,M2M100Tokenizer:pr,LlamaTokenizer:Sr,CodeLlamaTokenizer:$r,XLMRobertaTokenizer:Vr,MPNetTokenizer:ds,FalconTokenizer:kr,GPTNeoXTokenizer:Os,EsmTokenizer:Ds,Wav2Vec2CTCTokenizer:je,BlenderbotTokenizer:et,BlenderbotSmallTokenizer:Xt,SpeechT5Tokenizer:Vs,NougatTokenizer:Es,VitsTokenizer:Us,Qwen2Tokenizer:Ur,GemmaTokenizer:Wr,Grok1Tokenizer:ts,CohereTokenizer:Ps,MgpstrTokenizer:yn,Ernie4_5_Tokenizer:vn,PreTrainedTokenizer:pt})},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>K,hamming:()=>u,hanning:()=>d,mel_filter_bank:()=>$,read_audio:()=>c,spectrogram:()=>P,window_function:()=>O});var s=t("./src/utils/hub.js"),o=t("./src/utils/maths.js"),n=t("./src/utils/core.js"),i=t("./src/env.js"),a=t("./src/utils/tensor.js"),l=t("?7992");async function c(R,te){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const H=await(await(0,s.getFile)(R)).arrayBuffer(),ee=new AudioContext({sampleRate:te});typeof te>"u"&&console.warn(`No sampling rate provided, using default of ${ee.sampleRate}Hz.`);const Z=await ee.decodeAudioData(H);let ne;if(Z.numberOfChannels===2){const me=Math.sqrt(2),ue=Z.getChannelData(0),j=Z.getChannelData(1);ne=new Float32Array(ue.length);for(let F=0;F2595*Math.log10(1+R/700),kaldi:R=>1127*Math.log(1+R/700),slaney:(R,te=1e3,H=15,ee=27/Math.log(6.4))=>R>=te?H+Math.log(R/te)*ee:3*R/200};function _(R,te="htk"){const H=f[te];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof R=="number"?H(R):R.map(ee=>H(ee))}const b={htk:R=>700*(10**(R/2595)-1),kaldi:R=>700*(Math.exp(R/1127)-1),slaney:(R,te=1e3,H=15,ee=Math.log(6.4)/27)=>R>=H?te*Math.exp(ee*(R-H)):200*R/3};function k(R,te="htk"){const H=b[te];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof R=="number"?H(R):R.map(ee=>H(ee))}function g(R,te){const H=Float64Array.from({length:te.length-1},(me,ue)=>te[ue+1]-te[ue]),ee=Array.from({length:R.length},()=>new Array(te.length));for(let me=0;menew Array(R.length));for(let me=0;meR+ee*ne)}function $(R,te,H,ee,Z,ne=null,me="htk",ue=!1){if(ne!==null&&ne!=="slaney")throw new Error('norm must be one of null or "slaney"');if(R<2)throw new Error(`Require num_frequency_bins: ${R} >= 2`);if(H>ee)throw new Error(`Require min_frequency: ${H} <= max_frequency: ${ee}`);const j=_(H,me),F=_(ee,me),U=M(j,F,te+2);let se=k(U,me),_e;if(ue){const ve=Z/((R-1)*2);_e=_(Float64Array.from({length:R},(ze,Ge)=>Ge*ve),me),se=U}else _e=M(0,Math.floor(Z/2),R);const ie=g(_e,se);if(ne!==null&&ne==="slaney")for(let ve=0;veZ)throw Error(`frame_length (${H}) may not be larger than fft_length (${Z})`);if(ke!==H)throw new Error(`Length of the window (${ke}) must equal frame_length (${H})`);if(ee<=0)throw new Error("hop_length must be greater than zero");if(ne===null&&se!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!U)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(me){if(ue!=="reflect")throw new Error(`pad_mode="${ue}" not implemented yet.`);const Je=Math.floor((Z-1)/2)+1;R=v(R,Je,Je)}let Ee=Math.floor(1+Math.floor((R.length-H)/ee));X!==null&&EeEe?W&&(we=ae):we=Se=ae);const Ae=new o.FFT(Z),Be=new Float64Array(Z),Qe=new Float64Array(Ae.outputBufferSize),xe=new Float32Array(Me*we);for(let Je=0;Je=1;--ot)Be[ot]-=F*Be[ot-1];Be[0]*=1-F}for(let ot=0;otMath.pow(ue,.85));break;default:throw new Error(`Unknown window type ${te}.`)}if(H&&(me=me.subarray(0,R)),ee===null)return me;if(R>ee)throw new Error(`Length of the window (${R}) may not be larger than frame_length (${ee})`);return me}function L(R,te){let H=44;const ee=new ArrayBuffer(H+R.length*4),Z=new DataView(ee);G(Z,0,"RIFF"),Z.setUint32(4,36+R.length*4,!0),G(Z,8,"WAVE"),G(Z,12,"fmt "),Z.setUint32(16,16,!0),Z.setUint16(20,3,!0),Z.setUint16(22,1,!0),Z.setUint32(24,te,!0),Z.setUint32(28,te*4,!0),Z.setUint16(32,4,!0),Z.setUint16(34,32,!0),G(Z,36,"data"),Z.setUint32(40,R.length*4,!0);for(let ne=0;ne{let ne=await Z.arrayBuffer();l.writeFileSync(ee,Buffer.from(ne))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await H(te,this.toBlob())}}},"./src/utils/constants.js":(e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>o,FEATURE_EXTRACTOR_NAME:()=>n,GENERATION_CONFIG_NAME:()=>c,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",o="config.json",n="preprocessor_config.json",i=n,a="processor_config.json",l="chat_template.jinja",c="generation_config.json"},"./src/utils/core.js":(e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>c,calculateReflectOffset:()=>f,count:()=>g,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>k,mergeArrays:()=>d,pick:()=>b,pop:()=>p,product:()=>u,reverseDictionary:()=>o,saveBlob:()=>_});function s(M,$){M&&M($)}function o(M){return Object.fromEntries(Object.entries(M).map(([$,v])=>[v,$]))}function n(M){return M.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(M){var $,v,y;return((y=(v=($=M==null?void 0:M.prototype)==null?void 0:$.__proto__)==null?void 0:v.constructor)==null?void 0:y.name)==="TypedArray"}function a(M){return Number.isInteger(M)||typeof M=="bigint"}function l(M){return M==null||M===-1}function c(M){const $=[];let v=M;for(;Array.isArray(v);)$.push(v.length),v=v[0];return $}function p(M,$,v=void 0){const y=M[$];if(y!==void 0)return delete M[$],y;if(v===void 0)throw Error(`Key ${$} does not exist in object.`);return v}function d(...M){return Array.prototype.concat.apply([],M)}function u(...M){return M.reduce(($,v)=>$.flatMap(y=>v.map(T=>[y,T])))}function f(M,$){return Math.abs((M+$)%(2*$)-$)}function _(M,$){const v=URL.createObjectURL($),y=document.createElement("a");y.href=v,y.download=M,y.click(),y.remove(),URL.revokeObjectURL(v)}function b(M,$){return Object.assign({},...$.map(v=>{if(M[v]!==void 0)return{[v]:M[v]}}))}function k(M){let $=0;for(const v of M)++$;return $}function g(M,$){let v=0;for(const y of M)y===$&&++v;return v}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>o,DictionarySplitter:()=>l,LRUCache:()=>c,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(d=(f,_)=>f>_,u=1/0){this._heap=[],this._comparator=d,this._maxSize=u}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...d){return this.extend(d)}extend(d){for(const u of d)if(this.size0&&this._swap(0,u),this._heap.pop(),this._siftDown(),d}replace(d){const u=this.peek();return this._heap[0]=d,this._siftDown(),u}_parent(d){return(d+1>>>1)-1}_left(d){return(d<<1)+1}_right(d){return d+1<<1}_greater(d,u){return this._comparator(this._heap[d],this._heap[u])}_swap(d,u){const f=this._heap[d];this._heap[d]=this._heap[u],this._heap[u]=f}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(d){for(;d>0&&this._greater(d,this._parent(d));)this._swap(d,this._parent(d)),d=this._parent(d)}_siftDown(){let d=0;for(;this._left(d)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const _=new a(this.bosTokenId,0,0,0,0),b=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(_.clone()),this.nodes.push(b.clone()),this.beginNodes[this.len].push(b),this.endNodes[0].push(_)}insert(d,u,f,_){const b=this.nodes.length,k=new a(_,b,d,u,f);this.beginNodes[d].push(k),this.endNodes[d+u].push(k),this.nodes.push(k)}viterbi(){const d=this.len;let u=0;for(;u<=d;){if(this.beginNodes[u].length==0)return[];for(let g of this.beginNodes[u]){g.prev=null;let M=0,$=null;for(let v of this.endNodes[u]){const y=v.backtraceScore+g.score;($===null||y>M)&&($=v.clone(),M=y)}if($!==null)g.prev=$,g.backtraceScore=M;else return[]}++u}const f=[],b=this.beginNodes[d][0].prev;if(b===null)return[];let k=b.clone();for(;k.prev!==null;)f.push(k.clone()),k=k.clone().prev.clone();return f.reverse(),f}piece(d){return this.chars.slice(d.pos,d.pos+d.length).join("")}tokens(){return this.viterbi().map(u=>this.piece(u))}tokenIds(){return this.viterbi().map(u=>u.tokenId)}}class a{constructor(d,u,f,_,b){this.tokenId=d,this.nodeId=u,this.pos=f,this.length=_,this.score=b,this.prev=null,this.backtraceScore=0}clone(){const d=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return d.prev=this.prev,d.backtraceScore=this.backtraceScore,d}}class l{constructor(d){this.trie=this._buildTrie(d)}_buildTrie(d){var f;const u=Object.create(null);for(const _ of d){let b=u;for(let k=0;k<_.length;++k)b=b[f=_[k]]??(b[f]=Object.create(null));b.end=_}return u}split(d){const u=[],f=d.length;let _=0,b=0;for(;b_&&u.push(d.slice(_,b)),u.push(g),b+=g.length,_=b):++b}return _this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}},"./src/utils/devices.js":(e,r,t)=>{t.r(r),t.d(r,{DEVICE_TYPES:()=>s});const s=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(e,r,t)=>{t.r(r),t.d(r,{DATA_TYPES:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>n});var s=t("./src/env.js"),o=t("./src/utils/devices.js");const n=function(){let c;return async function(){if(c===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)c=!1;else try{c=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{c=!1}return c}}(),i=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[o.DEVICE_TYPES.wasm]:i.q8}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized",[i.q4]:"_q4",[i.q4f16]:"_q4f16",[i.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let o=function(...n){return o._call(...n)};return Object.setPrototypeOf(o,new.target.prototype)}_call(...o){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(e,r,t)=>{t.r(r),t.d(r,{MAX_EXTERNAL_DATA_CHUNKS:()=>a,getFile:()=>f,getModelFile:()=>M,getModelJSON:()=>v,getModelText:()=>$});var s=t("?7992"),o=t("?5af5"),n=t("./src/env.js"),i=t("./src/utils/core.js");const a=100,l={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class c{constructor(P){if(this.filePath=P,this.headers=new Headers,this.exists=s.existsSync(P),this.exists){this.status=200,this.statusText="OK";let O=s.statSync(P);this.headers.set("content-length",O.size.toString()),this.updateContentType();const L=s.createReadStream(P);this.body=new ReadableStream({start(G){L.on("data",K=>G.enqueue(K)),L.on("end",()=>G.close()),L.on("error",K=>G.error(K))},cancel(){L.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const P=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[P]??"application/octet-stream")}clone(){let P=new c(this.filePath);return P.exists=this.exists,P.status=this.status,P.statusText=this.statusText,P.headers=new Headers(this.headers),P}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const P=await s.promises.readFile(this.filePath);return new Blob([P],{type:this.headers.get("content-type")})}async text(){return await s.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function p(x,P=null,O=null){let L;try{L=new URL(x)}catch{return!1}return!(P&&!P.includes(L.protocol)||O&&!O.includes(L.hostname))}const d=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function u(x){return!(!d.test(x)||x.includes("..")||x.includes("--")||x.endsWith(".git")||x.endsWith(".ipynb"))}async function f(x){var P;if(n.env.useFS&&!p(x,["http:","https:","blob:"]))return new c(x instanceof URL?x.protocol==="file:"?x.pathname:x.toString():x);if(typeof process<"u"&&((P=process==null?void 0:process.release)==null?void 0:P.name)==="node"){const O=!!(js!=null&&js.TESTING_REMOTELY),L=n.env.version,G=new Headers;if(G.set("User-Agent",`transformers.js/${L}; is_ci/${O};`),p(x,["http:","https:"],["huggingface.co","hf.co"])){const R=(js==null?void 0:js.HF_TOKEN)??(js==null?void 0:js.HF_ACCESS_TOKEN);R&&G.set("Authorization",`Bearer ${R}`)}return fetch(x,{headers:G})}else return fetch(x)}const _={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function b(x,P,O){if(!O)return null;const L=_[x]??`Error (${x}) occurred while trying to load file`;throw Error(`${L}: "${P}".`)}class k{constructor(P){this.path=P}async match(P){let O=o.join(this.path,P),L=new c(O);if(L.exists)return L}async put(P,O,L=void 0){let G=o.join(this.path,P);try{const K=O.headers.get("Content-Length"),R=parseInt(K??"0");let te=0;await s.promises.mkdir(o.dirname(G),{recursive:!0});const H=s.createWriteStream(G),ee=O.body.getReader();for(;;){const{done:Z,value:ne}=await ee.read();if(Z)break;await new Promise((ue,j)=>{H.write(ne,F=>{if(F){j(F);return}ue()})}),te+=ne.length;const me=R?te/R*100:0;L==null||L({progress:me,loaded:te,total:R})}H.close()}catch(K){try{await s.promises.unlink(G)}catch{}throw K}}}async function g(x,...P){for(let O of P)try{let L=await x.match(O);if(L)return L}catch{continue}}async function M(x,P,O=!0,L={},G=!1){if(!n.env.allowLocalModels){if(L.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!n.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,i.dispatchCallback)(L.progress_callback,{status:"initiate",name:x,file:P});let K;if(!K&&n.env.useCustomCache){if(!n.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!n.env.customCache.match||!n.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");K=n.env.customCache}if(!K&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{K=await caches.open("transformers-cache")}catch(_e){console.warn("An error occurred while opening the browser cache:",_e)}}if(!K&&n.env.useFSCache){if(!n.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");K=new k(L.cache_dir??n.env.cacheDir)}const R=L.revision??"main",te=T(x,P),H=u(x),ee=H?T(n.env.localModelPath,te):te,Z=T(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",x).replaceAll("{revision}",encodeURIComponent(R)),P);let ne;const me=K instanceof k?R==="main"?te:T(x,R,P):Z;let ue=!1,j;K&&(j=await g(K,ee,me));const F=j!==void 0;if(j===void 0){if(n.env.allowLocalModels)if(p(te,["http:","https:"])){if(L.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${te}.`);if(!n.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${te}.`)}else try{j=await f(ee),ne=ee}catch(ie){console.warn(`Unable to load from local path "${ee}": "${ie}"`)}if(j===void 0||j.status===404){if(L.local_files_only||!n.env.allowRemoteModels){if(O)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ee}".`);return null}if(!H)throw Error(`Local file missing at "${ee}" and download aborted due to invalid model ID "${x}".`);if(j=await f(Z),j.status!==200)return b(j.status,Z,O);ne=me}ue=K&&typeof Response<"u"&&j instanceof Response&&j.status===200}(0,i.dispatchCallback)(L.progress_callback,{status:"download",name:x,file:P});let U;if(!(n.apis.IS_NODE_ENV&&G)){let _e;L.progress_callback?F&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(_e=new Uint8Array(await j.arrayBuffer()),(0,i.dispatchCallback)(L.progress_callback,{status:"progress",name:x,file:P,progress:100,loaded:_e.length,total:_e.length})):_e=await y(j,ie=>{(0,i.dispatchCallback)(L.progress_callback,{status:"progress",name:x,file:P,...ie})}):_e=new Uint8Array(await j.arrayBuffer()),U=_e}if(ue&&ne&&await K.match(ne)===void 0&&(U?await K.put(ne,new Response(U,{headers:j.headers})).catch(_e=>{console.warn(`Unable to add response to browser cache: ${_e}.`)}):await K.put(ne,j,L.progress_callback)),(0,i.dispatchCallback)(L.progress_callback,{status:"done",name:x,file:P}),U){if(!n.apis.IS_NODE_ENV&&G)throw new Error("Cannot return path in a browser environment.");return U}if(j instanceof c)return j.filePath;const se=await(K==null?void 0:K.match(ne));if(se instanceof c)return se.filePath;if(se instanceof Response)return new Uint8Array(await se.arrayBuffer());if(typeof se=="string")return se;throw new Error("Unable to get model file path or buffer.")}async function $(x,P,O=!0,L={}){const G=await M(x,P,O,L,!1);return G===null?null:new TextDecoder("utf-8").decode(G)}async function v(x,P,O=!0,L={}){const G=await $(x,P,O,L);return G===null?{}:JSON.parse(G)}async function y(x,P){const O=x.headers.get("Content-Length");O===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let L=parseInt(O??"0"),G=new Uint8Array(L),K=0;const R=x.body.getReader();async function te(){const{done:H,value:ee}=await R.read();if(H)return;const Z=K+ee.length;if(Z>L){L=Z;const me=new Uint8Array(L);me.set(G),G=me}G.set(ee,K),K=Z;const ne=K/L*100;return P({progress:ne,loaded:K,total:L}),te()}return await te(),G}function T(...x){return x=x.map((P,O)=>(O&&(P=P.replace(new RegExp("^/"),"")),O!==x.length-1&&(P=P.replace(new RegExp("/$"),"")),P)),x.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>_,load_image:()=>b});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),n=t("./src/env.js"),i=t("./src/utils/tensor.js"),a=t("?2b25");let l,c,p;const d=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;if(d)l=(k,g)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(k,g)},p=self.createImageBitmap,c=self.ImageData;else if(a)p=async k=>{const M=(await k.metadata()).channels,{data:$,info:v}=await k.rotate().raw().toBuffer({resolveWithObject:!0}),y=new _(new Uint8ClampedArray($),v.width,v.height,v.channels);return M!==void 0&&M!==v.channels&&y.convert(M),y};else throw new Error("Unable to load image processing library.");const u={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},f=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _{constructor(g,M,$,v){this.data=g,this.width=M,this.height=$,this.channels=v}get size(){return[this.width,this.height]}static async read(g){if(g instanceof _)return g;if(typeof g=="string"||g instanceof URL)return await this.fromURL(g);if(g instanceof Blob)return await this.fromBlob(g);if(typeof HTMLCanvasElement<"u"&&g instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&g instanceof OffscreenCanvas)return this.fromCanvas(g);throw new Error(`Unsupported input type: ${typeof g}`)}static fromCanvas(g){if(!d)throw new Error("fromCanvas() is only supported in browser environments.");const $=g.getContext("2d").getImageData(0,0,g.width,g.height).data;return new _($,g.width,g.height,4)}static async fromURL(g){const M=await(0,o.getFile)(g);if(M.status!==200)throw new Error(`Unable to read image from "${g}" (${M.status} ${M.statusText})`);const $=await M.blob();return this.fromBlob($)}static async fromBlob(g){if(d){const M=await p(g),$=l(M.width,M.height).getContext("2d");return $.drawImage(M,0,0),new this($.getImageData(0,0,M.width,M.height).data,M.width,M.height,4)}else{const M=a(await g.arrayBuffer());return await p(M)}}static fromTensor(g,M="CHW"){if(g.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${g.dims.length} dimensions.`);if(M==="CHW")g=g.transpose(1,2,0);else if(M!=="HWC")throw new Error(`Unsupported channel format: ${M}`);if(!(g.data instanceof Uint8ClampedArray||g.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${g.type}`);switch(g.dims[2]){case 1:case 2:case 3:case 4:return new _(g.data,g.dims[1],g.dims[0],g.dims[2]);default:throw new Error(`Unsupported number of channels: ${g.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const g=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let M=0,$=0;M=0?P=$:L=-$,v>=0?O=v:G=-v,x.drawImage(T,P,O,g,M,L,G,g,M),new _(x.getImageData(0,0,g,M).data,g,M,4).convert(y)}else{let y=this.toSharp();if($>=0&&v>=0)y=y.extract({left:Math.floor($),top:Math.floor(v),width:g,height:M});else if($<=0&&v<=0){const T=Math.floor(-v),x=Math.floor(-$);y=y.extend({top:T,left:x,right:g-this.width-x,bottom:M-this.height-T})}else{let T=[0,0],x=0;v<0?(T[0]=Math.floor(-v),T[1]=M-this.height-T[0]):x=Math.floor(v);let P=[0,0],O=0;$<0?(P[0]=Math.floor(-$),P[1]=g-this.width-P[0]):O=Math.floor($),y=y.extend({top:T[0],bottom:T[1],left:P[0],right:P[1]}).extract({left:O,top:x,width:g,height:M})}return await p(y)}}async toBlob(g="image/png",M=1){if(!d)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:g,quality:M})}toTensor(g="CHW"){let M=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(g!=="HWC")if(g==="CHW")M=M.permute(2,0,1);else throw new Error(`Unsupported channel format: ${g}`);return M}toCanvas(){if(!d)throw new Error("toCanvas() is only supported in browser environments.");const g=this.clone().rgba(),M=l(g.width,g.height),$=new c(g.data,g.width,g.height);return M.getContext("2d").putImageData($,0,0),M}split(){const{data:g,width:M,height:$,channels:v}=this,y=g.constructor,T=g.length/v,x=Array.from({length:v},()=>new y(T));for(let P=0;Pnew _(P,M,$,1))}_update(g,M,$,v=null){return this.data=g,this.width=M,this.height=$,v!==null&&(this.channels=v),this}clone(){return new _(this.data.slice(),this.width,this.height,this.channels)}convert(g){if(this.channels===g)return this;switch(g){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(g){if(d){if(n.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const M=g.split(".").pop().toLowerCase(),$=f.get(M)??"image/png",v=await this.toBlob($);(0,s.saveBlob)(g,v)}else{if(n.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(g);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(d)throw new Error("toSharp() is only supported in server-side environments.");return a(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const b=_.read.bind(_)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>b,bankers_round:()=>M,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>$,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>c,max:()=>d,medianFilter:()=>k,min:()=>p,permute_data:()=>o,round:()=>g,softmax:()=>n});function s(v,[y,T,x],[P,O],L="bilinear",G=!1){const K=O/x,R=P/T,te=new v.constructor(P*O*y),H=T*x,ee=P*O;for(let Z=0;Z=0;--G)P[G]=K,x[G]=y[T[G]],K*=x[G];const O=T.map((G,K)=>P[T.indexOf(K)]),L=new v.constructor(v.length);for(let G=0;G=0;--R)K+=te%y[R]*O[R],te=Math.floor(te/y[R]);L[K]=v[G]}return[L,x]}function n(v){const y=d(v)[0],T=v.map(O=>Math.exp(O-y)),x=T.reduce((O,L)=>O+L,0);return T.map(O=>O/x)}function i(v){const y=d(v)[0];let T=0;for(let O=0;OO-y-x)}function a(v,y){let T=0;for(let x=0;xy+T*T,0))}function p(v){if(v.length===0)throw Error("Array must not be empty");let y=v[0],T=0;for(let x=1;xy&&(y=v[x],T=x);return[y,T]}function u(v){return v>0&&(v&v-1)===0}class f{constructor(y){if(this.size=y|0,this.size<=1||!u(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=y<<1,this.table=new Float64Array(this.size*2);for(let x=0;xx;x<<=1)++T;this._width=T%2===0?T-1:T,this._bitrev=new Int32Array(1<>>P&3)<>>1);for(let P=0;P>>1]=y[P];return x}toComplexArray(y,T){const x=T||this.createComplexArray();for(let P=0;P>>1],x[P+1]=0;return x}transform(y,T){if(y===T)throw new Error("Input and output buffers must be different");this._transform4(y,T,1)}realTransform(y,T){if(y===T)throw new Error("Input and output buffers must be different");this._realTransform4(y,T,1)}inverseTransform(y,T){if(y===T)throw new Error("Input and output buffers must be different");this._transform4(y,T,-1);for(let x=0;x>=2;L>=2;L>>=2){G=P/L<<1;const ee=G>>>2;for(K=0;K>>1,L>>>1)}else for(K=0,R=0;K>>1,L>>>1,x)}const H=this.table;for(L>>=2;L>=2;L>>=2){G=P/L<<1;const Z=G>>>1,ne=Z>>>1,me=ne>>>1;for(K=0;K>>1;for(let Z=2;Z>1;++te){const H=(te+1-y)**2/2,ee=Math.sqrt(K**2+R**2)**H,Z=H*Math.atan2(R,K),ne=2*te;O[ne]=ee*Math.cos(Z),O[ne+1]=ee*Math.sin(Z),L[ne]=O[ne],L[ne+1]=-O[ne+1]}this._slicedChirpBuffer=O.subarray(T,x),this._f=new f(P>>1),this._f.transform(this._chirpBuffer,L)}_transform(y,T,x){const P=this._buffer1,O=this._buffer2,L=this._outBuffer1,G=this._outBuffer2,K=this._chirpBuffer,R=this._slicedChirpBuffer,te=this._a;if(x)for(let H=0;H>1,ne=T[Z];P[H]=ne*R[H],P[ee]=ne*R[ee]}else for(let H=0;H=v.length&&(K=2*(v.length-1)-K),x[L++]=v[K]}x.sort(),T[O]=x[P]}return T}function g(v,y){const T=Math.pow(10,y);return Math.round(v*T)/T}function M(v){const y=Math.round(v);return Math.abs(v)%1===.5?y%2===0?y:y-1:y}function $(v){const y=v.length,T=v[0].length,x=[y+1,T+1],P=Array.from({length:x[0]},()=>Array(x[1]).fill(1/0));P[0][0]=0;const O=Array.from({length:x[0]},()=>Array(x[1]).fill(-1));for(let te=1;te0||G>0;)switch(K.push(L-1),R.push(G-1),O[L][G]){case 0:--L,--G;break;case 1:--L;break;case 2:--G;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${L}, ${G}]. Please file a bug report.`)}return K.reverse(),R.reverse(),[K,R]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>T,full:()=>R,full_like:()=>te,interpolate:()=>p,interpolate_4d:()=>d,layer_norm:()=>M,matmul:()=>u,mean:()=>L,mean_pooling:()=>g,ones:()=>H,ones_like:()=>ee,permute:()=>c,quantize_embeddings:()=>ue,rand:()=>me,rfft:()=>f,slice:()=>k,stack:()=>x,std_mean:()=>O,topk:()=>_,zeros:()=>Z,zeros_like:()=>ne});var s=t("./src/utils/maths.js"),o=t("./src/backends/onnx.js"),n=t("./src/ops/registry.js");const i=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class a{constructor(...F){J(this,"ort_tensor");return(0,o.isONNXTensor)(F[0])?this.ort_tensor=F[0]:this.ort_tensor=new o.Tensor(F[0],F[1],F[2]),new Proxy(this,{get:(U,se)=>{if(typeof se=="string"){let _e=Number(se);if(Number.isInteger(_e))return U._getitem(_e)}return U[se]},set:(U,se,_e)=>U[se]=_e})}get dims(){return this.ort_tensor.dims}set dims(F){this.ort_tensor.dims=F}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[F,...U]=this.dims;if(U.length>0){const se=U.reduce((_e,ie)=>_e*ie);for(let _e=0;_e0){const _e=se.reduce((ie,ve)=>ie*ve);return this._subarray(F,_e,se)}else return new a(this.type,[this.data[F]],se)}indexOf(F){const U=this.data;for(let se=0;sebe)throw new Error(`Invalid slice: ${ae}`);const ke=[Math.max(W,0),Math.min(be,this.dims[X])];se.push(ke),U.push(ke[1]-ke[0])}else throw new Error(`Invalid slice: ${ae}`)}const _e=se.map(([X,ae])=>ae-X),ie=_e.reduce((X,ae)=>X*ae),ve=this.data,ze=new ve.constructor(ie),Ge=this.stride();let Ie=!0;for(let X=1;X<_e.length;++X)if(se[X][0]!==0||se[X][1]!==this.dims[X]){Ie=!1;break}if(Ie){const X=se[0][0]*Ge[0],ae=se[0][1]*Ge[0];if(ArrayBuffer.isView(ve))ze.set(ve.subarray(X,ae));else if(Array.isArray(ve)){const W=ve.slice(X,ae);for(let be=0;be=0;--W){const ke=_e[W];ae+=(be%ke+se[W][0])*Ge[W],be=Math.floor(be/ke)}ze[X]=ve[ae]}return new a(this.type,ze,U)}permute(...F){return c(this,F)}transpose(...F){return this.permute(...F)}sum(F=null,U=!1){return this.norm(1,F,U)}norm(F="fro",U=null,se=!1){if(F==="fro")F=2;else if(typeof F=="string")throw Error(`Unsupported norm: ${F}`);const _e=this.data,ie=(Ie,X)=>Ie+X**F;if(U===null){const Ie=_e.reduce(ie,0)**(1/F);return new a(this.type,[Ie],[])}const[ve,ze,Ge]=P(ie,this,U,se);if(F!==1)for(let Ie=0;Ie=0;--Ge){const ae=this.dims[Ge];if(Ge!==U){const W=Ie%ae;ze+=W*X,X*=this.dims[Ge]}Ie=Math.floor(Ie/ae)}_e[ve]/=ie[ze]}return this}normalize(F=2,U=1){return this.clone().normalize_(F,U)}stride(){return G(this.dims)}squeeze(F=null){return new a(this.type,this.data,$(this.dims,F))}squeeze_(F=null){return this.dims=$(this.dims,F),this}unsqueeze(F=null){return new a(this.type,this.data,v(this.dims,F))}unsqueeze_(F=null){return this.dims=v(this.dims,F),this}flatten_(F=0,U=-1){U=(U+this.dims.length)%this.dims.length;let se=this.dims.slice(0,F),_e=this.dims.slice(F,U+1),ie=this.dims.slice(U+1);return this.dims=[...se,_e.reduce((ve,ze)=>ve*ze,1),...ie],this}flatten(F=0,U=-1){return this.clone().flatten_(F,U)}view(...F){let U=-1;for(let _e=0;_eze!==U?ie*ve:ie,1);F[U]=se.length/_e}return new a(this.type,se,F)}neg_(){const F=this.data;for(let U=0;UF?1:0;return new a("bool",U,this.dims)}lt(F){const U=new Uint8Array(this.data.length),se=this.data;for(let _e=0;_eMath.min(ve,ze),this,F,U,1/0);return new a(se,_e,ie)}max(F=null,U=!1){if(F===null){const ve=(0,s.max)(this.data)[0];return new a(this.type,[ve],[])}const[se,_e,ie]=P((ve,ze)=>Math.max(ve,ze),this,F,U,-1/0);return new a(se,_e,ie)}argmin(F=null,U=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const se=(0,s.min)(this.data)[1];return new a("int64",[BigInt(se)],[])}argmax(F=null,U=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const se=(0,s.max)(this.data)[1];return new a("int64",[BigInt(se)],[])}to(F){if(this.type===F)return this;if(!i.hasOwnProperty(F))throw new Error(`Unsupported type: ${F}`);let U;const se=["int64","uint64"].includes(this.type),_e=["int64","uint64"].includes(F);return se&&!_e?U=Number:!se&&_e&&(U=BigInt),new a(F,i[F].from(this.data,U),this.dims)}}function l(j,F){const U=j.length,se=F.reduce((ie,ve)=>ie*ve);if(U!==se)throw Error(`cannot reshape array of size ${U} into shape (${F})`);let _e=j;for(let ie=F.length-1;ie>=0;ie--)_e=_e.reduce((ve,ze)=>{let Ge=ve[ve.length-1];return Ge.lengthnew a("int64",j,[j.length]);async function k(j,F,U,se,_e){return await(await n.TensorOpRegistry.slice)({x:j,s:b(F),e:b(U),a:b(se),t:b(_e??new Array(se.length).fill(1))})}function g(j,F){const U=j.data,se=F.data,_e=[j.dims[0],j.dims[2]],ie=new U.constructor(_e[0]*_e[1]),[ve,ze,Ge]=j.dims;let Ie=0;for(let X=0;XU!==1):typeof F=="number"?j[F]===1&&j.splice(F,1):Array.isArray(F)&&(j=j.filter((U,se)=>U!==1||!F.includes(se))),j}function v(j,F){return F=y(F,j.length+1),j=j.slice(),j.splice(F,0,1),j}function y(j,F,U=null,se=!0){if(j<-F||j>=F){if(se)throw new Error(`IndexError: index ${j} is out of bounds for dimension${U===null?"":" "+U} with size ${F}`);return j<-F?0:F}return j<0&&(j=(j%F+F)%F),j}function T(j,F=0){F=y(F,j[0].dims.length);const U=j[0].dims.slice();U[F]=j.reduce((ve,ze)=>ve+ze.dims[F],0);const se=U.reduce((ve,ze)=>ve*ze,1),_e=new j[0].data.constructor(se),ie=j[0].type;if(F===0){let ve=0;for(const ze of j){const Ge=ze.data;_e.set(Ge,ve),ve+=Ge.length}}else{let ve=0;for(let ze=0;ze=0;--W){const Ee=Ie[W];let Me=be%Ee;W===F&&(Me+=ve),ae+=Me*ke,ke*=U[W],be=Math.floor(be/Ee)}_e[ae]=Ge[X]}ve+=Ie[F]}}return new a(ie,_e,U)}function x(j,F=0){return T(j.map(U=>U.unsqueeze(F)),F)}function P(j,F,U=null,se=!1,_e=null){const ie=F.data,ve=F.dims;U=y(U,ve.length);const ze=ve.slice();ze[U]=1;const Ge=new ie.constructor(ie.length/ve[U]);_e!==null&&Ge.fill(_e);for(let Ie=0;Ie=0;--ae){const ke=ve[ae];if(ae!==U){const Ee=W%ke;X+=Ee*be,be*=ze[ae]}W=Math.floor(W/ke)}Ge[X]=j(Ge[X],ie[Ie],Ie,X)}return se||ze.splice(U,1),[F.type,Ge,ze]}function O(j,F=null,U=1,se=!1){const _e=j.data,ie=j.dims;if(F===null){const be=_e.reduce((Se,we)=>Se+we,0)/_e.length,ke=Math.sqrt(_e.reduce((Se,we)=>Se+(we-be)**2,0)/(_e.length-U)),Ee=new a(j.type,[be],[]);return[new a(j.type,[ke],[]),Ee]}F=y(F,ie.length);const ve=L(j,F,se),ze=ve.data,[Ge,Ie,X]=P((W,be,ke,Ee)=>W+(be-ze[Ee])**2,j,F,se);for(let W=0;WIe+X,0);return new a(j.type,[Ge/_e.length],[])}F=y(F,se.length);const[ie,ve,ze]=P((Ge,Ie)=>Ge+Ie,j,F,U);if(se[F]!==1)for(let Ge=0;Ge=0;--U)F[U]=se,se*=j[U];return F}function K(j,F,U,se){const _e=j.reduce((ie,ve)=>ie*ve,1);return new a(U,new se(_e).fill(F),j)}function R(j,F){let U,se;if(typeof F=="number")U="float32",se=Float32Array;else if(typeof F=="bigint")U="int64",se=BigInt64Array;else if(typeof F=="boolean")U="bool",se=Uint8Array;else throw new Error(`Unsupported data type: ${typeof F}`);return K(j,F,U,se)}function te(j,F){return R(j.dims,F)}function H(j){return K(j,1n,"int64",BigInt64Array)}function ee(j){return H(j.dims)}function Z(j){return K(j,0n,"int64",BigInt64Array)}function ne(j){return Z(j.dims)}function me(j){const F=j.reduce((U,se)=>U*se,1);return new a("float32",Float32Array.from({length:F},()=>Math.random()),j)}function ue(j,F){if(j.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(j.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(F))throw new Error("The precision must be either 'binary' or 'ubinary'");const U=F==="binary",se=U?"int8":"uint8",_e=U?Int8Array:Uint8Array,ie=j.data,ve=new _e(ie.length/8);for(let ze=0;ze0?1:0,Ie=Math.floor(ze/8),X=ze%8;ve[Ie]|=Ge<<7-X,U&&X===0&&(ve[Ie]-=128)}return new a(se,ve,[j.dims[0],j.dims[1]/8])}},"./src/utils/video.js":(e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>i,RawVideoFrame:()=>n,load_video:()=>a});var s=t("./src/utils/image.js"),o=t("./src/env.js");class n{constructor(c,p){this.image=c,this.timestamp=p}}class i{constructor(c,p){c.length>0&&c[0]instanceof s.RawImage&&(c=c.map((d,u)=>new n(d,(u+1)/(c.length+1)*p))),this.frames=c,this.duration=p}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function a(l,{num_frames:c=null,fps:p=null}={}){if(!o.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(c==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const d=[],u=document.createElement("video");if(u.crossOrigin="anonymous",u.muted=!0,typeof l=="string")u.src=l;else if(l instanceof Blob)u.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)u.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise($=>u.onloadedmetadata=$),u.seekable.start(0)===u.seekable.end(0)){const v=await(await fetch(u.src)).blob();u.src=URL.createObjectURL(v),await new Promise(y=>u.onloadedmetadata=y)}const f=u.duration;let _,b;c!=null?(_=c,b=c===1?0:f/(c-1)):(b=1/p,_=Math.floor(f/b));let k=[];for(let $=0;$<_;++$)k.push(c===1?f/2:$*b);const g=document.createElement("canvas");g.width=u.videoWidth,g.height=u.videoHeight;const M=g.getContext("2d",{willReadFrequently:!0});for(const $ of k){u.currentTime=$,await new Promise(x=>{u.onseeked=x}),M.drawImage(u,0,0,g.width,g.height);const v=M.getImageData(0,0,g.width,g.height),y=new s.RawImage(v.data,g.width,g.height,4),T=new n(y,$);d.push(T)}return u.remove(),new i(d,f)}}},Jg={};function Vt(e){var r=Jg[e];if(r!==void 0)return r.exports;var t=Jg[e]={exports:{}};return Jx[e](t,t.exports,Vt),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;Vt.t=function(t,s){if(s&1&&(t=this(t)),s&8||typeof t=="object"&&t&&(s&4&&t.__esModule||s&16&&typeof t.then=="function"))return t;var o=Object.create(null);Vt.r(o);var n={};r=r||[null,e({}),e([]),e(e)];for(var i=s&2&&t;typeof i=="object"&&!~r.indexOf(i);i=e(i))Object.getOwnPropertyNames(i).forEach(a=>n[a]=()=>t[a]);return n.default=()=>t,Vt.d(o,n),o}})(),Vt.d=(e,r)=>{for(var t in r)Vt.o(r,t)&&!Vt.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},Vt.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),Vt.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var m={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/Vt.r(m),Vt.d(m,{ASTFeatureExtractor:()=>d.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,ArceeForCausalLM:()=>t.ArceeForCausalLM,ArceeModel:()=>t.ArceeModel,ArceePreTrainedModel:()=>t.ArceePreTrainedModel,AudioClassificationPipeline:()=>r.AudioClassificationPipeline,AutoConfig:()=>o.AutoConfig,AutoFeatureExtractor:()=>u.AutoFeatureExtractor,AutoImageProcessor:()=>b.AutoImageProcessor,AutoModel:()=>t.AutoModel,AutoModelForAudioClassification:()=>t.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>t.AutoModelForAudioFrameClassification,AutoModelForAudioTextToText:()=>t.AutoModelForAudioTextToText,AutoModelForCTC:()=>t.AutoModelForCTC,AutoModelForCausalLM:()=>t.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>t.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>t.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>t.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>t.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>t.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>t.AutoModelForImageSegmentation,AutoModelForImageTextToText:()=>t.AutoModelForImageTextToText,AutoModelForImageToImage:()=>t.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>t.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>t.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>t.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>t.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>t.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>t.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>t.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>t.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>t.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>t.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>t.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>t.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>t.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>t.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>t.AutoModelForVision2Seq,AutoModelForXVector:()=>t.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>t.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>M.AutoProcessor,AutoTokenizer:()=>s.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>r.AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline:()=>r.BackgroundRemovalPipeline,BartForConditionalGeneration:()=>t.BartForConditionalGeneration,BartForSequenceClassification:()=>t.BartForSequenceClassification,BartModel:()=>t.BartModel,BartPretrainedModel:()=>t.BartPretrainedModel,BartTokenizer:()=>s.BartTokenizer,BaseModelOutput:()=>t.BaseModelOutput,BaseStreamer:()=>$.BaseStreamer,BeitFeatureExtractor:()=>_.BeitFeatureExtractor,BeitForImageClassification:()=>t.BeitForImageClassification,BeitModel:()=>t.BeitModel,BeitPreTrainedModel:()=>t.BeitPreTrainedModel,BertForMaskedLM:()=>t.BertForMaskedLM,BertForQuestionAnswering:()=>t.BertForQuestionAnswering,BertForSequenceClassification:()=>t.BertForSequenceClassification,BertForTokenClassification:()=>t.BertForTokenClassification,BertModel:()=>t.BertModel,BertPreTrainedModel:()=>t.BertPreTrainedModel,BertTokenizer:()=>s.BertTokenizer,BitImageProcessor:()=>_.BitImageProcessor,BlenderbotForConditionalGeneration:()=>t.BlenderbotForConditionalGeneration,BlenderbotModel:()=>t.BlenderbotModel,BlenderbotPreTrainedModel:()=>t.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>t.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>t.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>t.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>s.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>s.BlenderbotTokenizer,BloomForCausalLM:()=>t.BloomForCausalLM,BloomModel:()=>t.BloomModel,BloomPreTrainedModel:()=>t.BloomPreTrainedModel,BloomTokenizer:()=>s.BloomTokenizer,CLIPFeatureExtractor:()=>_.CLIPFeatureExtractor,CLIPImageProcessor:()=>_.CLIPImageProcessor,CLIPModel:()=>t.CLIPModel,CLIPPreTrainedModel:()=>t.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>t.CLIPSegForImageSegmentation,CLIPSegModel:()=>t.CLIPSegModel,CLIPSegPreTrainedModel:()=>t.CLIPSegPreTrainedModel,CLIPTextModel:()=>t.CLIPTextModel,CLIPTextModelWithProjection:()=>t.CLIPTextModelWithProjection,CLIPTokenizer:()=>s.CLIPTokenizer,CLIPVisionModel:()=>t.CLIPVisionModel,CLIPVisionModelWithProjection:()=>t.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>t.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>t.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>t.CamembertForSequenceClassification,CamembertForTokenClassification:()=>t.CamembertForTokenClassification,CamembertModel:()=>t.CamembertModel,CamembertPreTrainedModel:()=>t.CamembertPreTrainedModel,CamembertTokenizer:()=>s.CamembertTokenizer,CausalLMOutput:()=>t.CausalLMOutput,CausalLMOutputWithPast:()=>t.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>_.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>d.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>y.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>s.CodeGenTokenizer,CodeLlamaTokenizer:()=>s.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>s.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>s.ConvBertTokenizer,ConvNextFeatureExtractor:()=>_.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>_.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DFineForObjectDetection:()=>t.DFineForObjectDetection,DFineModel:()=>t.DFineModel,DFinePreTrainedModel:()=>t.DFinePreTrainedModel,DPTFeatureExtractor:()=>_.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>_.DPTImageProcessor,DPTModel:()=>t.DPTModel,DPTPreTrainedModel:()=>t.DPTPreTrainedModel,DacDecoderModel:()=>t.DacDecoderModel,DacDecoderOutput:()=>t.DacDecoderOutput,DacEncoderModel:()=>t.DacEncoderModel,DacEncoderOutput:()=>t.DacEncoderOutput,DacFeatureExtractor:()=>d.DacFeatureExtractor,DacModel:()=>t.DacModel,DacPreTrainedModel:()=>t.DacPreTrainedModel,DataTypeMap:()=>l.DataTypeMap,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>s.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>s.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>_.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>_.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>r.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>_.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>_.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>s.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>r.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>_.DonutFeatureExtractor,DonutImageProcessor:()=>_.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>_.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>s.ElectraTokenizer,EncodecFeatureExtractor:()=>d.EncodecFeatureExtractor,EosTokenCriteria:()=>v.EosTokenCriteria,Ernie4_5_ForCausalLM:()=>t.Ernie4_5_ForCausalLM,Ernie4_5_Model:()=>t.Ernie4_5_Model,Ernie4_5_PretrainedModel:()=>t.Ernie4_5_PretrainedModel,Ernie4_5_Tokenizer:()=>s.Ernie4_5_Tokenizer,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>s.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>c.FFT,FalconForCausalLM:()=>t.FalconForCausalLM,FalconModel:()=>t.FalconModel,FalconPreTrainedModel:()=>t.FalconPreTrainedModel,FalconTokenizer:()=>s.FalconTokenizer,FastViTForImageClassification:()=>t.FastViTForImageClassification,FastViTModel:()=>t.FastViTModel,FastViTPreTrainedModel:()=>t.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>r.FeatureExtractionPipeline,FeatureExtractor:()=>p.FeatureExtractor,FillMaskPipeline:()=>r.FillMaskPipeline,Florence2ForConditionalGeneration:()=>t.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>t.Florence2PreTrainedModel,Florence2Processor:()=>g.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>y.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>y.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>t.GLPNForDepthEstimation,GLPNModel:()=>t.GLPNModel,GLPNPreTrainedModel:()=>t.GLPNPreTrainedModel,GPT2LMHeadModel:()=>t.GPT2LMHeadModel,GPT2Model:()=>t.GPT2Model,GPT2PreTrainedModel:()=>t.GPT2PreTrainedModel,GPT2Tokenizer:()=>s.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>t.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>t.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>t.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>t.GPTJForCausalLM,GPTJModel:()=>t.GPTJModel,GPTJPreTrainedModel:()=>t.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>t.GPTNeoForCausalLM,GPTNeoModel:()=>t.GPTNeoModel,GPTNeoPreTrainedModel:()=>t.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>t.GPTNeoXForCausalLM,GPTNeoXModel:()=>t.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>t.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>s.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>t.Gemma2ForCausalLM,Gemma2Model:()=>t.Gemma2Model,Gemma2PreTrainedModel:()=>t.Gemma2PreTrainedModel,Gemma3ForCausalLM:()=>t.Gemma3ForCausalLM,Gemma3Model:()=>t.Gemma3Model,Gemma3PreTrainedModel:()=>t.Gemma3PreTrainedModel,Gemma3nAudioFeatureExtractor:()=>d.Gemma3nAudioFeatureExtractor,Gemma3nForConditionalGeneration:()=>t.Gemma3nForConditionalGeneration,Gemma3nPreTrainedModel:()=>t.Gemma3nPreTrainedModel,Gemma3nProcessor:()=>g.Gemma3nProcessor,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>s.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>g.GroundingDinoProcessor,GroupViTModel:()=>t.GroupViTModel,GroupViTPreTrainedModel:()=>t.GroupViTPreTrainedModel,HeliumForCausalLM:()=>t.HeliumForCausalLM,HeliumModel:()=>t.HeliumModel,HeliumPreTrainedModel:()=>t.HeliumPreTrainedModel,HerbertTokenizer:()=>s.HerbertTokenizer,HieraForImageClassification:()=>t.HieraForImageClassification,HieraModel:()=>t.HieraModel,HieraPreTrainedModel:()=>t.HieraPreTrainedModel,HubertForCTC:()=>t.HubertForCTC,HubertForSequenceClassification:()=>t.HubertForSequenceClassification,HubertModel:()=>t.HubertModel,HubertPreTrainedModel:()=>t.HubertPreTrainedModel,IJepaForImageClassification:()=>t.IJepaForImageClassification,IJepaModel:()=>t.IJepaModel,IJepaPreTrainedModel:()=>t.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>t.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>_.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>g.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>d.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>f.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>v.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>_.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>g.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,Lfm2ForCausalLM:()=>t.Lfm2ForCausalLM,Lfm2Model:()=>t.Lfm2Model,Lfm2PreTrainedModel:()=>t.Lfm2PreTrainedModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>_.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LlavaProcessor:()=>g.LlavaProcessor,LlavaQwen2ForCausalLM:()=>t.LlavaQwen2ForCausalLM,LogitsProcessor:()=>y.LogitsProcessor,LogitsProcessorList:()=>y.LogitsProcessorList,LogitsWarper:()=>y.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,Mask2FormerImageProcessor:()=>_.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>_.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>_.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>v.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>g.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>y.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>y.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>_.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>_.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>_.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>_.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>_.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>_.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>_.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>_.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>_.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>_.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertDecoderForCausalLM:()=>t.ModernBertDecoderForCausalLM,ModernBertDecoderModel:()=>t.ModernBertDecoderModel,ModernBertDecoderPreTrainedModel:()=>t.ModernBertDecoderPreTrainedModel,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>d.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>g.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NeoBertForMaskedLM:()=>t.NeoBertForMaskedLM,NeoBertForQuestionAnswering:()=>t.NeoBertForQuestionAnswering,NeoBertForSequenceClassification:()=>t.NeoBertForSequenceClassification,NeoBertForTokenClassification:()=>t.NeoBertForTokenClassification,NeoBertModel:()=>t.NeoBertModel,NeoBertPreTrainedModel:()=>t.NeoBertPreTrainedModel,NllbTokenizer:()=>s.NllbTokenizer,NoBadWordsLogitsProcessor:()=>y.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>y.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>_.NougatImageProcessor,NougatTokenizer:()=>s.NougatTokenizer,OPTForCausalLM:()=>t.OPTForCausalLM,OPTModel:()=>t.OPTModel,OPTPreTrainedModel:()=>t.OPTPreTrainedModel,ObjectDetectionPipeline:()=>r.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>t.Olmo2ForCausalLM,Olmo2Model:()=>t.Olmo2Model,Olmo2PreTrainedModel:()=>t.Olmo2PreTrainedModel,OlmoForCausalLM:()=>t.OlmoForCausalLM,OlmoModel:()=>t.OlmoModel,OlmoPreTrainedModel:()=>t.OlmoPreTrainedModel,OpenELMForCausalLM:()=>t.OpenELMForCausalLM,OpenELMModel:()=>t.OpenELMModel,OpenELMPreTrainedModel:()=>t.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>_.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>_.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>g.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>_.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>g.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>_.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>g.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>o.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>k.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>_.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>d.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>g.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>t.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>r.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>t.Qwen2ForCausalLM,Qwen2Model:()=>t.Qwen2Model,Qwen2PreTrainedModel:()=>t.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>s.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>t.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>_.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>g.Qwen2VLProcessor,Qwen3ForCausalLM:()=>t.Qwen3ForCausalLM,Qwen3Model:()=>t.Qwen3Model,Qwen3PreTrainedModel:()=>t.Qwen3PreTrainedModel,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>_.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>n.RawAudio,RawImage:()=>i.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>y.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>s.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>s.RobertaTokenizer,SamImageProcessor:()=>_.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>g.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>_.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>_.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>_.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>s.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SmolLM3ForCausalLM:()=>t.SmolLM3ForCausalLM,SmolLM3Model:()=>t.SmolLM3Model,SmolLM3PreTrainedModel:()=>t.SmolLM3PreTrainedModel,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>_.SmolVLMImageProcessor,SmolVLMProcessor:()=>g.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>d.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>g.SpeechT5Processor,SpeechT5Tokenizer:()=>s.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>s.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>v.StoppingCriteria,StoppingCriteriaList:()=>v.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>y.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>_.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinForSemanticSegmentation:()=>t.SwinForSemanticSegmentation,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>s.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>y.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>$.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>y.TopKLogitsWarper,TopPLogitsWarper:()=>y.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>g.UltravoxProcessor,UniSpeechForCTC:()=>t.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>t.UniSpeechForSequenceClassification,UniSpeechModel:()=>t.UniSpeechModel,UniSpeechPreTrainedModel:()=>t.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>t.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>t.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>t.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>t.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>t.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>g.VLChatProcessor,VLMImageProcessor:()=>_.VLMImageProcessor,ViTFeatureExtractor:()=>_.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>_.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>_.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>_.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,VoxtralForConditionalGeneration:()=>t.VoxtralForConditionalGeneration,VoxtralProcessor:()=>g.VoxtralProcessor,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>s.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>d.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>g.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>g.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>d.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>d.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>g.WhisperProcessor,WhisperTextStreamer:()=>$.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>y.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>s.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>s.XLMRobertaTokenizer,XLMTokenizer:()=>s.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>_.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>_.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>r.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>r.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>r.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>r.ZeroShotObjectDetectionPipeline,bankers_round:()=>c.bankers_round,cat:()=>l.cat,cos_sim:()=>c.cos_sim,dot:()=>c.dot,dynamic_time_warping:()=>c.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getCacheShapes:()=>o.getCacheShapes,hamming:()=>n.hamming,hanning:()=>n.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>c.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>i.load_image,load_video:()=>a.load_video,log_softmax:()=>c.log_softmax,magnitude:()=>c.magnitude,matmul:()=>l.matmul,max:()=>c.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>c.medianFilter,mel_filter_bank:()=>n.mel_filter_bank,min:()=>c.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>c.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,read_audio:()=>n.read_audio,rfft:()=>l.rfft,round:()=>c.round,slice:()=>l.slice,softmax:()=>c.softmax,spectrogram:()=>n.spectrogram,stack:()=>l.stack,std_mean:()=>l.std_mean,topk:()=>l.topk,window_function:()=>n.window_function,zeros:()=>l.zeros,zeros_like:()=>l.zeros_like});var e=Vt("./src/env.js"),r=Vt("./src/pipelines.js"),t=Vt("./src/models.js"),s=Vt("./src/tokenizers.js"),o=Vt("./src/configs.js"),n=Vt("./src/utils/audio.js"),i=Vt("./src/utils/image.js"),a=Vt("./src/utils/video.js"),l=Vt("./src/utils/tensor.js"),c=Vt("./src/utils/maths.js"),p=Vt("./src/base/feature_extraction_utils.js"),d=Vt("./src/models/feature_extractors.js"),u=Vt("./src/models/auto/feature_extraction_auto.js"),f=Vt("./src/base/image_processors_utils.js"),_=Vt("./src/models/image_processors.js"),b=Vt("./src/models/auto/image_processing_auto.js"),k=Vt("./src/base/processing_utils.js"),g=Vt("./src/models/processors.js"),M=Vt("./src/models/auto/processing_auto.js"),$=Vt("./src/generation/streamers.js"),v=Vt("./src/generation/stopping_criteria.js"),y=Vt("./src/generation/logits_process.js")})(),m.ASTFeatureExtractor,m.ASTForAudioClassification,m.ASTModel,m.ASTPreTrainedModel,m.AlbertForMaskedLM,m.AlbertForQuestionAnswering,m.AlbertForSequenceClassification,m.AlbertModel,m.AlbertPreTrainedModel,m.AlbertTokenizer,m.ArceeForCausalLM,m.ArceeModel,m.ArceePreTrainedModel,m.AudioClassificationPipeline,m.AutoConfig,m.AutoFeatureExtractor,m.AutoImageProcessor,m.AutoModel,m.AutoModelForAudioClassification,m.AutoModelForAudioFrameClassification,m.AutoModelForAudioTextToText,m.AutoModelForCTC,m.AutoModelForCausalLM,m.AutoModelForDepthEstimation,m.AutoModelForDocumentQuestionAnswering,m.AutoModelForImageClassification,m.AutoModelForImageFeatureExtraction,m.AutoModelForImageMatting,m.AutoModelForImageSegmentation,m.AutoModelForImageTextToText,m.AutoModelForImageToImage,m.AutoModelForMaskGeneration,m.AutoModelForMaskedLM,m.AutoModelForNormalEstimation,m.AutoModelForObjectDetection,m.AutoModelForPoseEstimation,m.AutoModelForQuestionAnswering,m.AutoModelForSemanticSegmentation,m.AutoModelForSeq2SeqLM,m.AutoModelForSequenceClassification,m.AutoModelForSpeechSeq2Seq,m.AutoModelForTextToSpectrogram,m.AutoModelForTextToWaveform,m.AutoModelForTokenClassification,m.AutoModelForUniversalSegmentation,m.AutoModelForVision2Seq,m.AutoModelForXVector,m.AutoModelForZeroShotObjectDetection,m.AutoProcessor,m.AutoTokenizer,m.AutomaticSpeechRecognitionPipeline,m.BackgroundRemovalPipeline,m.BartForConditionalGeneration,m.BartForSequenceClassification,m.BartModel,m.BartPretrainedModel,m.BartTokenizer,m.BaseModelOutput,m.BaseStreamer,m.BeitFeatureExtractor,m.BeitForImageClassification,m.BeitModel,m.BeitPreTrainedModel,m.BertForMaskedLM,m.BertForQuestionAnswering,m.BertForSequenceClassification,m.BertForTokenClassification,m.BertModel,m.BertPreTrainedModel,m.BertTokenizer,m.BitImageProcessor,m.BlenderbotForConditionalGeneration,m.BlenderbotModel,m.BlenderbotPreTrainedModel,m.BlenderbotSmallForConditionalGeneration,m.BlenderbotSmallModel,m.BlenderbotSmallPreTrainedModel,m.BlenderbotSmallTokenizer,m.BlenderbotTokenizer,m.BloomForCausalLM,m.BloomModel,m.BloomPreTrainedModel,m.BloomTokenizer,m.CLIPFeatureExtractor,m.CLIPImageProcessor,m.CLIPModel,m.CLIPPreTrainedModel,m.CLIPSegForImageSegmentation,m.CLIPSegModel,m.CLIPSegPreTrainedModel,m.CLIPTextModel,m.CLIPTextModelWithProjection,m.CLIPTokenizer,m.CLIPVisionModel,m.CLIPVisionModelWithProjection,m.CamembertForMaskedLM,m.CamembertForQuestionAnswering,m.CamembertForSequenceClassification,m.CamembertForTokenClassification,m.CamembertModel,m.CamembertPreTrainedModel,m.CamembertTokenizer,m.CausalLMOutput,m.CausalLMOutputWithPast,m.ChineseCLIPFeatureExtractor,m.ChineseCLIPModel,m.ChineseCLIPPreTrainedModel,m.ClapAudioModelWithProjection,m.ClapFeatureExtractor,m.ClapModel,m.ClapPreTrainedModel,m.ClapTextModelWithProjection,m.ClassifierFreeGuidanceLogitsProcessor,m.CodeGenForCausalLM,m.CodeGenModel,m.CodeGenPreTrainedModel,m.CodeGenTokenizer,m.CodeLlamaTokenizer,m.CohereForCausalLM,m.CohereModel,m.CoherePreTrainedModel,m.CohereTokenizer,m.ConvBertForMaskedLM,m.ConvBertForQuestionAnswering,m.ConvBertForSequenceClassification,m.ConvBertForTokenClassification,m.ConvBertModel,m.ConvBertPreTrainedModel,m.ConvBertTokenizer,m.ConvNextFeatureExtractor,m.ConvNextForImageClassification,m.ConvNextImageProcessor,m.ConvNextModel,m.ConvNextPreTrainedModel,m.ConvNextV2ForImageClassification,m.ConvNextV2Model,m.ConvNextV2PreTrainedModel,m.DFineForObjectDetection,m.DFineModel,m.DFinePreTrainedModel,m.DPTFeatureExtractor,m.DPTForDepthEstimation,m.DPTImageProcessor,m.DPTModel,m.DPTPreTrainedModel,m.DacDecoderModel,m.DacDecoderOutput,m.DacEncoderModel,m.DacEncoderOutput,m.DacFeatureExtractor,m.DacModel,m.DacPreTrainedModel,m.DataTypeMap,m.DebertaForMaskedLM,m.DebertaForQuestionAnswering,m.DebertaForSequenceClassification,m.DebertaForTokenClassification,m.DebertaModel,m.DebertaPreTrainedModel,m.DebertaTokenizer,m.DebertaV2ForMaskedLM,m.DebertaV2ForQuestionAnswering,m.DebertaV2ForSequenceClassification,m.DebertaV2ForTokenClassification,m.DebertaV2Model,m.DebertaV2PreTrainedModel,m.DebertaV2Tokenizer,m.DecisionTransformerModel,m.DecisionTransformerPreTrainedModel,m.DeiTFeatureExtractor,m.DeiTForImageClassification,m.DeiTImageProcessor,m.DeiTModel,m.DeiTPreTrainedModel,m.DepthAnythingForDepthEstimation,m.DepthAnythingPreTrainedModel,m.DepthEstimationPipeline,m.DepthProForDepthEstimation,m.DepthProPreTrainedModel,m.DetrFeatureExtractor,m.DetrForObjectDetection,m.DetrForSegmentation,m.DetrImageProcessor,m.DetrModel,m.DetrObjectDetectionOutput,m.DetrPreTrainedModel,m.DetrSegmentationOutput,m.Dinov2ForImageClassification,m.Dinov2Model,m.Dinov2PreTrainedModel,m.Dinov2WithRegistersForImageClassification,m.Dinov2WithRegistersModel,m.Dinov2WithRegistersPreTrainedModel,m.DistilBertForMaskedLM,m.DistilBertForQuestionAnswering,m.DistilBertForSequenceClassification,m.DistilBertForTokenClassification,m.DistilBertModel,m.DistilBertPreTrainedModel,m.DistilBertTokenizer,m.DocumentQuestionAnsweringPipeline,m.DonutFeatureExtractor,m.DonutImageProcessor,m.DonutSwinModel,m.DonutSwinPreTrainedModel,m.EfficientNetForImageClassification,m.EfficientNetImageProcessor,m.EfficientNetModel,m.EfficientNetPreTrainedModel,m.ElectraForMaskedLM,m.ElectraForQuestionAnswering,m.ElectraForSequenceClassification,m.ElectraForTokenClassification,m.ElectraModel,m.ElectraPreTrainedModel,m.ElectraTokenizer,m.EncodecFeatureExtractor,m.EosTokenCriteria,m.Ernie4_5_ForCausalLM,m.Ernie4_5_Model,m.Ernie4_5_PretrainedModel,m.Ernie4_5_Tokenizer,m.EsmForMaskedLM,m.EsmForSequenceClassification,m.EsmForTokenClassification,m.EsmModel,m.EsmPreTrainedModel,m.EsmTokenizer,m.ExaoneForCausalLM,m.ExaoneModel,m.ExaonePreTrainedModel,m.FFT,m.FalconForCausalLM,m.FalconModel,m.FalconPreTrainedModel,m.FalconTokenizer,m.FastViTForImageClassification,m.FastViTModel,m.FastViTPreTrainedModel,m.FeatureExtractionPipeline,m.FeatureExtractor,m.FillMaskPipeline,m.Florence2ForConditionalGeneration,m.Florence2PreTrainedModel,m.Florence2Processor,m.ForcedBOSTokenLogitsProcessor,m.ForcedEOSTokenLogitsProcessor,m.GLPNFeatureExtractor,m.GLPNForDepthEstimation,m.GLPNModel,m.GLPNPreTrainedModel,m.GPT2LMHeadModel,m.GPT2Model,m.GPT2PreTrainedModel,m.GPT2Tokenizer,m.GPTBigCodeForCausalLM,m.GPTBigCodeModel,m.GPTBigCodePreTrainedModel,m.GPTJForCausalLM,m.GPTJModel,m.GPTJPreTrainedModel,m.GPTNeoForCausalLM,m.GPTNeoModel,m.GPTNeoPreTrainedModel,m.GPTNeoXForCausalLM,m.GPTNeoXModel,m.GPTNeoXPreTrainedModel,m.GPTNeoXTokenizer,m.Gemma2ForCausalLM,m.Gemma2Model,m.Gemma2PreTrainedModel,m.Gemma3ForCausalLM,m.Gemma3Model,m.Gemma3PreTrainedModel,m.Gemma3nAudioFeatureExtractor,m.Gemma3nForConditionalGeneration,m.Gemma3nPreTrainedModel,m.Gemma3nProcessor,m.GemmaForCausalLM,m.GemmaModel,m.GemmaPreTrainedModel,m.GemmaTokenizer,m.GlmForCausalLM,m.GlmModel,m.GlmPreTrainedModel,m.GraniteForCausalLM,m.GraniteModel,m.GranitePreTrainedModel,m.Grok1Tokenizer,m.GroundingDinoForObjectDetection,m.GroundingDinoImageProcessor,m.GroundingDinoPreTrainedModel,m.GroundingDinoProcessor,m.GroupViTModel,m.GroupViTPreTrainedModel,m.HeliumForCausalLM,m.HeliumModel,m.HeliumPreTrainedModel,m.HerbertTokenizer,m.HieraForImageClassification,m.HieraModel,m.HieraPreTrainedModel,m.HubertForCTC,m.HubertForSequenceClassification,m.HubertModel,m.HubertPreTrainedModel,m.IJepaForImageClassification,m.IJepaModel,m.IJepaPreTrainedModel,m.Idefics3ForConditionalGeneration,m.Idefics3ImageProcessor,m.Idefics3PreTrainedModel,m.Idefics3Processor,m.ImageClassificationPipeline,m.ImageFeatureExtractionPipeline,m.ImageFeatureExtractor,m.ImageMattingOutput,m.ImageProcessor,m.ImageSegmentationPipeline,m.ImageToImagePipeline,m.ImageToTextPipeline,m.InterruptableStoppingCriteria,m.JAISLMHeadModel,m.JAISModel,m.JAISPreTrainedModel,m.JinaCLIPImageProcessor,m.JinaCLIPModel,m.JinaCLIPPreTrainedModel,m.JinaCLIPProcessor,m.JinaCLIPTextModel,m.JinaCLIPVisionModel,m.Lfm2ForCausalLM,m.Lfm2Model,m.Lfm2PreTrainedModel,m.LiteWhisperForConditionalGeneration,m.LlamaForCausalLM,m.LlamaModel,m.LlamaPreTrainedModel,m.LlamaTokenizer,m.LlavaForConditionalGeneration,m.LlavaOnevisionForConditionalGeneration,m.LlavaOnevisionImageProcessor,m.LlavaPreTrainedModel,m.LlavaProcessor,m.LlavaQwen2ForCausalLM,m.LogitsProcessor,m.LogitsProcessorList,m.LogitsWarper,m.LongT5ForConditionalGeneration,m.LongT5Model,m.LongT5PreTrainedModel,m.M2M100ForConditionalGeneration,m.M2M100Model,m.M2M100PreTrainedModel,m.M2M100Tokenizer,m.MBart50Tokenizer,m.MBartForCausalLM,m.MBartForConditionalGeneration,m.MBartForSequenceClassification,m.MBartModel,m.MBartPreTrainedModel,m.MBartTokenizer,m.MPNetForMaskedLM,m.MPNetForQuestionAnswering,m.MPNetForSequenceClassification,m.MPNetForTokenClassification,m.MPNetModel,m.MPNetPreTrainedModel,m.MPNetTokenizer,m.MT5ForConditionalGeneration,m.MT5Model,m.MT5PreTrainedModel,m.MarianMTModel,m.MarianModel,m.MarianPreTrainedModel,m.MarianTokenizer,m.Mask2FormerImageProcessor,m.MaskFormerFeatureExtractor,m.MaskFormerForInstanceSegmentation,m.MaskFormerImageProcessor,m.MaskFormerModel,m.MaskFormerPreTrainedModel,m.MaskedLMOutput,m.MaxLengthCriteria,m.Metric3DForDepthEstimation,m.Metric3DPreTrainedModel,m.Metric3Dv2ForDepthEstimation,m.Metric3Dv2PreTrainedModel,m.MgpstrForSceneTextRecognition,m.MgpstrModelOutput,m.MgpstrPreTrainedModel,m.MgpstrProcessor,m.MgpstrTokenizer,m.MimiDecoderModel,m.MimiDecoderOutput,m.MimiEncoderModel,m.MimiEncoderOutput,m.MimiModel,m.MimiPreTrainedModel,m.MinLengthLogitsProcessor,m.MinNewTokensLengthLogitsProcessor,m.MistralForCausalLM,m.MistralModel,m.MistralPreTrainedModel,m.MobileBertForMaskedLM,m.MobileBertForQuestionAnswering,m.MobileBertForSequenceClassification,m.MobileBertModel,m.MobileBertPreTrainedModel,m.MobileBertTokenizer,m.MobileLLMForCausalLM,m.MobileLLMModel,m.MobileLLMPreTrainedModel,m.MobileNetV1FeatureExtractor,m.MobileNetV1ForImageClassification,m.MobileNetV1ForSemanticSegmentation,m.MobileNetV1ImageProcessor,m.MobileNetV1Model,m.MobileNetV1PreTrainedModel,m.MobileNetV2FeatureExtractor,m.MobileNetV2ForImageClassification,m.MobileNetV2ForSemanticSegmentation,m.MobileNetV2ImageProcessor,m.MobileNetV2Model,m.MobileNetV2PreTrainedModel,m.MobileNetV3FeatureExtractor,m.MobileNetV3ForImageClassification,m.MobileNetV3ForSemanticSegmentation,m.MobileNetV3ImageProcessor,m.MobileNetV3Model,m.MobileNetV3PreTrainedModel,m.MobileNetV4FeatureExtractor,m.MobileNetV4ForImageClassification,m.MobileNetV4ForSemanticSegmentation,m.MobileNetV4ImageProcessor,m.MobileNetV4Model,m.MobileNetV4PreTrainedModel,m.MobileViTFeatureExtractor,m.MobileViTForImageClassification,m.MobileViTImageProcessor,m.MobileViTModel,m.MobileViTPreTrainedModel,m.MobileViTV2ForImageClassification,m.MobileViTV2Model,m.MobileViTV2PreTrainedModel,m.ModelOutput,m.ModernBertDecoderForCausalLM,m.ModernBertDecoderModel,m.ModernBertDecoderPreTrainedModel,m.ModernBertForMaskedLM,m.ModernBertForSequenceClassification,m.ModernBertForTokenClassification,m.ModernBertModel,m.ModernBertPreTrainedModel,m.Moondream1ForConditionalGeneration,m.MoonshineFeatureExtractor,m.MoonshineForConditionalGeneration,m.MoonshineModel,m.MoonshinePreTrainedModel,m.MoonshineProcessor,m.MptForCausalLM,m.MptModel,m.MptPreTrainedModel,m.MultiModalityCausalLM,m.MultiModalityPreTrainedModel,m.MusicgenForCausalLM,m.MusicgenForConditionalGeneration,m.MusicgenModel,m.MusicgenPreTrainedModel,m.NeoBertForMaskedLM,m.NeoBertForQuestionAnswering,m.NeoBertForSequenceClassification,m.NeoBertForTokenClassification,m.NeoBertModel,m.NeoBertPreTrainedModel,m.NllbTokenizer,m.NoBadWordsLogitsProcessor,m.NoRepeatNGramLogitsProcessor,m.NomicBertModel,m.NomicBertPreTrainedModel,m.NougatImageProcessor,m.NougatTokenizer,m.OPTForCausalLM,m.OPTModel,m.OPTPreTrainedModel,m.ObjectDetectionPipeline,m.Olmo2ForCausalLM,m.Olmo2Model,m.Olmo2PreTrainedModel,m.OlmoForCausalLM,m.OlmoModel,m.OlmoPreTrainedModel,m.OpenELMForCausalLM,m.OpenELMModel,m.OpenELMPreTrainedModel,m.OwlViTFeatureExtractor,m.OwlViTForObjectDetection,m.OwlViTImageProcessor,m.OwlViTModel,m.OwlViTPreTrainedModel,m.OwlViTProcessor,m.Owlv2ForObjectDetection,m.Owlv2ImageProcessor,m.Owlv2Model,m.Owlv2PreTrainedModel,m.PaliGemmaForConditionalGeneration,m.PaliGemmaPreTrainedModel,m.PaliGemmaProcessor,m.PatchTSMixerForPrediction,m.PatchTSMixerModel,m.PatchTSMixerPreTrainedModel,m.PatchTSTForPrediction,m.PatchTSTModel,m.PatchTSTPreTrainedModel,m.Phi3ForCausalLM,m.Phi3Model,m.Phi3PreTrainedModel,m.Phi3VForCausalLM,m.Phi3VImageProcessor,m.Phi3VPreTrainedModel,m.Phi3VProcessor,m.PhiForCausalLM,m.PhiModel,m.PhiPreTrainedModel,m.Pipeline,m.PreTrainedModel,m.PreTrainedTokenizer,m.PretrainedConfig,m.PretrainedMixin,m.Processor,m.PvtForImageClassification,m.PvtImageProcessor,m.PvtModel,m.PvtPreTrainedModel,m.PyAnnoteFeatureExtractor,m.PyAnnoteForAudioFrameClassification,m.PyAnnoteModel,m.PyAnnotePreTrainedModel,m.PyAnnoteProcessor,m.QuestionAnsweringModelOutput,m.QuestionAnsweringPipeline,m.Qwen2ForCausalLM,m.Qwen2Model,m.Qwen2PreTrainedModel,m.Qwen2Tokenizer,m.Qwen2VLForConditionalGeneration,m.Qwen2VLImageProcessor,m.Qwen2VLPreTrainedModel,m.Qwen2VLProcessor,m.Qwen3ForCausalLM,m.Qwen3Model,m.Qwen3PreTrainedModel,m.RFDetrForObjectDetection,m.RFDetrModel,m.RFDetrObjectDetectionOutput,m.RFDetrPreTrainedModel,m.RTDetrForObjectDetection,m.RTDetrImageProcessor,m.RTDetrModel,m.RTDetrObjectDetectionOutput,m.RTDetrPreTrainedModel,m.RTDetrV2ForObjectDetection,m.RTDetrV2Model,m.RTDetrV2ObjectDetectionOutput,m.RTDetrV2PreTrainedModel,m.RawAudio,m.RawImage,m.RawVideo,m.RawVideoFrame,m.RepetitionPenaltyLogitsProcessor,m.ResNetForImageClassification,m.ResNetModel,m.ResNetPreTrainedModel,m.RoFormerForMaskedLM,m.RoFormerForQuestionAnswering,m.RoFormerForSequenceClassification,m.RoFormerForTokenClassification,m.RoFormerModel,m.RoFormerPreTrainedModel,m.RoFormerTokenizer,m.RobertaForMaskedLM,m.RobertaForQuestionAnswering,m.RobertaForSequenceClassification,m.RobertaForTokenClassification,m.RobertaModel,m.RobertaPreTrainedModel,m.RobertaTokenizer,m.SamImageProcessor,m.SamImageSegmentationOutput,m.SamModel,m.SamPreTrainedModel,m.SamProcessor,m.SapiensForDepthEstimation,m.SapiensForNormalEstimation,m.SapiensForSemanticSegmentation,m.SapiensPreTrainedModel,m.SeamlessM4TFeatureExtractor,m.SegformerFeatureExtractor,m.SegformerForImageClassification,m.SegformerForSemanticSegmentation,m.SegformerImageProcessor,m.SegformerModel,m.SegformerPreTrainedModel,m.Seq2SeqLMOutput,m.SequenceClassifierOutput,m.SiglipImageProcessor,m.SiglipModel,m.SiglipPreTrainedModel,m.SiglipTextModel,m.SiglipTokenizer,m.SiglipVisionModel,m.SmolLM3ForCausalLM,m.SmolLM3Model,m.SmolLM3PreTrainedModel,m.SmolVLMForConditionalGeneration,m.SmolVLMImageProcessor,m.SmolVLMProcessor,m.SnacDecoderModel,m.SnacEncoderModel,m.SnacFeatureExtractor,m.SnacModel,m.SnacPreTrainedModel,m.SpeechT5FeatureExtractor,m.SpeechT5ForSpeechToText,m.SpeechT5ForTextToSpeech,m.SpeechT5HifiGan,m.SpeechT5Model,m.SpeechT5PreTrainedModel,m.SpeechT5Processor,m.SpeechT5Tokenizer,m.SqueezeBertForMaskedLM,m.SqueezeBertForQuestionAnswering,m.SqueezeBertForSequenceClassification,m.SqueezeBertModel,m.SqueezeBertPreTrainedModel,m.SqueezeBertTokenizer,m.StableLmForCausalLM,m.StableLmModel,m.StableLmPreTrainedModel,m.Starcoder2ForCausalLM,m.Starcoder2Model,m.Starcoder2PreTrainedModel,m.StoppingCriteria,m.StoppingCriteriaList,m.StyleTextToSpeech2Model,m.StyleTextToSpeech2PreTrainedModel,m.SummarizationPipeline,m.SuppressTokensAtBeginLogitsProcessor,m.Swin2SRForImageSuperResolution,m.Swin2SRImageProcessor,m.Swin2SRModel,m.Swin2SRPreTrainedModel,m.SwinForImageClassification,m.SwinForSemanticSegmentation,m.SwinModel,m.SwinPreTrainedModel,m.T5ForConditionalGeneration,m.T5Model,m.T5PreTrainedModel,m.T5Tokenizer,m.TableTransformerForObjectDetection,m.TableTransformerModel,m.TableTransformerObjectDetectionOutput,m.TableTransformerPreTrainedModel,m.TemperatureLogitsWarper,m.Tensor,m.Text2TextGenerationPipeline,m.TextClassificationPipeline,m.TextGenerationPipeline,m.TextStreamer,m.TextToAudioPipeline,m.TokenClassificationPipeline,m.TokenClassifierOutput,m.TokenizerModel,m.TopKLogitsWarper,m.TopPLogitsWarper,m.TrOCRForCausalLM,m.TrOCRPreTrainedModel,m.TranslationPipeline,m.UltravoxModel,m.UltravoxPreTrainedModel,m.UltravoxProcessor,m.UniSpeechForCTC,m.UniSpeechForSequenceClassification,m.UniSpeechModel,m.UniSpeechPreTrainedModel,m.UniSpeechSatForAudioFrameClassification,m.UniSpeechSatForCTC,m.UniSpeechSatForSequenceClassification,m.UniSpeechSatModel,m.UniSpeechSatPreTrainedModel,m.VLChatProcessor,m.VLMImageProcessor,m.ViTFeatureExtractor,m.ViTForImageClassification,m.ViTImageProcessor,m.ViTMAEModel,m.ViTMAEPreTrainedModel,m.ViTMSNForImageClassification,m.ViTMSNModel,m.ViTMSNPreTrainedModel,m.ViTModel,m.ViTPreTrainedModel,m.VisionEncoderDecoderModel,m.VitMatteForImageMatting,m.VitMatteImageProcessor,m.VitMattePreTrainedModel,m.VitPoseForPoseEstimation,m.VitPoseImageProcessor,m.VitPosePreTrainedModel,m.VitsModel,m.VitsModelOutput,m.VitsPreTrainedModel,m.VitsTokenizer,m.VoxtralForConditionalGeneration,m.VoxtralProcessor,m.Wav2Vec2BertForCTC,m.Wav2Vec2BertForSequenceClassification,m.Wav2Vec2BertModel,m.Wav2Vec2BertPreTrainedModel,m.Wav2Vec2CTCTokenizer,m.Wav2Vec2FeatureExtractor,m.Wav2Vec2ForAudioFrameClassification,m.Wav2Vec2ForCTC,m.Wav2Vec2ForSequenceClassification,m.Wav2Vec2Model,m.Wav2Vec2PreTrainedModel,m.Wav2Vec2Processor,m.Wav2Vec2ProcessorWithLM,m.WavLMForAudioFrameClassification,m.WavLMForCTC,m.WavLMForSequenceClassification,m.WavLMForXVector,m.WavLMModel,m.WavLMPreTrainedModel,m.WeSpeakerFeatureExtractor,m.WeSpeakerResNetModel,m.WeSpeakerResNetPreTrainedModel,m.WhisperFeatureExtractor,m.WhisperForConditionalGeneration,m.WhisperModel,m.WhisperPreTrainedModel,m.WhisperProcessor,m.WhisperTextStreamer,m.WhisperTimeStampLogitsProcessor,m.WhisperTokenizer,m.XLMForQuestionAnswering,m.XLMForSequenceClassification,m.XLMForTokenClassification,m.XLMModel,m.XLMPreTrainedModel,m.XLMRobertaForMaskedLM,m.XLMRobertaForQuestionAnswering,m.XLMRobertaForSequenceClassification,m.XLMRobertaForTokenClassification,m.XLMRobertaModel,m.XLMRobertaPreTrainedModel,m.XLMRobertaTokenizer,m.XLMTokenizer,m.XLMWithLMHeadModel,m.XVectorOutput,m.YolosFeatureExtractor,m.YolosForObjectDetection,m.YolosImageProcessor,m.YolosModel,m.YolosObjectDetectionOutput,m.YolosPreTrainedModel,m.ZeroShotAudioClassificationPipeline,m.ZeroShotClassificationPipeline,m.ZeroShotImageClassificationPipeline,m.ZeroShotObjectDetectionPipeline,m.bankers_round,m.cat,m.cos_sim,m.dot,m.dynamic_time_warping,m.env,m.full,m.full_like,m.getCacheShapes,m.hamming,m.hanning,m.interpolate,m.interpolate_4d,m.interpolate_data,m.is_chinese_char,m.layer_norm,m.load_image,m.load_video,m.log_softmax,m.magnitude,m.matmul,m.max,m.mean,m.mean_pooling,m.medianFilter,m.mel_filter_bank,m.min,m.ones,m.ones_like,m.permute,m.permute_data;var Yx=m.pipeline;m.quantize_embeddings,m.rand,m.read_audio,m.rfft,m.round,m.slice,m.softmax,m.spectrogram,m.stack,m.std_mean,m.topk,m.window_function,m.zeros,m.zeros_like;class xi{static async getInstance(r=null){return this.instance===null&&(this.instance=Yx(this.task,this.model,{progress_callback:r,dtype:"fp32",device:navigator.gpu?"webgpu":"wasm"})),this.instance}}J(xi,"task","feature-extraction"),J(xi,"model","sentence-transformers/all-MiniLM-L6-v2"),J(xi,"instance",null),self.addEventListener("message",async e=>{const t=await(await xi.getInstance(o=>{self.postMessage(o)}))(e.data.text,{pooling:"mean",normalize:!0}),s=Array.from(t.data);self.postMessage({status:"complete",embedding:s,originalMessage:e.data.originalMessage})})})(); diff --git a/assets/index-Dv-VkWvZ.js b/assets/index-Dv-VkWvZ.js new file mode 100644 index 0000000000000000000000000000000000000000..a576d71c93d1328b36b41f6313056df7c75b276f --- /dev/null +++ b/assets/index-Dv-VkWvZ.js @@ -0,0 +1,151 @@ +var F5=Object.defineProperty;var j3=e=>{throw TypeError(e)};var P5=(e,r,M)=>r in e?F5(e,r,{enumerable:!0,configurable:!0,writable:!0,value:M}):e[r]=M;var $r=(e,r,M)=>P5(e,typeof r!="symbol"?r+"":r,M),R5=(e,r,M)=>r.has(e)||j3("Cannot "+M);var B3=(e,r,M)=>r.has(e)?j3("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(e):r.set(e,M);var Nl=(e,r,M)=>(R5(e,r,"access private method"),M);(function(){const r=document.createElement("link").relList;if(r&&r.supports&&r.supports("modulepreload"))return;for(const s0 of document.querySelectorAll('link[rel="modulepreload"]'))r0(s0);new MutationObserver(s0=>{for(const a0 of s0)if(a0.type==="childList")for(const i0 of a0.addedNodes)i0.tagName==="LINK"&&i0.rel==="modulepreload"&&r0(i0)}).observe(document,{childList:!0,subtree:!0});function M(s0){const a0={};return s0.integrity&&(a0.integrity=s0.integrity),s0.referrerPolicy&&(a0.referrerPolicy=s0.referrerPolicy),s0.crossOrigin==="use-credentials"?a0.credentials="include":s0.crossOrigin==="anonymous"?a0.credentials="omit":a0.credentials="same-origin",a0}function r0(s0){if(s0.ep)return;s0.ep=!0;const a0=M(s0);fetch(s0.href,a0)}})();function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var jsxRuntime={exports:{}},reactJsxRuntime_production_min={},react={exports:{}},react_production_min={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var hasRequiredReact_production_min;function requireReact_production_min(){if(hasRequiredReact_production_min)return react_production_min;hasRequiredReact_production_min=1;var e=Symbol.for("react.element"),r=Symbol.for("react.portal"),M=Symbol.for("react.fragment"),r0=Symbol.for("react.strict_mode"),s0=Symbol.for("react.profiler"),a0=Symbol.for("react.provider"),i0=Symbol.for("react.context"),u0=Symbol.for("react.forward_ref"),d0=Symbol.for("react.suspense"),m0=Symbol.for("react.memo"),_0=Symbol.for("react.lazy"),f0=Symbol.iterator;function g0(S0){return S0===null||typeof S0!="object"?null:(S0=f0&&S0[f0]||S0["@@iterator"],typeof S0=="function"?S0:null)}var x0={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},k0=Object.assign,F0={};function C0(S0,I0,J0){this.props=S0,this.context=I0,this.refs=F0,this.updater=J0||x0}C0.prototype.isReactComponent={},C0.prototype.setState=function(S0,I0){if(typeof S0!="object"&&typeof S0!="function"&&S0!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,S0,I0,"setState")},C0.prototype.forceUpdate=function(S0){this.updater.enqueueForceUpdate(this,S0,"forceUpdate")};function R0(){}R0.prototype=C0.prototype;function y0(S0,I0,J0){this.props=S0,this.context=I0,this.refs=F0,this.updater=J0||x0}var w0=y0.prototype=new R0;w0.constructor=y0,k0(w0,C0.prototype),w0.isPureReactComponent=!0;var A0=Array.isArray,q0=Object.prototype.hasOwnProperty,U0={current:null},X0={key:!0,ref:!0,__self:!0,__source:!0};function xr(S0,I0,J0){var gr,tr={},Mr=null,Fr=null;if(I0!=null)for(gr in I0.ref!==void 0&&(Fr=I0.ref),I0.key!==void 0&&(Mr=""+I0.key),I0)q0.call(I0,gr)&&!X0.hasOwnProperty(gr)&&(tr[gr]=I0[gr]);var kr=arguments.length-2;if(kr===1)tr.children=J0;else if(1>>1,I0=$0[S0];if(0>>1;S0s0(tr,j0))Mrs0(Fr,tr)?($0[S0]=Fr,$0[Mr]=j0,S0=Mr):($0[S0]=tr,$0[gr]=j0,S0=gr);else if(Mrs0(Fr,j0))$0[S0]=Fr,$0[Mr]=j0,S0=Mr;else break e}}return Z0}function s0($0,Z0){var j0=$0.sortIndex-Z0.sortIndex;return j0!==0?j0:$0.id-Z0.id}if(typeof performance=="object"&&typeof performance.now=="function"){var a0=performance;e.unstable_now=function(){return a0.now()}}else{var i0=Date,u0=i0.now();e.unstable_now=function(){return i0.now()-u0}}var d0=[],m0=[],_0=1,f0=null,g0=3,x0=!1,k0=!1,F0=!1,C0=typeof setTimeout=="function"?setTimeout:null,R0=typeof clearTimeout=="function"?clearTimeout:null,y0=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w0($0){for(var Z0=M(m0);Z0!==null;){if(Z0.callback===null)r0(m0);else if(Z0.startTime<=$0)r0(m0),Z0.sortIndex=Z0.expirationTime,r(d0,Z0);else break;Z0=M(m0)}}function A0($0){if(F0=!1,w0($0),!k0)if(M(d0)!==null)k0=!0,_r(q0);else{var Z0=M(m0);Z0!==null&&wr(A0,Z0.startTime-$0)}}function q0($0,Z0){k0=!1,F0&&(F0=!1,R0(xr),xr=-1),x0=!0;var j0=g0;try{for(w0(Z0),f0=M(d0);f0!==null&&(!(f0.expirationTime>Z0)||$0&&!mr());){var S0=f0.callback;if(typeof S0=="function"){f0.callback=null,g0=f0.priorityLevel;var I0=S0(f0.expirationTime<=Z0);Z0=e.unstable_now(),typeof I0=="function"?f0.callback=I0:f0===M(d0)&&r0(d0),w0(Z0)}else r0(d0);f0=M(d0)}if(f0!==null)var J0=!0;else{var gr=M(m0);gr!==null&&wr(A0,gr.startTime-Z0),J0=!1}return J0}finally{f0=null,g0=j0,x0=!1}}var U0=!1,X0=null,xr=-1,Ir=5,Ur=-1;function mr(){return!(e.unstable_now()-Ur$0||125<$0?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):Ir=0<$0?Math.floor(1e3/$0):5},e.unstable_getCurrentPriorityLevel=function(){return g0},e.unstable_getFirstCallbackNode=function(){return M(d0)},e.unstable_next=function($0){switch(g0){case 1:case 2:case 3:var Z0=3;break;default:Z0=g0}var j0=g0;g0=Z0;try{return $0()}finally{g0=j0}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function($0,Z0){switch($0){case 1:case 2:case 3:case 4:case 5:break;default:$0=3}var j0=g0;g0=$0;try{return Z0()}finally{g0=j0}},e.unstable_scheduleCallback=function($0,Z0,j0){var S0=e.unstable_now();switch(typeof j0=="object"&&j0!==null?(j0=j0.delay,j0=typeof j0=="number"&&0S0?($0.sortIndex=j0,r(m0,$0),M(d0)===null&&$0===M(m0)&&(F0?(R0(xr),xr=-1):F0=!0,wr(A0,j0-S0))):($0.sortIndex=I0,r(d0,$0),k0||x0||(k0=!0,_r(q0))),$0},e.unstable_shouldYield=mr,e.unstable_wrapCallback=function($0){var Z0=g0;return function(){var j0=g0;g0=Z0;try{return $0.apply(this,arguments)}finally{g0=j0}}}}(scheduler_production_min)),scheduler_production_min}var hasRequiredScheduler;function requireScheduler(){return hasRequiredScheduler||(hasRequiredScheduler=1,scheduler.exports=requireScheduler_production_min()),scheduler.exports}/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var hasRequiredReactDom_production_min;function requireReactDom_production_min(){if(hasRequiredReactDom_production_min)return reactDom_production_min;hasRequiredReactDom_production_min=1;var e=requireReact(),r=requireScheduler();function M(e0){for(var t0="https://reactjs.org/docs/error-decoder.html?invariant="+e0,n0=1;n0"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),d0=Object.prototype.hasOwnProperty,m0=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,_0={},f0={};function g0(e0){return d0.call(f0,e0)?!0:d0.call(_0,e0)?!1:m0.test(e0)?f0[e0]=!0:(_0[e0]=!0,!1)}function x0(e0,t0,n0,o0){if(n0!==null&&n0.type===0)return!1;switch(typeof t0){case"function":case"symbol":return!0;case"boolean":return o0?!1:n0!==null?!n0.acceptsBooleans:(e0=e0.toLowerCase().slice(0,5),e0!=="data-"&&e0!=="aria-");default:return!1}}function k0(e0,t0,n0,o0){if(t0===null||typeof t0>"u"||x0(e0,t0,n0,o0))return!0;if(o0)return!1;if(n0!==null)switch(n0.type){case 3:return!t0;case 4:return t0===!1;case 5:return isNaN(t0);case 6:return isNaN(t0)||1>t0}return!1}function F0(e0,t0,n0,o0,l0,c0,p0){this.acceptsBooleans=t0===2||t0===3||t0===4,this.attributeName=o0,this.attributeNamespace=l0,this.mustUseProperty=n0,this.propertyName=e0,this.type=t0,this.sanitizeURL=c0,this.removeEmptyString=p0}var C0={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e0){C0[e0]=new F0(e0,0,!1,e0,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e0){var t0=e0[0];C0[t0]=new F0(t0,1,!1,e0[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e0){C0[e0]=new F0(e0,2,!1,e0.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e0){C0[e0]=new F0(e0,2,!1,e0,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e0){C0[e0]=new F0(e0,3,!1,e0.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e0){C0[e0]=new F0(e0,3,!0,e0,null,!1,!1)}),["capture","download"].forEach(function(e0){C0[e0]=new F0(e0,4,!1,e0,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e0){C0[e0]=new F0(e0,6,!1,e0,null,!1,!1)}),["rowSpan","start"].forEach(function(e0){C0[e0]=new F0(e0,5,!1,e0.toLowerCase(),null,!1,!1)});var R0=/[\-:]([a-z])/g;function y0(e0){return e0[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e0){var t0=e0.replace(R0,y0);C0[t0]=new F0(t0,1,!1,e0,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e0){var t0=e0.replace(R0,y0);C0[t0]=new F0(t0,1,!1,e0,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e0){var t0=e0.replace(R0,y0);C0[t0]=new F0(t0,1,!1,e0,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e0){C0[e0]=new F0(e0,1,!1,e0.toLowerCase(),null,!1,!1)}),C0.xlinkHref=new F0("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e0){C0[e0]=new F0(e0,1,!1,e0.toLowerCase(),null,!0,!0)});function w0(e0,t0,n0,o0){var l0=C0.hasOwnProperty(t0)?C0[t0]:null;(l0!==null?l0.type!==0:o0||!(2h0||l0[p0]!==c0[h0]){var E0=` +`+l0[p0].replace(" at new "," at ");return e0.displayName&&E0.includes("")&&(E0=E0.replace("",e0.displayName)),E0}while(1<=p0&&0<=h0);break}}}finally{J0=!1,Error.prepareStackTrace=n0}return(e0=e0?e0.displayName||e0.name:"")?I0(e0):""}function tr(e0){switch(e0.tag){case 5:return I0(e0.type);case 16:return I0("Lazy");case 13:return I0("Suspense");case 19:return I0("SuspenseList");case 0:case 2:case 15:return e0=gr(e0.type,!1),e0;case 11:return e0=gr(e0.type.render,!1),e0;case 1:return e0=gr(e0.type,!0),e0;default:return""}}function Mr(e0){if(e0==null)return null;if(typeof e0=="function")return e0.displayName||e0.name||null;if(typeof e0=="string")return e0;switch(e0){case X0:return"Fragment";case U0:return"Portal";case Ir:return"Profiler";case xr:return"StrictMode";case H0:return"Suspense";case lr:return"SuspenseList"}if(typeof e0=="object")switch(e0.$$typeof){case mr:return(e0.displayName||"Context")+".Consumer";case Ur:return(e0._context.displayName||"Context")+".Provider";case vr:var t0=e0.render;return e0=e0.displayName,e0||(e0=t0.displayName||t0.name||"",e0=e0!==""?"ForwardRef("+e0+")":"ForwardRef"),e0;case fr:return t0=e0.displayName||null,t0!==null?t0:Mr(e0.type)||"Memo";case _r:t0=e0._payload,e0=e0._init;try{return Mr(e0(t0))}catch{}}return null}function Fr(e0){var t0=e0.type;switch(e0.tag){case 24:return"Cache";case 9:return(t0.displayName||"Context")+".Consumer";case 10:return(t0._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e0=t0.render,e0=e0.displayName||e0.name||"",t0.displayName||(e0!==""?"ForwardRef("+e0+")":"ForwardRef");case 7:return"Fragment";case 5:return t0;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Mr(t0);case 8:return t0===xr?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t0=="function")return t0.displayName||t0.name||null;if(typeof t0=="string")return t0}return null}function kr(e0){switch(typeof e0){case"boolean":case"number":case"string":case"undefined":return e0;case"object":return e0;default:return""}}function Cr(e0){var t0=e0.type;return(e0=e0.nodeName)&&e0.toLowerCase()==="input"&&(t0==="checkbox"||t0==="radio")}function as(e0){var t0=Cr(e0)?"checked":"value",n0=Object.getOwnPropertyDescriptor(e0.constructor.prototype,t0),o0=""+e0[t0];if(!e0.hasOwnProperty(t0)&&typeof n0<"u"&&typeof n0.get=="function"&&typeof n0.set=="function"){var l0=n0.get,c0=n0.set;return Object.defineProperty(e0,t0,{configurable:!0,get:function(){return l0.call(this)},set:function(p0){o0=""+p0,c0.call(this,p0)}}),Object.defineProperty(e0,t0,{enumerable:n0.enumerable}),{getValue:function(){return o0},setValue:function(p0){o0=""+p0},stopTracking:function(){e0._valueTracker=null,delete e0[t0]}}}}function $a(e0){e0._valueTracker||(e0._valueTracker=as(e0))}function Ys(e0){if(!e0)return!1;var t0=e0._valueTracker;if(!t0)return!0;var n0=t0.getValue(),o0="";return e0&&(o0=Cr(e0)?e0.checked?"true":"false":e0.value),e0=o0,e0!==n0?(t0.setValue(e0),!0):!1}function ca(e0){if(e0=e0||(typeof document<"u"?document:void 0),typeof e0>"u")return null;try{return e0.activeElement||e0.body}catch{return e0.body}}function Is(e0,t0){var n0=t0.checked;return j0({},t0,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n0??e0._wrapperState.initialChecked})}function uo(e0,t0){var n0=t0.defaultValue==null?"":t0.defaultValue,o0=t0.checked!=null?t0.checked:t0.defaultChecked;n0=kr(t0.value!=null?t0.value:n0),e0._wrapperState={initialChecked:o0,initialValue:n0,controlled:t0.type==="checkbox"||t0.type==="radio"?t0.checked!=null:t0.value!=null}}function co(e0,t0){t0=t0.checked,t0!=null&&w0(e0,"checked",t0,!1)}function Bs(e0,t0){co(e0,t0);var n0=kr(t0.value),o0=t0.type;if(n0!=null)o0==="number"?(n0===0&&e0.value===""||e0.value!=n0)&&(e0.value=""+n0):e0.value!==""+n0&&(e0.value=""+n0);else if(o0==="submit"||o0==="reset"){e0.removeAttribute("value");return}t0.hasOwnProperty("value")?da(e0,t0.type,n0):t0.hasOwnProperty("defaultValue")&&da(e0,t0.type,kr(t0.defaultValue)),t0.checked==null&&t0.defaultChecked!=null&&(e0.defaultChecked=!!t0.defaultChecked)}function ja(e0,t0,n0){if(t0.hasOwnProperty("value")||t0.hasOwnProperty("defaultValue")){var o0=t0.type;if(!(o0!=="submit"&&o0!=="reset"||t0.value!==void 0&&t0.value!==null))return;t0=""+e0._wrapperState.initialValue,n0||t0===e0.value||(e0.value=t0),e0.defaultValue=t0}n0=e0.name,n0!==""&&(e0.name=""),e0.defaultChecked=!!e0._wrapperState.initialChecked,n0!==""&&(e0.name=n0)}function da(e0,t0,n0){(t0!=="number"||ca(e0.ownerDocument)!==e0)&&(n0==null?e0.defaultValue=""+e0._wrapperState.initialValue:e0.defaultValue!==""+n0&&(e0.defaultValue=""+n0))}var pa=Array.isArray;function Qs(e0,t0,n0,o0){if(e0=e0.options,t0){t0={};for(var l0=0;l0"+t0.valueOf().toString()+"",t0=Ba.firstChild;e0.firstChild;)e0.removeChild(e0.firstChild);for(;t0.firstChild;)e0.appendChild(t0.firstChild)}});function ea(e0,t0){if(t0){var n0=e0.firstChild;if(n0&&n0===e0.lastChild&&n0.nodeType===3){n0.nodeValue=t0;return}}e0.textContent=t0}var _a={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},_o=["Webkit","ms","Moz","O"];Object.keys(_a).forEach(function(e0){_o.forEach(function(t0){t0=t0+e0.charAt(0).toUpperCase()+e0.substring(1),_a[t0]=_a[e0]})});function Ua(e0,t0,n0){return t0==null||typeof t0=="boolean"||t0===""?"":n0||typeof t0!="number"||t0===0||_a.hasOwnProperty(e0)&&_a[e0]?(""+t0).trim():t0+"px"}function Ss(e0,t0){e0=e0.style;for(var n0 in t0)if(t0.hasOwnProperty(n0)){var o0=n0.indexOf("--")===0,l0=Ua(n0,t0[n0],o0);n0==="float"&&(n0="cssFloat"),o0?e0.setProperty(n0,l0):e0[n0]=l0}}var fa=j0({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Ha(e0,t0){if(t0){if(fa[e0]&&(t0.children!=null||t0.dangerouslySetInnerHTML!=null))throw Error(M(137,e0));if(t0.dangerouslySetInnerHTML!=null){if(t0.children!=null)throw Error(M(60));if(typeof t0.dangerouslySetInnerHTML!="object"||!("__html"in t0.dangerouslySetInnerHTML))throw Error(M(61))}if(t0.style!=null&&typeof t0.style!="object")throw Error(M(62))}}function Ga(e0,t0){if(e0.indexOf("-")===-1)return typeof t0.is=="string";switch(e0){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Bo=null;function ha(e0){return e0=e0.target||e0.srcElement||window,e0.correspondingUseElement&&(e0=e0.correspondingUseElement),e0.nodeType===3?e0.parentNode:e0}var ga=null,ya=null,ks=null;function bi(e0){if(e0=ci(e0)){if(typeof ga!="function")throw Error(M(280));var t0=e0.stateNode;t0&&(t0=Qi(t0),ga(e0.stateNode,e0.type,t0))}}function Ti(e0){ya?ks?ks.push(e0):ks=[e0]:ya=e0}function $n(){if(ya){var e0=ya,t0=ks;if(ks=ya=null,bi(e0),t0)for(e0=0;e0>>=0,e0===0?32:31-(G3(e0)/W3|0)|0}var Ii=64,zi=4194304;function Wo(e0){switch(e0&-e0){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e0&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e0&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e0}}function Di(e0,t0){var n0=e0.pendingLanes;if(n0===0)return 0;var o0=0,l0=e0.suspendedLanes,c0=e0.pingedLanes,p0=n0&268435455;if(p0!==0){var h0=p0&~l0;h0!==0?o0=Wo(h0):(c0&=p0,c0!==0&&(o0=Wo(c0)))}else p0=n0&~l0,p0!==0?o0=Wo(p0):c0!==0&&(o0=Wo(c0));if(o0===0)return 0;if(t0!==0&&t0!==o0&&(t0&l0)===0&&(l0=o0&-o0,c0=t0&-t0,l0>=c0||l0===16&&(c0&4194240)!==0))return t0;if((o0&4)!==0&&(o0|=n0&16),t0=e0.entangledLanes,t0!==0)for(e0=e0.entanglements,t0&=o0;0n0;n0++)t0.push(e0);return t0}function Vo(e0,t0,n0){e0.pendingLanes|=t0,t0!==536870912&&(e0.suspendedLanes=0,e0.pingedLanes=0),e0=e0.eventTimes,t0=31-Ds(t0),e0[t0]=n0}function Y3(e0,t0){var n0=e0.pendingLanes&~t0;e0.pendingLanes=t0,e0.suspendedLanes=0,e0.pingedLanes=0,e0.expiredLanes&=t0,e0.mutableReadLanes&=t0,e0.entangledLanes&=t0,t0=e0.entanglements;var o0=e0.eventTimes;for(e0=e0.expirationTimes;0=ti),z4=" ",D4=!1;function N4(e0,t0){switch(e0){case"keyup":return S6.indexOf(t0.keyCode)!==-1;case"keydown":return t0.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function L4(e0){return e0=e0.detail,typeof e0=="object"&&"data"in e0?e0.data:null}var Eo=!1;function b6(e0,t0){switch(e0){case"compositionend":return L4(t0);case"keypress":return t0.which!==32?null:(D4=!0,z4);case"textInput":return e0=t0.data,e0===z4&&D4?null:e0;default:return null}}function T6(e0,t0){if(Eo)return e0==="compositionend"||!Ql&&N4(e0,t0)?(e0=A4(),$i=Gl=ka=null,Eo=!1,e0):null;switch(e0){case"paste":return null;case"keypress":if(!(t0.ctrlKey||t0.altKey||t0.metaKey)||t0.ctrlKey&&t0.altKey){if(t0.char&&1=t0)return{node:n0,offset:t0-e0};e0=o0}e:{for(;n0;){if(n0.nextSibling){n0=n0.nextSibling;break e}n0=n0.parentNode}n0=void 0}n0=H4(n0)}}function W4(e0,t0){return e0&&t0?e0===t0?!0:e0&&e0.nodeType===3?!1:t0&&t0.nodeType===3?W4(e0,t0.parentNode):"contains"in e0?e0.contains(t0):e0.compareDocumentPosition?!!(e0.compareDocumentPosition(t0)&16):!1:!1}function V4(){for(var e0=window,t0=ca();t0 instanceof e0.HTMLIFrameElement;){try{var n0=typeof t0.contentWindow.location.href=="string"}catch{n0=!1}if(n0)e0=t0.contentWindow;else break;t0=ca(e0.document)}return t0}function e1(e0){var t0=e0&&e0.nodeName&&e0.nodeName.toLowerCase();return t0&&(t0==="input"&&(e0.type==="text"||e0.type==="search"||e0.type==="tel"||e0.type==="url"||e0.type==="password")||t0==="textarea"||e0.contentEditable==="true")}function N6(e0){var t0=V4(),n0=e0.focusedElem,o0=e0.selectionRange;if(t0!==n0&&n0&&n0.ownerDocument&&W4(n0.ownerDocument.documentElement,n0)){if(o0!==null&&e1(n0)){if(t0=o0.start,e0=o0.end,e0===void 0&&(e0=t0),"selectionStart"in n0)n0.selectionStart=t0,n0.selectionEnd=Math.min(e0,n0.value.length);else if(e0=(t0=n0.ownerDocument||document)&&t0.defaultView||window,e0.getSelection){e0=e0.getSelection();var l0=n0.textContent.length,c0=Math.min(o0.start,l0);o0=o0.end===void 0?c0:Math.min(o0.end,l0),!e0.extend&&c0>o0&&(l0=o0,o0=c0,c0=l0),l0=G4(n0,c0);var p0=G4(n0,o0);l0&&p0&&(e0.rangeCount!==1||e0.anchorNode!==l0.node||e0.anchorOffset!==l0.offset||e0.focusNode!==p0.node||e0.focusOffset!==p0.offset)&&(t0=t0.createRange(),t0.setStart(l0.node,l0.offset),e0.removeAllRanges(),c0>o0?(e0.addRange(t0),e0.extend(p0.node,p0.offset)):(t0.setEnd(p0.node,p0.offset),e0.addRange(t0)))}}for(t0=[],e0=n0;e0=e0.parentNode;)e0.nodeType===1&&t0.push({element:e0,left:e0.scrollLeft,top:e0.scrollTop});for(typeof n0.focus=="function"&&n0.focus(),n0=0;n0=document.documentMode,Mo=null,t1=null,ai=null,r1=!1;function K4(e0,t0,n0){var o0=n0.window===n0?n0.document:n0.nodeType===9?n0:n0.ownerDocument;r1||Mo==null||Mo!==ca(o0)||(o0=Mo,"selectionStart"in o0&&e1(o0)?o0={start:o0.selectionStart,end:o0.selectionEnd}:(o0=(o0.ownerDocument&&o0.ownerDocument.defaultView||window).getSelection(),o0={anchorNode:o0.anchorNode,anchorOffset:o0.anchorOffset,focusNode:o0.focusNode,focusOffset:o0.focusOffset}),ai&&si(ai,o0)||(ai=o0,o0=Ki(t1,"onSelect"),0bo||(e0.current=_1[bo],_1[bo]=null,bo--)}function Dr(e0,t0){bo++,_1[bo]=e0.current,e0.current=t0}var Fa={},is=Aa(Fa),_s=Aa(!1),Qa=Fa;function To(e0,t0){var n0=e0.type.contextTypes;if(!n0)return Fa;var o0=e0.stateNode;if(o0&&o0.__reactInternalMemoizedUnmaskedChildContext===t0)return o0.__reactInternalMemoizedMaskedChildContext;var l0={},c0;for(c0 in n0)l0[c0]=t0[c0];return o0&&(e0=e0.stateNode,e0.__reactInternalMemoizedUnmaskedChildContext=t0,e0.__reactInternalMemoizedMaskedChildContext=l0),l0}function hs(e0){return e0=e0.childContextTypes,e0!=null}function Zi(){Or(_s),Or(is)}function u2(e0,t0,n0){if(is.current!==Fa)throw Error(M(168));Dr(is,t0),Dr(_s,n0)}function c2(e0,t0,n0){var o0=e0.stateNode;if(t0=t0.childContextTypes,typeof o0.getChildContext!="function")return n0;o0=o0.getChildContext();for(var l0 in o0)if(!(l0 in t0))throw Error(M(108,Fr(e0)||"Unknown",l0));return j0({},n0,o0)}function Ji(e0){return e0=(e0=e0.stateNode)&&e0.__reactInternalMemoizedMergedChildContext||Fa,Qa=is.current,Dr(is,e0),Dr(_s,_s.current),!0}function d2(e0,t0,n0){var o0=e0.stateNode;if(!o0)throw Error(M(169));n0?(e0=c2(e0,t0,Qa),o0.__reactInternalMemoizedMergedChildContext=e0,Or(_s),Or(is),Dr(is,e0)):Or(_s),Dr(_s,n0)}var na=null,el=!1,f1=!1;function p2(e0){na===null?na=[e0]:na.push(e0)}function K6(e0){el=!0,p2(e0)}function Pa(){if(!f1&&na!==null){f1=!0;var e0=0,t0=Pr;try{var n0=na;for(Pr=1;e0>=p0,l0-=p0,sa=1<<32-Ds(t0)+l0|n0<dr?(rs=ir,ir=null):rs=ir.sibling;var Ar=z0(b0,ir,T0[dr],O0);if(Ar===null){ir===null&&(ir=rs);break}e0&&ir&&Ar.alternate===null&&t0(b0,ir),v0=c0(Ar,v0,dr),rr===null?Y0=Ar:rr.sibling=Ar,rr=Ar,ir=rs}if(dr===T0.length)return n0(b0,ir),Gr&&Ja(b0,dr),Y0;if(ir===null){for(;drdr?(rs=ir,ir=null):rs=ir.sibling;var qa=z0(b0,ir,Ar.value,O0);if(qa===null){ir===null&&(ir=rs);break}e0&&ir&&qa.alternate===null&&t0(b0,ir),v0=c0(qa,v0,dr),rr===null?Y0=qa:rr.sibling=qa,rr=qa,ir=rs}if(Ar.done)return n0(b0,ir),Gr&&Ja(b0,dr),Y0;if(ir===null){for(;!Ar.done;dr++,Ar=T0.next())Ar=N0(b0,Ar.value,O0),Ar!==null&&(v0=c0(Ar,v0,dr),rr===null?Y0=Ar:rr.sibling=Ar,rr=Ar);return Gr&&Ja(b0,dr),Y0}for(ir=o0(b0,ir);!Ar.done;dr++,Ar=T0.next())Ar=B0(ir,b0,dr,Ar.value,O0),Ar!==null&&(e0&&Ar.alternate!==null&&ir.delete(Ar.key===null?dr:Ar.key),v0=c0(Ar,v0,dr),rr===null?Y0=Ar:rr.sibling=Ar,rr=Ar);return e0&&ir.forEach(function(A5){return t0(b0,A5)}),Gr&&Ja(b0,dr),Y0}function Hn(b0,v0,T0,O0){if(typeof T0=="object"&&T0!==null&&T0.type===X0&&T0.key===null&&(T0=T0.props.children),typeof T0=="object"&&T0!==null){switch(T0.$$typeof){case q0:e:{for(var Y0=T0.key,rr=v0;rr!==null;){if(rr.key===Y0){if(Y0=T0.type,Y0===X0){if(rr.tag===7){n0(b0,rr.sibling),v0=l0(rr,T0.props.children),v0.return=b0,b0=v0;break e}}else if(rr.elementType===Y0||typeof Y0=="object"&&Y0!==null&&Y0.$$typeof===_r&&y2(Y0)===rr.type){n0(b0,rr.sibling),v0=l0(rr,T0.props),v0.ref=di(b0,rr,T0),v0.return=b0,b0=v0;break e}n0(b0,rr);break}else t0(b0,rr);rr=rr.sibling}T0.type===X0?(v0=io(T0.props.children,b0.mode,O0,T0.key),v0.return=b0,b0=v0):(O0=Al(T0.type,T0.key,T0.props,null,b0.mode,O0),O0.ref=di(b0,v0,T0),O0.return=b0,b0=O0)}return p0(b0);case U0:e:{for(rr=T0.key;v0!==null;){if(v0.key===rr)if(v0.tag===4&&v0.stateNode.containerInfo===T0.containerInfo&&v0.stateNode.implementation===T0.implementation){n0(b0,v0.sibling),v0=l0(v0,T0.children||[]),v0.return=b0,b0=v0;break e}else{n0(b0,v0);break}else t0(b0,v0);v0=v0.sibling}v0=p4(T0,b0.mode,O0),v0.return=b0,b0=v0}return p0(b0);case _r:return rr=T0._init,Hn(b0,v0,rr(T0._payload),O0)}if(pa(T0))return W0(b0,v0,T0,O0);if(Z0(T0))return K0(b0,v0,T0,O0);sl(b0,T0)}return typeof T0=="string"&&T0!==""||typeof T0=="number"?(T0=""+T0,v0!==null&&v0.tag===6?(n0(b0,v0.sibling),v0=l0(v0,T0),v0.return=b0,b0=v0):(n0(b0,v0),v0=d4(T0,b0.mode,O0),v0.return=b0,b0=v0),p0(b0)):n0(b0,v0)}return Hn}var Ro=w2(!0),E2=w2(!1),al=Aa(null),ol=null,Co=null,M1=null;function v1(){M1=Co=ol=null}function x1(e0){var t0=al.current;Or(al),e0._currentValue=t0}function S1(e0,t0,n0){for(;e0!==null;){var o0=e0.alternate;if((e0.childLanes&t0)!==t0?(e0.childLanes|=t0,o0!==null&&(o0.childLanes|=t0)):o0!==null&&(o0.childLanes&t0)!==t0&&(o0.childLanes|=t0),e0===n0)break;e0=e0.return}}function Io(e0,t0){ol=e0,M1=Co=null,e0=e0.dependencies,e0!==null&&e0.firstContext!==null&&((e0.lanes&t0)!==0&&(gs=!0),e0.firstContext=null)}function Fs(e0){var t0=e0._currentValue;if(M1!==e0)if(e0={context:e0,memoizedValue:t0,next:null},Co===null){if(ol===null)throw Error(M(308));Co=e0,ol.dependencies={lanes:0,firstContext:e0}}else Co=Co.next=e0;return t0}var eo=null;function k1(e0){eo===null?eo=[e0]:eo.push(e0)}function M2(e0,t0,n0,o0){var l0=t0.interleaved;return l0===null?(n0.next=n0,k1(t0)):(n0.next=l0.next,l0.next=n0),t0.interleaved=n0,oa(e0,o0)}function oa(e0,t0){e0.lanes|=t0;var n0=e0.alternate;for(n0!==null&&(n0.lanes|=t0),n0=e0,e0=e0.return;e0!==null;)e0.childLanes|=t0,n0=e0.alternate,n0!==null&&(n0.childLanes|=t0),n0=e0,e0=e0.return;return n0.tag===3?n0.stateNode:null}var Ra=!1;function b1(e0){e0.updateQueue={baseState:e0.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function v2(e0,t0){e0=e0.updateQueue,t0.updateQueue===e0&&(t0.updateQueue={baseState:e0.baseState,firstBaseUpdate:e0.firstBaseUpdate,lastBaseUpdate:e0.lastBaseUpdate,shared:e0.shared,effects:e0.effects})}function ia(e0,t0){return{eventTime:e0,lane:t0,tag:0,payload:null,callback:null,next:null}}function Ca(e0,t0,n0){var o0=e0.updateQueue;if(o0===null)return null;if(o0=o0.shared,(Sr&2)!==0){var l0=o0.pending;return l0===null?t0.next=t0:(t0.next=l0.next,l0.next=t0),o0.pending=t0,oa(e0,n0)}return l0=o0.interleaved,l0===null?(t0.next=t0,k1(o0)):(t0.next=l0.next,l0.next=t0),o0.interleaved=t0,oa(e0,n0)}function il(e0,t0,n0){if(t0=t0.updateQueue,t0!==null&&(t0=t0.shared,(n0&4194240)!==0)){var o0=t0.lanes;o0&=e0.pendingLanes,n0|=o0,t0.lanes=n0,$l(e0,n0)}}function x2(e0,t0){var n0=e0.updateQueue,o0=e0.alternate;if(o0!==null&&(o0=o0.updateQueue,n0===o0)){var l0=null,c0=null;if(n0=n0.firstBaseUpdate,n0!==null){do{var p0={eventTime:n0.eventTime,lane:n0.lane,tag:n0.tag,payload:n0.payload,callback:n0.callback,next:null};c0===null?l0=c0=p0:c0=c0.next=p0,n0=n0.next}while(n0!==null);c0===null?l0=c0=t0:c0=c0.next=t0}else l0=c0=t0;n0={baseState:o0.baseState,firstBaseUpdate:l0,lastBaseUpdate:c0,shared:o0.shared,effects:o0.effects},e0.updateQueue=n0;return}e0=n0.lastBaseUpdate,e0===null?n0.firstBaseUpdate=t0:e0.next=t0,n0.lastBaseUpdate=t0}function ll(e0,t0,n0,o0){var l0=e0.updateQueue;Ra=!1;var c0=l0.firstBaseUpdate,p0=l0.lastBaseUpdate,h0=l0.shared.pending;if(h0!==null){l0.shared.pending=null;var E0=h0,P0=E0.next;E0.next=null,p0===null?c0=P0:p0.next=P0,p0=E0;var D0=e0.alternate;D0!==null&&(D0=D0.updateQueue,h0=D0.lastBaseUpdate,h0!==p0&&(h0===null?D0.firstBaseUpdate=P0:h0.next=P0,D0.lastBaseUpdate=E0))}if(c0!==null){var N0=l0.baseState;p0=0,D0=P0=E0=null,h0=c0;do{var z0=h0.lane,B0=h0.eventTime;if((o0&z0)===z0){D0!==null&&(D0=D0.next={eventTime:B0,lane:0,tag:h0.tag,payload:h0.payload,callback:h0.callback,next:null});e:{var W0=e0,K0=h0;switch(z0=t0,B0=n0,K0.tag){case 1:if(W0=K0.payload,typeof W0=="function"){N0=W0.call(B0,N0,z0);break e}N0=W0;break e;case 3:W0.flags=W0.flags&-65537|128;case 0:if(W0=K0.payload,z0=typeof W0=="function"?W0.call(B0,N0,z0):W0,z0==null)break e;N0=j0({},N0,z0);break e;case 2:Ra=!0}}h0.callback!==null&&h0.lane!==0&&(e0.flags|=64,z0=l0.effects,z0===null?l0.effects=[h0]:z0.push(h0))}else B0={eventTime:B0,lane:z0,tag:h0.tag,payload:h0.payload,callback:h0.callback,next:null},D0===null?(P0=D0=B0,E0=N0):D0=D0.next=B0,p0|=z0;if(h0=h0.next,h0===null){if(h0=l0.shared.pending,h0===null)break;z0=h0,h0=z0.next,z0.next=null,l0.lastBaseUpdate=z0,l0.shared.pending=null}}while(!0);if(D0===null&&(E0=N0),l0.baseState=E0,l0.firstBaseUpdate=P0,l0.lastBaseUpdate=D0,t0=l0.shared.interleaved,t0!==null){l0=t0;do p0|=l0.lane,l0=l0.next;while(l0!==t0)}else c0===null&&(l0.shared.lanes=0);no|=p0,e0.lanes=p0,e0.memoizedState=N0}}function S2(e0,t0,n0){if(e0=t0.effects,t0.effects=null,e0!==null)for(t0=0;t0n0?n0:4,e0(!0);var o0=R1.transition;R1.transition={};try{e0(!1),t0()}finally{Pr=n0,R1.transition=o0}}function U2(){return Ps().memoizedState}function Z6(e0,t0,n0){var o0=Na(e0);if(n0={lane:o0,action:n0,hasEagerState:!1,eagerState:null,next:null},H2(e0))G2(t0,n0);else if(n0=M2(e0,t0,n0,o0),n0!==null){var l0=ps();js(n0,e0,o0,l0),W2(n0,t0,o0)}}function J6(e0,t0,n0){var o0=Na(e0),l0={lane:o0,action:n0,hasEagerState:!1,eagerState:null,next:null};if(H2(e0))G2(t0,l0);else{var c0=e0.alternate;if(e0.lanes===0&&(c0===null||c0.lanes===0)&&(c0=t0.lastRenderedReducer,c0!==null))try{var p0=t0.lastRenderedState,h0=c0(p0,n0);if(l0.hasEagerState=!0,l0.eagerState=h0,Ns(h0,p0)){var E0=t0.interleaved;E0===null?(l0.next=l0,k1(t0)):(l0.next=E0.next,E0.next=l0),t0.interleaved=l0;return}}catch{}finally{}n0=M2(e0,t0,l0,o0),n0!==null&&(l0=ps(),js(n0,e0,o0,l0),W2(n0,t0,o0))}}function H2(e0){var t0=e0.alternate;return e0===Jr||t0!==null&&t0===Jr}function G2(e0,t0){fi=dl=!0;var n0=e0.pending;n0===null?t0.next=t0:(t0.next=n0.next,n0.next=t0),e0.pending=t0}function W2(e0,t0,n0){if((n0&4194240)!==0){var o0=t0.lanes;o0&=e0.pendingLanes,n0|=o0,t0.lanes=n0,$l(e0,n0)}}var _l={readContext:Fs,useCallback:ls,useContext:ls,useEffect:ls,useImperativeHandle:ls,useInsertionEffect:ls,useLayoutEffect:ls,useMemo:ls,useReducer:ls,useRef:ls,useState:ls,useDebugValue:ls,useDeferredValue:ls,useTransition:ls,useMutableSource:ls,useSyncExternalStore:ls,useId:ls,unstable_isNewReconciler:!1},e5={readContext:Fs,useCallback:function(e0,t0){return Ks().memoizedState=[e0,t0===void 0?null:t0],e0},useContext:Fs,useEffect:D2,useImperativeHandle:function(e0,t0,n0){return n0=n0!=null?n0.concat([e0]):null,pl(4194308,4,O2.bind(null,t0,e0),n0)},useLayoutEffect:function(e0,t0){return pl(4194308,4,e0,t0)},useInsertionEffect:function(e0,t0){return pl(4,2,e0,t0)},useMemo:function(e0,t0){var n0=Ks();return t0=t0===void 0?null:t0,e0=e0(),n0.memoizedState=[e0,t0],e0},useReducer:function(e0,t0,n0){var o0=Ks();return t0=n0!==void 0?n0(t0):t0,o0.memoizedState=o0.baseState=t0,e0={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e0,lastRenderedState:t0},o0.queue=e0,e0=e0.dispatch=Z6.bind(null,Jr,e0),[o0.memoizedState,e0]},useRef:function(e0){var t0=Ks();return e0={current:e0},t0.memoizedState=e0},useState:I2,useDebugValue:O1,useDeferredValue:function(e0){return Ks().memoizedState=e0},useTransition:function(){var e0=I2(!1),t0=e0[0];return e0=Q6.bind(null,e0[1]),Ks().memoizedState=e0,[t0,e0]},useMutableSource:function(){},useSyncExternalStore:function(e0,t0,n0){var o0=Jr,l0=Ks();if(Gr){if(n0===void 0)throw Error(M(407));n0=n0()}else{if(n0=t0(),ts===null)throw Error(M(349));(ro&30)!==0||A2(o0,t0,n0)}l0.memoizedState=n0;var c0={value:n0,getSnapshot:t0};return l0.queue=c0,D2(P2.bind(null,o0,c0,e0),[e0]),o0.flags|=2048,yi(9,F2.bind(null,o0,c0,n0,t0),void 0,null),n0},useId:function(){var e0=Ks(),t0=ts.identifierPrefix;if(Gr){var n0=aa,o0=sa;n0=(o0&~(1<<32-Ds(o0)-1)).toString(32)+n0,t0=":"+t0+"R"+n0,n0=hi++,0<\/script>",e0=e0.removeChild(e0.firstChild)):typeof o0.is=="string"?e0=p0.createElement(n0,{is:o0.is}):(e0=p0.createElement(n0),n0==="select"&&(p0=e0,o0.multiple?p0.multiple=!0:o0.size&&(p0.size=o0.size))):e0=p0.createElementNS(e0,n0),e0[Ws]=t0,e0[ui]=o0,p3(e0,t0,!1,!1),t0.stateNode=e0;e:{switch(p0=Ga(n0,o0),n0){case"dialog":Lr("cancel",e0),Lr("close",e0),l0=o0;break;case"iframe":case"object":case"embed":Lr("load",e0),l0=o0;break;case"video":case"audio":for(l0=0;l0Oo&&(t0.flags|=128,o0=!0,wi(c0,!1),t0.lanes=4194304)}else{if(!o0)if(e0=ul(p0),e0!==null){if(t0.flags|=128,o0=!0,n0=e0.updateQueue,n0!==null&&(t0.updateQueue=n0,t0.flags|=4),wi(c0,!0),c0.tail===null&&c0.tailMode==="hidden"&&!p0.alternate&&!Gr)return us(t0),null}else 2*yr()-c0.renderingStartTime>Oo&&n0!==1073741824&&(t0.flags|=128,o0=!0,wi(c0,!1),t0.lanes=4194304);c0.isBackwards?(p0.sibling=t0.child,t0.child=p0):(n0=c0.last,n0!==null?n0.sibling=p0:t0.child=p0,c0.last=p0)}return c0.tail!==null?(t0=c0.tail,c0.rendering=t0,c0.tail=t0.sibling,c0.renderingStartTime=yr(),t0.sibling=null,n0=Qr.current,Dr(Qr,o0?n0&1|2:n0&1),t0):(us(t0),null);case 22:case 23:return l4(),o0=t0.memoizedState!==null,e0!==null&&e0.memoizedState!==null!==o0&&(t0.flags|=8192),o0&&(t0.mode&1)!==0?(xs&1073741824)!==0&&(us(t0),t0.subtreeFlags&6&&(t0.flags|=8192)):us(t0),null;case 24:return null;case 25:return null}throw Error(M(156,t0.tag))}function l5(e0,t0){switch(g1(t0),t0.tag){case 1:return hs(t0.type)&&Zi(),e0=t0.flags,e0&65536?(t0.flags=e0&-65537|128,t0):null;case 3:return zo(),Or(_s),Or(is),P1(),e0=t0.flags,(e0&65536)!==0&&(e0&128)===0?(t0.flags=e0&-65537|128,t0):null;case 5:return A1(t0),null;case 13:if(Or(Qr),e0=t0.memoizedState,e0!==null&&e0.dehydrated!==null){if(t0.alternate===null)throw Error(M(340));Po()}return e0=t0.flags,e0&65536?(t0.flags=e0&-65537|128,t0):null;case 19:return Or(Qr),null;case 4:return zo(),null;case 10:return x1(t0.type._context),null;case 22:case 23:return l4(),null;case 24:return null;default:return null}}var yl=!1,cs=!1,u5=typeof WeakSet=="function"?WeakSet:Set,G0=null;function No(e0,t0){var n0=e0.ref;if(n0!==null)if(typeof n0=="function")try{n0(null)}catch(o0){qn(e0,t0,o0)}else n0.current=null}function Y1(e0,t0,n0){try{n0()}catch(o0){qn(e0,t0,o0)}}var f3=!1;function c5(e0,t0){if(l1=Oi,e0=V4(),e1(e0)){if("selectionStart"in e0)var n0={start:e0.selectionStart,end:e0.selectionEnd};else e:{n0=(n0=e0.ownerDocument)&&n0.defaultView||window;var o0=n0.getSelection&&n0.getSelection();if(o0&&o0.rangeCount!==0){n0=o0.anchorNode;var l0=o0.anchorOffset,c0=o0.focusNode;o0=o0.focusOffset;try{n0.nodeType,c0.nodeType}catch{n0=null;break e}var p0=0,h0=-1,E0=-1,P0=0,D0=0,N0=e0,z0=null;t:for(;;){for(var B0;N0!==n0||l0!==0&&N0.nodeType!==3||(h0=p0+l0),N0!==c0||o0!==0&&N0.nodeType!==3||(E0=p0+o0),N0.nodeType===3&&(p0+=N0.nodeValue.length),(B0=N0.firstChild)!==null;)z0=N0,N0=B0;for(;;){if(N0===e0)break t;if(z0===n0&&++P0===l0&&(h0=p0),z0===c0&&++D0===o0&&(E0=p0),(B0=N0.nextSibling)!==null)break;N0=z0,z0=N0.parentNode}N0=B0}n0=h0===-1||E0===-1?null:{start:h0,end:E0}}else n0=null}n0=n0||{start:0,end:0}}else n0=null;for(u1={focusedElem:e0,selectionRange:n0},Oi=!1,G0=t0;G0!==null;)if(t0=G0,e0=t0.child,(t0.subtreeFlags&1028)!==0&&e0!==null)e0.return=t0,G0=e0;else for(;G0!==null;){t0=G0;try{var W0=t0.alternate;if((t0.flags&1024)!==0)switch(t0.tag){case 0:case 11:case 15:break;case 1:if(W0!==null){var K0=W0.memoizedProps,Hn=W0.memoizedState,b0=t0.stateNode,v0=b0.getSnapshotBeforeUpdate(t0.elementType===t0.type?K0:Os(t0.type,K0),Hn);b0.__reactInternalSnapshotBeforeUpdate=v0}break;case 3:var T0=t0.stateNode.containerInfo;T0.nodeType===1?T0.textContent="":T0.nodeType===9&&T0.documentElement&&T0.removeChild(T0.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(M(163))}}catch(O0){qn(t0,t0.return,O0)}if(e0=t0.sibling,e0!==null){e0.return=t0.return,G0=e0;break}G0=t0.return}return W0=f3,f3=!1,W0}function Ei(e0,t0,n0){var o0=t0.updateQueue;if(o0=o0!==null?o0.lastEffect:null,o0!==null){var l0=o0=o0.next;do{if((l0.tag&e0)===e0){var c0=l0.destroy;l0.destroy=void 0,c0!==void 0&&Y1(t0,n0,c0)}l0=l0.next}while(l0!==o0)}}function wl(e0,t0){if(t0=t0.updateQueue,t0=t0!==null?t0.lastEffect:null,t0!==null){var n0=t0=t0.next;do{if((n0.tag&e0)===e0){var o0=n0.create;n0.destroy=o0()}n0=n0.next}while(n0!==t0)}}function Q1(e0){var t0=e0.ref;if(t0!==null){var n0=e0.stateNode;switch(e0.tag){case 5:e0=n0;break;default:e0=n0}typeof t0=="function"?t0(e0):t0.current=e0}}function h3(e0){var t0=e0.alternate;t0!==null&&(e0.alternate=null,h3(t0)),e0.child=null,e0.deletions=null,e0.sibling=null,e0.tag===5&&(t0=e0.stateNode,t0!==null&&(delete t0[Ws],delete t0[ui],delete t0[m1],delete t0[W6],delete t0[V6])),e0.stateNode=null,e0.return=null,e0.dependencies=null,e0.memoizedProps=null,e0.memoizedState=null,e0.pendingProps=null,e0.stateNode=null,e0.updateQueue=null}function g3(e0){return e0.tag===5||e0.tag===3||e0.tag===4}function y3(e0){e:for(;;){for(;e0.sibling===null;){if(e0.return===null||g3(e0.return))return null;e0=e0.return}for(e0.sibling.return=e0.return,e0=e0.sibling;e0.tag!==5&&e0.tag!==6&&e0.tag!==18;){if(e0.flags&2||e0.child===null||e0.tag===4)continue e;e0.child.return=e0,e0=e0.child}if(!(e0.flags&2))return e0.stateNode}}function Z1(e0,t0,n0){var o0=e0.tag;if(o0===5||o0===6)e0=e0.stateNode,t0?n0.nodeType===8?n0.parentNode.insertBefore(e0,t0):n0.insertBefore(e0,t0):(n0.nodeType===8?(t0=n0.parentNode,t0.insertBefore(e0,n0)):(t0=n0,t0.appendChild(e0)),n0=n0._reactRootContainer,n0!=null||t0.onclick!==null||(t0.onclick=Yi));else if(o0!==4&&(e0=e0.child,e0!==null))for(Z1(e0,t0,n0),e0=e0.sibling;e0!==null;)Z1(e0,t0,n0),e0=e0.sibling}function J1(e0,t0,n0){var o0=e0.tag;if(o0===5||o0===6)e0=e0.stateNode,t0?n0.insertBefore(e0,t0):n0.appendChild(e0);else if(o0!==4&&(e0=e0.child,e0!==null))for(J1(e0,t0,n0),e0=e0.sibling;e0!==null;)J1(e0,t0,n0),e0=e0.sibling}var ns=null,qs=!1;function Ia(e0,t0,n0){for(n0=n0.child;n0!==null;)w3(e0,t0,n0),n0=n0.sibling}function w3(e0,t0,n0){if(Gs&&typeof Gs.onCommitFiberUnmount=="function")try{Gs.onCommitFiberUnmount(Ci,n0)}catch{}switch(n0.tag){case 5:cs||No(n0,t0);case 6:var o0=ns,l0=qs;ns=null,Ia(e0,t0,n0),ns=o0,qs=l0,ns!==null&&(qs?(e0=ns,n0=n0.stateNode,e0.nodeType===8?e0.parentNode.removeChild(n0):e0.removeChild(n0)):ns.removeChild(n0.stateNode));break;case 18:ns!==null&&(qs?(e0=ns,n0=n0.stateNode,e0.nodeType===8?p1(e0.parentNode,n0):e0.nodeType===1&&p1(e0,n0),Zo(e0)):p1(ns,n0.stateNode));break;case 4:o0=ns,l0=qs,ns=n0.stateNode.containerInfo,qs=!0,Ia(e0,t0,n0),ns=o0,qs=l0;break;case 0:case 11:case 14:case 15:if(!cs&&(o0=n0.updateQueue,o0!==null&&(o0=o0.lastEffect,o0!==null))){l0=o0=o0.next;do{var c0=l0,p0=c0.destroy;c0=c0.tag,p0!==void 0&&((c0&2)!==0||(c0&4)!==0)&&Y1(n0,t0,p0),l0=l0.next}while(l0!==o0)}Ia(e0,t0,n0);break;case 1:if(!cs&&(No(n0,t0),o0=n0.stateNode,typeof o0.componentWillUnmount=="function"))try{o0.props=n0.memoizedProps,o0.state=n0.memoizedState,o0.componentWillUnmount()}catch(h0){qn(n0,t0,h0)}Ia(e0,t0,n0);break;case 21:Ia(e0,t0,n0);break;case 22:n0.mode&1?(cs=(o0=cs)||n0.memoizedState!==null,Ia(e0,t0,n0),cs=o0):Ia(e0,t0,n0);break;default:Ia(e0,t0,n0)}}function E3(e0){var t0=e0.updateQueue;if(t0!==null){e0.updateQueue=null;var n0=e0.stateNode;n0===null&&(n0=e0.stateNode=new u5),t0.forEach(function(o0){var l0=w5.bind(null,e0,o0);n0.has(o0)||(n0.add(o0),o0.then(l0,l0))})}}function $s(e0,t0){var n0=t0.deletions;if(n0!==null)for(var o0=0;o0l0&&(l0=p0),o0&=~c0}if(o0=l0,o0=yr()-o0,o0=(120>o0?120:480>o0?480:1080>o0?1080:1920>o0?1920:3e3>o0?3e3:4320>o0?4320:1960*p5(o0/1960))-o0,10e0?16:e0,Da===null)var o0=!1;else{if(e0=Da,Da=null,Sl=0,(Sr&6)!==0)throw Error(M(331));var l0=Sr;for(Sr|=4,G0=e0.current;G0!==null;){var c0=G0,p0=c0.child;if((G0.flags&16)!==0){var h0=c0.deletions;if(h0!==null){for(var E0=0;E0yr()-r4?ao(e0,0):t4|=n0),ws(e0,t0)}function I3(e0,t0){t0===0&&((e0.mode&1)===0?t0=1:(t0=zi,zi<<=1,(zi&130023424)===0&&(zi=4194304)));var n0=ps();e0=oa(e0,t0),e0!==null&&(Vo(e0,t0,n0),ws(e0,n0))}function y5(e0){var t0=e0.memoizedState,n0=0;t0!==null&&(n0=t0.retryLane),I3(e0,n0)}function w5(e0,t0){var n0=0;switch(e0.tag){case 13:var o0=e0.stateNode,l0=e0.memoizedState;l0!==null&&(n0=l0.retryLane);break;case 19:o0=e0.stateNode;break;default:throw Error(M(314))}o0!==null&&o0.delete(t0),I3(e0,n0)}var z3;z3=function(e0,t0,n0){if(e0!==null)if(e0.memoizedProps!==t0.pendingProps||_s.current)gs=!0;else{if((e0.lanes&n0)===0&&(t0.flags&128)===0)return gs=!1,o5(e0,t0,n0);gs=(e0.flags&131072)!==0}else gs=!1,Gr&&(t0.flags&1048576)!==0&&m2(t0,rl,t0.index);switch(t0.lanes=0,t0.tag){case 2:var o0=t0.type;gl(e0,t0),e0=t0.pendingProps;var l0=To(t0,is.current);Io(t0,n0),l0=I1(null,t0,o0,e0,l0,n0);var c0=z1();return t0.flags|=1,typeof l0=="object"&&l0!==null&&typeof l0.render=="function"&&l0.$$typeof===void 0?(t0.tag=1,t0.memoizedState=null,t0.updateQueue=null,hs(o0)?(c0=!0,Ji(t0)):c0=!1,t0.memoizedState=l0.state!==null&&l0.state!==void 0?l0.state:null,b1(t0),l0.updater=fl,t0.stateNode=l0,l0._reactInternals=t0,$1(t0,o0,e0,n0),t0=H1(null,t0,o0,!0,c0,n0)):(t0.tag=0,Gr&&c0&&h1(t0),ds(null,t0,l0,n0),t0=t0.child),t0;case 16:o0=t0.elementType;e:{switch(gl(e0,t0),e0=t0.pendingProps,l0=o0._init,o0=l0(o0._payload),t0.type=o0,l0=t0.tag=M5(o0),e0=Os(o0,e0),l0){case 0:t0=U1(null,t0,o0,e0,n0);break e;case 1:t0=o3(null,t0,o0,e0,n0);break e;case 11:t0=t3(null,t0,o0,e0,n0);break e;case 14:t0=r3(null,t0,o0,Os(o0.type,e0),n0);break e}throw Error(M(306,o0,""))}return t0;case 0:return o0=t0.type,l0=t0.pendingProps,l0=t0.elementType===o0?l0:Os(o0,l0),U1(e0,t0,o0,l0,n0);case 1:return o0=t0.type,l0=t0.pendingProps,l0=t0.elementType===o0?l0:Os(o0,l0),o3(e0,t0,o0,l0,n0);case 3:e:{if(i3(t0),e0===null)throw Error(M(387));o0=t0.pendingProps,c0=t0.memoizedState,l0=c0.element,v2(e0,t0),ll(t0,o0,null,n0);var p0=t0.memoizedState;if(o0=p0.element,c0.isDehydrated)if(c0={element:o0,isDehydrated:!1,cache:p0.cache,pendingSuspenseBoundaries:p0.pendingSuspenseBoundaries,transitions:p0.transitions},t0.updateQueue.baseState=c0,t0.memoizedState=c0,t0.flags&256){l0=Do(Error(M(423)),t0),t0=l3(e0,t0,o0,n0,l0);break e}else if(o0!==l0){l0=Do(Error(M(424)),t0),t0=l3(e0,t0,o0,n0,l0);break e}else for(vs=Ta(t0.stateNode.containerInfo.firstChild),Ms=t0,Gr=!0,Ls=null,n0=E2(t0,null,o0,n0),t0.child=n0;n0;)n0.flags=n0.flags&-3|4096,n0=n0.sibling;else{if(Po(),o0===l0){t0=la(e0,t0,n0);break e}ds(e0,t0,o0,n0)}t0=t0.child}return t0;case 5:return k2(t0),e0===null&&w1(t0),o0=t0.type,l0=t0.pendingProps,c0=e0!==null?e0.memoizedProps:null,p0=l0.children,c1(o0,l0)?p0=null:c0!==null&&c1(o0,c0)&&(t0.flags|=32),a3(e0,t0),ds(e0,t0,p0,n0),t0.child;case 6:return e0===null&&w1(t0),null;case 13:return u3(e0,t0,n0);case 4:return T1(t0,t0.stateNode.containerInfo),o0=t0.pendingProps,e0===null?t0.child=Ro(t0,null,o0,n0):ds(e0,t0,o0,n0),t0.child;case 11:return o0=t0.type,l0=t0.pendingProps,l0=t0.elementType===o0?l0:Os(o0,l0),t3(e0,t0,o0,l0,n0);case 7:return ds(e0,t0,t0.pendingProps,n0),t0.child;case 8:return ds(e0,t0,t0.pendingProps.children,n0),t0.child;case 12:return ds(e0,t0,t0.pendingProps.children,n0),t0.child;case 10:e:{if(o0=t0.type._context,l0=t0.pendingProps,c0=t0.memoizedProps,p0=l0.value,Dr(al,o0._currentValue),o0._currentValue=p0,c0!==null)if(Ns(c0.value,p0)){if(c0.children===l0.children&&!_s.current){t0=la(e0,t0,n0);break e}}else for(c0=t0.child,c0!==null&&(c0.return=t0);c0!==null;){var h0=c0.dependencies;if(h0!==null){p0=c0.child;for(var E0=h0.firstContext;E0!==null;){if(E0.context===o0){if(c0.tag===1){E0=ia(-1,n0&-n0),E0.tag=2;var P0=c0.updateQueue;if(P0!==null){P0=P0.shared;var D0=P0.pending;D0===null?E0.next=E0:(E0.next=D0.next,D0.next=E0),P0.pending=E0}}c0.lanes|=n0,E0=c0.alternate,E0!==null&&(E0.lanes|=n0),S1(c0.return,n0,t0),h0.lanes|=n0;break}E0=E0.next}}else if(c0.tag===10)p0=c0.type===t0.type?null:c0.child;else if(c0.tag===18){if(p0=c0.return,p0===null)throw Error(M(341));p0.lanes|=n0,h0=p0.alternate,h0!==null&&(h0.lanes|=n0),S1(p0,n0,t0),p0=c0.sibling}else p0=c0.child;if(p0!==null)p0.return=c0;else for(p0=c0;p0!==null;){if(p0===t0){p0=null;break}if(c0=p0.sibling,c0!==null){c0.return=p0.return,p0=c0;break}p0=p0.return}c0=p0}ds(e0,t0,l0.children,n0),t0=t0.child}return t0;case 9:return l0=t0.type,o0=t0.pendingProps.children,Io(t0,n0),l0=Fs(l0),o0=o0(l0),t0.flags|=1,ds(e0,t0,o0,n0),t0.child;case 14:return o0=t0.type,l0=Os(o0,t0.pendingProps),l0=Os(o0.type,l0),r3(e0,t0,o0,l0,n0);case 15:return n3(e0,t0,t0.type,t0.pendingProps,n0);case 17:return o0=t0.type,l0=t0.pendingProps,l0=t0.elementType===o0?l0:Os(o0,l0),gl(e0,t0),t0.tag=1,hs(o0)?(e0=!0,Ji(t0)):e0=!1,Io(t0,n0),K2(t0,o0,l0),$1(t0,o0,l0,n0),H1(null,t0,o0,!0,e0,n0);case 19:return d3(e0,t0,n0);case 22:return s3(e0,t0,n0)}throw Error(M(156,t0.tag))};function D3(e0,t0){return L0(e0,t0)}function E5(e0,t0,n0,o0){this.tag=e0,this.key=n0,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t0,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=o0,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Cs(e0,t0,n0,o0){return new E5(e0,t0,n0,o0)}function c4(e0){return e0=e0.prototype,!(!e0||!e0.isReactComponent)}function M5(e0){if(typeof e0=="function")return c4(e0)?1:0;if(e0!=null){if(e0=e0.$$typeof,e0===vr)return 11;if(e0===fr)return 14}return 2}function Oa(e0,t0){var n0=e0.alternate;return n0===null?(n0=Cs(e0.tag,t0,e0.key,e0.mode),n0.elementType=e0.elementType,n0.type=e0.type,n0.stateNode=e0.stateNode,n0.alternate=e0,e0.alternate=n0):(n0.pendingProps=t0,n0.type=e0.type,n0.flags=0,n0.subtreeFlags=0,n0.deletions=null),n0.flags=e0.flags&14680064,n0.childLanes=e0.childLanes,n0.lanes=e0.lanes,n0.child=e0.child,n0.memoizedProps=e0.memoizedProps,n0.memoizedState=e0.memoizedState,n0.updateQueue=e0.updateQueue,t0=e0.dependencies,n0.dependencies=t0===null?null:{lanes:t0.lanes,firstContext:t0.firstContext},n0.sibling=e0.sibling,n0.index=e0.index,n0.ref=e0.ref,n0}function Al(e0,t0,n0,o0,l0,c0){var p0=2;if(o0=e0,typeof e0=="function")c4(e0)&&(p0=1);else if(typeof e0=="string")p0=5;else e:switch(e0){case X0:return io(n0.children,l0,c0,t0);case xr:p0=8,l0|=8;break;case Ir:return e0=Cs(12,n0,t0,l0|2),e0.elementType=Ir,e0.lanes=c0,e0;case H0:return e0=Cs(13,n0,t0,l0),e0.elementType=H0,e0.lanes=c0,e0;case lr:return e0=Cs(19,n0,t0,l0),e0.elementType=lr,e0.lanes=c0,e0;case wr:return Fl(n0,l0,c0,t0);default:if(typeof e0=="object"&&e0!==null)switch(e0.$$typeof){case Ur:p0=10;break e;case mr:p0=9;break e;case vr:p0=11;break e;case fr:p0=14;break e;case _r:p0=16,o0=null;break e}throw Error(M(130,e0==null?e0:typeof e0,""))}return t0=Cs(p0,n0,t0,l0),t0.elementType=e0,t0.type=o0,t0.lanes=c0,t0}function io(e0,t0,n0,o0){return e0=Cs(7,e0,o0,t0),e0.lanes=n0,e0}function Fl(e0,t0,n0,o0){return e0=Cs(22,e0,o0,t0),e0.elementType=wr,e0.lanes=n0,e0.stateNode={isHidden:!1},e0}function d4(e0,t0,n0){return e0=Cs(6,e0,null,t0),e0.lanes=n0,e0}function p4(e0,t0,n0){return t0=Cs(4,e0.children!==null?e0.children:[],e0.key,t0),t0.lanes=n0,t0.stateNode={containerInfo:e0.containerInfo,pendingChildren:null,implementation:e0.implementation},t0}function v5(e0,t0,n0,o0,l0){this.tag=t0,this.containerInfo=e0,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=ql(0),this.expirationTimes=ql(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ql(0),this.identifierPrefix=o0,this.onRecoverableError=l0,this.mutableSourceEagerHydrationData=null}function m4(e0,t0,n0,o0,l0,c0,p0,h0,E0){return e0=new v5(e0,t0,n0,h0,E0),t0===1?(t0=1,c0===!0&&(t0|=8)):t0=0,c0=Cs(3,null,null,t0),e0.current=c0,c0.stateNode=e0,c0.memoizedState={element:o0,isDehydrated:n0,cache:null,transitions:null,pendingSuspenseBoundaries:null},b1(c0),e0}function x5(e0,t0,n0){var o0=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(r){console.error(r)}}return e(),reactDom.exports=requireReactDom_production_min(),reactDom.exports}var hasRequiredClient;function requireClient(){if(hasRequiredClient)return client;hasRequiredClient=1;var e=requireReactDom();return client.createRoot=e.createRoot,client.hydrateRoot=e.hydrateRoot,client}var clientExports=requireClient();const ReactDOM=getDefaultExportFromCjs(clientExports);/*! @license DOMPurify 3.2.4 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.4/LICENSE */const{entries,setPrototypeOf,isFrozen,getPrototypeOf,getOwnPropertyDescriptor}=Object;let{freeze,seal,create}=Object,{apply,construct}=typeof Reflect<"u"&&Reflect;freeze||(freeze=function(r){return r});seal||(seal=function(r){return r});apply||(apply=function(r,M,r0){return r.apply(M,r0)});construct||(construct=function(r,M){return new r(...M)});const arrayForEach=unapply(Array.prototype.forEach),arrayLastIndexOf=unapply(Array.prototype.lastIndexOf),arrayPop=unapply(Array.prototype.pop),arrayPush=unapply(Array.prototype.push),arraySplice=unapply(Array.prototype.splice),stringToLowerCase=unapply(String.prototype.toLowerCase),stringToString=unapply(String.prototype.toString),stringMatch=unapply(String.prototype.match),stringReplace=unapply(String.prototype.replace),stringIndexOf=unapply(String.prototype.indexOf),stringTrim=unapply(String.prototype.trim),objectHasOwnProperty=unapply(Object.prototype.hasOwnProperty),regExpTest=unapply(RegExp.prototype.test),typeErrorCreate=unconstruct(TypeError);function unapply(e){return function(r){for(var M=arguments.length,r0=new Array(M>1?M-1:0),s0=1;s02&&arguments[2]!==void 0?arguments[2]:stringToLowerCase;setPrototypeOf&&setPrototypeOf(e,null);let r0=r.length;for(;r0--;){let s0=r[r0];if(typeof s0=="string"){const a0=M(s0);a0!==s0&&(isFrozen(r)||(r[r0]=a0),s0=a0)}e[s0]=!0}return e}function cleanArray(e){for(let r=0;r/gm),TMPLIT_EXPR=seal(/\$\{[\w\W]*/gm),DATA_ATTR=seal(/^data-[\-\w.\u00B7-\uFFFF]+$/),ARIA_ATTR=seal(/^aria-[\-\w]+$/),IS_ALLOWED_URI=seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),IS_SCRIPT_OR_DATA=seal(/^(?:\w+script|data):/i),ATTR_WHITESPACE=seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),DOCTYPE_NAME=seal(/^html$/i),CUSTOM_ELEMENT=seal(/^[a-z][.\w]*(-[.\w]+)+$/i);var EXPRESSIONS=Object.freeze({__proto__:null,ARIA_ATTR,ATTR_WHITESPACE,CUSTOM_ELEMENT,DATA_ATTR,DOCTYPE_NAME,ERB_EXPR,IS_ALLOWED_URI,IS_SCRIPT_OR_DATA,MUSTACHE_EXPR,TMPLIT_EXPR});const NODE_TYPE={element:1,text:3,progressingInstruction:7,comment:8,document:9},getGlobal=function(){return typeof window>"u"?null:window},_createTrustedTypesPolicy=function(r,M){if(typeof r!="object"||typeof r.createPolicy!="function")return null;let r0=null;const s0="data-tt-policy-suffix";M&&M.hasAttribute(s0)&&(r0=M.getAttribute(s0));const a0="dompurify"+(r0?"#"+r0:"");try{return r.createPolicy(a0,{createHTML(i0){return i0},createScriptURL(i0){return i0}})}catch{return console.warn("TrustedTypes policy "+a0+" could not be created."),null}},_createHooksMap=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function createDOMPurify(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:getGlobal();const r=Q0=>createDOMPurify(Q0);if(r.version="3.2.4",r.removed=[],!e||!e.document||e.document.nodeType!==NODE_TYPE.document||!e.Element)return r.isSupported=!1,r;let{document:M}=e;const r0=M,s0=r0.currentScript,{DocumentFragment:a0,HTMLTemplateElement:i0,Node:u0,Element:d0,NodeFilter:m0,NamedNodeMap:_0=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:f0,DOMParser:g0,trustedTypes:x0}=e,k0=d0.prototype,F0=lookupGetter(k0,"cloneNode"),C0=lookupGetter(k0,"remove"),R0=lookupGetter(k0,"nextSibling"),y0=lookupGetter(k0,"childNodes"),w0=lookupGetter(k0,"parentNode");if(typeof i0=="function"){const Q0=M.createElement("template");Q0.content&&Q0.content.ownerDocument&&(M=Q0.content.ownerDocument)}let A0,q0="";const{implementation:U0,createNodeIterator:X0,createDocumentFragment:xr,getElementsByTagName:Ir}=M,{importNode:Ur}=r0;let mr=_createHooksMap();r.isSupported=typeof entries=="function"&&typeof w0=="function"&&U0&&U0.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:vr,ERB_EXPR:H0,TMPLIT_EXPR:lr,DATA_ATTR:fr,ARIA_ATTR:_r,IS_SCRIPT_OR_DATA:wr,ATTR_WHITESPACE:$0,CUSTOM_ELEMENT:Z0}=EXPRESSIONS;let{IS_ALLOWED_URI:j0}=EXPRESSIONS,S0=null;const I0=addToSet({},[...html$1,...svg$1,...svgFilters,...mathMl$1,...text]);let J0=null;const gr=addToSet({},[...html$2,...svg,...mathMl,...xml]);let tr=Object.seal(create(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Mr=null,Fr=null,kr=!0,Cr=!0,as=!1,$a=!0,Ys=!1,ca=!0,Is=!1,uo=!1,co=!1,Bs=!1,ja=!1,da=!1,pa=!0,Qs=!1;const $o="user-content-";let po=!0,ma=!1,Zs={},Js=null;const mo=addToSet({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ba=null;const jo=addToSet({},["audio","video","img","source","image","track"]);let ea=null;const _a=addToSet({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),_o="http://www.w3.org/1998/Math/MathML",Ua="http://www.w3.org/2000/svg",Ss="http://www.w3.org/1999/xhtml";let fa=Ss,Ha=!1,Ga=null;const Bo=addToSet({},[_o,Ua,Ss],stringToString);let ha=addToSet({},["mi","mo","mn","ms","mtext"]),ga=addToSet({},["annotation-xml"]);const ya=addToSet({},["title","style","font","a","script"]);let ks=null;const bi=["application/xhtml+xml","text/html"],Ti="text/html";let $n=null,ta=null;const Ai=M.createElement("form"),fo=function(M0){return M0 instanceof RegExp||M0 instanceof Function},ho=function(){let M0=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(ta&&ta===M0)){if((!M0||typeof M0!="object")&&(M0={}),M0=clone(M0),ks=bi.indexOf(M0.PARSER_MEDIA_TYPE)===-1?Ti:M0.PARSER_MEDIA_TYPE,$n=ks==="application/xhtml+xml"?stringToString:stringToLowerCase,S0=objectHasOwnProperty(M0,"ALLOWED_TAGS")?addToSet({},M0.ALLOWED_TAGS,$n):I0,J0=objectHasOwnProperty(M0,"ALLOWED_ATTR")?addToSet({},M0.ALLOWED_ATTR,$n):gr,Ga=objectHasOwnProperty(M0,"ALLOWED_NAMESPACES")?addToSet({},M0.ALLOWED_NAMESPACES,stringToString):Bo,ea=objectHasOwnProperty(M0,"ADD_URI_SAFE_ATTR")?addToSet(clone(_a),M0.ADD_URI_SAFE_ATTR,$n):_a,Ba=objectHasOwnProperty(M0,"ADD_DATA_URI_TAGS")?addToSet(clone(jo),M0.ADD_DATA_URI_TAGS,$n):jo,Js=objectHasOwnProperty(M0,"FORBID_CONTENTS")?addToSet({},M0.FORBID_CONTENTS,$n):mo,Mr=objectHasOwnProperty(M0,"FORBID_TAGS")?addToSet({},M0.FORBID_TAGS,$n):{},Fr=objectHasOwnProperty(M0,"FORBID_ATTR")?addToSet({},M0.FORBID_ATTR,$n):{},Zs=objectHasOwnProperty(M0,"USE_PROFILES")?M0.USE_PROFILES:!1,kr=M0.ALLOW_ARIA_ATTR!==!1,Cr=M0.ALLOW_DATA_ATTR!==!1,as=M0.ALLOW_UNKNOWN_PROTOCOLS||!1,$a=M0.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Ys=M0.SAFE_FOR_TEMPLATES||!1,ca=M0.SAFE_FOR_XML!==!1,Is=M0.WHOLE_DOCUMENT||!1,Bs=M0.RETURN_DOM||!1,ja=M0.RETURN_DOM_FRAGMENT||!1,da=M0.RETURN_TRUSTED_TYPE||!1,co=M0.FORCE_BODY||!1,pa=M0.SANITIZE_DOM!==!1,Qs=M0.SANITIZE_NAMED_PROPS||!1,po=M0.KEEP_CONTENT!==!1,ma=M0.IN_PLACE||!1,j0=M0.ALLOWED_URI_REGEXP||IS_ALLOWED_URI,fa=M0.NAMESPACE||Ss,ha=M0.MATHML_TEXT_INTEGRATION_POINTS||ha,ga=M0.HTML_INTEGRATION_POINTS||ga,tr=M0.CUSTOM_ELEMENT_HANDLING||{},M0.CUSTOM_ELEMENT_HANDLING&&fo(M0.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(tr.tagNameCheck=M0.CUSTOM_ELEMENT_HANDLING.tagNameCheck),M0.CUSTOM_ELEMENT_HANDLING&&fo(M0.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(tr.attributeNameCheck=M0.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),M0.CUSTOM_ELEMENT_HANDLING&&typeof M0.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(tr.allowCustomizedBuiltInElements=M0.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),Ys&&(Cr=!1),ja&&(Bs=!0),Zs&&(S0=addToSet({},text),J0=[],Zs.html===!0&&(addToSet(S0,html$1),addToSet(J0,html$2)),Zs.svg===!0&&(addToSet(S0,svg$1),addToSet(J0,svg),addToSet(J0,xml)),Zs.svgFilters===!0&&(addToSet(S0,svgFilters),addToSet(J0,svg),addToSet(J0,xml)),Zs.mathMl===!0&&(addToSet(S0,mathMl$1),addToSet(J0,mathMl),addToSet(J0,xml))),M0.ADD_TAGS&&(S0===I0&&(S0=clone(S0)),addToSet(S0,M0.ADD_TAGS,$n)),M0.ADD_ATTR&&(J0===gr&&(J0=clone(J0)),addToSet(J0,M0.ADD_ATTR,$n)),M0.ADD_URI_SAFE_ATTR&&addToSet(ea,M0.ADD_URI_SAFE_ATTR,$n),M0.FORBID_CONTENTS&&(Js===mo&&(Js=clone(Js)),addToSet(Js,M0.FORBID_CONTENTS,$n)),po&&(S0["#text"]=!0),Is&&addToSet(S0,["html","head","body"]),S0.table&&(addToSet(S0,["tbody"]),delete Mr.tbody),M0.TRUSTED_TYPES_POLICY){if(typeof M0.TRUSTED_TYPES_POLICY.createHTML!="function")throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof M0.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');A0=M0.TRUSTED_TYPES_POLICY,q0=A0.createHTML("")}else A0===void 0&&(A0=_createTrustedTypesPolicy(x0,s0)),A0!==null&&typeof q0=="string"&&(q0=A0.createHTML(""));freeze&&freeze(M0),ta=M0}},wa=addToSet({},[...svg$1,...svgFilters,...svgDisallowed]),go=addToSet({},[...mathMl$1,...mathMlDisallowed]),Wa=function(M0){let L0=w0(M0);(!L0||!L0.tagName)&&(L0={namespaceURI:fa,tagName:"template"});const V0=stringToLowerCase(M0.tagName),zr=stringToLowerCase(L0.tagName);return Ga[M0.namespaceURI]?M0.namespaceURI===Ua?L0.namespaceURI===Ss?V0==="svg":L0.namespaceURI===_o?V0==="svg"&&(zr==="annotation-xml"||ha[zr]):!!wa[V0]:M0.namespaceURI===_o?L0.namespaceURI===Ss?V0==="math":L0.namespaceURI===Ua?V0==="math"&&ga[zr]:!!go[V0]:M0.namespaceURI===Ss?L0.namespaceURI===Ua&&!ga[zr]||L0.namespaceURI===_o&&!ha[zr]?!1:!go[V0]&&(ya[V0]||!wa[V0]):!!(ks==="application/xhtml+xml"&&Ga[M0.namespaceURI]):!1},bs=function(M0){arrayPush(r.removed,{element:M0});try{w0(M0).removeChild(M0)}catch{C0(M0)}},Us=function(M0,L0){try{arrayPush(r.removed,{attribute:L0.getAttributeNode(M0),from:L0})}catch{arrayPush(r.removed,{attribute:null,from:L0})}if(L0.removeAttribute(M0),M0==="is")if(Bs||ja)try{bs(L0)}catch{}else try{L0.setAttribute(M0,"")}catch{}},Va=function(M0){let L0=null,V0=null;if(co)M0=""+M0;else{const yr=stringMatch(M0,/^[\r\n\t ]+/);V0=yr&&yr[0]}ks==="application/xhtml+xml"&&fa===Ss&&(M0=''+M0+"");const zr=A0?A0.createHTML(M0):M0;if(fa===Ss)try{L0=new g0().parseFromString(zr,ks)}catch{}if(!L0||!L0.documentElement){L0=U0.createDocument(fa,"template",null);try{L0.documentElement.innerHTML=Ha?q0:zr}catch{}}const Jn=L0.body||L0.documentElement;return M0&&V0&&Jn.insertBefore(M.createTextNode(V0),Jn.childNodes[0]||null),fa===Ss?Ir.call(L0,Is?"html":"body")[0]:Is?L0.documentElement:Jn},Ka=function(M0){return X0.call(M0.ownerDocument||M0,M0,m0.SHOW_ELEMENT|m0.SHOW_COMMENT|m0.SHOW_TEXT|m0.SHOW_PROCESSING_INSTRUCTION|m0.SHOW_CDATA_SECTION,null)},Xa=function(M0){return M0 instanceof f0&&(typeof M0.nodeName!="string"||typeof M0.textContent!="string"||typeof M0.removeChild!="function"||!(M0.attributes instanceof _0)||typeof M0.removeAttribute!="function"||typeof M0.setAttribute!="function"||typeof M0.namespaceURI!="string"||typeof M0.insertBefore!="function"||typeof M0.hasChildNodes!="function")},Fi=function(M0){return typeof u0=="function"&&M0 instanceof u0};function zs(Q0,M0,L0){arrayForEach(Q0,V0=>{V0.call(r,M0,L0,ta)})}const Pi=function(M0){let L0=null;if(zs(mr.beforeSanitizeElements,M0,null),Xa(M0))return bs(M0),!0;const V0=$n(M0.nodeName);if(zs(mr.uponSanitizeElement,M0,{tagName:V0,allowedTags:S0}),M0.hasChildNodes()&&!Fi(M0.firstElementChild)&®ExpTest(/<[/\w]/g,M0.innerHTML)&®ExpTest(/<[/\w]/g,M0.textContent)||M0.nodeType===NODE_TYPE.progressingInstruction||ca&&M0.nodeType===NODE_TYPE.comment&®ExpTest(/<[/\w]/g,M0.data))return bs(M0),!0;if(!S0[V0]||Mr[V0]){if(!Mr[V0]&&Uo(V0)&&(tr.tagNameCheck instanceof RegExp&®ExpTest(tr.tagNameCheck,V0)||tr.tagNameCheck instanceof Function&&tr.tagNameCheck(V0)))return!1;if(po&&!Js[V0]){const zr=w0(M0)||M0.parentNode,Jn=y0(M0)||M0.childNodes;if(Jn&&zr){const yr=Jn.length;for(let os=yr-1;os>=0;--os){const ms=F0(Jn[os],!0);ms.__removalCount=(M0.__removalCount||0)+1,zr.insertBefore(ms,R0(M0))}}}return bs(M0),!0}return M0 instanceof d0&&!Wa(M0)||(V0==="noscript"||V0==="noembed"||V0==="noframes")&®ExpTest(/<\/no(script|embed|frames)/i,M0.innerHTML)?(bs(M0),!0):(Ys&&M0.nodeType===NODE_TYPE.text&&(L0=M0.textContent,arrayForEach([vr,H0,lr],zr=>{L0=stringReplace(L0,zr," ")}),M0.textContent!==L0&&(arrayPush(r.removed,{element:M0.cloneNode()}),M0.textContent=L0)),zs(mr.afterSanitizeElements,M0,null),!1)},Hs=function(M0,L0,V0){if(pa&&(L0==="id"||L0==="name")&&(V0 in M||V0 in Ai))return!1;if(!(Cr&&!Fr[L0]&®ExpTest(fr,L0))){if(!(kr&®ExpTest(_r,L0))){if(!J0[L0]||Fr[L0]){if(!(Uo(M0)&&(tr.tagNameCheck instanceof RegExp&®ExpTest(tr.tagNameCheck,M0)||tr.tagNameCheck instanceof Function&&tr.tagNameCheck(M0))&&(tr.attributeNameCheck instanceof RegExp&®ExpTest(tr.attributeNameCheck,L0)||tr.attributeNameCheck instanceof Function&&tr.attributeNameCheck(L0))||L0==="is"&&tr.allowCustomizedBuiltInElements&&(tr.tagNameCheck instanceof RegExp&®ExpTest(tr.tagNameCheck,V0)||tr.tagNameCheck instanceof Function&&tr.tagNameCheck(V0))))return!1}else if(!ea[L0]){if(!regExpTest(j0,stringReplace(V0,$0,""))){if(!((L0==="src"||L0==="xlink:href"||L0==="href")&&M0!=="script"&&stringIndexOf(V0,"data:")===0&&Ba[M0])){if(!(as&&!regExpTest(wr,stringReplace(V0,$0,"")))){if(V0)return!1}}}}}}return!0},Uo=function(M0){return M0!=="annotation-xml"&&stringMatch(M0,Z0)},Ho=function(M0){zs(mr.beforeSanitizeAttributes,M0,null);const{attributes:L0}=M0;if(!L0||Xa(M0))return;const V0={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:J0,forceKeepAttr:void 0};let zr=L0.length;for(;zr--;){const Jn=L0[zr],{name:yr,namespaceURI:os,value:ms}=Jn,Ea=$n(yr);let Kn=yr==="value"?ms:stringTrim(ms);if(V0.attrName=Ea,V0.attrValue=Kn,V0.keepAttr=!0,V0.forceKeepAttr=void 0,zs(mr.uponSanitizeAttribute,M0,V0),Kn=V0.attrValue,Qs&&(Ea==="id"||Ea==="name")&&(Us(yr,M0),Kn=$o+Kn),ca&®ExpTest(/((--!?|])>)|<\/(style|title)/i,Kn)){Us(yr,M0);continue}if(V0.forceKeepAttr||(Us(yr,M0),!V0.keepAttr))continue;if(!$a&®ExpTest(/\/>/i,Kn)){Us(yr,M0);continue}Ys&&arrayForEach([vr,H0,lr],Go=>{Kn=stringReplace(Kn,Go," ")});const Ri=$n(M0.nodeName);if(Hs(Ri,Ea,Kn)){if(A0&&typeof x0=="object"&&typeof x0.getAttributeType=="function"&&!os)switch(x0.getAttributeType(Ri,Ea)){case"TrustedHTML":{Kn=A0.createHTML(Kn);break}case"TrustedScriptURL":{Kn=A0.createScriptURL(Kn);break}}try{os?M0.setAttributeNS(os,yr,Kn):M0.setAttribute(yr,Kn),Xa(M0)?bs(M0):arrayPop(r.removed)}catch{}}}zs(mr.afterSanitizeAttributes,M0,null)},Ll=function Q0(M0){let L0=null;const V0=Ka(M0);for(zs(mr.beforeSanitizeShadowDOM,M0,null);L0=V0.nextNode();)zs(mr.uponSanitizeShadowNode,L0,null),Pi(L0),Ho(L0),L0.content instanceof a0&&Q0(L0.content);zs(mr.afterSanitizeShadowDOM,M0,null)};return r.sanitize=function(Q0){let M0=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},L0=null,V0=null,zr=null,Jn=null;if(Ha=!Q0,Ha&&(Q0=""),typeof Q0!="string"&&!Fi(Q0))if(typeof Q0.toString=="function"){if(Q0=Q0.toString(),typeof Q0!="string")throw typeErrorCreate("dirty is not a string, aborting")}else throw typeErrorCreate("toString is not a function");if(!r.isSupported)return Q0;if(uo||ho(M0),r.removed=[],typeof Q0=="string"&&(ma=!1),ma){if(Q0.nodeName){const ms=$n(Q0.nodeName);if(!S0[ms]||Mr[ms])throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place")}}else if(Q0 instanceof u0)L0=Va(""),V0=L0.ownerDocument.importNode(Q0,!0),V0.nodeType===NODE_TYPE.element&&V0.nodeName==="BODY"||V0.nodeName==="HTML"?L0=V0:L0.appendChild(V0);else{if(!Bs&&!Ys&&!Is&&Q0.indexOf("<")===-1)return A0&&da?A0.createHTML(Q0):Q0;if(L0=Va(Q0),!L0)return Bs?null:da?q0:""}L0&&co&&bs(L0.firstChild);const yr=Ka(ma?Q0:L0);for(;zr=yr.nextNode();)Pi(zr),Ho(zr),zr.content instanceof a0&&Ll(zr.content);if(ma)return Q0;if(Bs){if(ja)for(Jn=xr.call(L0.ownerDocument);L0.firstChild;)Jn.appendChild(L0.firstChild);else Jn=L0;return(J0.shadowroot||J0.shadowrootmode)&&(Jn=Ur.call(r0,Jn,!0)),Jn}let os=Is?L0.outerHTML:L0.innerHTML;return Is&&S0["!doctype"]&&L0.ownerDocument&&L0.ownerDocument.doctype&&L0.ownerDocument.doctype.name&®ExpTest(DOCTYPE_NAME,L0.ownerDocument.doctype.name)&&(os=" +`+os),Ys&&arrayForEach([vr,H0,lr],ms=>{os=stringReplace(os,ms," ")}),A0&&da?A0.createHTML(os):os},r.setConfig=function(){let Q0=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ho(Q0),uo=!0},r.clearConfig=function(){ta=null,uo=!1},r.isValidAttribute=function(Q0,M0,L0){ta||ho({});const V0=$n(Q0),zr=$n(M0);return Hs(V0,zr,L0)},r.addHook=function(Q0,M0){typeof M0=="function"&&arrayPush(mr[Q0],M0)},r.removeHook=function(Q0,M0){if(M0!==void 0){const L0=arrayLastIndexOf(mr[Q0],M0);return L0===-1?void 0:arraySplice(mr[Q0],L0,1)[0]}return arrayPop(mr[Q0])},r.removeHooks=function(Q0){mr[Q0]=[]},r.removeAllHooks=function(){mr=_createHooksMap()},r}var purify=createDOMPurify();function _getDefaults(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}let _defaults=_getDefaults();function changeDefaults(e){_defaults=e}const escapeTest=/[&<>"']/,escapeReplace=new RegExp(escapeTest.source,"g"),escapeTestNoEncode=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode=new RegExp(escapeTestNoEncode.source,"g"),escapeReplacements={"&":"&","<":"<",">":">",'"':""","'":"'"},getEscapeReplacement=e=>escapeReplacements[e];function escape$1(e,r){if(r){if(escapeTest.test(e))return e.replace(escapeReplace,getEscapeReplacement)}else if(escapeTestNoEncode.test(e))return e.replace(escapeReplaceNoEncode,getEscapeReplacement);return e}const unescapeTest=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function unescape(e){return e.replace(unescapeTest,(r,M)=>(M=M.toLowerCase(),M==="colon"?":":M.charAt(0)==="#"?M.charAt(1)==="x"?String.fromCharCode(parseInt(M.substring(2),16)):String.fromCharCode(+M.substring(1)):""))}const caret=/(^|[^\[])\^/g;function edit(e,r){let M=typeof e=="string"?e:e.source;r=r||"";const r0={replace:(s0,a0)=>{let i0=typeof a0=="string"?a0:a0.source;return i0=i0.replace(caret,"$1"),M=M.replace(s0,i0),r0},getRegex:()=>new RegExp(M,r)};return r0}function cleanUrl(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch{return null}return e}const noopTest={exec:()=>null};function splitCells(e,r){const M=e.replace(/\|/g,(a0,i0,u0)=>{let d0=!1,m0=i0;for(;--m0>=0&&u0[m0]==="\\";)d0=!d0;return d0?"|":" |"}),r0=M.split(/ \|/);let s0=0;if(r0[0].trim()||r0.shift(),r0.length>0&&!r0[r0.length-1].trim()&&r0.pop(),r)if(r0.length>r)r0.splice(r);else for(;r0.length{const a0=s0.match(/^\s+/);if(a0===null)return s0;const[i0]=a0;return i0.length>=r0.length?s0.slice(r0.length):s0}).join(` +`)}class _Tokenizer{constructor(r){$r(this,"options");$r(this,"rules");$r(this,"lexer");this.options=r||_defaults}space(r){const M=this.rules.block.newline.exec(r);if(M&&M[0].length>0)return{type:"space",raw:M[0]}}code(r){const M=this.rules.block.code.exec(r);if(M){const r0=M[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:M[0],codeBlockStyle:"indented",text:this.options.pedantic?r0:rtrim(r0,` +`)}}}fences(r){const M=this.rules.block.fences.exec(r);if(M){const r0=M[0],s0=indentCodeCompensation(r0,M[3]||"");return{type:"code",raw:r0,lang:M[2]?M[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):M[2],text:s0}}}heading(r){const M=this.rules.block.heading.exec(r);if(M){let r0=M[2].trim();if(/#$/.test(r0)){const s0=rtrim(r0,"#");(this.options.pedantic||!s0||/ $/.test(s0))&&(r0=s0.trim())}return{type:"heading",raw:M[0],depth:M[1].length,text:r0,tokens:this.lexer.inline(r0)}}}hr(r){const M=this.rules.block.hr.exec(r);if(M)return{type:"hr",raw:M[0]}}blockquote(r){const M=this.rules.block.blockquote.exec(r);if(M){let r0=M[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,` + $1`);r0=rtrim(r0.replace(/^ *>[ \t]?/gm,""),` +`);const s0=this.lexer.state.top;this.lexer.state.top=!0;const a0=this.lexer.blockTokens(r0);return this.lexer.state.top=s0,{type:"blockquote",raw:M[0],tokens:a0,text:r0}}}list(r){let M=this.rules.block.list.exec(r);if(M){let r0=M[1].trim();const s0=r0.length>1,a0={type:"list",raw:"",ordered:s0,start:s0?+r0.slice(0,-1):"",loose:!1,items:[]};r0=s0?`\\d{1,9}\\${r0.slice(-1)}`:`\\${r0}`,this.options.pedantic&&(r0=s0?r0:"[*+-]");const i0=new RegExp(`^( {0,3}${r0})((?:[ ][^\\n]*)?(?:\\n|$))`);let u0="",d0="",m0=!1;for(;r;){let _0=!1;if(!(M=i0.exec(r))||this.rules.block.hr.test(r))break;u0=M[0],r=r.substring(u0.length);let f0=M[2].split(` +`,1)[0].replace(/^\t+/,R0=>" ".repeat(3*R0.length)),g0=r.split(` +`,1)[0],x0=0;this.options.pedantic?(x0=2,d0=f0.trimStart()):(x0=M[2].search(/[^ ]/),x0=x0>4?1:x0,d0=f0.slice(x0),x0+=M[1].length);let k0=!1;if(!f0&&/^ *$/.test(g0)&&(u0+=g0+` +`,r=r.substring(g0.length+1),_0=!0),!_0){const R0=new RegExp(`^ {0,${Math.min(3,x0-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),y0=new RegExp(`^ {0,${Math.min(3,x0-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),w0=new RegExp(`^ {0,${Math.min(3,x0-1)}}(?:\`\`\`|~~~)`),A0=new RegExp(`^ {0,${Math.min(3,x0-1)}}#`);for(;r;){const q0=r.split(` +`,1)[0];if(g0=q0,this.options.pedantic&&(g0=g0.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),w0.test(g0)||A0.test(g0)||R0.test(g0)||y0.test(r))break;if(g0.search(/[^ ]/)>=x0||!g0.trim())d0+=` +`+g0.slice(x0);else{if(k0||f0.search(/[^ ]/)>=4||w0.test(f0)||A0.test(f0)||y0.test(f0))break;d0+=` +`+g0}!k0&&!g0.trim()&&(k0=!0),u0+=q0+` +`,r=r.substring(q0.length+1),f0=g0.slice(x0)}}a0.loose||(m0?a0.loose=!0:/\n *\n *$/.test(u0)&&(m0=!0));let F0=null,C0;this.options.gfm&&(F0=/^\[[ xX]\] /.exec(d0),F0&&(C0=F0[0]!=="[ ] ",d0=d0.replace(/^\[[ xX]\] +/,""))),a0.items.push({type:"list_item",raw:u0,task:!!F0,checked:C0,loose:!1,text:d0,tokens:[]}),a0.raw+=u0}a0.items[a0.items.length-1].raw=u0.trimEnd(),a0.items[a0.items.length-1].text=d0.trimEnd(),a0.raw=a0.raw.trimEnd();for(let _0=0;_0x0.type==="space"),g0=f0.length>0&&f0.some(x0=>/\n.*\n/.test(x0.raw));a0.loose=g0}if(a0.loose)for(let _0=0;_0$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",a0=M[3]?M[3].substring(1,M[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):M[3];return{type:"def",tag:r0,raw:M[0],href:s0,title:a0}}}table(r){const M=this.rules.block.table.exec(r);if(!M||!/[:|]/.test(M[2]))return;const r0=splitCells(M[1]),s0=M[2].replace(/^\||\| *$/g,"").split("|"),a0=M[3]&&M[3].trim()?M[3].replace(/\n[ \t]*$/,"").split(` +`):[],i0={type:"table",raw:M[0],header:[],align:[],rows:[]};if(r0.length===s0.length){for(const u0 of s0)/^ *-+: *$/.test(u0)?i0.align.push("right"):/^ *:-+: *$/.test(u0)?i0.align.push("center"):/^ *:-+ *$/.test(u0)?i0.align.push("left"):i0.align.push(null);for(const u0 of r0)i0.header.push({text:u0,tokens:this.lexer.inline(u0)});for(const u0 of a0)i0.rows.push(splitCells(u0,i0.header.length).map(d0=>({text:d0,tokens:this.lexer.inline(d0)})));return i0}}lheading(r){const M=this.rules.block.lheading.exec(r);if(M)return{type:"heading",raw:M[0],depth:M[2].charAt(0)==="="?1:2,text:M[1],tokens:this.lexer.inline(M[1])}}paragraph(r){const M=this.rules.block.paragraph.exec(r);if(M){const r0=M[1].charAt(M[1].length-1)===` +`?M[1].slice(0,-1):M[1];return{type:"paragraph",raw:M[0],text:r0,tokens:this.lexer.inline(r0)}}}text(r){const M=this.rules.block.text.exec(r);if(M)return{type:"text",raw:M[0],text:M[0],tokens:this.lexer.inline(M[0])}}escape(r){const M=this.rules.inline.escape.exec(r);if(M)return{type:"escape",raw:M[0],text:escape$1(M[1])}}tag(r){const M=this.rules.inline.tag.exec(r);if(M)return!this.lexer.state.inLink&&/^/i.test(M[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(M[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(M[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:M[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:M[0]}}link(r){const M=this.rules.inline.link.exec(r);if(M){const r0=M[2].trim();if(!this.options.pedantic&&/^$/.test(r0))return;const i0=rtrim(r0.slice(0,-1),"\\");if((r0.length-i0.length)%2===0)return}else{const i0=findClosingBracket(M[2],"()");if(i0>-1){const d0=(M[0].indexOf("!")===0?5:4)+M[1].length+i0;M[2]=M[2].substring(0,i0),M[0]=M[0].substring(0,d0).trim(),M[3]=""}}let s0=M[2],a0="";if(this.options.pedantic){const i0=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(s0);i0&&(s0=i0[1],a0=i0[3])}else a0=M[3]?M[3].slice(1,-1):"";return s0=s0.trim(),/^$/.test(r0)?s0=s0.slice(1):s0=s0.slice(1,-1)),outputLink(M,{href:s0&&s0.replace(this.rules.inline.anyPunctuation,"$1"),title:a0&&a0.replace(this.rules.inline.anyPunctuation,"$1")},M[0],this.lexer)}}reflink(r,M){let r0;if((r0=this.rules.inline.reflink.exec(r))||(r0=this.rules.inline.nolink.exec(r))){const s0=(r0[2]||r0[1]).replace(/\s+/g," "),a0=M[s0.toLowerCase()];if(!a0){const i0=r0[0].charAt(0);return{type:"text",raw:i0,text:i0}}return outputLink(r0,a0,r0[0],this.lexer)}}emStrong(r,M,r0=""){let s0=this.rules.inline.emStrongLDelim.exec(r);if(!s0||s0[3]&&r0.match(/[\p{L}\p{N}]/u))return;if(!(s0[1]||s0[2]||"")||!r0||this.rules.inline.punctuation.exec(r0)){const i0=[...s0[0]].length-1;let u0,d0,m0=i0,_0=0;const f0=s0[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(f0.lastIndex=0,M=M.slice(-1*r.length+i0);(s0=f0.exec(M))!=null;){if(u0=s0[1]||s0[2]||s0[3]||s0[4]||s0[5]||s0[6],!u0)continue;if(d0=[...u0].length,s0[3]||s0[4]){m0+=d0;continue}else if((s0[5]||s0[6])&&i0%3&&!((i0+d0)%3)){_0+=d0;continue}if(m0-=d0,m0>0)continue;d0=Math.min(d0,d0+m0+_0);const g0=[...s0[0]][0].length,x0=r.slice(0,i0+s0.index+g0+d0);if(Math.min(i0,d0)%2){const F0=x0.slice(1,-1);return{type:"em",raw:x0,text:F0,tokens:this.lexer.inlineTokens(F0)}}const k0=x0.slice(2,-2);return{type:"strong",raw:x0,text:k0,tokens:this.lexer.inlineTokens(k0)}}}}codespan(r){const M=this.rules.inline.code.exec(r);if(M){let r0=M[2].replace(/\n/g," ");const s0=/[^ ]/.test(r0),a0=/^ /.test(r0)&&/ $/.test(r0);return s0&&a0&&(r0=r0.substring(1,r0.length-1)),r0=escape$1(r0,!0),{type:"codespan",raw:M[0],text:r0}}}br(r){const M=this.rules.inline.br.exec(r);if(M)return{type:"br",raw:M[0]}}del(r){const M=this.rules.inline.del.exec(r);if(M)return{type:"del",raw:M[0],text:M[2],tokens:this.lexer.inlineTokens(M[2])}}autolink(r){const M=this.rules.inline.autolink.exec(r);if(M){let r0,s0;return M[2]==="@"?(r0=escape$1(M[1]),s0="mailto:"+r0):(r0=escape$1(M[1]),s0=r0),{type:"link",raw:M[0],text:r0,href:s0,tokens:[{type:"text",raw:r0,text:r0}]}}}url(r){var r0;let M;if(M=this.rules.inline.url.exec(r)){let s0,a0;if(M[2]==="@")s0=escape$1(M[0]),a0="mailto:"+s0;else{let i0;do i0=M[0],M[0]=((r0=this.rules.inline._backpedal.exec(M[0]))==null?void 0:r0[0])??"";while(i0!==M[0]);s0=escape$1(M[0]),M[1]==="www."?a0="http://"+M[0]:a0=M[0]}return{type:"link",raw:M[0],text:s0,href:a0,tokens:[{type:"text",raw:s0,text:s0}]}}}inlineText(r){const M=this.rules.inline.text.exec(r);if(M){let r0;return this.lexer.state.inRawBlock?r0=M[0]:r0=escape$1(M[0]),{type:"text",raw:M[0],text:r0}}}}const newline=/^(?: *(?:\n|$))+/,blockCode=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,fences=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,heading=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,bullet=/(?:[*+-]|\d{1,9}[.)])/,lheading=edit(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,bullet).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),_paragraph=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,blockText=/^[^\n]+/,_blockLabel=/(?!\s*\])(?:\\.|[^\[\]\\])+/,def=edit(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",_blockLabel).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),list=edit(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,bullet).getRegex(),_tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",_comment=/|$))/,html=edit("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",_comment).replace("tag",_tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),paragraph=edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex(),blockquote=edit(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",paragraph).getRegex(),blockNormal={blockquote,code:blockCode,def,fences,heading,hr,html,lheading,list,newline,paragraph,table:noopTest,text:blockText},gfmTable=edit("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex(),blockGfm={...blockNormal,table:gfmTable,paragraph:edit(_paragraph).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",gfmTable).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",_tag).getRegex()},blockPedantic={...blockNormal,html:edit(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",_comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:noopTest,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:edit(_paragraph).replace("hr",hr).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",lheading).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},escape=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,inlineCode=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,br=/^( {2,}|\\)\n(?!\s*$)/,inlineText=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g,emStrongLDelim=edit(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,_punctuation).getRegex(),emStrongRDelimAst=edit("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,_punctuation).getRegex(),emStrongRDelimUnd=edit("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,_punctuation).getRegex(),anyPunctuation=edit(/\\([punct])/,"gu").replace(/punct/g,_punctuation).getRegex(),autolink=edit(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),_inlineComment=edit(_comment).replace("(?:-->|$)","-->").getRegex(),tag=edit("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",_inlineComment).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),_inlineLabel=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,link=edit(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",_inlineLabel).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),reflink=edit(/^!?\[(label)\]\[(ref)\]/).replace("label",_inlineLabel).replace("ref",_blockLabel).getRegex(),nolink=edit(/^!?\[(ref)\](?:\[\])?/).replace("ref",_blockLabel).getRegex(),reflinkSearch=edit("reflink|nolink(?!\\()","g").replace("reflink",reflink).replace("nolink",nolink).getRegex(),inlineNormal={_backpedal:noopTest,anyPunctuation,autolink,blockSkip,br,code:inlineCode,del:noopTest,emStrongLDelim,emStrongRDelimAst,emStrongRDelimUnd,escape,link,nolink,punctuation,reflink,reflinkSearch,tag,text:inlineText,url:noopTest},inlinePedantic={...inlineNormal,link:edit(/^!?\[(label)\]\((.*?)\)/).replace("label",_inlineLabel).getRegex(),reflink:edit(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",_inlineLabel).getRegex()},inlineGfm={...inlineNormal,escape:edit(escape).replace("])","~|])").getRegex(),url:edit(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\d0+" ".repeat(m0.length));let r0,s0,a0,i0;for(;r;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(u0=>(r0=u0.call({lexer:this},r,M))?(r=r.substring(r0.raw.length),M.push(r0),!0):!1))){if(r0=this.tokenizer.space(r)){r=r.substring(r0.raw.length),r0.raw.length===1&&M.length>0?M[M.length-1].raw+=` +`:M.push(r0);continue}if(r0=this.tokenizer.code(r)){r=r.substring(r0.raw.length),s0=M[M.length-1],s0&&(s0.type==="paragraph"||s0.type==="text")?(s0.raw+=` +`+r0.raw,s0.text+=` +`+r0.text,this.inlineQueue[this.inlineQueue.length-1].src=s0.text):M.push(r0);continue}if(r0=this.tokenizer.fences(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(r0=this.tokenizer.heading(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(r0=this.tokenizer.hr(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(r0=this.tokenizer.blockquote(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(r0=this.tokenizer.list(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(r0=this.tokenizer.html(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(r0=this.tokenizer.def(r)){r=r.substring(r0.raw.length),s0=M[M.length-1],s0&&(s0.type==="paragraph"||s0.type==="text")?(s0.raw+=` +`+r0.raw,s0.text+=` +`+r0.raw,this.inlineQueue[this.inlineQueue.length-1].src=s0.text):this.tokens.links[r0.tag]||(this.tokens.links[r0.tag]={href:r0.href,title:r0.title});continue}if(r0=this.tokenizer.table(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(r0=this.tokenizer.lheading(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(a0=r,this.options.extensions&&this.options.extensions.startBlock){let u0=1/0;const d0=r.slice(1);let m0;this.options.extensions.startBlock.forEach(_0=>{m0=_0.call({lexer:this},d0),typeof m0=="number"&&m0>=0&&(u0=Math.min(u0,m0))}),u0<1/0&&u0>=0&&(a0=r.substring(0,u0+1))}if(this.state.top&&(r0=this.tokenizer.paragraph(a0))){s0=M[M.length-1],i0&&s0.type==="paragraph"?(s0.raw+=` +`+r0.raw,s0.text+=` +`+r0.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s0.text):M.push(r0),i0=a0.length!==r.length,r=r.substring(r0.raw.length);continue}if(r0=this.tokenizer.text(r)){r=r.substring(r0.raw.length),s0=M[M.length-1],s0&&s0.type==="text"?(s0.raw+=` +`+r0.raw,s0.text+=` +`+r0.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s0.text):M.push(r0);continue}if(r){const u0="Infinite loop on byte: "+r.charCodeAt(0);if(this.options.silent){console.error(u0);break}else throw new Error(u0)}}return this.state.top=!0,M}inline(r,M=[]){return this.inlineQueue.push({src:r,tokens:M}),M}inlineTokens(r,M=[]){let r0,s0,a0,i0=r,u0,d0,m0;if(this.tokens.links){const _0=Object.keys(this.tokens.links);if(_0.length>0)for(;(u0=this.tokenizer.rules.inline.reflinkSearch.exec(i0))!=null;)_0.includes(u0[0].slice(u0[0].lastIndexOf("[")+1,-1))&&(i0=i0.slice(0,u0.index)+"["+"a".repeat(u0[0].length-2)+"]"+i0.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(u0=this.tokenizer.rules.inline.blockSkip.exec(i0))!=null;)i0=i0.slice(0,u0.index)+"["+"a".repeat(u0[0].length-2)+"]"+i0.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(u0=this.tokenizer.rules.inline.anyPunctuation.exec(i0))!=null;)i0=i0.slice(0,u0.index)+"++"+i0.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;r;)if(d0||(m0=""),d0=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(_0=>(r0=_0.call({lexer:this},r,M))?(r=r.substring(r0.raw.length),M.push(r0),!0):!1))){if(r0=this.tokenizer.escape(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(r0=this.tokenizer.tag(r)){r=r.substring(r0.raw.length),s0=M[M.length-1],s0&&r0.type==="text"&&s0.type==="text"?(s0.raw+=r0.raw,s0.text+=r0.text):M.push(r0);continue}if(r0=this.tokenizer.link(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(r0=this.tokenizer.reflink(r,this.tokens.links)){r=r.substring(r0.raw.length),s0=M[M.length-1],s0&&r0.type==="text"&&s0.type==="text"?(s0.raw+=r0.raw,s0.text+=r0.text):M.push(r0);continue}if(r0=this.tokenizer.emStrong(r,i0,m0)){r=r.substring(r0.raw.length),M.push(r0);continue}if(r0=this.tokenizer.codespan(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(r0=this.tokenizer.br(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(r0=this.tokenizer.del(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(r0=this.tokenizer.autolink(r)){r=r.substring(r0.raw.length),M.push(r0);continue}if(!this.state.inLink&&(r0=this.tokenizer.url(r))){r=r.substring(r0.raw.length),M.push(r0);continue}if(a0=r,this.options.extensions&&this.options.extensions.startInline){let _0=1/0;const f0=r.slice(1);let g0;this.options.extensions.startInline.forEach(x0=>{g0=x0.call({lexer:this},f0),typeof g0=="number"&&g0>=0&&(_0=Math.min(_0,g0))}),_0<1/0&&_0>=0&&(a0=r.substring(0,_0+1))}if(r0=this.tokenizer.inlineText(a0)){r=r.substring(r0.raw.length),r0.raw.slice(-1)!=="_"&&(m0=r0.raw.slice(-1)),d0=!0,s0=M[M.length-1],s0&&s0.type==="text"?(s0.raw+=r0.raw,s0.text+=r0.text):M.push(r0);continue}if(r){const _0="Infinite loop on byte: "+r.charCodeAt(0);if(this.options.silent){console.error(_0);break}else throw new Error(_0)}}return M}}class _Renderer{constructor(r){$r(this,"options");this.options=r||_defaults}code(r,M,r0){var a0;const s0=(a0=(M||"").match(/^\S*/))==null?void 0:a0[0];return r=r.replace(/\n$/,"")+` +`,s0?'
'+(r0?r:escape$1(r,!0))+`
+`:"
"+(r0?r:escape$1(r,!0))+`
+`}blockquote(r){return`
+${r}
+`}html(r,M){return r}heading(r,M,r0){return`${r} +`}hr(){return`
+`}list(r,M,r0){const s0=M?"ol":"ul",a0=M&&r0!==1?' start="'+r0+'"':"";return"<"+s0+a0+`> +`+r+" +`}listitem(r,M,r0){return`
  • ${r}
  • +`}checkbox(r){return"'}paragraph(r){return`

    ${r}

    +`}table(r,M){return M&&(M=`${M}`),` + +`+r+` +`+M+`
    +`}tablerow(r){return` +${r} +`}tablecell(r,M){const r0=M.header?"th":"td";return(M.align?`<${r0} align="${M.align}">`:`<${r0}>`)+r+` +`}strong(r){return`${r}`}em(r){return`${r}`}codespan(r){return`${r}`}br(){return"
    "}del(r){return`${r}`}link(r,M,r0){const s0=cleanUrl(r);if(s0===null)return r0;r=s0;let a0='
    ",a0}image(r,M,r0){const s0=cleanUrl(r);if(s0===null)return r0;r=s0;let a0=`${r0}0&&g0.tokens[0].type==="paragraph"?(g0.tokens[0].text=C0+" "+g0.tokens[0].text,g0.tokens[0].tokens&&g0.tokens[0].tokens.length>0&&g0.tokens[0].tokens[0].type==="text"&&(g0.tokens[0].tokens[0].text=C0+" "+g0.tokens[0].tokens[0].text)):g0.tokens.unshift({type:"text",text:C0+" "}):F0+=C0+" "}F0+=this.parse(g0.tokens,m0),_0+=this.renderer.listitem(F0,k0,!!x0)}r0+=this.renderer.list(_0,u0,d0);continue}case"html":{const i0=a0;r0+=this.renderer.html(i0.text,i0.block);continue}case"paragraph":{const i0=a0;r0+=this.renderer.paragraph(this.parseInline(i0.tokens));continue}case"text":{let i0=a0,u0=i0.tokens?this.parseInline(i0.tokens):i0.text;for(;s0+1{const m0=u0[d0].flat(1/0);r0=r0.concat(this.walkTokens(m0,M))}):u0.tokens&&(r0=r0.concat(this.walkTokens(u0.tokens,M)))}}return r0}use(...r){const M=this.defaults.extensions||{renderers:{},childTokens:{}};return r.forEach(r0=>{const s0={...r0};if(s0.async=this.defaults.async||s0.async||!1,r0.extensions&&(r0.extensions.forEach(a0=>{if(!a0.name)throw new Error("extension name required");if("renderer"in a0){const i0=M.renderers[a0.name];i0?M.renderers[a0.name]=function(...u0){let d0=a0.renderer.apply(this,u0);return d0===!1&&(d0=i0.apply(this,u0)),d0}:M.renderers[a0.name]=a0.renderer}if("tokenizer"in a0){if(!a0.level||a0.level!=="block"&&a0.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");const i0=M[a0.level];i0?i0.unshift(a0.tokenizer):M[a0.level]=[a0.tokenizer],a0.start&&(a0.level==="block"?M.startBlock?M.startBlock.push(a0.start):M.startBlock=[a0.start]:a0.level==="inline"&&(M.startInline?M.startInline.push(a0.start):M.startInline=[a0.start]))}"childTokens"in a0&&a0.childTokens&&(M.childTokens[a0.name]=a0.childTokens)}),s0.extensions=M),r0.renderer){const a0=this.defaults.renderer||new _Renderer(this.defaults);for(const i0 in r0.renderer){if(!(i0 in a0))throw new Error(`renderer '${i0}' does not exist`);if(i0==="options")continue;const u0=i0,d0=r0.renderer[u0],m0=a0[u0];a0[u0]=(..._0)=>{let f0=d0.apply(a0,_0);return f0===!1&&(f0=m0.apply(a0,_0)),f0||""}}s0.renderer=a0}if(r0.tokenizer){const a0=this.defaults.tokenizer||new _Tokenizer(this.defaults);for(const i0 in r0.tokenizer){if(!(i0 in a0))throw new Error(`tokenizer '${i0}' does not exist`);if(["options","rules","lexer"].includes(i0))continue;const u0=i0,d0=r0.tokenizer[u0],m0=a0[u0];a0[u0]=(..._0)=>{let f0=d0.apply(a0,_0);return f0===!1&&(f0=m0.apply(a0,_0)),f0}}s0.tokenizer=a0}if(r0.hooks){const a0=this.defaults.hooks||new _Hooks;for(const i0 in r0.hooks){if(!(i0 in a0))throw new Error(`hook '${i0}' does not exist`);if(i0==="options")continue;const u0=i0,d0=r0.hooks[u0],m0=a0[u0];_Hooks.passThroughHooks.has(i0)?a0[u0]=_0=>{if(this.defaults.async)return Promise.resolve(d0.call(a0,_0)).then(g0=>m0.call(a0,g0));const f0=d0.call(a0,_0);return m0.call(a0,f0)}:a0[u0]=(..._0)=>{let f0=d0.apply(a0,_0);return f0===!1&&(f0=m0.apply(a0,_0)),f0}}s0.hooks=a0}if(r0.walkTokens){const a0=this.defaults.walkTokens,i0=r0.walkTokens;s0.walkTokens=function(u0){let d0=[];return d0.push(i0.call(this,u0)),a0&&(d0=d0.concat(a0.call(this,u0))),d0}}this.defaults={...this.defaults,...s0}}),this}setOptions(r){return this.defaults={...this.defaults,...r},this}lexer(r,M){return _Lexer.lex(r,M??this.defaults)}parser(r,M){return _Parser.parse(r,M??this.defaults)}}lo=new WeakSet,g4=function(r,M){return(r0,s0)=>{const a0={...s0},i0={...this.defaults,...a0};this.defaults.async===!0&&a0.async===!1&&(i0.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),i0.async=!0);const u0=Nl(this,lo,U3).call(this,!!i0.silent,!!i0.async);if(typeof r0>"u"||r0===null)return u0(new Error("marked(): input parameter is undefined or null"));if(typeof r0!="string")return u0(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(r0)+", string expected"));if(i0.hooks&&(i0.hooks.options=i0),i0.async)return Promise.resolve(i0.hooks?i0.hooks.preprocess(r0):r0).then(d0=>r(d0,i0)).then(d0=>i0.hooks?i0.hooks.processAllTokens(d0):d0).then(d0=>i0.walkTokens?Promise.all(this.walkTokens(d0,i0.walkTokens)).then(()=>d0):d0).then(d0=>M(d0,i0)).then(d0=>i0.hooks?i0.hooks.postprocess(d0):d0).catch(u0);try{i0.hooks&&(r0=i0.hooks.preprocess(r0));let d0=r(r0,i0);i0.hooks&&(d0=i0.hooks.processAllTokens(d0)),i0.walkTokens&&this.walkTokens(d0,i0.walkTokens);let m0=M(d0,i0);return i0.hooks&&(m0=i0.hooks.postprocess(m0)),m0}catch(d0){return u0(d0)}}},U3=function(r,M){return r0=>{if(r0.message+=` +Please report this to https://github.com/markedjs/marked.`,r){const s0="

    An error occurred:

    "+escape$1(r0.message+"",!0)+"
    ";return M?Promise.resolve(s0):s0}if(M)return Promise.reject(r0);throw r0}};const markedInstance=new Marked;function marked(e,r){return markedInstance.parse(e,r)}marked.options=marked.setOptions=function(e){return markedInstance.setOptions(e),marked.defaults=markedInstance.defaults,changeDefaults(marked.defaults),marked};marked.getDefaults=_getDefaults;marked.defaults=_defaults;marked.use=function(...e){return markedInstance.use(...e),marked.defaults=markedInstance.defaults,changeDefaults(marked.defaults),marked};marked.walkTokens=function(e,r){return markedInstance.walkTokens(e,r)};marked.parseInline=markedInstance.parseInline;marked.Parser=_Parser;marked.parser=_Parser.parse;marked.Renderer=_Renderer;marked.TextRenderer=_TextRenderer;marked.Lexer=_Lexer;marked.lexer=_Lexer.lex;marked.Tokenizer=_Tokenizer;marked.Hooks=_Hooks;marked.parse=marked;marked.options;marked.setOptions;marked.use;marked.walkTokens;marked.parseInline;_Parser.parse;_Lexer.lex;function BotIcon(e){return jsxRuntimeExports.jsxs("svg",{...e,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M12 8V4H8"}),jsxRuntimeExports.jsx("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),jsxRuntimeExports.jsx("path",{d:"M2 14h2"}),jsxRuntimeExports.jsx("path",{d:"M20 14h2"}),jsxRuntimeExports.jsx("path",{d:"M15 13v2"}),jsxRuntimeExports.jsx("path",{d:"M9 13v2"})]})}function UserIcon(e){return jsxRuntimeExports.jsxs("svg",{...e,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}),jsxRuntimeExports.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function render(e){return purify.sanitize(marked.parse(e))}function Chat({messages:e}){const r=e.length===0,[M,r0]=reactExports.useState(new Set),s0=a0=>{const i0=new Set(M);i0.has(a0)?i0.delete(a0):i0.add(a0),r0(i0)};return reactExports.useEffect(()=>{window.MathJax.typeset()},[e]),jsxRuntimeExports.jsx("div",{className:`flex-1 p-6 max-w-[960px] w-full ${r?"flex flex-col items-center justify-end":"space-y-4"}`,children:r?jsxRuntimeExports.jsx("div",{className:"text-xl",children:"Ready!"}):e.map((a0,i0)=>jsxRuntimeExports.jsx("div",{className:"flex items-start space-x-4",children:a0.role==="assistant"?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(BotIcon,{className:"h-6 w-6 min-h-6 min-w-6 my-3 text-gray-500 dark:text-gray-300"}),jsxRuntimeExports.jsx("div",{className:"bg-gray-200 dark:bg-gray-700 rounded-lg p-4",children:jsxRuntimeExports.jsx("p",{className:"min-h-6 text-gray-800 dark:text-gray-200 overflow-wrap-anywhere",children:a0.content.length>0?jsxRuntimeExports.jsx("span",{className:"markdown",dangerouslySetInnerHTML:{__html:render(a0.content)}}):jsxRuntimeExports.jsxs("span",{className:"h-6 flex items-center gap-1",children:[jsxRuntimeExports.jsx("span",{className:"w-2.5 h-2.5 bg-gray-600 dark:bg-gray-300 rounded-full animate-pulse"}),jsxRuntimeExports.jsx("span",{className:"w-2.5 h-2.5 bg-gray-600 dark:bg-gray-300 rounded-full animate-pulse animation-delay-200"}),jsxRuntimeExports.jsx("span",{className:"w-2.5 h-2.5 bg-gray-600 dark:bg-gray-300 rounded-full animate-pulse animation-delay-400"})]})})})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(UserIcon,{className:"h-6 w-6 min-h-6 min-w-6 my-3 text-gray-500 dark:text-gray-300"}),jsxRuntimeExports.jsxs("div",{className:"bg-blue-500 text-white rounded-lg p-4",children:[jsxRuntimeExports.jsx("p",{className:"min-h-6 overflow-wrap-anywhere",children:a0.content}),a0.sources&&a0.sources.length>0&&jsxRuntimeExports.jsxs("div",{className:"mt-3 pt-3 border-t border-blue-400",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>s0(i0),className:"text-sm font-medium text-blue-100 hover:text-white flex items-center gap-1 transition-colors",children:[jsxRuntimeExports.jsxs("span",{children:["Sources (",a0.sources.length,")"]}),jsxRuntimeExports.jsx("svg",{className:`w-4 h-4 transition-transform ${M.has(i0)?"rotate-180":""}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsxRuntimeExports.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),M.has(i0)&&jsxRuntimeExports.jsx("div",{className:"mt-2 space-y-2",children:a0.sources.map((u0,d0)=>jsxRuntimeExports.jsx("div",{className:"text-xs bg-blue-600 rounded p-2 text-blue-100",children:u0.content},d0))})]})]})]})},`message-${i0}`))})}function ArrowRightIcon(e){return jsxRuntimeExports.jsxs("svg",{...e,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M5 12h14"}),jsxRuntimeExports.jsx("path",{d:"m12 5 7 7-7 7"})]})}function StopIcon(e){return jsxRuntimeExports.jsxs("svg",{...e,xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsxRuntimeExports.jsx("path",{d:"M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"}),jsxRuntimeExports.jsx("path",{fill:"currentColor",d:"M9 9.563C9 9.252 9.252 9 9.563 9h4.874c.311 0 .563.252.563.563v4.874c0 .311-.252.563-.563.563H9.564A.562.562 0 0 1 9 14.437V9.564Z"})]})}function formatBytes(e){const r=e==0?0:Math.floor(Math.log(e)/Math.log(1024));return+(e/Math.pow(1024,r)).toFixed(2)*1+["B","kB","MB","GB","TB"][r]}function Progress({text:e,percentage:r,total:M}){return r??(r=0),jsxRuntimeExports.jsx("div",{className:"w-full bg-gray-100 dark:bg-gray-700 text-left rounded-lg overflow-hidden mb-0.5",children:jsxRuntimeExports.jsxs("div",{className:"bg-blue-400 whitespace-nowrap px-1 text-sm",style:{width:`${r}%`},children:[e," (",r.toFixed(2),"%",isNaN(M)?"":` of ${formatBytes(M)}`,")"]})})}const scriptRel="modulepreload",assetsURL=function(e){return"/"+e},seen={},__vitePreload=function(r,M,r0){let s0=Promise.resolve();if(M&&M.length>0){let i0=function(m0){return Promise.all(m0.map(_0=>Promise.resolve(_0).then(f0=>({status:"fulfilled",value:f0}),f0=>({status:"rejected",reason:f0}))))};document.getElementsByTagName("link");const u0=document.querySelector("meta[property=csp-nonce]"),d0=(u0==null?void 0:u0.nonce)||(u0==null?void 0:u0.getAttribute("nonce"));s0=i0(M.map(m0=>{if(m0=assetsURL(m0),m0 in seen)return;seen[m0]=!0;const _0=m0.endsWith(".css"),f0=_0?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m0}"]${f0}`))return;const g0=document.createElement("link");if(g0.rel=_0?"stylesheet":scriptRel,_0||(g0.as="script"),g0.crossOrigin="",g0.href=m0,d0&&g0.setAttribute("nonce",d0),document.head.appendChild(g0),_0)return new Promise((x0,k0)=>{g0.addEventListener("load",x0),g0.addEventListener("error",()=>k0(new Error(`Unable to preload CSS for ${m0}`)))})}))}function a0(i0){const u0=new Event("vite:preloadError",{cancelable:!0});if(u0.payload=i0,window.dispatchEvent(u0),!u0.defaultPrevented)throw i0}return s0.then(i0=>{for(const u0 of i0||[])u0.status==="rejected"&&a0(u0.reason);return r().catch(a0)})};var p$1=Object.create,i=Object.defineProperty,c=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyNames,l$1=Object.getPrototypeOf,s$1=Object.prototype.hasOwnProperty,a=e=>{throw TypeError(e)},_$1=(e,r,M)=>r in e?i(e,r,{enumerable:!0,configurable:!0,writable:!0,value:M}):e[r]=M,d=(e,r)=>()=>(e&&(r=e(e=0)),r),D$1=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),F$1=(e,r)=>{for(var M in r)i(e,M,{get:r[M],enumerable:!0})},g$3=(e,r,M,r0)=>{if(r&&typeof r=="object"||typeof r=="function")for(let s0 of f(r))!s$1.call(e,s0)&&s0!==M&&i(e,s0,{get:()=>r[s0],enumerable:!(r0=c(r,s0))||r0.enumerable});return e},L$3=(e,r,M)=>(M=e!=null?p$1(l$1(e)):{},g$3(i(M,"default",{value:e,enumerable:!0}),e)),P$1=(e,r,M)=>_$1(e,typeof r!="symbol"?r+"":r,M),n$1=(e,r,M)=>r.has(e)||a("Cannot "+M),h$1=(e,r,M)=>(n$1(e,r,"read from private field"),M?M.call(e):r.get(e)),R$1=(e,r,M)=>r.has(e)?a("Cannot add the same private member more than once"):r instanceof WeakSet?r.add(e):r.set(e,M),x$3=(e,r,M,r0)=>(n$1(e,r,"write to private field"),r.set(e,M),M),T$2=(e,r,M)=>(n$1(e,r,"access private method"),M),U$1=(e,r,M,r0)=>({set _(s0){x$3(e,r,s0)},get _(){return h$1(e,r,r0)}}),u=d(()=>{}),w$1=D$1((e,r)=>{u();var M=9007199254740991,r0=function(R0){return R0}();function s0(R0){return R0===r0}function a0(R0){return typeof R0=="string"||Object.prototype.toString.call(R0)=="[object String]"}function i0(R0){return Object.prototype.toString.call(R0)=="[object Date]"}function u0(R0){return R0!==null&&typeof R0=="object"}function d0(R0){return typeof R0=="function"}function m0(R0){return typeof R0=="number"&&R0>-1&&R0%1==0&&R0<=M}function _0(R0){return Object.prototype.toString.call(R0)=="[object Array]"}function f0(R0){return u0(R0)&&!d0(R0)&&m0(R0.length)}function g0(R0){return Object.prototype.toString.call(R0)=="[object ArrayBuffer]"}function x0(R0,y0){return Array.prototype.map.call(R0,y0)}function k0(R0,y0){var w0=r0;return d0(y0)&&Array.prototype.every.call(R0,function(A0,q0,U0){var X0=y0(A0,q0,U0);return X0&&(w0=A0),!X0}),w0}function F0(R0){return Object.assign.apply(null,arguments)}function C0(R0){var y0,w0,A0;if(a0(R0)){for(w0=R0.length,A0=new Uint8Array(w0),y0=0;y0{u();var M="\0";r.exports={NULL_CHAR:M,TMAGIC:"ustar"+M+"00",OLDGNU_MAGIC:"ustar "+M,REGTYPE:0,LNKTYPE:1,SYMTYPE:2,CHRTYPE:3,BLKTYPE:4,DIRTYPE:5,FIFOTYPE:6,CONTTYPE:7,TSUID:parseInt("4000",8),TSGID:parseInt("2000",8),TSVTX:parseInt("1000",8),TUREAD:parseInt("0400",8),TUWRITE:parseInt("0200",8),TUEXEC:parseInt("0100",8),TGREAD:parseInt("0040",8),TGWRITE:parseInt("0020",8),TGEXEC:parseInt("0010",8),TOREAD:parseInt("0004",8),TOWRITE:parseInt("0002",8),TOEXEC:parseInt("0001",8),TPERMALL:parseInt("0777",8),TPERMMASK:parseInt("0777",8)}}),L$2=D$1((e,r)=>{u();var M=w$1(),r0=x$2(),s0=512,a0=r0.TPERMALL,i0=0,u0=0,d0=[["name",100,0,function(y0,w0){return f0(y0[w0[0]],w0[1])},function(y0,w0,A0){return k0(y0.slice(w0,w0+A0[1]))}],["mode",8,100,function(y0,w0){var A0=y0[w0[0]]||a0;return A0=A0&r0.TPERMMASK,g0(A0,w0[1],a0)},function(y0,w0,A0){var q0=F0(y0.slice(w0,w0+A0[1]));return q0&=r0.TPERMMASK,q0}],["uid",8,108,function(y0,w0){return g0(y0[w0[0]],w0[1],i0)},function(y0,w0,A0){return F0(y0.slice(w0,w0+A0[1]))}],["gid",8,116,function(y0,w0){return g0(y0[w0[0]],w0[1],u0)},function(y0,w0,A0){return F0(y0.slice(w0,w0+A0[1]))}],["size",12,124,function(y0,w0){return g0(y0.data.length,w0[1])},function(y0,w0,A0){return F0(y0.slice(w0,w0+A0[1]))}],["modifyTime",12,136,function(y0,w0){return x0(y0[w0[0]],w0[1])},function(y0,w0,A0){return C0(y0.slice(w0,w0+A0[1]))}],["checksum",8,148,function(y0,w0){return" "},function(y0,w0,A0){return F0(y0.slice(w0,w0+A0[1]))}],["type",1,156,function(y0,w0){return""+(parseInt(y0[w0[0]],10)||0)%8},function(y0,w0,A0){return(parseInt(String.fromCharCode(y0[w0]),10)||0)%8}],["linkName",100,157,function(y0,w0){return""},function(y0,w0,A0){return k0(y0.slice(w0,w0+A0[1]))}],["ustar",8,257,function(y0,w0){return r0.TMAGIC},function(y0,w0,A0){return _0(k0(y0.slice(w0,w0+A0[1]),!0))},function(y0,w0){return y0[w0[0]]==r0.TMAGIC||y0[w0[0]]==r0.OLDGNU_MAGIC}],["owner",32,265,function(y0,w0){return f0(y0[w0[0]],w0[1])},function(y0,w0,A0){return k0(y0.slice(w0,w0+A0[1]))}],["group",32,297,function(y0,w0){return f0(y0[w0[0]],w0[1])},function(y0,w0,A0){return k0(y0.slice(w0,w0+A0[1]))}],["majorNumber",8,329,function(y0,w0){return""},function(y0,w0,A0){return F0(y0.slice(w0,w0+A0[1]))}],["minorNumber",8,337,function(y0,w0){return""},function(y0,w0,A0){return F0(y0.slice(w0,w0+A0[1]))}],["prefix",131,345,function(y0,w0){return f0(y0[w0[0]],w0[1])},function(y0,w0,A0){return k0(y0.slice(w0,w0+A0[1]))}],["accessTime",12,476,function(y0,w0){return x0(y0[w0[0]],w0[1])},function(y0,w0,A0){return C0(y0.slice(w0,w0+A0[1]))}],["createTime",12,488,function(y0,w0){return x0(y0[w0[0]],w0[1])},function(y0,w0,A0){return C0(y0.slice(w0,w0+A0[1]))}]],m0=function(y0){var w0=y0[y0.length-1];return w0[2]+w0[1]}(d0);function _0(y0){if(y0.length==8){var w0=y0.split("");if(w0[5]==r0.NULL_CHAR)return(w0[6]==" "||w0[6]==r0.NULL_CHAR)&&(w0[6]="0"),(w0[7]==" "||w0[7]==r0.NULL_CHAR)&&(w0[7]="0"),w0=w0.join(""),w0==r0.TMAGIC?w0:y0;if(w0[7]==r0.NULL_CHAR)return w0[5]==r0.NULL_CHAR&&(w0[5]=" "),w0[6]==r0.NULL_CHAR&&(w0[6]=" "),w0==r0.OLDGNU_MAGIC?w0:y0}return y0}function f0(y0,w0){return w0-=1,M.isUndefined(y0)&&(y0=""),y0=(""+y0).substr(0,w0),y0+r0.NULL_CHAR}function g0(y0,w0,A0){for(A0=parseInt(A0)||0,w0-=1,y0=(parseInt(y0)||A0).toString(8).substr(-w0,w0);y0.length=0?A0.substr(0,q0):A0}function F0(y0){var w0=String.fromCharCode.apply(null,y0);return parseInt(w0.replace(/^0+$/g,""),8)||0}function C0(y0){return y0.length==0||y0[0]==0?null:new Date(1e3*F0(y0))}function R0(y0,w0,A0){var q0=parseInt(w0,10)||0,U0=Math.min(q0+m0,y0.length),X0=0,xr=0,Ir=0;A0&&d0.every(function(H0){return H0[0]=="checksum"?(xr=q0+H0[2],Ir=xr+H0[1],!1):!0});for(var Ur=32,mr=q0;mr=xr&&mr{u();var M=x$2(),r0=w$1(),s0=L$2();function a0(f0){return s0.recordSize}function i0(f0){return Math.ceil(f0.data.length/s0.recordSize)*s0.recordSize}function u0(f0){var g0=0;return f0.forEach(function(x0){g0+=a0()+i0(x0)}),g0+=s0.recordSize*2,new Uint8Array(g0)}function d0(f0,g0,x0){x0=parseInt(x0)||0;var k0=x0;s0.posixHeader.forEach(function(w0){for(var A0=w0[3](g0,w0),q0=A0.length,U0=0;U0{u();var M=x$2(),r0=w$1(),s0=L$2(),a0={extractData:!0,checkHeader:!0,checkChecksum:!0,checkFileSize:!0},i0={size:!0,checksum:!0,ustar:!0},u0={unexpectedEndOfFile:"Unexpected end of file.",fileCorrupted:"File is corrupted.",checksumCheckFailed:"Checksum check failed."};function d0(F0){return s0.recordSize}function m0(F0){return Math.ceil(F0/s0.recordSize)*s0.recordSize}function _0(F0,C0){for(var R0=C0,y0=Math.min(F0.length,C0+s0.recordSize*2),w0=R0;w0=s0.recordSize;){F0=r0.toUint8Array(F0);var A0=f0(F0,y0,C0);if(!A0)break;y0+=d0();var q0=g0(F0,y0,A0,C0);if(R0.push(x0(A0,q0)),y0+=m0(A0.size),_0(F0,y0))break}return R0}r.exports.untar=k0}),or=D$1((e,r)=>{u();var M=w$1(),r0=x$2(),s0=er(),a0=nr();M.extend(r.exports,s0,a0,r0)});u();u();var g$2=L$3(or());async function H$1(e,r,M="pgdata",r0="auto"){let s0=Br(e,r),[a0,i0]=await qr(s0,r0),u0=M+(i0?".tar.gz":".tar"),d0=i0?"application/x-gzip":"application/x-tar";return typeof File<"u"?new File([a0],u0,{type:d0}):new Blob([a0],{type:d0})}var Hr=["application/x-gtar","application/x-tar+gzip","application/x-gzip","application/gzip"];async function ce$2(e,r,M){let r0=new Uint8Array(await r.arrayBuffer()),s0=typeof File<"u"&&r instanceof File?r.name:void 0;(Hr.includes(r.type)||s0!=null&&s0.endsWith(".tgz")||s0!=null&&s0.endsWith(".tar.gz"))&&(r0=await ar(r0));let a0;try{a0=(0,g$2.untar)(r0)}catch(i0){if(i0 instanceof Error&&i0.message.includes("File is corrupted"))r0=await ar(r0),a0=(0,g$2.untar)(r0);else throw i0}for(let i0 of a0){let u0=M+i0.name,d0=u0.split("/").slice(0,-1);for(let m0=1;m0<=d0.length;m0++){let _0=d0.slice(0,m0).join("/");e.analyzePath(_0).exists||e.mkdir(_0)}i0.type===g$2.REGTYPE?(e.writeFile(u0,i0.data),e.utime(u0,sr(i0.modifyTime),sr(i0.modifyTime))):i0.type===g$2.DIRTYPE&&e.mkdir(u0)}}function jr(e,r){let M=[],r0=s0=>{e.readdir(s0).forEach(a0=>{if(a0==="."||a0==="..")return;let i0=s0+"/"+a0,u0=e.stat(i0),d0=e.isFile(u0.mode)?e.readFile(i0,{encoding:"binary"}):new Uint8Array(0);M.push({name:i0.substring(r.length),mode:u0.mode,size:u0.size,type:e.isFile(u0.mode)?g$2.REGTYPE:g$2.DIRTYPE,modifyTime:u0.mtime,data:d0}),e.isDir(u0.mode)&&r0(i0)})};return r0(r),M}function Br(e,r){let M=jr(e,r);return(0,g$2.tar)(M)}async function qr(e,r="auto"){if(r==="none")return[e,!1];if(typeof CompressionStream<"u")return[await Yr(e),!0];if(typeof process<"u"&&process.versions&&process.versions.node)return[await Wr(e),!0];if(r==="auto")return[e,!1];throw new Error("Compression not supported in this environment")}async function Yr(e){let r=new CompressionStream("gzip"),M=r.writable.getWriter(),r0=r.readable.getReader();M.write(e),M.close();let s0=[];for(;;){let{value:u0,done:d0}=await r0.read();if(d0)break;u0&&s0.push(u0)}let a0=new Uint8Array(s0.reduce((u0,d0)=>u0+d0.length,0)),i0=0;return s0.forEach(u0=>{a0.set(u0,i0),i0+=u0.length}),a0}async function Wr(e){let{promisify:r}=await __vitePreload(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),{gzip:M}=await __vitePreload(async()=>{const{gzip:r0}=await import("./__vite-browser-external-BIHI7g3E.js");return{gzip:r0}},[]);return await r(M)(e)}async function ar(e){if(typeof CompressionStream<"u")return await Xr(e);if(typeof process<"u"&&process.versions&&process.versions.node)return await Kr(e);throw new Error("Unsupported environment for decompression")}async function Xr(e){let r=new DecompressionStream("gzip"),M=r.writable.getWriter(),r0=r.readable.getReader();M.write(e),M.close();let s0=[];for(;;){let{value:u0,done:d0}=await r0.read();if(d0)break;u0&&s0.push(u0)}let a0=new Uint8Array(s0.reduce((u0,d0)=>u0+d0.length,0)),i0=0;return s0.forEach(u0=>{a0.set(u0,i0),i0+=u0.length}),a0}async function Kr(e){let{promisify:r}=await __vitePreload(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),{gunzip:M}=await __vitePreload(async()=>{const{gunzip:r0}=await import("./__vite-browser-external-BIHI7g3E.js");return{gunzip:r0}},[]);return await r(M)(e)}function sr(e){return e?typeof e=="number"?e:Math.floor(e.getTime()/1e3):Math.floor(Date.now()/1e3)}var Vr="/tmp/pglite",C$2=Vr+"/base",ur=class{constructor(e){this.dataDir=e}async init(e,r){return this.pg=e,{emscriptenOpts:r}}async syncToFs(e){}async initialSyncFs(){}async closeFs(){}async dumpTar(e,r){return H$1(this.pg.Module.FS,C$2,e,r)}},cr=class{constructor(e,{debug:r=!1}={}){this.dataDir=e,this.debug=r}async syncToFs(e){}async initialSyncFs(){}async closeFs(){}async dumpTar(e,r){return H$1(this.pg.Module.FS,C$2,e,r)}async init(e,r){return this.pg=e,{emscriptenOpts:{...r,preRun:[...r.preRun||[],M=>{let r0=Zr(M,this);M.FS.mkdir(C$2),M.FS.mount(r0,{},C$2)}]}}}},pr={EBADF:8,EBADFD:127,EEXIST:20,EINVAL:28,EISDIR:31,ENODEV:43,ENOENT:44,ENOTDIR:54,ENOTEMPTY:55},Zr=(e,r)=>{let M=e.FS,r0=r.debug?console.log:null,s0={tryFSOperation(a0){try{return a0()}catch(i0){throw i0.code?i0.code==="UNKNOWN"?new M.ErrnoError(pr.EINVAL):new M.ErrnoError(i0.code):i0}},mount(a0){return s0.createNode(null,"/",16895,0)},syncfs(a0,i0,u0){},createNode(a0,i0,u0,d0){if(!M.isDir(u0)&&!M.isFile(u0))throw new M.ErrnoError(28);let m0=M.createNode(a0,i0,u0);return m0.node_ops=s0.node_ops,m0.stream_ops=s0.stream_ops,m0},getMode:function(a0){return r0==null||r0("getMode",a0),s0.tryFSOperation(()=>r.lstat(a0).mode)},realPath:function(a0){let i0=[];for(;a0.parent!==a0;)i0.push(a0.name),a0=a0.parent;return i0.push(a0.mount.opts.root),i0.reverse(),i0.join("/")},node_ops:{getattr(a0){r0==null||r0("getattr",s0.realPath(a0));let i0=s0.realPath(a0);return s0.tryFSOperation(()=>{let u0=r.lstat(i0);return{...u0,dev:0,ino:a0.id,nlink:1,rdev:a0.rdev,atime:new Date(u0.atime),mtime:new Date(u0.mtime),ctime:new Date(u0.ctime)}})},setattr(a0,i0){r0==null||r0("setattr",s0.realPath(a0),i0);let u0=s0.realPath(a0);s0.tryFSOperation(()=>{i0.mode!==void 0&&r.chmod(u0,i0.mode),i0.size!==void 0&&r.truncate(u0,i0.size),i0.timestamp!==void 0&&r.utimes(u0,i0.timestamp,i0.timestamp),i0.size!==void 0&&r.truncate(u0,i0.size)})},lookup(a0,i0){r0==null||r0("lookup",s0.realPath(a0),i0);let u0=[s0.realPath(a0),i0].join("/"),d0=s0.getMode(u0);return s0.createNode(a0,i0,d0)},mknod(a0,i0,u0,d0){r0==null||r0("mknod",s0.realPath(a0),i0,u0,d0);let m0=s0.createNode(a0,i0,u0,d0),_0=s0.realPath(m0);return s0.tryFSOperation(()=>(M.isDir(m0.mode)?r.mkdir(_0,{mode:u0}):r.writeFile(_0,"",{mode:u0}),m0))},rename(a0,i0,u0){r0==null||r0("rename",s0.realPath(a0),s0.realPath(i0),u0);let d0=s0.realPath(a0),m0=[s0.realPath(i0),u0].join("/");s0.tryFSOperation(()=>{r.rename(d0,m0)}),a0.name=u0},unlink(a0,i0){r0==null||r0("unlink",s0.realPath(a0),i0);let u0=[s0.realPath(a0),i0].join("/");try{r.unlink(u0)}catch{}},rmdir(a0,i0){r0==null||r0("rmdir",s0.realPath(a0),i0);let u0=[s0.realPath(a0),i0].join("/");return s0.tryFSOperation(()=>{r.rmdir(u0)})},readdir(a0){r0==null||r0("readdir",s0.realPath(a0));let i0=s0.realPath(a0);return s0.tryFSOperation(()=>r.readdir(i0))},symlink(a0,i0,u0){throw r0==null||r0("symlink",s0.realPath(a0),i0,u0),new M.ErrnoError(63)},readlink(a0){throw r0==null||r0("readlink",s0.realPath(a0)),new M.ErrnoError(63)}},stream_ops:{open(a0){r0==null||r0("open stream",s0.realPath(a0.node));let i0=s0.realPath(a0.node);return s0.tryFSOperation(()=>{M.isFile(a0.node.mode)&&(a0.shared.refcount=1,a0.nfd=r.open(i0))})},close(a0){return r0==null||r0("close stream",s0.realPath(a0.node)),s0.tryFSOperation(()=>{M.isFile(a0.node.mode)&&a0.nfd&&--a0.shared.refcount===0&&r.close(a0.nfd)})},dup(a0){r0==null||r0("dup stream",s0.realPath(a0.node)),a0.shared.refcount++},read(a0,i0,u0,d0,m0){return r0==null||r0("read stream",s0.realPath(a0.node),u0,d0,m0),d0===0?0:s0.tryFSOperation(()=>r.read(a0.nfd,i0,u0,d0,m0))},write(a0,i0,u0,d0,m0){return r0==null||r0("write stream",s0.realPath(a0.node),u0,d0,m0),s0.tryFSOperation(()=>r.write(a0.nfd,i0.buffer,u0,d0,m0))},llseek(a0,i0,u0){r0==null||r0("llseek stream",s0.realPath(a0.node),i0,u0);let d0=i0;if(u0===1?d0+=a0.position:u0===2&&M.isFile(a0.node.mode)&&s0.tryFSOperation(()=>{let m0=r.fstat(a0.nfd);d0+=m0.size}),d0<0)throw new M.ErrnoError(28);return d0},mmap(a0,i0,u0,d0,m0){if(r0==null||r0("mmap stream",s0.realPath(a0.node),i0,u0,d0,m0),!M.isFile(a0.node.mode))throw new M.ErrnoError(pr.ENODEV);let _0=e.mmapAlloc(i0);return s0.stream_ops.read(a0,e.HEAP8,_0,i0,u0),{ptr:_0,allocated:!0}},msync(a0,i0,u0,d0,m0){return r0==null||r0("msync stream",s0.realPath(a0.node),u0,d0,m0),s0.stream_ops.write(a0,i0,0,d0,u0),0}}};return s0},hn={};F$1(hn,{ABSTIME:()=>Et,ACLITEM:()=>Vt,BIT:()=>jt,BOOL:()=>be,BPCHAR:()=>_e$1,BYTEA:()=>ge$1,CHAR:()=>gt,CID:()=>St,CIDR:()=>Tt,CIRCLE:()=>Ut,DATE:()=>He$1,FLOAT4:()=>Qe,FLOAT8:()=>We$1,GTSVECTOR:()=>rn,INET:()=>kt,INT2:()=>ve,INT4:()=>Ge$1,INT8:()=>we$1,INTERVAL:()=>vt,JSON:()=>Ae,JSONB:()=>Ye$1,MACADDR:()=>Ot,MACADDR8:()=>Nt,MONEY:()=>Lt,NUMERIC:()=>Wt,OID:()=>je$1,PATH:()=>Mt,PG_DEPENDENCIES:()=>en,PG_LSN:()=>Xt,PG_NDISTINCT:()=>Zt,PG_NODE_TREE:()=>Bt,POLYGON:()=>Rt,REFCURSOR:()=>_t$1,REGCLASS:()=>Yt,REGCONFIG:()=>sn,REGDICTIONARY:()=>an,REGNAMESPACE:()=>on,REGOPER:()=>Ht,REGOPERATOR:()=>qt,REGPROC:()=>wt,REGPROCEDURE:()=>zt,REGROLE:()=>un,REGTYPE:()=>$t,RELTIME:()=>Ct,SMGR:()=>It,TEXT:()=>V,TID:()=>At,TIME:()=>Ft,TIMESTAMP:()=>qe,TIMESTAMPTZ:()=>xe$1,TIMETZ:()=>Gt,TINTERVAL:()=>Pt,TSQUERY:()=>nn,TSVECTOR:()=>tn,TXID_SNAPSHOT:()=>Jt,UUID:()=>Kt,VARBIT:()=>Qt,VARCHAR:()=>ze,XID:()=>xt,XML:()=>Dt,arrayParser:()=>yn,arraySerializer:()=>Ke$1,parseType:()=>ue$1,parsers:()=>ln,serializers:()=>cn,types:()=>$e});u();var ht=globalThis.JSON.parse,bt=globalThis.JSON.stringify,be=16,ge$1=17,gt=18,we$1=20,ve=21,Ge$1=23,wt=24,V=25,je$1=26,At=27,xt=28,St=29,Ae=114,Dt=142,Bt=194,It=210,Mt=602,Rt=604,Tt=650,Qe=700,We$1=701,Et=702,Ct=703,Pt=704,Ut=718,Nt=774,Lt=790,Ot=829,kt=869,Vt=1033,_e$1=1042,ze=1043,He$1=1082,Ft=1083,qe=1114,xe$1=1184,vt=1186,Gt=1266,jt=1560,Qt=1562,Wt=1700,_t$1=1790,zt=2202,Ht=2203,qt=2204,Yt=2205,$t=2206,Kt=2950,Jt=2970,Xt=3220,Zt=3361,en=3402,tn=3614,nn=3615,rn=3642,sn=3734,an=3769,Ye$1=3802,on=4089,un=4096,$e={string:{to:V,from:[V,ze,_e$1],serialize:e=>{if(typeof e=="string")return e;if(typeof e=="number")return e.toString();throw new Error("Invalid input for string type")},parse:e=>e},number:{to:0,from:[ve,Ge$1,je$1,Qe,We$1],serialize:e=>e.toString(),parse:e=>+e},bigint:{to:we$1,from:[we$1],serialize:e=>e.toString(),parse:e=>{let r=BigInt(e);return rNumber.MAX_SAFE_INTEGER?r:Number(r)}},json:{to:Ae,from:[Ae,Ye$1],serialize:e=>typeof e=="string"?e:bt(e),parse:e=>ht(e)},boolean:{to:be,from:[be],serialize:e=>{if(typeof e!="boolean")throw new Error("Invalid input for boolean type");return e?"t":"f"},parse:e=>e==="t"},date:{to:xe$1,from:[He$1,qe,xe$1],serialize:e=>{if(typeof e=="string")return e;if(typeof e=="number")return new Date(e).toISOString();if(e instanceof Date)return e.toISOString();throw new Error("Invalid input for date type")},parse:e=>new Date(e)},bytea:{to:ge$1,from:[ge$1],serialize:e=>{if(!(e instanceof Uint8Array))throw new Error("Invalid input for bytea type");return"\\x"+Array.from(e).map(r=>r.toString(16).padStart(2,"0")).join("")},parse:e=>{let r=e.slice(2);return Uint8Array.from({length:r.length/2},(M,r0)=>parseInt(r.substring(r0*2,(r0+1)*2),16))}}},Se$1=pn($e),ln=Se$1.parsers,cn=Se$1.serializers;function ue$1(e,r,M){if(e===null)return null;let r0=(M==null?void 0:M[r])??Se$1.parsers[r];return r0?r0(e,r):e}function pn(e){return Object.keys(e).reduce(({parsers:r,serializers:M},r0)=>{let{to:s0,from:a0,serialize:i0,parse:u0}=e[r0];return M[s0]=i0,M[r0]=i0,r[r0]=u0,Array.isArray(a0)?a0.forEach(d0=>{r[d0]=u0,M[d0]=i0}):(r[a0]=u0,M[a0]=i0),{parsers:r,serializers:M}},{parsers:{},serializers:{}})}var dn=/\\/g,fn=/"/g;function mn(e){return e.replace(dn,"\\\\").replace(fn,'\\"')}function Ke$1(e,r,M){if(Array.isArray(e)===!1)return e;if(!e.length)return"{}";let r0=e[0],s0=M===1020?";":",";return Array.isArray(r0)?`{${e.map(a0=>Ke$1(a0,r,M)).join(s0)}}`:`{${e.map(a0=>(a0===void 0&&(a0=null),a0===null?"null":'"'+mn(r?r(a0):a0.toString())+'"')).join(s0)}}`}var he$1={i:0,char:null,str:"",quoted:!1,last:0,p:null};function yn(e,r,M){return he$1.i=he$1.last=0,Je(he$1,e,r,M)[0]}function Je(e,r,M,r0){let s0=[],a0=r0===1020?";":",";for(;e.iDe,parseResults:()=>bn});u();function bn(e,r,M,r0){let s0=[],a0={rows:[],fields:[]},i0=0,u0={...r,...M==null?void 0:M.parsers};return e.forEach(d0=>{switch(d0.name){case"rowDescription":{let m0=d0;a0.fields=m0.fields.map(_0=>({name:_0.name,dataTypeID:_0.dataTypeID}));break}case"dataRow":{if(!a0)break;let m0=d0;(M==null?void 0:M.rowMode)==="array"?a0.rows.push(m0.fields.map((_0,f0)=>ue$1(_0,a0.fields[f0].dataTypeID,u0))):a0.rows.push(Object.fromEntries(m0.fields.map((_0,f0)=>[a0.fields[f0].name,ue$1(_0,a0.fields[f0].dataTypeID,u0)])));break}case"commandComplete":{i0+=gn(d0),s0.push({...a0,affectedRows:i0,...r0?{blob:r0}:{}}),a0={rows:[],fields:[]};break}}}),s0.length===0&&s0.push({affectedRows:0,rows:[],fields:[]}),s0}function gn(e){let r=e.text.split(" ");switch(r[0]){case"INSERT":return parseInt(r[2],10);case"UPDATE":case"DELETE":case"COPY":case"MERGE":return parseInt(r[1],10);default:return 0}}function De(e){let r=e.find(M=>M.name==="parameterDescription");return r?r.dataTypeIDs:[]}var Ue$1={};F$1(Ue$1,{AuthenticationCleartextPassword:()=>v,AuthenticationMD5Password:()=>G$1,AuthenticationOk:()=>F,AuthenticationSASL:()=>j,AuthenticationSASLContinue:()=>Q$1,AuthenticationSASLFinal:()=>W,BackendKeyDataMessage:()=>K$1,CommandCompleteMessage:()=>Z$1,CopyDataMessage:()=>_,CopyResponse:()=>z,DataRowMessage:()=>ee,DatabaseError:()=>C$1,Field:()=>H,NoticeMessage:()=>te$1,NotificationResponseMessage:()=>J$1,ParameterDescriptionMessage:()=>Y$1,ParameterStatusMessage:()=>$$1,ReadyForQueryMessage:()=>X,RowDescriptionMessage:()=>q$1,bindComplete:()=>Ie,closeComplete:()=>Me,copyDone:()=>Pe,emptyQuery:()=>Ce,noData:()=>Re,parseComplete:()=>Be$1,portalSuspended:()=>Te,replicationStart:()=>Ee});u();var Be$1={name:"parseComplete",length:5},Ie={name:"bindComplete",length:5},Me={name:"closeComplete",length:5},Re={name:"noData",length:5},Te={name:"portalSuspended",length:5},Ee={name:"replicationStart",length:4},Ce={name:"emptyQuery",length:4},Pe={name:"copyDone",length:4},F=class{constructor(e){this.length=e,this.name="authenticationOk"}},v=class{constructor(e){this.length=e,this.name="authenticationCleartextPassword"}},G$1=class{constructor(r,M){this.length=r,this.salt=M,this.name="authenticationMD5Password"}},j=class{constructor(e,r){this.length=e,this.mechanisms=r,this.name="authenticationSASL"}},Q$1=class{constructor(r,M){this.length=r,this.data=M,this.name="authenticationSASLContinue"}},W=class{constructor(e,r){this.length=e,this.data=r,this.name="authenticationSASLFinal"}},C$1=class extends Error{constructor(r,M,r0){super(r),this.length=M,this.name=r0}},_=class{constructor(e,r){this.length=e,this.chunk=r,this.name="copyData"}},z=class{constructor(e,r,M,r0){this.length=e,this.name=r,this.binary=M,this.columnTypes=new Array(r0)}},H=class{constructor(e,r,M,r0,s0,a0,i0){this.name=e,this.tableID=r,this.columnID=M,this.dataTypeID=r0,this.dataTypeSize=s0,this.dataTypeModifier=a0,this.format=i0}},q$1=class{constructor(r,M){this.length=r,this.fieldCount=M,this.name="rowDescription",this.fields=new Array(this.fieldCount)}},Y$1=class{constructor(r,M){this.length=r,this.parameterCount=M,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}},$$1=class{constructor(r,M,r0){this.length=r,this.parameterName=M,this.parameterValue=r0,this.name="parameterStatus"}},K$1=class{constructor(r,M,r0){this.length=r,this.processID=M,this.secretKey=r0,this.name="backendKeyData"}},J$1=class{constructor(r,M,r0,s0){this.length=r,this.processId=M,this.channel=r0,this.payload=s0,this.name="notification"}},X=class{constructor(e,r){this.length=e,this.status=r,this.name="readyForQuery"}},Z$1=class{constructor(r,M){this.length=r,this.text=M,this.name="commandComplete"}},ee=class{constructor(e,r){this.length=e,this.fields=r,this.name="dataRow",this.fieldCount=r.length}},te$1=class{constructor(r,M){this.length=r,this.message=M,this.name="notice"}},zn={};F$1(zn,{Parser:()=>ye$1,messages:()=>Ue$1,serialize:()=>k$1});u();u();u();u();function P(e){let r=e.length;for(let M=e.length-1;M>=0;M--){let r0=e.charCodeAt(M);r0>127&&r0<=2047?r++:r0>2047&&r0<=65535&&(r+=2),r0>=56320&&r0<=57343&&M--}return r}var b,g$1,N,ce$1,L$1,x$1,le$1,U,Xe$1,T$1=class{constructor(r=256){this.size=r,R$1(this,x$1),R$1(this,b),R$1(this,g$1,5),R$1(this,N,!1),R$1(this,ce$1,new TextEncoder),R$1(this,L$1,0),x$3(this,b,T$2(this,x$1,le$1).call(this,r))}addInt32(r){return T$2(this,x$1,U).call(this,4),h$1(this,b).setInt32(h$1(this,g$1),r,h$1(this,N)),x$3(this,g$1,h$1(this,g$1)+4),this}addInt16(r){return T$2(this,x$1,U).call(this,2),h$1(this,b).setInt16(h$1(this,g$1),r,h$1(this,N)),x$3(this,g$1,h$1(this,g$1)+2),this}addCString(r){return r&&this.addString(r),T$2(this,x$1,U).call(this,1),h$1(this,b).setUint8(h$1(this,g$1),0),U$1(this,g$1)._++,this}addString(r=""){let M=P(r);return T$2(this,x$1,U).call(this,M),h$1(this,ce$1).encodeInto(r,new Uint8Array(h$1(this,b).buffer,h$1(this,g$1))),x$3(this,g$1,h$1(this,g$1)+M),this}add(r){return T$2(this,x$1,U).call(this,r.byteLength),new Uint8Array(h$1(this,b).buffer).set(new Uint8Array(r),h$1(this,g$1)),x$3(this,g$1,h$1(this,g$1)+r.byteLength),this}flush(r){let M=T$2(this,x$1,Xe$1).call(this,r);return x$3(this,g$1,5),x$3(this,b,T$2(this,x$1,le$1).call(this,this.size)),new Uint8Array(M)}};b=new WeakMap,g$1=new WeakMap,N=new WeakMap,ce$1=new WeakMap,L$1=new WeakMap,x$1=new WeakSet,le$1=function(e){return new DataView(new ArrayBuffer(e))},U=function(e){if(h$1(this,b).byteLength-h$1(this,g$1)>1)+e;x$3(this,b,T$2(this,x$1,le$1).call(this,M)),new Uint8Array(h$1(this,b).buffer).set(new Uint8Array(r))}},Xe$1=function(e){if(e){h$1(this,b).setUint8(h$1(this,L$1),e);let r=h$1(this,g$1)-(h$1(this,L$1)+1);h$1(this,b).setInt32(h$1(this,L$1)+1,r,h$1(this,N))}return h$1(this,b).buffer.slice(e?0:5,h$1(this,g$1))};var m=new T$1,An=e=>{m.addInt16(3).addInt16(0);for(let r0 of Object.keys(e))m.addCString(r0).addCString(e[r0]);m.addCString("client_encoding").addCString("UTF8");let r=m.addCString("").flush(),M=r.byteLength+4;return new T$1().addInt32(M).add(r).flush()},xn=()=>{let e=new DataView(new ArrayBuffer(8));return e.setInt32(0,8,!1),e.setInt32(4,80877103,!1),new Uint8Array(e.buffer)},Sn=e=>m.addCString(e).flush(112),Dn=(e,r)=>(m.addCString(e).addInt32(P(r)).addString(r),m.flush(112)),Bn=e=>m.addString(e).flush(112),In=e=>m.addCString(e).flush(81),Mn=[],Rn=e=>{var r0,s0;let r=e.name??"";r.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",r,r.length),console.error("This can cause conflicts and silent errors executing queries"));let M=m.addCString(r).addCString(e.text).addInt16(((r0=e.types)==null?void 0:r0.length)??0);return(s0=e.types)==null||s0.forEach(a0=>M.addInt32(a0)),m.flush(80)},O$2=new T$1,Tn=(e,r)=>{for(let M=0;M{let r=e.portal??"",M=e.statement??"",r0=e.binary??!1,s0=e.values??Mn,a0=s0.length;return m.addCString(r).addCString(M),m.addInt16(a0),Tn(s0,e.valueMapper),m.addInt16(a0),m.add(O$2.flush()),m.addInt16(r0?1:0),m.flush(66)},Cn=new Uint8Array([69,0,0,0,9,0,0,0,0,0]),Pn=e=>{if(!e||!e.portal&&!e.rows)return Cn;let r=e.portal??"",M=e.rows??0,r0=P(r),s0=4+r0+1+4,a0=new DataView(new ArrayBuffer(1+s0));return a0.setUint8(0,69),a0.setInt32(1,s0,!1),new TextEncoder().encodeInto(r,new Uint8Array(a0.buffer,5)),a0.setUint8(r0+5,0),a0.setUint32(a0.byteLength-4,M,!1),new Uint8Array(a0.buffer)},Un=(e,r)=>{let M=new DataView(new ArrayBuffer(16));return M.setInt32(0,16,!1),M.setInt16(4,1234,!1),M.setInt16(6,5678,!1),M.setInt32(8,e,!1),M.setInt32(12,r,!1),new Uint8Array(M.buffer)},Ne=(e,r)=>{let M=new T$1;return M.addCString(r),M.flush(e)},Nn=m.addCString("P").flush(68),Ln=m.addCString("S").flush(68),On=e=>e.name?Ne(68,`${e.type}${e.name??""}`):e.type==="P"?Nn:Ln,kn=e=>{let r=`${e.type}${e.name??""}`;return Ne(67,r)},Vn=e=>m.add(e).flush(100),Fn=e=>Ne(102,e),pe$1=e=>new Uint8Array([e,0,0,0,4]),vn=pe$1(72),Gn=pe$1(83),jn=pe$1(88),Qn=pe$1(99),k$1={startup:An,password:Sn,requestSsl:xn,sendSASLInitialResponseMessage:Dn,sendSCRAMClientFinalMessage:Bn,query:In,parse:Rn,bind:En,execute:Pn,describe:On,close:kn,flush:()=>vn,sync:()=>Gn,end:()=>jn,copyData:Vn,copyDone:()=>Qn,copyFail:Fn,cancel:Un};u();u();var Le$1={text:0,binary:1};u();var Wn=new ArrayBuffer(0),R,w,fe$1,me$1,ne$1,de$1=class{constructor(r=0){R$1(this,R,new DataView(Wn)),R$1(this,w),R$1(this,fe$1,"utf-8"),R$1(this,me$1,new TextDecoder(h$1(this,fe$1))),R$1(this,ne$1,!1),x$3(this,w,r)}setBuffer(r,M){x$3(this,w,r),x$3(this,R,new DataView(M))}int16(){let r=h$1(this,R).getInt16(h$1(this,w),h$1(this,ne$1));return x$3(this,w,h$1(this,w)+2),r}byte(){let r=h$1(this,R).getUint8(h$1(this,w));return U$1(this,w)._++,r}int32(){let r=h$1(this,R).getInt32(h$1(this,w),h$1(this,ne$1));return x$3(this,w,h$1(this,w)+4),r}string(r){return h$1(this,me$1).decode(this.bytes(r))}cstring(){let r=h$1(this,w),M=r;for(;h$1(this,R).getUint8(M++)!==0;);let r0=this.string(M-r-1);return x$3(this,w,M),r0}bytes(r){let M=h$1(this,R).buffer.slice(h$1(this,w),h$1(this,w)+r);return x$3(this,w,h$1(this,w)+r),new Uint8Array(M)}};R=new WeakMap,w=new WeakMap,fe$1=new WeakMap,me$1=new WeakMap,ne$1=new WeakMap;var Oe=1,_n=4,Ze=Oe+_n,et=new ArrayBuffer(0),A,S,D,o$2,l,tt,nt$1,rt,st,it$1,at,ot$1,ke$1,ut,lt$1,ct,pt$1,dt,ft,mt,yt,Ve$1,ye$1=class{constructor(){R$1(this,l),R$1(this,A,new DataView(et)),R$1(this,S,0),R$1(this,D,0),R$1(this,o$2,new de$1)}parse(r,M){T$2(this,l,tt).call(this,ArrayBuffer.isView(r)?r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength):r);let r0=h$1(this,D)+h$1(this,S),s0=h$1(this,D);for(;s0+Ze<=r0;){let a0=h$1(this,A).getUint8(s0),i0=h$1(this,A).getUint32(s0+Oe,!1),u0=Oe+i0;if(u0+s0<=r0&&i0>0){let d0=T$2(this,l,nt$1).call(this,s0+Ze,a0,i0,h$1(this,A).buffer);M(d0),s0+=u0}else break}s0===r0?(x$3(this,A,new DataView(et)),x$3(this,S,0),x$3(this,D,0)):(x$3(this,S,r0-s0),x$3(this,D,s0))}};A=new WeakMap,S=new WeakMap,D=new WeakMap,o$2=new WeakMap,l=new WeakSet,tt=function(e){if(h$1(this,S)>0){let r=h$1(this,S)+e.byteLength;if(r+h$1(this,D)>h$1(this,A).byteLength){let M;if(r<=h$1(this,A).byteLength&&h$1(this,D)>=h$1(this,S))M=h$1(this,A).buffer;else{let r0=h$1(this,A).byteLength*2;for(;r>=r0;)r0*=2;M=new ArrayBuffer(r0)}new Uint8Array(M).set(new Uint8Array(h$1(this,A).buffer,h$1(this,D),h$1(this,S))),x$3(this,A,new DataView(M)),x$3(this,D,0)}new Uint8Array(h$1(this,A).buffer).set(new Uint8Array(e),h$1(this,D)+h$1(this,S)),x$3(this,S,r)}else x$3(this,A,new DataView(e)),x$3(this,D,0),x$3(this,S,e.byteLength)},nt$1=function(e,r,M,r0){switch(r){case 50:return Ie;case 49:return Be$1;case 51:return Me;case 110:return Re;case 115:return Te;case 99:return Pe;case 87:return Ee;case 73:return Ce;case 68:return T$2(this,l,dt).call(this,e,M,r0);case 67:return T$2(this,l,st).call(this,e,M,r0);case 90:return T$2(this,l,rt).call(this,e,M,r0);case 65:return T$2(this,l,ut).call(this,e,M,r0);case 82:return T$2(this,l,yt).call(this,e,M,r0);case 83:return T$2(this,l,ft).call(this,e,M,r0);case 75:return T$2(this,l,mt).call(this,e,M,r0);case 69:return T$2(this,l,Ve$1).call(this,e,M,r0,"error");case 78:return T$2(this,l,Ve$1).call(this,e,M,r0,"notice");case 84:return T$2(this,l,lt$1).call(this,e,M,r0);case 116:return T$2(this,l,pt$1).call(this,e,M,r0);case 71:return T$2(this,l,at).call(this,e,M,r0);case 72:return T$2(this,l,ot$1).call(this,e,M,r0);case 100:return T$2(this,l,it$1).call(this,e,M,r0);default:return new C$1("received invalid response: "+r.toString(16),M,"error")}},rt=function(e,r,M){h$1(this,o$2).setBuffer(e,M);let r0=h$1(this,o$2).string(1);return new X(r,r0)},st=function(e,r,M){h$1(this,o$2).setBuffer(e,M);let r0=h$1(this,o$2).cstring();return new Z$1(r,r0)},it$1=function(e,r,M){let r0=M.slice(e,e+(r-4));return new _(r,new Uint8Array(r0))},at=function(e,r,M){return T$2(this,l,ke$1).call(this,e,r,M,"copyInResponse")},ot$1=function(e,r,M){return T$2(this,l,ke$1).call(this,e,r,M,"copyOutResponse")},ke$1=function(e,r,M,r0){h$1(this,o$2).setBuffer(e,M);let s0=h$1(this,o$2).byte()!==0,a0=h$1(this,o$2).int16(),i0=new z(r,r0,s0,a0);for(let u0=0;u0{const{readFile:i0}=await import("./__vite-browser-external-BIHI7g3E.js");return{readFile:i0}},[])).readFile(M),{module:s0,instance:a0}=await WebAssembly.instantiate(r0,e);return re$1=s0,{instance:a0,module:s0}}else{se$1||(se$1=fetch(M));let r0=await se$1,{module:s0,instance:a0}=await WebAssembly.instantiateStreaming(r0,e);return re$1=s0,{instance:a0,module:s0}}}async function Er(){let e=new URL("/assets/pglite-CKoE7lOK.data",import.meta.url);return Fe$1?(await(await __vitePreload(async()=>{const{readFile:r}=await import("./__vite-browser-external-BIHI7g3E.js");return{readFile:r}},[])).readFile(e)).buffer:(await fetch(e)).arrayBuffer()}function Nr(e){let r;return e.startsWith('"')&&e.endsWith('"')?r=e.substring(1,e.length-1):r=e.toLowerCase(),r}u();var o$1={part:"part",container:"container"};function s(e,r,...M){let r0=e.length-1,s0=M.length-1;if(s0!==-1){if(s0===0){e[r0]=e[r0]+M[0]+r;return}e[r0]=e[r0]+M[0],e.push(...M.slice(1,s0)),e.push(M[s0]+r)}}function y$1(e,...r){let M=[e[0]];M.raw=[e.raw[0]];let r0=[];for(let s0=0;s0[`$${a0+1}`,M[a0+1]])].join(""),params:r0}}u();u();function E(e){let r=e.e;return r.query=e.query,r.params=e.params,r.queryOptions=e.options,r}var T,p,t,y,x,h,O$1,k=class{constructor(){R$1(this,t),this.serializers={...cn},this.parsers={...ln},R$1(this,T,!1),R$1(this,p,!1)}async _initArrayTypes({force:e=!1}={}){if(h$1(this,T)&&!e)return;x$3(this,T,!0);let r=await this.query(` + SELECT b.oid, b.typarray + FROM pg_catalog.pg_type a + LEFT JOIN pg_catalog.pg_type b ON b.oid = a.typelem + WHERE a.typcategory = 'A' + GROUP BY b.oid, b.typarray + ORDER BY b.oid + `);for(let M of r.rows)this.serializers[M.typarray]=r0=>Ke$1(r0,this.serializers[M.oid],M.typarray),this.parsers[M.typarray]=r0=>yn(r0,this.parsers[M.oid],M.typarray)}async refreshArrayTypes(){await this._initArrayTypes({force:!0})}async query(e,r,M){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await T$2(this,t,x).call(this,e,r,M))}async sql(e,...r){let{query:M,params:r0}=g(e,...r);return await this.query(M,r0)}async exec(e,r){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await T$2(this,t,h).call(this,e,r))}async describeQuery(e,r){let M=[];try{await T$2(this,t,y).call(this,k$1.parse({text:e,types:r==null?void 0:r.paramTypes}),r),M=await T$2(this,t,y).call(this,k$1.describe({type:"S"}),r)}catch(u0){throw u0 instanceof C$1?E({e:u0,options:r,params:void 0,query:e}):u0}finally{M.push(...await T$2(this,t,y).call(this,k$1.sync(),r))}let r0=M.find(u0=>u0.name==="parameterDescription"),s0=M.find(u0=>u0.name==="rowDescription"),a0=(r0==null?void 0:r0.dataTypeIDs.map(u0=>({dataTypeID:u0,serializer:this.serializers[u0]})))??[],i0=(s0==null?void 0:s0.fields.map(u0=>({name:u0.name,dataTypeID:u0.dataTypeID,parser:this.parsers[u0.dataTypeID]})))??[];return{queryParams:a0,resultFields:i0}}async transaction(e){return await this._checkReady(),await this._runExclusiveTransaction(async()=>{await T$2(this,t,h).call(this,"BEGIN"),x$3(this,p,!0);let r=!1,M=()=>{if(r)throw new Error("Transaction is closed")},r0={query:async(s0,a0,i0)=>(M(),await T$2(this,t,x).call(this,s0,a0,i0)),sql:async(s0,...a0)=>{let{query:i0,params:u0}=g(s0,...a0);return await T$2(this,t,x).call(this,i0,u0)},exec:async(s0,a0)=>(M(),await T$2(this,t,h).call(this,s0,a0)),rollback:async()=>{M(),await T$2(this,t,h).call(this,"ROLLBACK"),r=!0},listen:async(s0,a0)=>(M(),await this.listen(s0,a0,r0)),get closed(){return r}};try{let s0=await e(r0);return r||(r=!0,await T$2(this,t,h).call(this,"COMMIT")),x$3(this,p,!1),s0}catch(s0){throw r||await T$2(this,t,h).call(this,"ROLLBACK"),x$3(this,p,!1),s0}})}async runExclusive(e){return await this._runExclusiveQuery(e)}};T=new WeakMap,p=new WeakMap,t=new WeakSet,y=async function(e,r={}){return await this.execProtocolStream(e,{...r,syncToFs:!1})},x=async function(e,r=[],M){return await this._runExclusiveQuery(async()=>{T$2(this,t,O$1).call(this,"runQuery",e,r,M),await this._handleBlob(M==null?void 0:M.blob);let r0=[];try{let a0=await T$2(this,t,y).call(this,k$1.parse({text:e,types:M==null?void 0:M.paramTypes}),M),i0=De(await T$2(this,t,y).call(this,k$1.describe({type:"S"}),M)),u0=r.map((d0,m0)=>{var g0;let _0=i0[m0];if(d0==null)return null;let f0=((g0=M==null?void 0:M.serializers)==null?void 0:g0[_0])??this.serializers[_0];return f0?f0(d0):d0.toString()});r0=[...a0,...await T$2(this,t,y).call(this,k$1.bind({values:u0}),M),...await T$2(this,t,y).call(this,k$1.describe({type:"P"}),M),...await T$2(this,t,y).call(this,k$1.execute({}),M)]}catch(a0){throw a0 instanceof C$1?E({e:a0,options:M,params:r,query:e}):a0}finally{r0.push(...await T$2(this,t,y).call(this,k$1.sync(),M))}await this._cleanupBlob(),h$1(this,p)||await this.syncToFs();let s0=await this._getWrittenBlob();return bn(r0,this.parsers,M,s0)[0]})},h=async function(e,r){return await this._runExclusiveQuery(async()=>{T$2(this,t,O$1).call(this,"runExec",e,r),await this._handleBlob(r==null?void 0:r.blob);let M=[];try{M=await T$2(this,t,y).call(this,k$1.query(e),r)}catch(s0){throw s0 instanceof C$1?E({e:s0,options:r,params:void 0,query:e}):s0}finally{M.push(...await T$2(this,t,y).call(this,k$1.sync(),r))}this._cleanupBlob(),h$1(this,p)||await this.syncToFs();let r0=await this._getWrittenBlob();return bn(M,this.parsers,r,r0)})},O$1=function(...e){this.debug>0&&console.log(...e)};u();u();u();var ot=new Error("request for lock canceled"),nt=function(e,r,M,r0){function s0(a0){return a0 instanceof M?a0:new M(function(i0){i0(a0)})}return new(M||(M=Promise))(function(a0,i0){function u0(_0){try{m0(r0.next(_0))}catch(f0){i0(f0)}}function d0(_0){try{m0(r0.throw(_0))}catch(f0){i0(f0)}}function m0(_0){_0.done?a0(_0.value):s0(_0.value).then(u0,d0)}m0((r0=r0.apply(e,[])).next())})},Fe=class{constructor(e,r=ot){this._value=e,this._cancelError=r,this._weightedQueues=[],this._weightedWaiters=[]}acquire(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((r,M)=>{this._weightedQueues[e-1]||(this._weightedQueues[e-1]=[]),this._weightedQueues[e-1].push({resolve:r,reject:M}),this._dispatch()})}runExclusive(e,r=1){return nt(this,void 0,void 0,function*(){let[M,r0]=yield this.acquire(r);try{return yield e(M)}finally{r0()}})}waitForUnlock(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),this._weightedWaiters[e-1].push(r),this._dispatch()})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatch()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatch()}cancel(){this._weightedQueues.forEach(e=>e.forEach(r=>r.reject(this._cancelError))),this._weightedQueues=[]}_dispatch(){var e;for(let r=this._value;r>0;r--){let M=(e=this._weightedQueues[r-1])===null||e===void 0?void 0:e.shift();if(!M)continue;let r0=this._value,s0=r;this._value-=r,r=this._value+1,M.resolve([r0,this._newReleaser(s0)])}this._drainUnlockWaiters()}_newReleaser(e){let r=!1;return()=>{r||(r=!0,this.release(e))}}_drainUnlockWaiters(){for(let e=this._value;e>0;e--)this._weightedWaiters[e-1]&&(this._weightedWaiters[e-1].forEach(r=>r()),this._weightedWaiters[e-1]=[])}},it=function(e,r,M,r0){function s0(a0){return a0 instanceof M?a0:new M(function(i0){i0(a0)})}return new(M||(M=Promise))(function(a0,i0){function u0(_0){try{m0(r0.next(_0))}catch(f0){i0(f0)}}function d0(_0){try{m0(r0.throw(_0))}catch(f0){i0(f0)}}function m0(_0){_0.done?a0(_0.value):s0(_0.value).then(u0,d0)}m0((r0=r0.apply(e,[])).next())})},Y=class{constructor(e){this._semaphore=new Fe(1,e)}acquire(){return it(this,void 0,void 0,function*(){let[,e]=yield this._semaphore.acquire();return e})}runExclusive(e){return this._semaphore.runExclusive(()=>e())}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};u();var Le=L$3(or());async function ke(e){if(Fe$1){let r=await __vitePreload(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),M=await __vitePreload(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),{Writable:r0}=await __vitePreload(async()=>{const{Writable:u0}=await import("./__vite-browser-external-BIHI7g3E.js");return{Writable:u0}},[]),{pipeline:s0}=await __vitePreload(async()=>{const{pipeline:u0}=await import("./__vite-browser-external-BIHI7g3E.js");return{pipeline:u0}},[]);if(!r.existsSync(e))throw new Error(`Extension bundle not found: ${e}`);let a0=M.createGunzip(),i0=[];return await s0(r.createReadStream(e),a0,new r0({write(u0,d0,m0){i0.push(u0),m0()}})),new Blob(i0)}else{let r=await fetch(e.toString());if(!r.ok||!r.body)return null;if(r.headers.get("Content-Encoding")==="gzip")return r.blob();{let M=new DecompressionStream("gzip");return new Response(r.body.pipeThrough(M)).blob()}}}async function Be(e,r){for(let M in e.pg_extensions){let r0;try{r0=await e.pg_extensions[M]}catch(s0){console.error("Failed to fetch extension:",M,s0);continue}if(r0){let s0=new Uint8Array(await r0.arrayBuffer());_t(e,M,s0,r)}else console.error("Could not get binary data for extension:",M)}}function _t(e,r,M,r0){Le.default.untar(M).forEach(s0=>{if(!s0.name.startsWith(".")){let a0=e.WASM_PREFIX+"/"+s0.name;if(s0.name.endsWith(".so")){let i0=(...d0)=>{r0("pgfs:ext OK",a0,d0)},u0=(...d0)=>{r0("pgfs:ext FAIL",a0,d0)};e.FS.createPreloadedFile(lt(a0),s0.name.split("/").pop().slice(0,-3),s0.data,!0,!0,i0,u0,!1)}else try{let i0=a0.substring(0,a0.lastIndexOf("/"));e.FS.analyzePath(i0).exists===!1&&e.FS.mkdirTree(i0),e.FS.writeFile(a0,s0.data)}catch(i0){console.error(`Error writing file ${a0}`,i0)}}})}function lt(e){let r=e.lastIndexOf("/");return r>0?e.slice(0,r):e}u();u();var ue=class extends ur{async init(e,r){return this.pg=e,{emscriptenOpts:{...r,preRun:[...r.preRun||[],M=>{let r0=M.FS.filesystems.IDBFS;M.FS.mkdir("/pglite"),M.FS.mkdir(`/pglite/${this.dataDir}`),M.FS.mount(r0,{},`/pglite/${this.dataDir}`),M.FS.symlink(`/pglite/${this.dataDir}`,C$2)}]}}}initialSyncFs(){return new Promise((e,r)=>{this.pg.Module.FS.syncfs(!0,M=>{M?r(M):e()})})}syncToFs(e){return new Promise((r,M)=>{this.pg.Module.FS.syncfs(!1,r0=>{r0?M(r0):r()})})}async closeFs(){let e=this.pg.Module.FS.filesystems.IDBFS.dbs[this.dataDir];e&&e.close(),this.pg.Module.FS.quit()}};u();var ce=class extends ur{async closeFs(){this.pg.Module.FS.quit()}};function Ge(e){let r;if(e!=null&&e.startsWith("file://")){if(e=e.slice(7),!e)throw new Error("Invalid dataDir, must be a valid path");r="nodefs"}else e!=null&&e.startsWith("idb://")?(e=e.slice(6),r="idbfs"):e!=null&&e.startsWith("opfs-ahp://")?(e=e.slice(11),r="opfs-ahp"):!e||e!=null&&e.startsWith("memory://")?r="memoryfs":r="nodefs";return{dataDir:e,fsType:r}}async function Ue(e,r){let M;if(e&&r==="nodefs"){let{NodeFS:r0}=await __vitePreload(()=>import("./nodefs-Dvj6UlUO.js"),[]);M=new r0(e)}else if(e&&r==="idbfs")M=new ue(e);else if(e&&r==="opfs-ahp"){let{OpfsAhpFS:r0}=await __vitePreload(()=>import("./opfs-ahp-3r0djkxf.js"),[]);M=new r0(e)}else M=new ce;return M}u();u();var pt=(()=>{var _scriptName=import.meta.url;return async function(moduleArg={}){var moduleRtn,Module=moduleArg,readyPromiseResolve,readyPromiseReject,readyPromise=new Promise((e,r)=>{readyPromiseResolve=e,readyPromiseReject=r}),ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope<"u",ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&process.type!="renderer";if(ENVIRONMENT_IS_NODE){let{createRequire:e}=await __vitePreload(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),r=import.meta.url;r.startsWith("data:")&&(r="/");var require=e(r)}Module.expectedDataFileDownloads??(Module.expectedDataFileDownloads=0),Module.expectedDataFileDownloads++,(()=>{var e=typeof ENVIRONMENT_IS_PTHREAD<"u"&&ENVIRONMENT_IS_PTHREAD,r=typeof ENVIRONMENT_IS_WASM_WORKER<"u"&&ENVIRONMENT_IS_WASM_WORKER;if(e||r)return;var M=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string";function r0(s0){typeof window=="object"?window.encodeURIComponent(window.location.pathname.substring(0,window.location.pathname.lastIndexOf("/"))+"/"):typeof process>"u"&&typeof location<"u"&&encodeURIComponent(location.pathname.substring(0,location.pathname.lastIndexOf("/"))+"/");var a0="pglite.data",i0="pglite.data",u0=Module.locateFile?Module.locateFile(i0,""):i0,d0=s0.remote_package_size;function m0(k0,F0,C0,R0){if(M){require("fs").readFile(k0,(y0,w0)=>{y0?R0(y0):C0(w0.buffer)});return}Module.dataFileDownloads??(Module.dataFileDownloads={}),fetch(k0).catch(y0=>Promise.reject(new Error(`Network Error: ${k0}`,{cause:y0}))).then(y0=>{var Ur;if(!y0.ok)return Promise.reject(new Error(`${y0.status}: ${y0.url}`));if(!y0.body&&y0.arrayBuffer)return y0.arrayBuffer().then(C0);let w0=y0.body.getReader(),A0=()=>w0.read().then(Ir).catch(mr=>Promise.reject(new Error(`Unexpected error while handling : ${y0.url} ${mr}`,{cause:mr}))),q0=[],U0=y0.headers,X0=Number(U0.get("Content-Length")??F0),xr=0,Ir=({done:mr,value:vr})=>{var H0;if(mr){let lr=new Uint8Array(q0.map(_r=>_r.length).reduce((_r,wr)=>_r+wr,0)),fr=0;for(let _r of q0)lr.set(_r,fr),fr+=_r.length;C0(lr.buffer)}else{q0.push(vr),xr+=vr.length,Module.dataFileDownloads[k0]={loaded:xr,total:X0};let lr=0,fr=0;for(let _r of Object.values(Module.dataFileDownloads))lr+=_r.loaded,fr+=_r.total;return(H0=Module.setStatus)==null||H0.call(Module,`Downloading data... (${lr}/${fr})`),A0()}};return(Ur=Module.setStatus)==null||Ur.call(Module,"Downloading data..."),A0()})}function _0(k0){console.error("package error:",k0)}var f0=null,g0=Module.getPreloadedPackage?Module.getPreloadedPackage(u0,d0):null;g0||m0(u0,d0,k0=>{f0?(f0(k0),f0=null):g0=k0},_0);function x0(k0){function F0(A0,q0){if(!A0)throw q0+new Error().stack}k0.FS_createPath("/","home",!0,!0),k0.FS_createPath("/home","web_user",!0,!0),k0.FS_createPath("/","tmp",!0,!0),k0.FS_createPath("/tmp","pglite",!0,!0),k0.FS_createPath("/tmp/pglite","bin",!0,!0),k0.FS_createPath("/tmp/pglite","lib",!0,!0),k0.FS_createPath("/tmp/pglite/lib","postgresql",!0,!0),k0.FS_createPath("/tmp/pglite/lib/postgresql","pgxs",!0,!0),k0.FS_createPath("/tmp/pglite/lib/postgresql/pgxs","config",!0,!0),k0.FS_createPath("/tmp/pglite/lib/postgresql/pgxs","src",!0,!0),k0.FS_createPath("/tmp/pglite/lib/postgresql/pgxs/src","makefiles",!0,!0),k0.FS_createPath("/tmp/pglite","share",!0,!0),k0.FS_createPath("/tmp/pglite/share","postgresql",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql","extension",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql","timezone",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Africa",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","America",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone/America","Argentina",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone/America","Indiana",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone/America","Kentucky",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone/America","North_Dakota",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Antarctica",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Arctic",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Asia",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Atlantic",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Australia",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Brazil",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Canada",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Chile",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Etc",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Europe",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Indian",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Mexico",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","Pacific",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql/timezone","US",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql","timezonesets",!0,!0),k0.FS_createPath("/tmp/pglite/share/postgresql","tsearch_data",!0,!0);function C0(A0,q0,U0){this.start=A0,this.end=q0,this.audio=U0}C0.prototype={requests:{},open:function(A0,q0){this.name=q0,this.requests[q0]=this,k0.addRunDependency(`fp ${this.name}`)},send:function(){},onload:function(){var A0=this.byteArray.subarray(this.start,this.end);this.finish(A0)},finish:function(A0){var q0=this;k0.FS_createDataFile(this.name,null,A0,!0,!0,!0),k0.removeRunDependency(`fp ${q0.name}`),this.requests[this.name]=null}};for(var R0=s0.files,y0=0;y0{throw r},scriptDirectory="";function locateFile(e){return Module.locateFile?Module.locateFile(e,scriptDirectory):scriptDirectory+e}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs"),nodePath=require("path");import.meta.url.startsWith("data:")||(scriptDirectory=nodePath.dirname(require("url").fileURLToPath(import.meta.url))+"/"),readBinary=e=>{e=isFileURI(e)?new URL(e):e;var r=fs.readFileSync(e);return r},readAsync=async(e,r=!0)=>{e=isFileURI(e)?new URL(e):e;var M=fs.readFileSync(e,r?void 0:"utf8");return M},!Module.thisProgram&&process.argv.length>1&&(thisProgram=process.argv[1].replace(/\\/g,"/")),arguments_=process.argv.slice(2),quit_=(e,r)=>{throw process.exitCode=e,r}}else(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:typeof document<"u"&&document.currentScript&&(scriptDirectory=document.currentScript.src),_scriptName&&(scriptDirectory=_scriptName),scriptDirectory.startsWith("blob:")?scriptDirectory="":scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1),ENVIRONMENT_IS_WORKER&&(readBinary=e=>{var r=new XMLHttpRequest;return r.open("GET",e,!1),r.responseType="arraybuffer",r.send(null),new Uint8Array(r.response)}),readAsync=async e=>{var r=await fetch(e,{credentials:"same-origin"});if(r.ok)return r.arrayBuffer();throw new Error(r.status+" : "+r.url)});var out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram);var dynamicLibraries=Module.dynamicLibraries||[],wasmBinary=Module.wasmBinary,wasmMemory,ABORT=!1,EXITSTATUS;function assert(e,r){e||abort(r)}var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAP64,HEAPF64;function updateMemoryViews(){var e=wasmMemory.buffer;Module.HEAP8=HEAP8=new Int8Array(e),Module.HEAP16=HEAP16=new Int16Array(e),Module.HEAPU8=HEAPU8=new Uint8Array(e),Module.HEAPU16=HEAPU16=new Uint16Array(e),Module.HEAP32=HEAP32=new Int32Array(e),Module.HEAPU32=HEAPU32=new Uint32Array(e),Module.HEAPF32=HEAPF32=new Float32Array(e),Module.HEAPF64=HEAPF64=new Float64Array(e),Module.HEAP64=HEAP64=new BigInt64Array(e),Module.HEAPU64=new BigUint64Array(e)}if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var INITIAL_MEMORY=Module.INITIAL_MEMORY||16777216;wasmMemory=new WebAssembly.Memory({initial:INITIAL_MEMORY/65536,maximum:32768})}updateMemoryViews();var __ATPRERUN__=[],__ATINIT__=[],__ATMAIN__=[],__ATPOSTRUN__=[],__RELOC_FUNCS__=[],runtimeInitialized=!1;function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),!Module.noFSInit&&!FS.initialized&&FS.init(),FS.ignorePermissions=!1,SOCKFS.root=FS.mount(SOCKFS,{},null),PIPEFS.root=FS.mount(PIPEFS,{},null),callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(e){__ATPRERUN__.unshift(e)}function addOnInit(e){__ATINIT__.unshift(e)}function addOnPostRun(e){__ATPOSTRUN__.unshift(e)}var runDependencies=0,dependenciesFulfilled=null;function addRunDependency(e){var r;runDependencies++,(r=Module.monitorRunDependencies)==null||r.call(Module,runDependencies)}function removeRunDependency(e){var M;if(runDependencies--,(M=Module.monitorRunDependencies)==null||M.call(Module,runDependencies),runDependencies==0&&dependenciesFulfilled){var r=dependenciesFulfilled;dependenciesFulfilled=null,r()}}function abort(e){var M;(M=Module.onAbort)==null||M.call(Module,e),e="Aborted("+e+")",err(e),ABORT=!0,e+=". Build with -sASSERTIONS for more info.";var r=new WebAssembly.RuntimeError(e);throw readyPromiseReject(r),r}var dataURIPrefix="data:application/octet-stream;base64,",isDataURI=e=>e.startsWith(dataURIPrefix),isFileURI=e=>e.startsWith("file://");function findWasmBinary(){if(Module.locateFile){var e="pglite.wasm";return isDataURI(e)?e:locateFile(e)}return new URL("/assets/pglite-BHNxCJwl.wasm",import.meta.url).href}var wasmBinaryFile;function getBinarySync(e){if(e==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(e);throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(e){if(!wasmBinary)try{var r=await readAsync(e);return new Uint8Array(r)}catch{}return getBinarySync(e)}async function instantiateArrayBuffer(e,r){try{var M=await getWasmBinary(e),r0=await WebAssembly.instantiate(M,r);return r0}catch(s0){err(`failed to asynchronously prepare wasm: ${s0}`),abort(s0)}}async function instantiateAsync(e,r,M){if(!e&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(r)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function")try{var r0=fetch(r,{credentials:"same-origin"}),s0=await WebAssembly.instantiateStreaming(r0,M);return s0}catch(a0){err(`wasm streaming compile failed: ${a0}`),err("falling back to ArrayBuffer instantiation")}return instantiateArrayBuffer(r,M)}function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}async function createWasm(){function e(s0,a0){wasmExports=s0.exports,wasmExports=relocateExports(wasmExports,1024);var i0=getDylinkMetadata(a0);return i0.neededDynlibs&&(dynamicLibraries=i0.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports),LDSO.init(),loadDylibs(),addOnInit(wasmExports.__wasm_call_ctors),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),removeRunDependency(),wasmExports}addRunDependency();function r(s0){e(s0.instance,s0.module)}var M=getWasmImports();if(Module.instantiateWasm)try{return Module.instantiateWasm(M,e)}catch(s0){err(`Module.instantiateWasm callback failed with error: ${s0}`),readyPromiseReject(s0)}wasmBinaryFile??(wasmBinaryFile=findWasmBinary());try{var r0=await instantiateAsync(wasmBinary,wasmBinaryFile,M);return r(r0),r0}catch(s0){readyPromiseReject(s0);return}}var ASM_CONSTS={2537480:e=>{Module.is_worker=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope,Module.FD_BUFFER_MAX=e,Module.emscripten_copy_to=console.warn},2537652:()=>{Module.postMessage=function(e){console.log("# pg_main_emsdk.c:544: onCustomMessage:",e)}},2537781:()=>{if(Module.is_worker){let e=function(r){console.log("onCustomMessage:",r)};Module.onCustomMessage=e}else Module.postMessage=function(e){switch(e.type){case"raw":break;case"stdin":{stringToUTF8(e.data,1,Module.FD_BUFFER_MAX);break}case"rcon":break;default:console.warn("custom_postMessage?",e)}}}};class ExitStatus{constructor(r){P$1(this,"name","ExitStatus"),this.message=`Program terminated with exit(${r})`,this.status=r}}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(e,r){var M=GOT[r];return M||(M=GOT[r]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(r)||(M.required=!0),M}},callRuntimeCallbacks=e=>{for(;e.length>0;)e.shift()(Module)},UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,UTF8ArrayToString=(e,r=0,M=NaN)=>{for(var r0=r+M,s0=r;e[s0]&&!(s0>=r0);)++s0;if(s0-r>16&&e.buffer&&UTF8Decoder)return UTF8Decoder.decode(e.subarray(r,s0));for(var a0="";r>10,56320|m0&1023)}}return a0},getDylinkMetadata=e=>{var r=0,M=0;function r0(){return e[r++]}function s0(){for(var vr=0,H0=1;;){var lr=e[r++];if(vr+=(lr&127)*H0,H0*=128,!(lr&128))break}return vr}function a0(){var vr=s0();return r+=vr,UTF8ArrayToString(e,r-vr,vr)}function i0(vr,H0){if(vr)throw new Error(H0)}var u0="dylink.0";if(e instanceof WebAssembly.Module){var d0=WebAssembly.Module.customSections(e,u0);d0.length===0&&(u0="dylink",d0=WebAssembly.Module.customSections(e,u0)),i0(d0.length===0,"need dylink section"),e=new Uint8Array(d0[0]),M=e.length}else{var m0=new Uint32Array(new Uint8Array(e.subarray(0,24)).buffer),_0=m0[0]==1836278016;i0(!_0,"need to see wasm magic number"),i0(e[8]!==0,"need the dylink section to be first"),r=9;var f0=s0();M=r+f0,u0=a0()}var g0={neededDynlibs:[],tlsExports:new Set,weakImports:new Set};if(u0=="dylink"){g0.memorySize=s0(),g0.memoryAlign=s0(),g0.tableSize=s0(),g0.tableAlign=s0();for(var x0=s0(),k0=0;k0>1];case"i32":return HEAP32[e>>2];case"i64":return HEAP64[e>>3];case"float":return HEAPF32[e>>2];case"double":return HEAPF64[e>>3];case"*":return HEAPU32[e>>2];default:abort(`invalid type for getValue: ${r}`)}}var newDSO=(e,r,M)=>{var r0={refcount:1/0,name:e,exports:M,global:!0};return LDSO.loadedLibsByName[e]=r0,r!=null&&(LDSO.loadedLibsByHandle[r]=r0),r0},LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=2765600,alignMemory=(e,r)=>Math.ceil(e/r)*r,getMemory=e=>{if(runtimeInitialized)return _calloc(e,1);var r=___heap_base,M=r+alignMemory(e,16);return ___heap_base=M,GOT.__heap_base.value=M,r},isInternalSym=e=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(e)||e.startsWith("__em_js__"),uleb128Encode=(e,r)=>{e<128?r.push(e):r.push(e%128|128,e>>7)},sigToWasmTypes=e=>{for(var r={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},M={parameters:[],results:e[0]=="v"?[]:[r[e[0]]]},r0=1;r0{var M=e.slice(0,1),r0=e.slice(1),s0={i:127,p:127,j:126,f:125,d:124,e:111};r.push(96),uleb128Encode(r0.length,r);for(var a0=0;a0{if(typeof WebAssembly.Function=="function")return new WebAssembly.Function(sigToWasmTypes(r),e);var M=[1];generateFuncType(r,M);var r0=[0,97,115,109,1,0,0,0,1];uleb128Encode(M.length,r0),r0.push(...M),r0.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var s0=new WebAssembly.Module(new Uint8Array(r0)),a0=new WebAssembly.Instance(s0,{e:{f:e}}),i0=a0.exports.f;return i0},wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:5609,element:"anyfunc"}),getWasmTableEntry=e=>{var r=wasmTableMirror[e];return r||(e>=wasmTableMirror.length&&(wasmTableMirror.length=e+1),wasmTableMirror[e]=r=wasmTable.get(e)),r},updateTableMap=(e,r)=>{if(functionsInTableMap)for(var M=e;M(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(e)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(e){throw e instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":e}return wasmTable.length-1},setWasmTableEntry=(e,r)=>{wasmTable.set(e,r),wasmTableMirror[e]=wasmTable.get(e)},addFunction=(e,r)=>{var M=getFunctionAddress(e);if(M)return M;var r0=getEmptyTableSlot();try{setWasmTableEntry(r0,e)}catch(a0){if(!(a0 instanceof TypeError))throw a0;var s0=convertJsFunctionToWasm(e,r);setWasmTableEntry(r0,s0)}return functionsInTableMap.set(e,r0),r0},updateGOT=(e,r)=>{for(var M in e)if(!isInternalSym(M)){var r0=e[M];GOT[M]||(GOT[M]=new WebAssembly.Global({value:"i32",mutable:!0})),GOT[M].value==0&&(typeof r0=="function"?GOT[M].value=addFunction(r0):typeof r0=="number"?GOT[M].value=r0:err(`unhandled export type for '${M}': ${typeof r0}`))}},relocateExports=(e,r,M)=>{var r0={};for(var s0 in e){var a0=e[s0];typeof a0=="object"&&(a0=a0.value),typeof a0=="number"&&(a0+=r),r0[s0]=a0}return updateGOT(r0),r0},isSymbolDefined=e=>{var r=wasmImports[e];return!(!r||r.stub)},dynCall=(e,r,M=[])=>{var r0=getWasmTableEntry(r)(...M);return r0},stackSave=()=>_emscripten_stack_get_current(),stackRestore=e=>__emscripten_stack_restore(e),createInvokeFunction=e=>(r,...M)=>{var r0=stackSave();try{return dynCall(e,r,M)}catch(s0){if(stackRestore(r0),s0!==s0+0)throw s0;if(_setThrew(1,0),e[0]=="j")return 0n}},resolveGlobalSymbol=(e,r=!1)=>{var M;return isSymbolDefined(e)?M=wasmImports[e]:e.startsWith("invoke_")&&(M=wasmImports[e]=createInvokeFunction(e.split("_")[1])),{sym:M,name:e}},UTF8ToString=(e,r)=>e?UTF8ArrayToString(HEAPU8,e,r):"",loadWebAssemblyModule=(binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);currentModuleWeakSymbols=metadata.weakImports;function loadModule(){var firstLoad=!handle||!HEAP8[handle+8];if(firstLoad){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,HEAPU32[handle+12>>2]=memoryBase,HEAP32[handle+16>>2]=metadata.memorySize,HEAPU32[handle+20>>2]=tableBase,HEAP32[handle+24>>2]=metadata.tableSize)}else memoryBase=HEAPU32[handle+12>>2],tableBase=HEAPU32[handle+20>>2];var tableGrowthNeeded=tableBase+metadata.tableSize-wasmTable.length;tableGrowthNeeded>0&&wasmTable.grow(tableGrowthNeeded);var moduleExports;function resolveSymbol(e){var r=resolveGlobalSymbol(e).sym;return!r&&localScope&&(r=localScope[e]),r||(r=moduleExports[e]),r}var proxyHandler={get(e,r){switch(r){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(r in wasmImports&&!wasmImports[r].stub)return wasmImports[r];if(!(r in e)){var M;e[r]=(...r0)=>(M||(M=resolveSymbol(r)),M(...r0))}return e[r]}},proxy=new Proxy({},proxyHandler),info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if("__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start ${body};`;moduleExports[name]=eval(func)}for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():__ATINIT__.push(init)),moduleExports}if(flags.loadAsync){if(binary instanceof WebAssembly.Module){var instance=new WebAssembly.Instance(binary,info);return Promise.resolve(postInstantiation(binary,instance))}return WebAssembly.instantiate(binary,info).then(e=>postInstantiation(e.module,e.instance))}var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return flags.loadAsync?metadata.neededDynlibs.reduce((e,r)=>e.then(()=>loadDynamicLibrary(r,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(e=>loadDynamicLibrary(e,flags,localScope)),loadModule())},mergeLibSymbols=(e,r)=>{for(var[M,r0]of Object.entries(e)){let s0=i0=>{isSymbolDefined(i0)||(wasmImports[i0]=r0)};s0(M);let a0="__main_argc_argv";M=="main"&&s0(a0),M==a0&&s0("main")}},asyncLoad=async e=>{var r=await readAsync(e);return new Uint8Array(r)},preloadPlugins=Module.preloadPlugins||[],registerWasmPlugin=()=>{var e={promiseChainEnd:Promise.resolve(),canHandle:r=>!Module.noWasmDecoding&&r.endsWith(".so"),handle:(r,M,r0,s0)=>{e.promiseChainEnd=e.promiseChainEnd.then(()=>loadWebAssemblyModule(r,{loadAsync:!0,nodelete:!0},M,{})).then(a0=>{preloadedWasm[M]=a0,r0(r)},a0=>{err(`failed to instantiate wasm: ${M}: ${a0}`),s0()})}};preloadPlugins.push(e)},preloadedWasm={};function loadDynamicLibrary(e,r={global:!0,nodelete:!0},M,r0){var s0=LDSO.loadedLibsByName[e];if(s0)return r.global?s0.global||(s0.global=!0,mergeLibSymbols(s0.exports)):M&&Object.assign(M,s0.exports),r.nodelete&&s0.refcount!==1/0&&(s0.refcount=1/0),s0.refcount++,r0&&(LDSO.loadedLibsByHandle[r0]=s0),r.loadAsync?Promise.resolve(!0):!0;s0=newDSO(e,r0,"loading"),s0.refcount=r.nodelete?1/0:1,s0.global=r.global;function a0(){if(r0){var d0=HEAPU32[r0+28>>2],m0=HEAPU32[r0+32>>2];if(d0&&m0){var _0=HEAP8.slice(d0,d0+m0);return r.loadAsync?Promise.resolve(_0):_0}}var f0=locateFile(e);if(r.loadAsync)return asyncLoad(f0);if(!readBinary)throw new Error(`${f0}: file not found, and synchronous loading of external files is not available`);return readBinary(f0)}function i0(){var d0=preloadedWasm[e];return d0?r.loadAsync?Promise.resolve(d0):d0:r.loadAsync?a0().then(m0=>loadWebAssemblyModule(m0,r,e,M,r0)):loadWebAssemblyModule(a0(),r,e,M,r0)}function u0(d0){s0.global?mergeLibSymbols(d0):M&&Object.assign(M,d0),s0.exports=d0}return r.loadAsync?i0().then(d0=>(u0(d0),!0)):(u0(i0()),!0)}var reportUndefinedSymbols=()=>{for(var[e,r]of Object.entries(GOT))if(r.value==0){var M=resolveGlobalSymbol(e,!0).sym;if(!M&&!r.required)continue;if(typeof M=="function")r.value=addFunction(M,M.sig);else if(typeof M=="number")r.value=M;else throw new Error(`bad export type for '${e}': ${typeof M}`)}},loadDylibs=()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency(),dynamicLibraries.reduce((e,r)=>e.then(()=>loadDynamicLibrary(r,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0})),Promise.resolve()).then(()=>{reportUndefinedSymbols(),removeRunDependency()})},noExitRuntime=Module.noExitRuntime||!0;function setValue(e,r,M="i8"){switch(M.endsWith("*")&&(M="*"),M){case"i1":HEAP8[e]=r;break;case"i8":HEAP8[e]=r;break;case"i16":HEAP16[e>>1]=r;break;case"i32":HEAP32[e>>2]=r;break;case"i64":HEAP64[e>>3]=BigInt(r);break;case"float":HEAPF32[e>>2]=r;break;case"double":HEAPF64[e>>3]=r;break;case"*":HEAPU32[e>>2]=r;break;default:abort(`invalid type for setValue: ${M}`)}}var ___assert_fail=(e,r,M,r0)=>abort(`Assertion failed: ${UTF8ToString(e)}, at: `+[r?UTF8ToString(r):"unknown filename",M,r0?UTF8ToString(r0):"unknown function"]);___assert_fail.sig="vppip";var ___call_sighandler=(e,r)=>getWasmTableEntry(e)(r);___call_sighandler.sig="vpi";var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024);Module.___memory_base=___memory_base;var ___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},2765600);Module.___stack_pointer=___stack_pointer;var PATH={isAbs:e=>e.charAt(0)==="/",splitPath:e=>{var r=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return r.exec(e).slice(1)},normalizeArray:(e,r)=>{for(var M=0,r0=e.length-1;r0>=0;r0--){var s0=e[r0];s0==="."?e.splice(r0,1):s0===".."?(e.splice(r0,1),M++):M&&(e.splice(r0,1),M--)}if(r)for(;M;M--)e.unshift("..");return e},normalize:e=>{var r=PATH.isAbs(e),M=e.substr(-1)==="/";return e=PATH.normalizeArray(e.split("/").filter(r0=>!!r0),!r).join("/"),!e&&!r&&(e="."),e&&M&&(e+="/"),(r?"/":"")+e},dirname:e=>{var r=PATH.splitPath(e),M=r[0],r0=r[1];return!M&&!r0?".":(r0&&(r0=r0.substr(0,r0.length-1)),M+r0)},basename:e=>{if(e==="/")return"/";e=PATH.normalize(e),e=e.replace(/\/$/,"");var r=e.lastIndexOf("/");return r===-1?e:e.substr(r+1)},join:(...e)=>PATH.normalize(e.join("/")),join2:(e,r)=>PATH.normalize(e+"/"+r)},initRandomFill=()=>{if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function")return r0=>crypto.getRandomValues(r0);if(ENVIRONMENT_IS_NODE)try{var e=require("crypto"),r=e.randomFillSync;if(r)return r0=>e.randomFillSync(r0);var M=e.randomBytes;return r0=>(r0.set(M(r0.byteLength)),r0)}catch{}abort("initRandomDevice")},randomFill=e=>(randomFill=initRandomFill())(e),PATH_FS={resolve:(...e)=>{for(var r="",M=!1,r0=e.length-1;r0>=-1&&!M;r0--){var s0=r0>=0?e[r0]:FS.cwd();if(typeof s0!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!s0)return"";r=s0+"/"+r,M=PATH.isAbs(s0)}return r=PATH.normalizeArray(r.split("/").filter(a0=>!!a0),!M).join("/"),(M?"/":"")+r||"."},relative:(e,r)=>{e=PATH_FS.resolve(e).substr(1),r=PATH_FS.resolve(r).substr(1);function M(m0){for(var _0=0;_0=0&&m0[f0]==="";f0--);return _0>f0?[]:m0.slice(_0,f0-_0+1)}for(var r0=M(e.split("/")),s0=M(r.split("/")),a0=Math.min(r0.length,s0.length),i0=a0,u0=0;u0{for(var r=0,M=0;M=55296&&r0<=57343?(r+=4,++M):r+=3}return r},stringToUTF8Array=(e,r,M,r0)=>{if(!(r0>0))return 0;for(var s0=M,a0=M+r0-1,i0=0;i0=55296&&u0<=57343){var d0=e.charCodeAt(++i0);u0=65536+((u0&1023)<<10)|d0&1023}if(u0<=127){if(M>=a0)break;r[M++]=u0}else if(u0<=2047){if(M+1>=a0)break;r[M++]=192|u0>>6,r[M++]=128|u0&63}else if(u0<=65535){if(M+2>=a0)break;r[M++]=224|u0>>12,r[M++]=128|u0>>6&63,r[M++]=128|u0&63}else{if(M+3>=a0)break;r[M++]=240|u0>>18,r[M++]=128|u0>>12&63,r[M++]=128|u0>>6&63,r[M++]=128|u0&63}}return r[M]=0,M-s0};function intArrayFromString(e,r,M){var r0=lengthBytesUTF8(e)+1,s0=new Array(r0),a0=stringToUTF8Array(e,s0,0,s0.length);return s0.length=a0,s0}var FS_stdin_getChar=()=>{if(!FS_stdin_getChar_buffer.length){var e=null;if(ENVIRONMENT_IS_NODE){var r=256,M=Buffer.alloc(r),r0=0,s0=process.stdin.fd;try{r0=fs.readSync(s0,M,0,r)}catch(a0){if(a0.toString().includes("EOF"))r0=0;else throw a0}r0>0&&(e=M.slice(0,r0).toString("utf-8"))}else typeof window<"u"&&typeof window.prompt=="function"&&(e=window.prompt("Input: "),e!==null&&(e+=` +`));if(!e)return null;FS_stdin_getChar_buffer=intArrayFromString(e)}return FS_stdin_getChar_buffer.shift()},TTY={ttys:[],init(){},shutdown(){},register(e,r){TTY.ttys[e]={input:[],output:[],ops:r},FS.registerDevice(e,TTY.stream_ops)},stream_ops:{open(e){var r=TTY.ttys[e.node.rdev];if(!r)throw new FS.ErrnoError(43);e.tty=r,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,r,M,r0,s0){if(!e.tty||!e.tty.ops.get_char)throw new FS.ErrnoError(60);for(var a0=0,i0=0;i00&&(out(UTF8ArrayToString(e.output)),e.output=[])},ioctl_tcgets(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(e,r,M){return 0},ioctl_tiocgwinsz(e){return[24,80]}},default_tty1_ops:{put_char(e,r){r===null||r===10?(err(UTF8ArrayToString(e.output)),e.output=[]):r!=0&&e.output.push(r)},fsync(e){e.output&&e.output.length>0&&(err(UTF8ArrayToString(e.output)),e.output=[])}}},zeroMemory=(e,r)=>{HEAPU8.fill(0,e,e+r)},mmapAlloc=e=>{e=alignMemory(e,65536);var r=_emscripten_builtin_memalign(65536,e);return r&&zeroMemory(r,e),r},MEMFS={ops_table:null,mount(e){return MEMFS.createNode(null,"/",16895,0)},createNode(e,r,M,r0){if(FS.isBlkdev(M)||FS.isFIFO(M))throw new FS.ErrnoError(63);MEMFS.ops_table||(MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}});var s0=FS.createNode(e,r,M,r0);return FS.isDir(s0.mode)?(s0.node_ops=MEMFS.ops_table.dir.node,s0.stream_ops=MEMFS.ops_table.dir.stream,s0.contents={}):FS.isFile(s0.mode)?(s0.node_ops=MEMFS.ops_table.file.node,s0.stream_ops=MEMFS.ops_table.file.stream,s0.usedBytes=0,s0.contents=null):FS.isLink(s0.mode)?(s0.node_ops=MEMFS.ops_table.link.node,s0.stream_ops=MEMFS.ops_table.link.stream):FS.isChrdev(s0.mode)&&(s0.node_ops=MEMFS.ops_table.chrdev.node,s0.stream_ops=MEMFS.ops_table.chrdev.stream),s0.atime=s0.mtime=s0.ctime=Date.now(),e&&(e.contents[r]=s0,e.atime=e.mtime=e.ctime=s0.atime),s0},getFileDataAsTypedArray(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array(0)},expandFileStorage(e,r){var M=e.contents?e.contents.length:0;if(!(M>=r)){var r0=1048576;r=Math.max(r,M*(M>>0),M!=0&&(r=Math.max(r,256));var s0=e.contents;e.contents=new Uint8Array(r),e.usedBytes>0&&e.contents.set(s0.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,r){if(e.usedBytes!=r)if(r==0)e.contents=null,e.usedBytes=0;else{var M=e.contents;e.contents=new Uint8Array(r),M&&e.contents.set(M.subarray(0,Math.min(r,e.usedBytes))),e.usedBytes=r}},node_ops:{getattr(e){var r={};return r.dev=FS.isChrdev(e.mode)?e.id:1,r.ino=e.id,r.mode=e.mode,r.nlink=1,r.uid=0,r.gid=0,r.rdev=e.rdev,FS.isDir(e.mode)?r.size=4096:FS.isFile(e.mode)?r.size=e.usedBytes:FS.isLink(e.mode)?r.size=e.link.length:r.size=0,r.atime=new Date(e.atime),r.mtime=new Date(e.mtime),r.ctime=new Date(e.ctime),r.blksize=4096,r.blocks=Math.ceil(r.size/r.blksize),r},setattr(e,r){for(let M of["mode","atime","mtime","ctime"])r[M]&&(e[M]=r[M]);r.size!==void 0&&MEMFS.resizeFileStorage(e,r.size)},lookup(e,r){throw MEMFS.doesNotExistError},mknod(e,r,M,r0){return MEMFS.createNode(e,r,M,r0)},rename(e,r,M){var r0;try{r0=FS.lookupNode(r,M)}catch{}if(r0){if(FS.isDir(e.mode))for(var s0 in r0.contents)throw new FS.ErrnoError(55);FS.hashRemoveNode(r0)}delete e.parent.contents[e.name],r.contents[M]=e,e.name=M,r.ctime=r.mtime=e.parent.ctime=e.parent.mtime=Date.now()},unlink(e,r){delete e.contents[r],e.ctime=e.mtime=Date.now()},rmdir(e,r){var M=FS.lookupNode(e,r);for(var r0 in M.contents)throw new FS.ErrnoError(55);delete e.contents[r],e.ctime=e.mtime=Date.now()},readdir(e){return[".","..",...Object.keys(e.contents)]},symlink(e,r,M){var r0=MEMFS.createNode(e,r,41471,0);return r0.link=M,r0},readlink(e){if(!FS.isLink(e.mode))throw new FS.ErrnoError(28);return e.link}},stream_ops:{read(e,r,M,r0,s0){var a0=e.node.contents;if(s0>=e.node.usedBytes)return 0;var i0=Math.min(e.node.usedBytes-s0,r0);if(i0>8&&a0.subarray)r.set(a0.subarray(s0,s0+i0),M);else for(var u0=0;u00||M+r{FS.createDataFile(e,r,M,r0,s0,a0)},FS_handledByPreloadPlugin=(e,r,M,r0)=>{typeof Browser<"u"&&Browser.init();var s0=!1;return preloadPlugins.forEach(a0=>{s0||a0.canHandle(r)&&(a0.handle(e,r,M,r0),s0=!0)}),s0},FS_createPreloadedFile=(e,r,M,r0,s0,a0,i0,u0,d0,m0)=>{var _0=r?PATH_FS.resolve(PATH.join2(e,r)):e;function f0(g0){function x0(k0){m0==null||m0(),u0||FS_createDataFile(e,r,k0,r0,s0,d0),a0==null||a0(),removeRunDependency()}FS_handledByPreloadPlugin(g0,_0,x0,()=>{i0==null||i0(),removeRunDependency()})||x0(g0)}addRunDependency(),typeof M=="string"?asyncLoad(M).then(f0,i0):f0(M)},FS_modeStringToFlags=e=>{var r={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090},M=r[e];if(typeof M>"u")throw new Error(`Unknown file open mode: ${e}`);return M},FS_getMode=(e,r)=>{var M=0;return e&&(M|=365),r&&(M|=146),M},IDBFS={dbs:{},indexedDB:()=>{if(typeof indexedDB<"u")return indexedDB;var e=null;return typeof window=="object"&&(e=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB),e},DB_VERSION:21,DB_STORE_NAME:"FILE_DATA",queuePersist:e=>{function r(){e.idbPersistState==="again"?M():e.idbPersistState=0}function M(){e.idbPersistState="idb",IDBFS.syncfs(e,!1,r)}e.idbPersistState?e.idbPersistState==="idb"&&(e.idbPersistState="again"):e.idbPersistState=setTimeout(M,0)},mount:e=>{var r0;var r=MEMFS.mount(e);if((r0=e==null?void 0:e.opts)!=null&&r0.autoPersist){r.idbPersistState=0;var M=r.node_ops;r.node_ops=Object.assign({},r.node_ops),r.node_ops.mknod=(s0,a0,i0,u0)=>{var d0=M.mknod(s0,a0,i0,u0);return d0.node_ops=r.node_ops,d0.idbfs_mount=r.mount,d0.memfs_stream_ops=d0.stream_ops,d0.stream_ops=Object.assign({},d0.stream_ops),d0.stream_ops.write=(m0,_0,f0,g0,x0,k0)=>(m0.node.isModified=!0,d0.memfs_stream_ops.write(m0,_0,f0,g0,x0,k0)),d0.stream_ops.close=m0=>{var _0=m0.node;if(_0.isModified&&(IDBFS.queuePersist(_0.idbfs_mount),_0.isModified=!1),_0.memfs_stream_ops.close)return _0.memfs_stream_ops.close(m0)},d0},r.node_ops.mkdir=(...s0)=>(IDBFS.queuePersist(r.mount),M.mkdir(...s0)),r.node_ops.rmdir=(...s0)=>(IDBFS.queuePersist(r.mount),M.rmdir(...s0)),r.node_ops.symlink=(...s0)=>(IDBFS.queuePersist(r.mount),M.symlink(...s0)),r.node_ops.unlink=(...s0)=>(IDBFS.queuePersist(r.mount),M.unlink(...s0)),r.node_ops.rename=(...s0)=>(IDBFS.queuePersist(r.mount),M.rename(...s0))}return r},syncfs:(e,r,M)=>{IDBFS.getLocalSet(e,(r0,s0)=>{if(r0)return M(r0);IDBFS.getRemoteSet(e,(a0,i0)=>{if(a0)return M(a0);var u0=r?i0:s0,d0=r?s0:i0;IDBFS.reconcile(u0,d0,M)})})},quit:()=>{Object.values(IDBFS.dbs).forEach(e=>e.close()),IDBFS.dbs={}},getDB:(e,r)=>{var M=IDBFS.dbs[e];if(M)return r(null,M);var r0;try{r0=IDBFS.indexedDB().open(e,IDBFS.DB_VERSION)}catch(s0){return r(s0)}if(!r0)return r("Unable to connect to IndexedDB");r0.onupgradeneeded=s0=>{var a0=s0.target.result,i0=s0.target.transaction,u0;a0.objectStoreNames.contains(IDBFS.DB_STORE_NAME)?u0=i0.objectStore(IDBFS.DB_STORE_NAME):u0=a0.createObjectStore(IDBFS.DB_STORE_NAME),u0.indexNames.contains("timestamp")||u0.createIndex("timestamp","timestamp",{unique:!1})},r0.onsuccess=()=>{M=r0.result,IDBFS.dbs[e]=M,r(null,M)},r0.onerror=s0=>{r(s0.target.error),s0.preventDefault()}},getLocalSet:(e,r)=>{var M={};function r0(d0){return d0!=="."&&d0!==".."}function s0(d0){return m0=>PATH.join2(d0,m0)}for(var a0=FS.readdir(e.mountpoint).filter(r0).map(s0(e.mountpoint));a0.length;){var i0=a0.pop(),u0;try{u0=FS.stat(i0)}catch(d0){return r(d0)}FS.isDir(u0.mode)&&a0.push(...FS.readdir(i0).filter(r0).map(s0(i0))),M[i0]={timestamp:u0.mtime}}return r(null,{type:"local",entries:M})},getRemoteSet:(e,r)=>{var M={};IDBFS.getDB(e.mountpoint,(r0,s0)=>{if(r0)return r(r0);try{var a0=s0.transaction([IDBFS.DB_STORE_NAME],"readonly");a0.onerror=d0=>{r(d0.target.error),d0.preventDefault()};var i0=a0.objectStore(IDBFS.DB_STORE_NAME),u0=i0.index("timestamp");u0.openKeyCursor().onsuccess=d0=>{var m0=d0.target.result;if(!m0)return r(null,{type:"remote",db:s0,entries:M});M[m0.primaryKey]={timestamp:m0.key},m0.continue()}}catch(d0){return r(d0)}})},loadLocalEntry:(e,r)=>{var M,r0;try{var s0=FS.lookupPath(e);r0=s0.node,M=FS.stat(e)}catch(a0){return r(a0)}return FS.isDir(M.mode)?r(null,{timestamp:M.mtime,mode:M.mode}):FS.isFile(M.mode)?(r0.contents=MEMFS.getFileDataAsTypedArray(r0),r(null,{timestamp:M.mtime,mode:M.mode,contents:r0.contents})):r(new Error("node type not supported"))},storeLocalEntry:(e,r,M)=>{try{if(FS.isDir(r.mode))FS.mkdirTree(e,r.mode);else if(FS.isFile(r.mode))FS.writeFile(e,r.contents,{canOwn:!0});else return M(new Error("node type not supported"));FS.chmod(e,r.mode),FS.utime(e,r.timestamp,r.timestamp)}catch(r0){return M(r0)}M(null)},removeLocalEntry:(e,r)=>{try{var M=FS.stat(e);FS.isDir(M.mode)?FS.rmdir(e):FS.isFile(M.mode)&&FS.unlink(e)}catch(r0){return r(r0)}r(null)},loadRemoteEntry:(e,r,M)=>{var r0=e.get(r);r0.onsuccess=s0=>M(null,s0.target.result),r0.onerror=s0=>{M(s0.target.error),s0.preventDefault()}},storeRemoteEntry:(e,r,M,r0)=>{try{var s0=e.put(M,r)}catch(a0){r0(a0);return}s0.onsuccess=a0=>r0(),s0.onerror=a0=>{r0(a0.target.error),a0.preventDefault()}},removeRemoteEntry:(e,r,M)=>{var r0=e.delete(r);r0.onsuccess=s0=>M(),r0.onerror=s0=>{M(s0.target.error),s0.preventDefault()}},reconcile:(e,r,M)=>{var r0=0,s0=[];Object.keys(e.entries).forEach(f0=>{var g0=e.entries[f0],x0=r.entries[f0];(!x0||g0.timestamp.getTime()!=x0.timestamp.getTime())&&(s0.push(f0),r0++)});var a0=[];if(Object.keys(r.entries).forEach(f0=>{e.entries[f0]||(a0.push(f0),r0++)}),!r0)return M(null);var i0=!1,u0=e.type==="remote"?e.db:r.db,d0=u0.transaction([IDBFS.DB_STORE_NAME],"readwrite"),m0=d0.objectStore(IDBFS.DB_STORE_NAME);function _0(f0){if(f0&&!i0)return i0=!0,M(f0)}d0.onerror=d0.onabort=f0=>{_0(f0.target.error),f0.preventDefault()},d0.oncomplete=f0=>{i0||M(null)},s0.sort().forEach(f0=>{r.type==="local"?IDBFS.loadRemoteEntry(m0,f0,(g0,x0)=>{if(g0)return _0(g0);IDBFS.storeLocalEntry(f0,x0,_0)}):IDBFS.loadLocalEntry(f0,(g0,x0)=>{if(g0)return _0(g0);IDBFS.storeRemoteEntry(m0,f0,x0,_0)})}),a0.sort().reverse().forEach(f0=>{r.type==="local"?IDBFS.removeLocalEntry(f0,_0):IDBFS.removeRemoteEntry(m0,f0,_0)})}},ERRNO_CODES={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135},NODEFS={isWindows:!1,staticInit(){NODEFS.isWindows=!!process.platform.match(/^win/);var e=process.binding("constants");e.fs&&(e=e.fs),NODEFS.flagsForNodeMap={1024:e.O_APPEND,64:e.O_CREAT,128:e.O_EXCL,256:e.O_NOCTTY,0:e.O_RDONLY,2:e.O_RDWR,4096:e.O_SYNC,512:e.O_TRUNC,1:e.O_WRONLY,131072:e.O_NOFOLLOW}},convertNodeCode(e){var r=e.code;return ERRNO_CODES[r]},tryFSOperation(e){try{return e()}catch(r){throw r.code?r.code==="UNKNOWN"?new FS.ErrnoError(28):new FS.ErrnoError(NODEFS.convertNodeCode(r)):r}},mount(e){return NODEFS.createNode(null,"/",NODEFS.getMode(e.opts.root),0)},createNode(e,r,M,r0){if(!FS.isDir(M)&&!FS.isFile(M)&&!FS.isLink(M))throw new FS.ErrnoError(28);var s0=FS.createNode(e,r,M);return s0.node_ops=NODEFS.node_ops,s0.stream_ops=NODEFS.stream_ops,s0},getMode(e){return NODEFS.tryFSOperation(()=>{var r=fs.lstatSync(e).mode;return NODEFS.isWindows&&(r|=(r&292)>>2),r})},realPath(e){for(var r=[];e.parent!==e;)r.push(e.name),e=e.parent;return r.push(e.mount.opts.root),r.reverse(),PATH.join(...r)},flagsForNode(e){e&=-2097153,e&=-2049,e&=-32769,e&=-524289,e&=-65537;var r=0;for(var M in NODEFS.flagsForNodeMap)e&M&&(r|=NODEFS.flagsForNodeMap[M],e^=M);if(e)throw new FS.ErrnoError(28);return r},node_ops:{getattr(e){var r=NODEFS.realPath(e),M;return NODEFS.tryFSOperation(()=>M=fs.lstatSync(r)),NODEFS.isWindows&&(M.blksize||(M.blksize=4096),M.blocks||(M.blocks=(M.size+M.blksize-1)/M.blksize|0),M.mode|=(M.mode&292)>>2),{dev:M.dev,ino:M.ino,mode:M.mode,nlink:M.nlink,uid:M.uid,gid:M.gid,rdev:M.rdev,size:M.size,atime:M.atime,mtime:M.mtime,ctime:M.ctime,blksize:M.blksize,blocks:M.blocks}},setattr(e,r){var M=NODEFS.realPath(e);NODEFS.tryFSOperation(()=>{if(r.mode!==void 0){var r0=r.mode;NODEFS.isWindows&&(r0&=384),fs.chmodSync(M,r0),e.mode=r.mode}if(r.atime||r.mtime){var s0=r.atime&&new Date(r.atime),a0=r.mtime&&new Date(r.mtime);fs.utimesSync(M,s0,a0)}r.size!==void 0&&fs.truncateSync(M,r.size)})},lookup(e,r){var M=PATH.join2(NODEFS.realPath(e),r),r0=NODEFS.getMode(M);return NODEFS.createNode(e,r,r0)},mknod(e,r,M,r0){var s0=NODEFS.createNode(e,r,M,r0),a0=NODEFS.realPath(s0);return NODEFS.tryFSOperation(()=>{FS.isDir(s0.mode)?fs.mkdirSync(a0,s0.mode):fs.writeFileSync(a0,"",{mode:s0.mode})}),s0},rename(e,r,M){var r0=NODEFS.realPath(e),s0=PATH.join2(NODEFS.realPath(r),M);try{FS.unlink(s0)}catch{}NODEFS.tryFSOperation(()=>fs.renameSync(r0,s0)),e.name=M},unlink(e,r){var M=PATH.join2(NODEFS.realPath(e),r);NODEFS.tryFSOperation(()=>fs.unlinkSync(M))},rmdir(e,r){var M=PATH.join2(NODEFS.realPath(e),r);NODEFS.tryFSOperation(()=>fs.rmdirSync(M))},readdir(e){var r=NODEFS.realPath(e);return NODEFS.tryFSOperation(()=>fs.readdirSync(r))},symlink(e,r,M){var r0=PATH.join2(NODEFS.realPath(e),r);NODEFS.tryFSOperation(()=>fs.symlinkSync(M,r0))},readlink(e){var r=NODEFS.realPath(e);return NODEFS.tryFSOperation(()=>fs.readlinkSync(r))},statfs(e){var r=NODEFS.tryFSOperation(()=>fs.statfsSync(e));return r.frsize=r.bsize,r}},stream_ops:{open(e){var r=NODEFS.realPath(e.node);NODEFS.tryFSOperation(()=>{FS.isFile(e.node.mode)&&(e.shared.refcount=1,e.nfd=fs.openSync(r,NODEFS.flagsForNode(e.flags)))})},close(e){NODEFS.tryFSOperation(()=>{FS.isFile(e.node.mode)&&e.nfd&&--e.shared.refcount===0&&fs.closeSync(e.nfd)})},dup(e){e.shared.refcount++},read(e,r,M,r0,s0){return r0===0?0:NODEFS.tryFSOperation(()=>fs.readSync(e.nfd,new Int8Array(r.buffer,M,r0),0,r0,s0))},write(e,r,M,r0,s0){return NODEFS.tryFSOperation(()=>fs.writeSync(e.nfd,new Int8Array(r.buffer,M,r0),0,r0,s0))},llseek(e,r,M){var r0=r;if(M===1?r0+=e.position:M===2&&FS.isFile(e.node.mode)&&NODEFS.tryFSOperation(()=>{var s0=fs.fstatSync(e.nfd);r0+=s0.size}),r0<0)throw new FS.ErrnoError(28);return r0},mmap(e,r,M,r0,s0){if(!FS.isFile(e.node.mode))throw new FS.ErrnoError(43);var a0=mmapAlloc(r);return NODEFS.stream_ops.read(e,HEAP8,a0,r,M),{ptr:a0,allocated:!0}},msync(e,r,M,r0,s0){return NODEFS.stream_ops.write(e,r,0,r0,M,!1),0}}},FS={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:class{constructor(e){P$1(this,"name","ErrnoError"),this.errno=e}},filesystems:null,syncFSRequests:0,readFiles:{},FSStream:class{constructor(){P$1(this,"shared",{})}get object(){return this.node}set object(e){this.node=e}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(e){this.shared.flags=e}get position(){return this.shared.position}set position(e){this.shared.position=e}},FSNode:class{constructor(e,r,M,r0){P$1(this,"node_ops",{}),P$1(this,"stream_ops",{}),P$1(this,"readMode",365),P$1(this,"writeMode",146),P$1(this,"mounted",null),e||(e=this),this.parent=e,this.mount=e.mount,this.id=FS.nextInode++,this.name=r,this.mode=M,this.rdev=r0,this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(e){e?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(e){e?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return FS.isDir(this.mode)}get isDevice(){return FS.isChrdev(this.mode)}},lookupPath(e,r={}){if(!e)return{path:"",node:null};r.follow_mount??(r.follow_mount=!0),PATH.isAbs(e)||(e=FS.cwd()+"/"+e);e:for(var M=0;M<40;M++){for(var r0=e.split("/").filter(m0=>!!m0&&m0!=="."),s0=FS.root,a0="/",i0=0;i0>>0)%FS.nameTable.length},hashAddNode(e){var r=FS.hashName(e.parent.id,e.name);e.name_next=FS.nameTable[r],FS.nameTable[r]=e},hashRemoveNode(e){var r=FS.hashName(e.parent.id,e.name);if(FS.nameTable[r]===e)FS.nameTable[r]=e.name_next;else for(var M=FS.nameTable[r];M;){if(M.name_next===e){M.name_next=e.name_next;break}M=M.name_next}},lookupNode(e,r){var M=FS.mayLookup(e);if(M)throw new FS.ErrnoError(M);for(var r0=FS.hashName(e.id,r),s0=FS.nameTable[r0];s0;s0=s0.name_next){var a0=s0.name;if(s0.parent.id===e.id&&a0===r)return s0}return FS.lookup(e,r)},createNode(e,r,M,r0){var s0=new FS.FSNode(e,r,M,r0);return FS.hashAddNode(s0),s0},destroyNode(e){FS.hashRemoveNode(e)},isRoot(e){return e===e.parent},isMountpoint(e){return!!e.mounted},isFile(e){return(e&61440)===32768},isDir(e){return(e&61440)===16384},isLink(e){return(e&61440)===40960},isChrdev(e){return(e&61440)===8192},isBlkdev(e){return(e&61440)===24576},isFIFO(e){return(e&61440)===4096},isSocket(e){return(e&49152)===49152},flagsToPermissionString(e){var r=["r","w","rw"][e&3];return e&512&&(r+="w"),r},nodePermissions(e,r){return FS.ignorePermissions?0:r.includes("r")&&!(e.mode&292)||r.includes("w")&&!(e.mode&146)||r.includes("x")&&!(e.mode&73)?2:0},mayLookup(e){if(!FS.isDir(e.mode))return 54;var r=FS.nodePermissions(e,"x");return r||(e.node_ops.lookup?0:2)},mayCreate(e,r){if(!FS.isDir(e.mode))return 54;try{var M=FS.lookupNode(e,r);return 20}catch{}return FS.nodePermissions(e,"wx")},mayDelete(e,r,M){var r0;try{r0=FS.lookupNode(e,r)}catch(a0){return a0.errno}var s0=FS.nodePermissions(e,"wx");if(s0)return s0;if(M){if(!FS.isDir(r0.mode))return 54;if(FS.isRoot(r0)||FS.getPath(r0)===FS.cwd())return 10}else if(FS.isDir(r0.mode))return 31;return 0},mayOpen(e,r){return e?FS.isLink(e.mode)?32:FS.isDir(e.mode)&&(FS.flagsToPermissionString(r)!=="r"||r&512)?31:FS.nodePermissions(e,FS.flagsToPermissionString(r)):44},MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=FS.MAX_OPEN_FDS;e++)if(!FS.streams[e])return e;throw new FS.ErrnoError(33)},getStreamChecked(e){var r=FS.getStream(e);if(!r)throw new FS.ErrnoError(8);return r},getStream:e=>FS.streams[e],createStream(e,r=-1){return e=Object.assign(new FS.FSStream,e),r==-1&&(r=FS.nextfd()),e.fd=r,FS.streams[r]=e,e},closeStream(e){FS.streams[e]=null},dupStream(e,r=-1){var r0,s0;var M=FS.createStream(e,r);return(s0=(r0=M.stream_ops)==null?void 0:r0.dup)==null||s0.call(r0,M),M},chrdev_stream_ops:{open(e){var M,r0;var r=FS.getDevice(e.node.rdev);e.stream_ops=r.stream_ops,(r0=(M=e.stream_ops).open)==null||r0.call(M,e)},llseek(){throw new FS.ErrnoError(70)}},major:e=>e>>8,minor:e=>e&255,makedev:(e,r)=>e<<8|r,registerDevice(e,r){FS.devices[e]={stream_ops:r}},getDevice:e=>FS.devices[e],getMounts(e){for(var r=[],M=[e];M.length;){var r0=M.pop();r.push(r0),M.push(...r0.mounts)}return r},syncfs(e,r){typeof e=="function"&&(r=e,e=!1),FS.syncFSRequests++,FS.syncFSRequests>1&&err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var M=FS.getMounts(FS.root.mount),r0=0;function s0(i0){return FS.syncFSRequests--,r(i0)}function a0(i0){if(i0)return a0.errored?void 0:(a0.errored=!0,s0(i0));++r0>=M.length&&s0(null)}M.forEach(i0=>{if(!i0.type.syncfs)return a0(null);i0.type.syncfs(i0,e,a0)})},mount(e,r,M){var r0=M==="/",s0=!M,a0;if(r0&&FS.root)throw new FS.ErrnoError(10);if(!r0&&!s0){var i0=FS.lookupPath(M,{follow_mount:!1});if(M=i0.path,a0=i0.node,FS.isMountpoint(a0))throw new FS.ErrnoError(10);if(!FS.isDir(a0.mode))throw new FS.ErrnoError(54)}var u0={type:e,opts:r,mountpoint:M,mounts:[]},d0=e.mount(u0);return d0.mount=u0,u0.root=d0,r0?FS.root=d0:a0&&(a0.mounted=u0,a0.mount&&a0.mount.mounts.push(u0)),d0},unmount(e){var r=FS.lookupPath(e,{follow_mount:!1});if(!FS.isMountpoint(r.node))throw new FS.ErrnoError(28);var M=r.node,r0=M.mounted,s0=FS.getMounts(r0);Object.keys(FS.nameTable).forEach(i0=>{for(var u0=FS.nameTable[i0];u0;){var d0=u0.name_next;s0.includes(u0.mount)&&FS.destroyNode(u0),u0=d0}}),M.mounted=null;var a0=M.mount.mounts.indexOf(r0);M.mount.mounts.splice(a0,1)},lookup(e,r){return e.node_ops.lookup(e,r)},mknod(e,r,M){var r0=FS.lookupPath(e,{parent:!0}),s0=r0.node,a0=PATH.basename(e);if(!a0||a0==="."||a0==="..")throw new FS.ErrnoError(28);var i0=FS.mayCreate(s0,a0);if(i0)throw new FS.ErrnoError(i0);if(!s0.node_ops.mknod)throw new FS.ErrnoError(63);return s0.node_ops.mknod(s0,a0,r,M)},statfs(e){var r={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:FS.nextInode,ffree:FS.nextInode-1,fsid:42,flags:2,namelen:255},M=FS.lookupPath(e,{follow:!0}).node;return M!=null&&M.node_ops.statfs&&Object.assign(r,M.node_ops.statfs(M.mount.opts.root)),r},create(e,r=438){return r&=4095,r|=32768,FS.mknod(e,r,0)},mkdir(e,r=511){return r&=1023,r|=16384,FS.mknod(e,r,0)},mkdirTree(e,r){for(var M=e.split("/"),r0="",s0=0;s0"u"&&(M=r,r=438),r|=8192,FS.mknod(e,r,M)},symlink(e,r){if(!PATH_FS.resolve(e))throw new FS.ErrnoError(44);var M=FS.lookupPath(r,{parent:!0}),r0=M.node;if(!r0)throw new FS.ErrnoError(44);var s0=PATH.basename(r),a0=FS.mayCreate(r0,s0);if(a0)throw new FS.ErrnoError(a0);if(!r0.node_ops.symlink)throw new FS.ErrnoError(63);return r0.node_ops.symlink(r0,s0,e)},rename(e,r){var M=PATH.dirname(e),r0=PATH.dirname(r),s0=PATH.basename(e),a0=PATH.basename(r),i0,u0,d0;if(i0=FS.lookupPath(e,{parent:!0}),u0=i0.node,i0=FS.lookupPath(r,{parent:!0}),d0=i0.node,!u0||!d0)throw new FS.ErrnoError(44);if(u0.mount!==d0.mount)throw new FS.ErrnoError(75);var m0=FS.lookupNode(u0,s0),_0=PATH_FS.relative(e,r0);if(_0.charAt(0)!==".")throw new FS.ErrnoError(28);if(_0=PATH_FS.relative(r,M),_0.charAt(0)!==".")throw new FS.ErrnoError(55);var f0;try{f0=FS.lookupNode(d0,a0)}catch{}if(m0!==f0){var g0=FS.isDir(m0.mode),x0=FS.mayDelete(u0,s0,g0);if(x0)throw new FS.ErrnoError(x0);if(x0=f0?FS.mayDelete(d0,a0,g0):FS.mayCreate(d0,a0),x0)throw new FS.ErrnoError(x0);if(!u0.node_ops.rename)throw new FS.ErrnoError(63);if(FS.isMountpoint(m0)||f0&&FS.isMountpoint(f0))throw new FS.ErrnoError(10);if(d0!==u0&&(x0=FS.nodePermissions(u0,"w"),x0))throw new FS.ErrnoError(x0);FS.hashRemoveNode(m0);try{u0.node_ops.rename(m0,d0,a0),m0.parent=d0}catch(k0){throw k0}finally{FS.hashAddNode(m0)}}},rmdir(e){var r=FS.lookupPath(e,{parent:!0}),M=r.node,r0=PATH.basename(e),s0=FS.lookupNode(M,r0),a0=FS.mayDelete(M,r0,!0);if(a0)throw new FS.ErrnoError(a0);if(!M.node_ops.rmdir)throw new FS.ErrnoError(63);if(FS.isMountpoint(s0))throw new FS.ErrnoError(10);M.node_ops.rmdir(M,r0),FS.destroyNode(s0)},readdir(e){var r=FS.lookupPath(e,{follow:!0}),M=r.node;if(!M.node_ops.readdir)throw new FS.ErrnoError(54);return M.node_ops.readdir(M)},unlink(e){var r=FS.lookupPath(e,{parent:!0}),M=r.node;if(!M)throw new FS.ErrnoError(44);var r0=PATH.basename(e),s0=FS.lookupNode(M,r0),a0=FS.mayDelete(M,r0,!1);if(a0)throw new FS.ErrnoError(a0);if(!M.node_ops.unlink)throw new FS.ErrnoError(63);if(FS.isMountpoint(s0))throw new FS.ErrnoError(10);M.node_ops.unlink(M,r0),FS.destroyNode(s0)},readlink(e){var r=FS.lookupPath(e),M=r.node;if(!M)throw new FS.ErrnoError(44);if(!M.node_ops.readlink)throw new FS.ErrnoError(28);return M.node_ops.readlink(M)},stat(e,r){var M=FS.lookupPath(e,{follow:!r}),r0=M.node;if(!r0)throw new FS.ErrnoError(44);if(!r0.node_ops.getattr)throw new FS.ErrnoError(63);return r0.node_ops.getattr(r0)},lstat(e){return FS.stat(e,!0)},chmod(e,r,M){var r0;if(typeof e=="string"){var s0=FS.lookupPath(e,{follow:!M});r0=s0.node}else r0=e;if(!r0.node_ops.setattr)throw new FS.ErrnoError(63);r0.node_ops.setattr(r0,{mode:r&4095|r0.mode&-4096,ctime:Date.now()})},lchmod(e,r){FS.chmod(e,r,!0)},fchmod(e,r){var M=FS.getStreamChecked(e);FS.chmod(M.node,r)},chown(e,r,M,r0){var s0;if(typeof e=="string"){var a0=FS.lookupPath(e,{follow:!r0});s0=a0.node}else s0=e;if(!s0.node_ops.setattr)throw new FS.ErrnoError(63);s0.node_ops.setattr(s0,{timestamp:Date.now()})},lchown(e,r,M){FS.chown(e,r,M,!0)},fchown(e,r,M){var r0=FS.getStreamChecked(e);FS.chown(r0.node,r,M)},truncate(e,r){if(r<0)throw new FS.ErrnoError(28);var M;if(typeof e=="string"){var r0=FS.lookupPath(e,{follow:!0});M=r0.node}else M=e;if(!M.node_ops.setattr)throw new FS.ErrnoError(63);if(FS.isDir(M.mode))throw new FS.ErrnoError(31);if(!FS.isFile(M.mode))throw new FS.ErrnoError(28);var s0=FS.nodePermissions(M,"w");if(s0)throw new FS.ErrnoError(s0);M.node_ops.setattr(M,{size:r,timestamp:Date.now()})},ftruncate(e,r){var M=FS.getStreamChecked(e);if(!(M.flags&2097155))throw new FS.ErrnoError(28);FS.truncate(M.node,r)},utime(e,r,M){var r0=FS.lookupPath(e,{follow:!0}),s0=r0.node;s0.node_ops.setattr(s0,{atime:r,mtime:M})},open(e,r,M=438){if(e==="")throw new FS.ErrnoError(44);r=typeof r=="string"?FS_modeStringToFlags(r):r,r&64?M=M&4095|32768:M=0;var r0;if(typeof e=="object")r0=e;else{var s0=FS.lookupPath(e,{follow:!(r&131072),noent_okay:!0});r0=s0.node,e=s0.path}var a0=!1;if(r&64)if(r0){if(r&128)throw new FS.ErrnoError(20)}else r0=FS.mknod(e,M,0),a0=!0;if(!r0)throw new FS.ErrnoError(44);if(FS.isChrdev(r0.mode)&&(r&=-513),r&65536&&!FS.isDir(r0.mode))throw new FS.ErrnoError(54);if(!a0){var i0=FS.mayOpen(r0,r);if(i0)throw new FS.ErrnoError(i0)}r&512&&!a0&&FS.truncate(r0,0),r&=-131713;var u0=FS.createStream({node:r0,path:FS.getPath(r0),flags:r,seekable:!0,position:0,stream_ops:r0.stream_ops,ungotten:[],error:!1});return u0.stream_ops.open&&u0.stream_ops.open(u0),Module.logReadFiles&&!(r&1)&&(e in FS.readFiles||(FS.readFiles[e]=1)),u0},close(e){if(FS.isClosed(e))throw new FS.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(r){throw r}finally{FS.closeStream(e.fd)}e.fd=null},isClosed(e){return e.fd===null},llseek(e,r,M){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new FS.ErrnoError(70);if(M!=0&&M!=1&&M!=2)throw new FS.ErrnoError(28);return e.position=e.stream_ops.llseek(e,r,M),e.ungotten=[],e.position},read(e,r,M,r0,s0){if(r0<0||s0<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if((e.flags&2097155)===1)throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.read)throw new FS.ErrnoError(28);var a0=typeof s0<"u";if(!a0)s0=e.position;else if(!e.seekable)throw new FS.ErrnoError(70);var i0=e.stream_ops.read(e,r,M,r0,s0);return a0||(e.position+=i0),i0},write(e,r,M,r0,s0,a0){if(r0<0||s0<0)throw new FS.ErrnoError(28);if(FS.isClosed(e))throw new FS.ErrnoError(8);if(!(e.flags&2097155))throw new FS.ErrnoError(8);if(FS.isDir(e.node.mode))throw new FS.ErrnoError(31);if(!e.stream_ops.write)throw new FS.ErrnoError(28);e.seekable&&e.flags&1024&&FS.llseek(e,0,2);var i0=typeof s0<"u";if(!i0)s0=e.position;else if(!e.seekable)throw new FS.ErrnoError(70);var u0=e.stream_ops.write(e,r,M,r0,s0,a0);return i0||(e.position+=u0),u0},allocate(e,r,M){if(FS.isClosed(e))throw new FS.ErrnoError(8);if(r<0||M<=0)throw new FS.ErrnoError(28);if(!(e.flags&2097155))throw new FS.ErrnoError(8);if(!FS.isFile(e.node.mode)&&!FS.isDir(e.node.mode))throw new FS.ErrnoError(43);if(!e.stream_ops.allocate)throw new FS.ErrnoError(138);e.stream_ops.allocate(e,r,M)},mmap(e,r,M,r0,s0){if(r0&2&&!(s0&2)&&(e.flags&2097155)!==2)throw new FS.ErrnoError(2);if((e.flags&2097155)===1)throw new FS.ErrnoError(2);if(!e.stream_ops.mmap)throw new FS.ErrnoError(43);if(!r)throw new FS.ErrnoError(28);return e.stream_ops.mmap(e,r,M,r0,s0)},msync(e,r,M,r0,s0){return e.stream_ops.msync?e.stream_ops.msync(e,r,M,r0,s0):0},ioctl(e,r,M){if(!e.stream_ops.ioctl)throw new FS.ErrnoError(59);return e.stream_ops.ioctl(e,r,M)},readFile(e,r={}){if(r.flags=r.flags||0,r.encoding=r.encoding||"binary",r.encoding!=="utf8"&&r.encoding!=="binary")throw new Error(`Invalid encoding type "${r.encoding}"`);var M,r0=FS.open(e,r.flags),s0=FS.stat(e),a0=s0.size,i0=new Uint8Array(a0);return FS.read(r0,i0,0,a0,0),r.encoding==="utf8"?M=UTF8ArrayToString(i0):r.encoding==="binary"&&(M=i0),FS.close(r0),M},writeFile(e,r,M={}){M.flags=M.flags||577;var r0=FS.open(e,M.flags,M.mode);if(typeof r=="string"){var s0=new Uint8Array(lengthBytesUTF8(r)+1),a0=stringToUTF8Array(r,s0,0,s0.length);FS.write(r0,s0,0,a0,void 0,M.canOwn)}else if(ArrayBuffer.isView(r))FS.write(r0,r,0,r.byteLength,void 0,M.canOwn);else throw new Error("Unsupported data type");FS.close(r0)},cwd:()=>FS.currentPath,chdir(e){var r=FS.lookupPath(e,{follow:!0});if(r.node===null)throw new FS.ErrnoError(44);if(!FS.isDir(r.node.mode))throw new FS.ErrnoError(54);var M=FS.nodePermissions(r.node,"x");if(M)throw new FS.ErrnoError(M);FS.currentPath=r.path},createDefaultDirectories(){FS.mkdir("/tmp"),FS.mkdir("/home"),FS.mkdir("/home/web_user")},createDefaultDevices(){FS.mkdir("/dev"),FS.registerDevice(FS.makedev(1,3),{read:()=>0,write:(r0,s0,a0,i0,u0)=>i0,llseek:()=>0}),FS.mkdev("/dev/null",FS.makedev(1,3)),TTY.register(FS.makedev(5,0),TTY.default_tty_ops),TTY.register(FS.makedev(6,0),TTY.default_tty1_ops),FS.mkdev("/dev/tty",FS.makedev(5,0)),FS.mkdev("/dev/tty1",FS.makedev(6,0));var e=new Uint8Array(1024),r=0,M=()=>(r===0&&(r=randomFill(e).byteLength),e[--r]);FS.createDevice("/dev","random",M),FS.createDevice("/dev","urandom",M),FS.mkdir("/dev/shm"),FS.mkdir("/dev/shm/tmp")},createSpecialDirectories(){FS.mkdir("/proc");var e=FS.mkdir("/proc/self");FS.mkdir("/proc/self/fd"),FS.mount({mount(){var r=FS.createNode(e,"fd",16895,73);return r.stream_ops={llseek:MEMFS.stream_ops.llseek},r.node_ops={lookup(M,r0){var s0=+r0,a0=FS.getStreamChecked(s0),i0={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>a0.path},id:s0+1};return i0.parent=i0,i0},readdir(){return Array.from(FS.streams.entries()).filter(([M,r0])=>r0).map(([M,r0])=>M.toString())}},r}},{},"/proc/self/fd")},createStandardStreams(e,r,M){e?FS.createDevice("/dev","stdin",e):FS.symlink("/dev/tty","/dev/stdin"),r?FS.createDevice("/dev","stdout",null,r):FS.symlink("/dev/tty","/dev/stdout"),M?FS.createDevice("/dev","stderr",null,M):FS.symlink("/dev/tty1","/dev/stderr"),FS.open("/dev/stdin",0),FS.open("/dev/stdout",1),FS.open("/dev/stderr",1)},staticInit(){FS.nameTable=new Array(4096),FS.mount(MEMFS,{},"/"),FS.createDefaultDirectories(),FS.createDefaultDevices(),FS.createSpecialDirectories(),FS.filesystems={MEMFS,IDBFS,NODEFS}},init(e,r,M){FS.initialized=!0,e??(e=Module.stdin),r??(r=Module.stdout),M??(M=Module.stderr),FS.createStandardStreams(e,r,M)},quit(){FS.initialized=!1,_fflush(0);for(var e=0;ethis.length-1||x0<0)){var k0=x0%this.chunkSize,F0=x0/this.chunkSize|0;return this.getter(F0)[k0]}}setDataGetter(x0){this.getter=x0}cacheLength(){var x0=new XMLHttpRequest;if(x0.open("HEAD",M,!1),x0.send(null),!(x0.status>=200&&x0.status<300||x0.status===304))throw new Error("Couldn't load "+M+". Status: "+x0.status);var k0=Number(x0.getResponseHeader("Content-length")),F0,C0=(F0=x0.getResponseHeader("Accept-Ranges"))&&F0==="bytes",R0=(F0=x0.getResponseHeader("Content-Encoding"))&&F0==="gzip",y0=1024*1024;C0||(y0=k0);var w0=(q0,U0)=>{if(q0>U0)throw new Error("invalid range ("+q0+", "+U0+") or no bytes requested!");if(U0>k0-1)throw new Error("only "+k0+" bytes available! programmer error!");var X0=new XMLHttpRequest;if(X0.open("GET",M,!1),k0!==y0&&X0.setRequestHeader("Range","bytes="+q0+"-"+U0),X0.responseType="arraybuffer",X0.overrideMimeType&&X0.overrideMimeType("text/plain; charset=x-user-defined"),X0.send(null),!(X0.status>=200&&X0.status<300||X0.status===304))throw new Error("Couldn't load "+M+". Status: "+X0.status);return X0.response!==void 0?new Uint8Array(X0.response||[]):intArrayFromString(X0.responseText||"")},A0=this;A0.setDataGetter(q0=>{var U0=q0*y0,X0=(q0+1)*y0-1;if(X0=Math.min(X0,k0-1),typeof A0.chunks[q0]>"u"&&(A0.chunks[q0]=w0(U0,X0)),typeof A0.chunks[q0]>"u")throw new Error("doXHR failed!");return A0.chunks[q0]}),(R0||!k0)&&(y0=k0=1,k0=this.getter(0).length,y0=k0,out("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=k0,this._chunkSize=y0,this.lengthKnown=!0}get length(){return this.lengthKnown||this.cacheLength(),this._length}get chunkSize(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}if(typeof XMLHttpRequest<"u"){if(!ENVIRONMENT_IS_WORKER)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var i0=new a0,u0={isDevice:!1,contents:i0}}else var u0={isDevice:!1,url:M};var d0=FS.createFile(e,r,u0,r0,s0);u0.contents?d0.contents=u0.contents:u0.url&&(d0.contents=null,d0.url=u0.url),Object.defineProperties(d0,{usedBytes:{get:function(){return this.contents.length}}});var m0={},_0=Object.keys(d0.stream_ops);_0.forEach(g0=>{var x0=d0.stream_ops[g0];m0[g0]=(...k0)=>(FS.forceLoadFile(d0),x0(...k0))});function f0(g0,x0,k0,F0,C0){var R0=g0.node.contents;if(C0>=R0.length)return 0;var y0=Math.min(R0.length-C0,F0);if(R0.slice)for(var w0=0;w0(FS.forceLoadFile(d0),f0(g0,x0,k0,F0,C0)),m0.mmap=(g0,x0,k0,F0,C0)=>{FS.forceLoadFile(d0);var R0=mmapAlloc(x0);if(!R0)throw new FS.ErrnoError(48);return f0(g0,HEAP8,R0,x0,k0),{ptr:R0,allocated:!0}},d0.stream_ops=m0,d0}},SYSCALLS={DEFAULT_POLLMASK:5,calculateAt(e,r,M){if(PATH.isAbs(r))return r;var r0;if(e===-100)r0=FS.cwd();else{var s0=SYSCALLS.getStreamFromFD(e);r0=s0.path}if(r.length==0){if(!M)throw new FS.ErrnoError(44);return r0}return r0+"/"+r},doStat(e,r,M){var r0=e(r);HEAP32[M>>2]=r0.dev,HEAP32[M+4>>2]=r0.mode,HEAPU32[M+8>>2]=r0.nlink,HEAP32[M+12>>2]=r0.uid,HEAP32[M+16>>2]=r0.gid,HEAP32[M+20>>2]=r0.rdev,HEAP64[M+24>>3]=BigInt(r0.size),HEAP32[M+32>>2]=4096,HEAP32[M+36>>2]=r0.blocks;var s0=r0.atime.getTime(),a0=r0.mtime.getTime(),i0=r0.ctime.getTime();return HEAP64[M+40>>3]=BigInt(Math.floor(s0/1e3)),HEAPU32[M+48>>2]=s0%1e3*1e3*1e3,HEAP64[M+56>>3]=BigInt(Math.floor(a0/1e3)),HEAPU32[M+64>>2]=a0%1e3*1e3*1e3,HEAP64[M+72>>3]=BigInt(Math.floor(i0/1e3)),HEAPU32[M+80>>2]=i0%1e3*1e3*1e3,HEAP64[M+88>>3]=BigInt(r0.ino),0},doMsync(e,r,M,r0,s0){if(!FS.isFile(r.node.mode))throw new FS.ErrnoError(43);if(r0&2)return 0;var a0=HEAPU8.slice(e,e+M);FS.msync(r,a0,s0,M,r0)},getStreamFromFD(e){var r=FS.getStreamChecked(e);return r},varargs:void 0,getStr(e){var r=UTF8ToString(e);return r}},___syscall__newselect=function(e,r,M,r0,s0){try{for(var a0=0,i0=r?HEAP32[r>>2]:0,u0=r?HEAP32[r+4>>2]:0,d0=M?HEAP32[M>>2]:0,m0=M?HEAP32[M+4>>2]:0,_0=r0?HEAP32[r0>>2]:0,f0=r0?HEAP32[r0+4>>2]:0,g0=0,x0=0,k0=0,F0=0,C0=0,R0=0,y0=(r?HEAP32[r>>2]:0)|(M?HEAP32[M>>2]:0)|(r0?HEAP32[r0>>2]:0),w0=(r?HEAP32[r+4>>2]:0)|(M?HEAP32[M+4>>2]:0)|(r0?HEAP32[r0+4>>2]:0),A0=(vr,H0,lr,fr)=>vr<32?H0&fr:lr&fr,q0=0;q0>2]:0,mr=r?HEAP32[s0+4>>2]:0;Ir=(Ur+mr/1e6)*1e3}xr=X0.stream_ops.poll(X0,Ir)}xr&1&&A0(q0,i0,u0,U0)&&(q0<32?g0=g0|U0:x0=x0|U0,a0++),xr&4&&A0(q0,d0,m0,U0)&&(q0<32?k0=k0|U0:F0=F0|U0,a0++),xr&2&&A0(q0,_0,f0,U0)&&(q0<32?C0=C0|U0:R0=R0|U0,a0++)}}return r&&(HEAP32[r>>2]=g0,HEAP32[r+4>>2]=x0),M&&(HEAP32[M>>2]=k0,HEAP32[M+4>>2]=F0),r0&&(HEAP32[r0>>2]=C0,HEAP32[r0+4>>2]=R0),a0}catch(vr){if(typeof FS>"u"||vr.name!=="ErrnoError")throw vr;return-vr.errno}};___syscall__newselect.sig="iipppp";var SOCKFS={websocketArgs:{},callbacks:{},on(e,r){SOCKFS.callbacks[e]=r},emit(e,r){var M,r0;(r0=(M=SOCKFS.callbacks)[e])==null||r0.call(M,r)},mount(e){return SOCKFS.websocketArgs=Module.websocket||{},(Module.websocket??(Module.websocket={})).on=SOCKFS.on,FS.createNode(null,"/",16895,0)},createSocket(e,r,M){r&=-526337;var r0=r==1;if(r0&&M&&M!=6)throw new FS.ErrnoError(66);var s0={family:e,type:r,protocol:M,server:null,error:null,peers:{},pending:[],recv_queue:[],sock_ops:SOCKFS.websocket_sock_ops},a0=SOCKFS.nextname(),i0=FS.createNode(SOCKFS.root,a0,49152,0);i0.sock=s0;var u0=FS.createStream({path:a0,node:i0,flags:2,seekable:!1,stream_ops:SOCKFS.stream_ops});return s0.stream=u0,s0},getSocket(e){var r=FS.getStream(e);return!r||!FS.isSocket(r.node.mode)?null:r.node.sock},stream_ops:{poll(e){var r=e.node.sock;return r.sock_ops.poll(r)},ioctl(e,r,M){var r0=e.node.sock;return r0.sock_ops.ioctl(r0,r,M)},read(e,r,M,r0,s0){var a0=e.node.sock,i0=a0.sock_ops.recvmsg(a0,r0);return i0?(r.set(i0.buffer,M),i0.buffer.length):0},write(e,r,M,r0,s0){var a0=e.node.sock;return a0.sock_ops.sendmsg(a0,r,M,r0)},close(e){var r=e.node.sock;r.sock_ops.close(r)}},nextname(){return SOCKFS.nextname.current||(SOCKFS.nextname.current=0),`socket[${SOCKFS.nextname.current++}]`},websocket_sock_ops:{createPeer(e,r,M){var r0;if(typeof r=="object"&&(r0=r,r=null,M=null),r0)if(r0._socket)r=r0._socket.remoteAddress,M=r0._socket.remotePort;else{var s0=/ws[s]?:\/\/([^:]+):(\d+)/.exec(r0.url);if(!s0)throw new Error("WebSocket URL must be in the format ws(s)://address:port");r=s0[1],M=parseInt(s0[2],10)}else try{var a0="ws:#".replace("#","//"),i0="binary",u0=void 0;if(SOCKFS.websocketArgs.url&&(a0=SOCKFS.websocketArgs.url),SOCKFS.websocketArgs.subprotocol?i0=SOCKFS.websocketArgs.subprotocol:SOCKFS.websocketArgs.subprotocol===null&&(i0="null"),a0==="ws://"||a0==="wss://"){var d0=r.split("/");a0=a0+d0[0]+":"+M+"/"+d0.slice(1).join("/")}i0!=="null"&&(i0=i0.replace(/^ +| +$/g,"").split(/ *, */),u0=i0);var m0;ENVIRONMENT_IS_NODE?m0=require("ws"):m0=WebSocket,r0=new m0(a0,u0),r0.binaryType="arraybuffer"}catch{throw new FS.ErrnoError(23)}var _0={addr:r,port:M,socket:r0,msg_send_queue:[]};return SOCKFS.websocket_sock_ops.addPeer(e,_0),SOCKFS.websocket_sock_ops.handlePeerEvents(e,_0),e.type===2&&typeof e.sport<"u"&&_0.msg_send_queue.push(new Uint8Array([255,255,255,255,112,111,114,116,(e.sport&65280)>>8,e.sport&255])),_0},getPeer(e,r,M){return e.peers[r+":"+M]},addPeer(e,r){e.peers[r.addr+":"+r.port]=r},removePeer(e,r){delete e.peers[r.addr+":"+r.port]},handlePeerEvents(e,r){var M=!0,r0=function(){e.connecting=!1,SOCKFS.emit("open",e.stream.fd);try{for(var a0=r.msg_send_queue.shift();a0;)r.socket.send(a0),a0=r.msg_send_queue.shift()}catch{r.socket.close()}};function s0(a0){if(typeof a0=="string"){var i0=new TextEncoder;a0=i0.encode(a0)}else{if(assert(a0.byteLength!==void 0),a0.byteLength==0)return;a0=new Uint8Array(a0)}var u0=M;if(M=!1,u0&&a0.length===10&&a0[0]===255&&a0[1]===255&&a0[2]===255&&a0[3]===255&&a0[4]===112&&a0[5]===111&&a0[6]===114&&a0[7]===116){var d0=a0[8]<<8|a0[9];SOCKFS.websocket_sock_ops.removePeer(e,r),r.port=d0,SOCKFS.websocket_sock_ops.addPeer(e,r);return}e.recv_queue.push({addr:r.addr,port:r.port,data:a0}),SOCKFS.emit("message",e.stream.fd)}ENVIRONMENT_IS_NODE?(r.socket.on("open",r0),r.socket.on("message",function(a0,i0){i0&&s0(new Uint8Array(a0).buffer)}),r.socket.on("close",function(){SOCKFS.emit("close",e.stream.fd)}),r.socket.on("error",function(a0){e.error=14,SOCKFS.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})):(r.socket.onopen=r0,r.socket.onclose=function(){SOCKFS.emit("close",e.stream.fd)},r.socket.onmessage=function(a0){s0(a0.data)},r.socket.onerror=function(a0){e.error=14,SOCKFS.emit("error",[e.stream.fd,e.error,"ECONNREFUSED: Connection refused"])})},poll(e){if(e.type===1&&e.server)return e.pending.length?65:0;var r=0,M=e.type===1?SOCKFS.websocket_sock_ops.getPeer(e,e.daddr,e.dport):null;return(e.recv_queue.length||!M||M&&M.socket.readyState===M.socket.CLOSING||M&&M.socket.readyState===M.socket.CLOSED)&&(r|=65),(!M||M&&M.socket.readyState===M.socket.OPEN)&&(r|=4),(M&&M.socket.readyState===M.socket.CLOSING||M&&M.socket.readyState===M.socket.CLOSED)&&(e.connecting?r|=4:r|=16),r},ioctl(e,r,M){switch(r){case 21531:var r0=0;return e.recv_queue.length&&(r0=e.recv_queue[0].data.length),HEAP32[M>>2]=r0,0;default:return 28}},close(e){if(e.server){try{e.server.close()}catch{}e.server=null}for(var r=Object.keys(e.peers),M=0;M{var r=SOCKFS.getSocket(e);if(!r)throw new FS.ErrnoError(8);return r},inetNtop4=e=>(e&255)+"."+(e>>8&255)+"."+(e>>16&255)+"."+(e>>24&255),inetNtop6=e=>{var r="",M=0,r0=0,s0=0,a0=0,i0=0,u0=0,d0=[e[0]&65535,e[0]>>16,e[1]&65535,e[1]>>16,e[2]&65535,e[2]>>16,e[3]&65535,e[3]>>16],m0=!0,_0="";for(u0=0;u0<5;u0++)if(d0[u0]!==0){m0=!1;break}if(m0){if(_0=inetNtop4(d0[6]|d0[7]<<16),d0[5]===-1)return r="::ffff:",r+=_0,r;if(d0[5]===0)return r="::",_0==="0.0.0.0"&&(_0=""),_0==="0.0.0.1"&&(_0="1"),r+=_0,r}for(M=0;M<8;M++)d0[M]===0&&(M-s0>1&&(i0=0),s0=M,i0++),i0>r0&&(r0=i0,a0=M-r0+1);for(M=0;M<8;M++){if(r0>1&&d0[M]===0&&M>=a0&&M{var M=HEAP16[e>>1],r0=_ntohs(HEAPU16[e+2>>1]),s0;switch(M){case 2:if(r!==16)return{errno:28};s0=HEAP32[e+4>>2],s0=inetNtop4(s0);break;case 10:if(r!==28)return{errno:28};s0=[HEAP32[e+8>>2],HEAP32[e+12>>2],HEAP32[e+16>>2],HEAP32[e+20>>2]],s0=inetNtop6(s0);break;default:return{errno:5}}return{family:M,addr:s0,port:r0}},inetPton4=e=>{for(var r=e.split("."),M=0;M<4;M++){var r0=Number(r[M]);if(isNaN(r0))return null;r[M]=r0}return(r[0]|r[1]<<8|r[2]<<16|r[3]<<24)>>>0},jstoi_q=e=>parseInt(e),inetPton6=e=>{var r,M,r0,s0,a0=/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i,i0=[];if(!a0.test(e))return null;if(e==="::")return[0,0,0,0,0,0,0,0];for(e.startsWith("::")?e=e.replace("::","Z:"):e=e.replace("::",":Z:"),e.indexOf(".")>0?(e=e.replace(new RegExp("[.]","g"),":"),r=e.split(":"),r[r.length-4]=jstoi_q(r[r.length-4])+jstoi_q(r[r.length-3])*256,r[r.length-3]=jstoi_q(r[r.length-2])+jstoi_q(r[r.length-1])*256,r=r.slice(0,r.length-2)):r=e.split(":"),r0=0,s0=0,M=0;M{var M=readSockaddr(e,r);if(M.errno)throw new FS.ErrnoError(M.errno);return M.addr=DNS.lookup_addr(M.addr)||M.addr,M};function ___syscall_bind(e,r,M,r0,s0,a0){try{var i0=getSocketFromFD(e),u0=getSocketAddress(r,M);return i0.sock_ops.bind(i0,u0.addr,u0.port),0}catch(d0){if(typeof FS>"u"||d0.name!=="ErrnoError")throw d0;return-d0.errno}}___syscall_bind.sig="iippiii";function ___syscall_chdir(e){try{return e=SYSCALLS.getStr(e),FS.chdir(e),0}catch(r){if(typeof FS>"u"||r.name!=="ErrnoError")throw r;return-r.errno}}___syscall_chdir.sig="ip";function ___syscall_chmod(e,r){try{return e=SYSCALLS.getStr(e),FS.chmod(e,r),0}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_chmod.sig="ipi";function ___syscall_connect(e,r,M,r0,s0,a0){try{var i0=getSocketFromFD(e),u0=getSocketAddress(r,M);return i0.sock_ops.connect(i0,u0.addr,u0.port),0}catch(d0){if(typeof FS>"u"||d0.name!=="ErrnoError")throw d0;return-d0.errno}}___syscall_connect.sig="iippiii";function ___syscall_dup(e){try{var r=SYSCALLS.getStreamFromFD(e);return FS.dupStream(r).fd}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_dup.sig="ii";function ___syscall_dup3(e,r,M){try{var r0=SYSCALLS.getStreamFromFD(e);if(r0.fd===r)return-28;if(r<0||r>=FS.MAX_OPEN_FDS)return-8;var s0=FS.getStream(r);return s0&&FS.close(s0),FS.dupStream(r0,r).fd}catch(a0){if(typeof FS>"u"||a0.name!=="ErrnoError")throw a0;return-a0.errno}}___syscall_dup3.sig="iiii";function ___syscall_faccessat(e,r,M,r0){try{if(r=SYSCALLS.getStr(r),r=SYSCALLS.calculateAt(e,r),M&-8)return-28;var s0=FS.lookupPath(r,{follow:!0}),a0=s0.node;if(!a0)return-44;var i0="";return M&4&&(i0+="r"),M&2&&(i0+="w"),M&1&&(i0+="x"),i0&&FS.nodePermissions(a0,i0)?-2:0}catch(u0){if(typeof FS>"u"||u0.name!=="ErrnoError")throw u0;return-u0.errno}}___syscall_faccessat.sig="iipii";var ___syscall_fadvise64=(e,r,M,r0)=>0;___syscall_fadvise64.sig="iijji";var INT53_MAX=9007199254740992,INT53_MIN=-9007199254740992,bigintToI53Checked=e=>eINT53_MAX?NaN:Number(e);function ___syscall_fallocate(e,r,M,r0){M=bigintToI53Checked(M),r0=bigintToI53Checked(r0);try{if(isNaN(M))return 61;var s0=SYSCALLS.getStreamFromFD(e);return FS.allocate(s0,M,r0),0}catch(a0){if(typeof FS>"u"||a0.name!=="ErrnoError")throw a0;return-a0.errno}}___syscall_fallocate.sig="iiijj";var syscallGetVarargI=()=>{var e=HEAP32[+SYSCALLS.varargs>>2];return SYSCALLS.varargs+=4,e},syscallGetVarargP=syscallGetVarargI;function ___syscall_fcntl64(e,r,M){SYSCALLS.varargs=M;try{var r0=SYSCALLS.getStreamFromFD(e);switch(r){case 0:{var s0=syscallGetVarargI();if(s0<0)return-28;for(;FS.streams[s0];)s0++;var a0;return a0=FS.dupStream(r0,s0),a0.fd}case 1:case 2:return 0;case 3:return r0.flags;case 4:{var s0=syscallGetVarargI();return r0.flags|=s0,0}case 12:{var s0=syscallGetVarargP(),i0=0;return HEAP16[s0+i0>>1]=2,0}case 13:case 14:return 0}return-28}catch(u0){if(typeof FS>"u"||u0.name!=="ErrnoError")throw u0;return-u0.errno}}___syscall_fcntl64.sig="iiip";function ___syscall_fdatasync(e){try{var r=SYSCALLS.getStreamFromFD(e);return 0}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_fdatasync.sig="ii";function ___syscall_fstat64(e,r){try{var M=SYSCALLS.getStreamFromFD(e);return SYSCALLS.doStat(FS.stat,M.path,r)}catch(r0){if(typeof FS>"u"||r0.name!=="ErrnoError")throw r0;return-r0.errno}}___syscall_fstat64.sig="iip";function ___syscall_ftruncate64(e,r){r=bigintToI53Checked(r);try{return isNaN(r)?61:(FS.ftruncate(e,r),0)}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_ftruncate64.sig="iij";var stringToUTF8=(e,r,M)=>stringToUTF8Array(e,HEAPU8,r,M);function ___syscall_getcwd(e,r){try{if(r===0)return-28;var M=FS.cwd(),r0=lengthBytesUTF8(M)+1;return r"u"||s0.name!=="ErrnoError")throw s0;return-s0.errno}}___syscall_getcwd.sig="ipp";function ___syscall_getdents64(e,r,M){try{var r0=SYSCALLS.getStreamFromFD(e);r0.getdents||(r0.getdents=FS.readdir(r0.path));for(var s0=280,a0=0,i0=FS.llseek(r0,0,1),u0=Math.floor(i0/s0),d0=Math.min(r0.getdents.length,u0+Math.floor(M/s0)),m0=u0;m0>3]=BigInt(_0),HEAP64[r+a0+8>>3]=BigInt((m0+1)*s0),HEAP16[r+a0+16>>1]=280,HEAP8[r+a0+18]=f0,stringToUTF8(g0,r+a0+19,256),a0+=s0}return FS.llseek(r0,m0*s0,0),a0}catch(F0){if(typeof FS>"u"||F0.name!=="ErrnoError")throw F0;return-F0.errno}}___syscall_getdents64.sig="iipp";function ___syscall_ioctl(e,r,M){SYSCALLS.varargs=M;try{var r0=SYSCALLS.getStreamFromFD(e);switch(r){case 21509:return r0.tty?0:-59;case 21505:{if(!r0.tty)return-59;if(r0.tty.ops.ioctl_tcgets){var s0=r0.tty.ops.ioctl_tcgets(r0),a0=syscallGetVarargP();HEAP32[a0>>2]=s0.c_iflag||0,HEAP32[a0+4>>2]=s0.c_oflag||0,HEAP32[a0+8>>2]=s0.c_cflag||0,HEAP32[a0+12>>2]=s0.c_lflag||0;for(var i0=0;i0<32;i0++)HEAP8[a0+i0+17]=s0.c_cc[i0]||0;return 0}return 0}case 21510:case 21511:case 21512:return r0.tty?0:-59;case 21506:case 21507:case 21508:{if(!r0.tty)return-59;if(r0.tty.ops.ioctl_tcsets){for(var a0=syscallGetVarargP(),u0=HEAP32[a0>>2],d0=HEAP32[a0+4>>2],m0=HEAP32[a0+8>>2],_0=HEAP32[a0+12>>2],f0=[],i0=0;i0<32;i0++)f0.push(HEAP8[a0+i0+17]);return r0.tty.ops.ioctl_tcsets(r0.tty,r,{c_iflag:u0,c_oflag:d0,c_cflag:m0,c_lflag:_0,c_cc:f0})}return 0}case 21519:{if(!r0.tty)return-59;var a0=syscallGetVarargP();return HEAP32[a0>>2]=0,0}case 21520:return r0.tty?-28:-59;case 21531:{var a0=syscallGetVarargP();return FS.ioctl(r0,r,a0)}case 21523:{if(!r0.tty)return-59;if(r0.tty.ops.ioctl_tiocgwinsz){var g0=r0.tty.ops.ioctl_tiocgwinsz(r0.tty),a0=syscallGetVarargP();HEAP16[a0>>1]=g0[0],HEAP16[a0+2>>1]=g0[1]}return 0}case 21524:return r0.tty?0:-59;case 21515:return r0.tty?0:-59;default:return-28}}catch(x0){if(typeof FS>"u"||x0.name!=="ErrnoError")throw x0;return-x0.errno}}___syscall_ioctl.sig="iiip";function ___syscall_lstat64(e,r){try{return e=SYSCALLS.getStr(e),SYSCALLS.doStat(FS.lstat,e,r)}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_lstat64.sig="ipp";function ___syscall_mkdirat(e,r,M){try{return r=SYSCALLS.getStr(r),r=SYSCALLS.calculateAt(e,r),FS.mkdir(r,M,0),0}catch(r0){if(typeof FS>"u"||r0.name!=="ErrnoError")throw r0;return-r0.errno}}___syscall_mkdirat.sig="iipi";function ___syscall_newfstatat(e,r,M,r0){try{r=SYSCALLS.getStr(r);var s0=r0&256,a0=r0&4096;return r0=r0&-6401,r=SYSCALLS.calculateAt(e,r,a0),SYSCALLS.doStat(s0?FS.lstat:FS.stat,r,M)}catch(i0){if(typeof FS>"u"||i0.name!=="ErrnoError")throw i0;return-i0.errno}}___syscall_newfstatat.sig="iippi";function ___syscall_openat(e,r,M,r0){SYSCALLS.varargs=r0;try{r=SYSCALLS.getStr(r),r=SYSCALLS.calculateAt(e,r);var s0=r0?syscallGetVarargI():0;return FS.open(r,M,s0).fd}catch(a0){if(typeof FS>"u"||a0.name!=="ErrnoError")throw a0;return-a0.errno}}___syscall_openat.sig="iipip";var PIPEFS={BUCKET_BUFFER_SIZE:8192,mount(e){return FS.createNode(null,"/",16895,0)},createPipe(){var e={buckets:[],refcnt:2};e.buckets.push({buffer:new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE),offset:0,roffset:0});var r=PIPEFS.nextname(),M=PIPEFS.nextname(),r0=FS.createNode(PIPEFS.root,r,4096,0),s0=FS.createNode(PIPEFS.root,M,4096,0);r0.pipe=e,s0.pipe=e;var a0=FS.createStream({path:r,node:r0,flags:0,seekable:!1,stream_ops:PIPEFS.stream_ops});r0.stream=a0;var i0=FS.createStream({path:M,node:s0,flags:1,seekable:!1,stream_ops:PIPEFS.stream_ops});return s0.stream=i0,{readable_fd:a0.fd,writable_fd:i0.fd}},stream_ops:{poll(e){var r=e.node.pipe;if((e.flags&2097155)===1)return 260;if(r.buckets.length>0)for(var M=0;M0)return 65}return 0},ioctl(e,r,M){return 28},fsync(e){return 28},read(e,r,M,r0,s0){for(var a0=e.node.pipe,i0=0,u0=0;u0=u0)return d0.buffer.set(i0,d0.offset),d0.offset+=u0,u0;m0>0&&(d0.buffer.set(i0.subarray(0,m0),d0.offset),d0.offset+=m0,i0=i0.subarray(m0,i0.byteLength));for(var _0=i0.byteLength/PIPEFS.BUCKET_BUFFER_SIZE|0,f0=i0.byteLength%PIPEFS.BUCKET_BUFFER_SIZE,g0=0;g0<_0;g0++){var x0={buffer:new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE),offset:PIPEFS.BUCKET_BUFFER_SIZE,roffset:0};a0.buckets.push(x0),x0.buffer.set(i0.subarray(0,PIPEFS.BUCKET_BUFFER_SIZE)),i0=i0.subarray(PIPEFS.BUCKET_BUFFER_SIZE,i0.byteLength)}if(f0>0){var x0={buffer:new Uint8Array(PIPEFS.BUCKET_BUFFER_SIZE),offset:i0.byteLength,roffset:0};a0.buckets.push(x0),x0.buffer.set(i0)}return u0},close(e){var r=e.node.pipe;r.refcnt--,r.refcnt===0&&(r.buckets=null)}},nextname(){return PIPEFS.nextname.current||(PIPEFS.nextname.current=0),"pipe["+PIPEFS.nextname.current+++"]"}};function ___syscall_pipe(e){try{if(e==0)throw new FS.ErrnoError(21);var r=PIPEFS.createPipe();return HEAP32[e>>2]=r.readable_fd,HEAP32[e+4>>2]=r.writable_fd,0}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_pipe.sig="ip";function ___syscall_poll(e,r,M){try{for(var r0=0,s0=0;s0>2],u0=HEAP16[a0+4>>1],d0=32,m0=FS.getStream(i0);m0&&(d0=SYSCALLS.DEFAULT_POLLMASK,m0.stream_ops.poll&&(d0=m0.stream_ops.poll(m0,-1))),d0&=u0|8|16,d0&&r0++,HEAP16[a0+6>>1]=d0}return r0}catch(_0){if(typeof FS>"u"||_0.name!=="ErrnoError")throw _0;return-_0.errno}}___syscall_poll.sig="ipii";function ___syscall_readlinkat(e,r,M,r0){try{if(r=SYSCALLS.getStr(r),r=SYSCALLS.calculateAt(e,r),r0<=0)return-28;var s0=FS.readlink(r),a0=Math.min(r0,lengthBytesUTF8(s0)),i0=HEAP8[M+a0];return stringToUTF8(s0,M,r0+1),HEAP8[M+a0]=i0,a0}catch(u0){if(typeof FS>"u"||u0.name!=="ErrnoError")throw u0;return-u0.errno}}___syscall_readlinkat.sig="iippp";var writeSockaddr=(e,r,M,r0,s0)=>{switch(r){case 2:M=inetPton4(M),zeroMemory(e,16),s0&&(HEAP32[s0>>2]=16),HEAP16[e>>1]=r,HEAP32[e+4>>2]=M,HEAP16[e+2>>1]=_htons(r0);break;case 10:M=inetPton6(M),zeroMemory(e,28),s0&&(HEAP32[s0>>2]=28),HEAP32[e>>2]=r,HEAP32[e+8>>2]=M[0],HEAP32[e+12>>2]=M[1],HEAP32[e+16>>2]=M[2],HEAP32[e+20>>2]=M[3],HEAP16[e+2>>1]=_htons(r0);break;default:return 5}return 0};function ___syscall_recvfrom(e,r,M,r0,s0,a0){try{var i0=getSocketFromFD(e),u0=i0.sock_ops.recvmsg(i0,M);if(!u0)return 0;if(s0)var d0=writeSockaddr(s0,i0.family,DNS.lookup_name(u0.addr),u0.port,a0);return HEAPU8.set(u0.buffer,r),u0.buffer.byteLength}catch(m0){if(typeof FS>"u"||m0.name!=="ErrnoError")throw m0;return-m0.errno}}___syscall_recvfrom.sig="iippipp";function ___syscall_renameat(e,r,M,r0){try{return r=SYSCALLS.getStr(r),r0=SYSCALLS.getStr(r0),r=SYSCALLS.calculateAt(e,r),r0=SYSCALLS.calculateAt(M,r0),FS.rename(r,r0),0}catch(s0){if(typeof FS>"u"||s0.name!=="ErrnoError")throw s0;return-s0.errno}}___syscall_renameat.sig="iipip";function ___syscall_rmdir(e){try{return e=SYSCALLS.getStr(e),FS.rmdir(e),0}catch(r){if(typeof FS>"u"||r.name!=="ErrnoError")throw r;return-r.errno}}___syscall_rmdir.sig="ip";function ___syscall_sendto(e,r,M,r0,s0,a0){try{var i0=getSocketFromFD(e);if(!s0)return FS.write(i0.stream,HEAP8,r,M);var u0=getSocketAddress(s0,a0);return i0.sock_ops.sendmsg(i0,HEAP8,r,M,u0.addr,u0.port)}catch(d0){if(typeof FS>"u"||d0.name!=="ErrnoError")throw d0;return-d0.errno}}___syscall_sendto.sig="iippipp";function ___syscall_socket(e,r,M){try{var r0=SOCKFS.createSocket(e,r,M);return r0.stream.fd}catch(s0){if(typeof FS>"u"||s0.name!=="ErrnoError")throw s0;return-s0.errno}}___syscall_socket.sig="iiiiiii";function ___syscall_stat64(e,r){try{return e=SYSCALLS.getStr(e),SYSCALLS.doStat(FS.stat,e,r)}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_stat64.sig="ipp";function ___syscall_symlinkat(e,r,M){try{return e=SYSCALLS.getStr(e),M=SYSCALLS.getStr(M),M=SYSCALLS.calculateAt(r,M),FS.symlink(e,M),0}catch(r0){if(typeof FS>"u"||r0.name!=="ErrnoError")throw r0;return-r0.errno}}___syscall_symlinkat.sig="ipip";function ___syscall_truncate64(e,r){r=bigintToI53Checked(r);try{return isNaN(r)?61:(e=SYSCALLS.getStr(e),FS.truncate(e,r),0)}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}___syscall_truncate64.sig="ipj";function ___syscall_unlinkat(e,r,M){try{return r=SYSCALLS.getStr(r),r=SYSCALLS.calculateAt(e,r),M===0?FS.unlink(r):M===512?FS.rmdir(r):abort("Invalid flags passed to unlinkat"),0}catch(r0){if(typeof FS>"u"||r0.name!=="ErrnoError")throw r0;return-r0.errno}}___syscall_unlinkat.sig="iipi";var ___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1);Module.___table_base=___table_base;var __abort_js=()=>abort("");__abort_js.sig="v";var ENV={},stackAlloc=e=>__emscripten_stack_alloc(e),stringToUTF8OnStack=e=>{var r=lengthBytesUTF8(e)+1,M=stackAlloc(r);return stringToUTF8(e,M,r),M},dlSetError=e=>{var r=stackSave(),M=stringToUTF8OnStack(e);___dl_seterr(M,0),stackRestore(r)},dlopenInternal=(e,r)=>{var M=UTF8ToString(e+36),r0=HEAP32[e+4>>2];M=PATH.normalize(M);var s0=!!(r0&256),a0=s0?null:{},i0={global:s0,nodelete:!!(r0&4096),loadAsync:r.loadAsync};try{return loadDynamicLibrary(M,i0,a0,e)}catch(u0){return dlSetError(`Could not load dynamic lib: ${M} +${u0}`),0}},__dlopen_js=e=>dlopenInternal(e,{loadAsync:!1});__dlopen_js.sig="pp";var __dlsym_js=(e,r,M)=>{r=UTF8ToString(r);var r0,s0,a0=LDSO.loadedLibsByHandle[e];if(!a0.exports.hasOwnProperty(r)||a0.exports[r].stub)return dlSetError(`Tried to lookup unknown symbol "${r}" in dynamic lib: ${a0.name}`),0;if(s0=Object.keys(a0.exports).indexOf(r),r0=a0.exports[r],typeof r0=="function"){var i0=getFunctionAddress(r0);i0?r0=i0:(r0=addFunction(r0,r0.sig),HEAPU32[M>>2]=s0)}return r0};__dlsym_js.sig="pppp";var __emscripten_memcpy_js=(e,r,M)=>HEAPU8.copyWithin(e,r,r+M);__emscripten_memcpy_js.sig="vppp";var runtimeKeepaliveCounter=0,__emscripten_runtime_keepalive_clear=()=>{noExitRuntime=!1,runtimeKeepaliveCounter=0};__emscripten_runtime_keepalive_clear.sig="v";var __emscripten_system=e=>{if(ENVIRONMENT_IS_NODE){if(!e)return 1;var r=UTF8ToString(e);if(!r.length)return 0;var M=require("child_process"),r0=M.spawnSync(r,[],{shell:!0,stdio:"inherit"}),s0=(i0,u0)=>i0<<8|u0;if(r0.status===null){var a0=i0=>{switch(i0){case"SIGHUP":return 1;case"SIGQUIT":return 3;case"SIGFPE":return 8;case"SIGKILL":return 9;case"SIGALRM":return 14;case"SIGTERM":return 15;default:return 2}};return s0(0,a0(r0.signal))}return s0(r0.status,0)}return e?-52:0};__emscripten_system.sig="ip";var __emscripten_throw_longjmp=()=>{throw 1/0};__emscripten_throw_longjmp.sig="v";function __gmtime_js(e,r){e=bigintToI53Checked(e);var M=new Date(e*1e3);HEAP32[r>>2]=M.getUTCSeconds(),HEAP32[r+4>>2]=M.getUTCMinutes(),HEAP32[r+8>>2]=M.getUTCHours(),HEAP32[r+12>>2]=M.getUTCDate(),HEAP32[r+16>>2]=M.getUTCMonth(),HEAP32[r+20>>2]=M.getUTCFullYear()-1900,HEAP32[r+24>>2]=M.getUTCDay();var r0=Date.UTC(M.getUTCFullYear(),0,1,0,0,0,0),s0=(M.getTime()-r0)/(1e3*60*60*24)|0;HEAP32[r+28>>2]=s0}__gmtime_js.sig="vjp";var isLeapYear=e=>e%4===0&&(e%100!==0||e%400===0),MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335],MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334],ydayFromDate=e=>{var r=isLeapYear(e.getFullYear()),M=r?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE,r0=M[e.getMonth()]+e.getDate()-1;return r0};function __localtime_js(e,r){e=bigintToI53Checked(e);var M=new Date(e*1e3);HEAP32[r>>2]=M.getSeconds(),HEAP32[r+4>>2]=M.getMinutes(),HEAP32[r+8>>2]=M.getHours(),HEAP32[r+12>>2]=M.getDate(),HEAP32[r+16>>2]=M.getMonth(),HEAP32[r+20>>2]=M.getFullYear()-1900,HEAP32[r+24>>2]=M.getDay();var r0=ydayFromDate(M)|0;HEAP32[r+28>>2]=r0,HEAP32[r+36>>2]=-(M.getTimezoneOffset()*60);var s0=new Date(M.getFullYear(),0,1),a0=new Date(M.getFullYear(),6,1).getTimezoneOffset(),i0=s0.getTimezoneOffset(),u0=(a0!=i0&&M.getTimezoneOffset()==Math.min(i0,a0))|0;HEAP32[r+32>>2]=u0}__localtime_js.sig="vjp";function __mmap_js(e,r,M,r0,s0,a0,i0){s0=bigintToI53Checked(s0);try{if(isNaN(s0))return 61;var u0=SYSCALLS.getStreamFromFD(r0),d0=FS.mmap(u0,e,s0,r,M),m0=d0.ptr;return HEAP32[a0>>2]=d0.allocated,HEAPU32[i0>>2]=m0,0}catch(_0){if(typeof FS>"u"||_0.name!=="ErrnoError")throw _0;return-_0.errno}}__mmap_js.sig="ipiiijpp";function __munmap_js(e,r,M,r0,s0,a0){a0=bigintToI53Checked(a0);try{var i0=SYSCALLS.getStreamFromFD(s0);M&2&&SYSCALLS.doMsync(e,i0,r,r0,a0)}catch(u0){if(typeof FS>"u"||u0.name!=="ErrnoError")throw u0;return-u0.errno}}__munmap_js.sig="ippiiij";var timers={},handleException=e=>{if(e instanceof ExitStatus||e=="unwind")return EXITSTATUS;quit_(1,e)},keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0,_proc_exit=e=>{var r;EXITSTATUS=e,keepRuntimeAlive()||((r=Module.onExit)==null||r.call(Module,e),ABORT=!0),quit_(e,new ExitStatus(e))};_proc_exit.sig="vi";var exitJS=(e,r)=>{EXITSTATUS=e,_proc_exit(e)},_exit=exitJS;_exit.sig="vi";var maybeExit=()=>{if(!keepRuntimeAlive())try{_exit(EXITSTATUS)}catch(e){handleException(e)}},callUserCallback=e=>{if(!ABORT)try{e(),maybeExit()}catch(r){handleException(r)}},_emscripten_get_now=()=>performance.now();_emscripten_get_now.sig="d";var __setitimer_js=(e,r)=>{if(timers[e]&&(clearTimeout(timers[e].id),delete timers[e]),!r)return 0;var M=setTimeout(()=>{delete timers[e],callUserCallback(()=>__emscripten_timeout(e,_emscripten_get_now()))},r);return timers[e]={id:M,timeout_ms:r},0};__setitimer_js.sig="iid";var __tzset_js=(e,r,M,r0)=>{var s0=new Date().getFullYear(),a0=new Date(s0,0,1),i0=new Date(s0,6,1),u0=a0.getTimezoneOffset(),d0=i0.getTimezoneOffset(),m0=Math.max(u0,d0);HEAPU32[e>>2]=m0*60,HEAP32[r>>2]=+(u0!=d0);var _0=x0=>{var k0=x0>=0?"-":"+",F0=Math.abs(x0),C0=String(Math.floor(F0/60)).padStart(2,"0"),R0=String(F0%60).padStart(2,"0");return`UTC${k0}${C0}${R0}`},f0=_0(u0),g0=_0(d0);d0Date.now();_emscripten_date_now.sig="d";var checkWasiClock=e=>e>=0&&e<=3;function _clock_time_get(e,r,M){if(!checkWasiClock(e))return 28;var r0;e===0?r0=_emscripten_date_now():r0=_emscripten_get_now();var s0=Math.round(r0*1e3*1e3);return HEAP64[M>>3]=BigInt(s0),0}_clock_time_get.sig="iijp";var readEmAsmArgsArray=[],readEmAsmArgs=(e,r)=>{readEmAsmArgsArray.length=0;for(var M;M=HEAPU8[e++];){var r0=M!=105;r0&=M!=112,r+=r0&&r%8?4:0,readEmAsmArgsArray.push(M==112?HEAPU32[r>>2]:M==106?HEAP64[r>>3]:M==105?HEAP32[r>>2]:HEAPF64[r>>3]),r+=r0?8:4}return readEmAsmArgsArray},runEmAsmFunction=(e,r,M)=>{var r0=readEmAsmArgs(r,M);return ASM_CONSTS[e](...r0)},_emscripten_asm_const_int=(e,r,M)=>runEmAsmFunction(e,r,M);_emscripten_asm_const_int.sig="ippp";var _emscripten_force_exit=e=>{__emscripten_runtime_keepalive_clear(),_exit(e)};_emscripten_force_exit.sig="vi";var getHeapMax=()=>2147483648,growMemory=e=>{var r=wasmMemory.buffer,M=(e-r.byteLength+65535)/65536|0;try{return wasmMemory.grow(M),updateMemoryViews(),1}catch{}},_emscripten_resize_heap=e=>{var r=HEAPU8.length;e>>>=0;var M=getHeapMax();if(e>M)return!1;for(var r0=1;r0<=4;r0*=2){var s0=r*(1+.2/r0);s0=Math.min(s0,e+100663296);var a0=Math.min(M,alignMemory(Math.max(e,s0),65536)),i0=growMemory(a0);if(i0)return!0}return!1};_emscripten_resize_heap.sig="ip";var getExecutableName=()=>thisProgram||"./this.program",getEnvStrings=()=>{if(!getEnvStrings.strings){var e=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",r={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:e,_:getExecutableName()};for(var M in ENV)ENV[M]===void 0?delete r[M]:r[M]=ENV[M];var r0=[];for(var M in r)r0.push(`${M}=${r[M]}`);getEnvStrings.strings=r0}return getEnvStrings.strings},stringToAscii=(e,r)=>{for(var M=0;M{var M=0;return getEnvStrings().forEach((r0,s0)=>{var a0=r+M;HEAPU32[e+s0*4>>2]=a0,stringToAscii(r0,a0),M+=r0.length+1}),0};_environ_get.sig="ipp";var _environ_sizes_get=(e,r)=>{var M=getEnvStrings();HEAPU32[e>>2]=M.length;var r0=0;return M.forEach(s0=>r0+=s0.length+1),HEAPU32[r>>2]=r0,0};_environ_sizes_get.sig="ipp";function _fd_close(e){try{var r=SYSCALLS.getStreamFromFD(e);return FS.close(r),0}catch(M){if(typeof FS>"u"||M.name!=="ErrnoError")throw M;return M.errno}}_fd_close.sig="ii";function _fd_fdstat_get(e,r){try{var M=0,r0=0,s0=0,a0=SYSCALLS.getStreamFromFD(e),i0=a0.tty?2:FS.isDir(a0.mode)?3:FS.isLink(a0.mode)?7:4;return HEAP8[r]=i0,HEAP16[r+2>>1]=s0,HEAP64[r+8>>3]=BigInt(M),HEAP64[r+16>>3]=BigInt(r0),0}catch(u0){if(typeof FS>"u"||u0.name!=="ErrnoError")throw u0;return u0.errno}}_fd_fdstat_get.sig="iip";var doReadv=(e,r,M,r0)=>{for(var s0=0,a0=0;a0>2],u0=HEAPU32[r+4>>2];r+=8;var d0=FS.read(e,HEAP8,i0,u0,r0);if(d0<0)return-1;if(s0+=d0,d0>2]=i0,0}catch(u0){if(typeof FS>"u"||u0.name!=="ErrnoError")throw u0;return u0.errno}}_fd_pread.sig="iippjp";var doWritev=(e,r,M,r0)=>{for(var s0=0,a0=0;a0>2],u0=HEAPU32[r+4>>2];r+=8;var d0=FS.write(e,HEAP8,i0,u0,r0);if(d0<0)return-1;if(s0+=d0,d0>2]=i0,0}catch(u0){if(typeof FS>"u"||u0.name!=="ErrnoError")throw u0;return u0.errno}}_fd_pwrite.sig="iippjp";function _fd_read(e,r,M,r0){try{var s0=SYSCALLS.getStreamFromFD(e),a0=doReadv(s0,r,M);return HEAPU32[r0>>2]=a0,0}catch(i0){if(typeof FS>"u"||i0.name!=="ErrnoError")throw i0;return i0.errno}}_fd_read.sig="iippp";function _fd_seek(e,r,M,r0){r=bigintToI53Checked(r);try{if(isNaN(r))return 61;var s0=SYSCALLS.getStreamFromFD(e);return FS.llseek(s0,r,M),HEAP64[r0>>3]=BigInt(s0.position),s0.getdents&&r===0&&M===0&&(s0.getdents=null),0}catch(a0){if(typeof FS>"u"||a0.name!=="ErrnoError")throw a0;return a0.errno}}_fd_seek.sig="iijip";function _fd_sync(e){var M;try{var r=SYSCALLS.getStreamFromFD(e);return(M=r.stream_ops)!=null&&M.fsync?r.stream_ops.fsync(r):0}catch(r0){if(typeof FS>"u"||r0.name!=="ErrnoError")throw r0;return r0.errno}}_fd_sync.sig="ii";function _fd_write(e,r,M,r0){try{var s0=SYSCALLS.getStreamFromFD(e),a0=doWritev(s0,r,M);return HEAPU32[r0>>2]=a0,0}catch(i0){if(typeof FS>"u"||i0.name!=="ErrnoError")throw i0;return i0.errno}}_fd_write.sig="iippp";var _getaddrinfo=(e,r,M,r0)=>{var s0=0,a0=0,i0=0,u0=0,d0=0,m0=0,_0;function f0(g0,x0,k0,F0,C0,R0){var y0,w0,A0,q0;return w0=g0===10?28:16,C0=g0===10?inetNtop6(C0):inetNtop4(C0),y0=_malloc(w0),q0=writeSockaddr(y0,g0,C0,R0),assert(!q0),A0=_malloc(32),HEAP32[A0+4>>2]=g0,HEAP32[A0+8>>2]=x0,HEAP32[A0+12>>2]=k0,HEAPU32[A0+24>>2]=F0,HEAPU32[A0+20>>2]=y0,g0===10?HEAP32[A0+16>>2]=28:HEAP32[A0+16>>2]=16,HEAP32[A0+28>>2]=0,A0}if(M&&(i0=HEAP32[M>>2],u0=HEAP32[M+4>>2],d0=HEAP32[M+8>>2],m0=HEAP32[M+12>>2]),d0&&!m0&&(m0=d0===2?17:6),!d0&&m0&&(d0=m0===17?2:1),m0===0&&(m0=6),d0===0&&(d0=1),!e&&!r)return-2;if(i0&-1088||M!==0&&HEAP32[M>>2]&2&&!e)return-1;if(i0&32)return-2;if(d0!==0&&d0!==1&&d0!==2)return-7;if(u0!==0&&u0!==2&&u0!==10)return-6;if(r&&(r=UTF8ToString(r),a0=parseInt(r,10),isNaN(a0)))return i0&1024?-2:-8;if(!e)return u0===0&&(u0=2),i0&1||(u0===2?s0=_htonl(2130706433):s0=[0,0,0,_htonl(1)]),_0=f0(u0,d0,m0,null,s0,a0),HEAPU32[r0>>2]=_0,0;if(e=UTF8ToString(e),s0=inetPton4(e),s0!==null)if(u0===0||u0===2)u0=2;else if(u0===10&&i0&8)s0=[0,0,_htonl(65535),s0],u0=10;else return-2;else if(s0=inetPton6(e),s0!==null)if(u0===0||u0===10)u0=10;else return-2;return s0!=null?(_0=f0(u0,d0,m0,e,s0,a0),HEAPU32[r0>>2]=_0,0):i0&4?-2:(e=DNS.lookup_name(e),s0=inetPton4(e),u0===0?u0=2:u0===10&&(s0=[0,0,_htonl(65535),s0]),_0=f0(u0,d0,m0,null,s0,a0),HEAPU32[r0>>2]=_0,0)};_getaddrinfo.sig="ipppp";var _getnameinfo=(e,r,M,r0,s0,a0,i0)=>{var u0=readSockaddr(e,r);if(u0.errno)return-6;var d0=u0.port,m0=u0.addr,_0=!1;if(M&&r0){var f0;if(i0&1||!(f0=DNS.lookup_addr(m0))){if(i0&8)return-2}else m0=f0;var g0=stringToUTF8(m0,M,r0);g0+1>=r0&&(_0=!0)}if(s0&&a0){d0=""+d0;var g0=stringToUTF8(d0,s0,a0);g0+1>=a0&&(_0=!0)}return _0?-12:0};_getnameinfo.sig="ipipipii";var stringToNewUTF8=e=>{var r=lengthBytesUTF8(e)+1,M=_malloc(r);return M&&stringToUTF8(e,M,r),M},removeFunction=e=>{functionsInTableMap.delete(getWasmTableEntry(e)),setWasmTableEntry(e,null),freeTableIndexes.push(e)},FS_createPath=FS.createPath,FS_unlink=e=>FS.unlink(e),FS_createLazyFile=FS.createLazyFile,FS_createDevice=FS.createDevice,setTempRet0=e=>__emscripten_tempret_set(e),_setTempRet0=setTempRet0;Module._setTempRet0=_setTempRet0;var getTempRet0=e=>__emscripten_tempret_get(),_getTempRet0=getTempRet0;Module._getTempRet0=_getTempRet0,registerWasmPlugin(),FS.createPreloadedFile=FS_createPreloadedFile,FS.staticInit(),Module.FS_createPath=FS.createPath,Module.FS_createDataFile=FS.createDataFile,Module.FS_createPreloadedFile=FS.createPreloadedFile,Module.FS_unlink=FS.unlink,Module.FS_createLazyFile=FS.createLazyFile,Module.FS_createDevice=FS.createDevice,MEMFS.doesNotExistError=new FS.ErrnoError(44),MEMFS.doesNotExistError.stack="",ENVIRONMENT_IS_NODE&&NODEFS.staticInit();var wasmImports={__assert_fail:___assert_fail,__call_sighandler:___call_sighandler,__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_pointer:___stack_pointer,__syscall__newselect:___syscall__newselect,__syscall_bind:___syscall_bind,__syscall_chdir:___syscall_chdir,__syscall_chmod:___syscall_chmod,__syscall_connect:___syscall_connect,__syscall_dup:___syscall_dup,__syscall_dup3:___syscall_dup3,__syscall_faccessat:___syscall_faccessat,__syscall_fadvise64:___syscall_fadvise64,__syscall_fallocate:___syscall_fallocate,__syscall_fcntl64:___syscall_fcntl64,__syscall_fdatasync:___syscall_fdatasync,__syscall_fstat64:___syscall_fstat64,__syscall_ftruncate64:___syscall_ftruncate64,__syscall_getcwd:___syscall_getcwd,__syscall_getdents64:___syscall_getdents64,__syscall_ioctl:___syscall_ioctl,__syscall_lstat64:___syscall_lstat64,__syscall_mkdirat:___syscall_mkdirat,__syscall_newfstatat:___syscall_newfstatat,__syscall_openat:___syscall_openat,__syscall_pipe:___syscall_pipe,__syscall_poll:___syscall_poll,__syscall_readlinkat:___syscall_readlinkat,__syscall_recvfrom:___syscall_recvfrom,__syscall_renameat:___syscall_renameat,__syscall_rmdir:___syscall_rmdir,__syscall_sendto:___syscall_sendto,__syscall_socket:___syscall_socket,__syscall_stat64:___syscall_stat64,__syscall_symlinkat:___syscall_symlinkat,__syscall_truncate64:___syscall_truncate64,__syscall_unlinkat:___syscall_unlinkat,__table_base:___table_base,_abort_js:__abort_js,_dlopen_js:__dlopen_js,_dlsym_js:__dlsym_js,_emscripten_memcpy_js:__emscripten_memcpy_js,_emscripten_runtime_keepalive_clear:__emscripten_runtime_keepalive_clear,_emscripten_system:__emscripten_system,_emscripten_throw_longjmp:__emscripten_throw_longjmp,_gmtime_js:__gmtime_js,_localtime_js:__localtime_js,_mmap_js:__mmap_js,_munmap_js:__munmap_js,_setitimer_js:__setitimer_js,_tzset_js:__tzset_js,clock_time_get:_clock_time_get,emscripten_asm_const_int:_emscripten_asm_const_int,emscripten_date_now:_emscripten_date_now,emscripten_force_exit:_emscripten_force_exit,emscripten_get_now:_emscripten_get_now,emscripten_resize_heap:_emscripten_resize_heap,environ_get:_environ_get,environ_sizes_get:_environ_sizes_get,exit:_exit,fd_close:_fd_close,fd_fdstat_get:_fd_fdstat_get,fd_pread:_fd_pread,fd_pwrite:_fd_pwrite,fd_read:_fd_read,fd_seek:_fd_seek,fd_sync:_fd_sync,fd_write:_fd_write,getTempRet0:_getTempRet0,getaddrinfo:_getaddrinfo,getnameinfo:_getnameinfo,invoke_di,invoke_i,invoke_id,invoke_ii,invoke_iii,invoke_iiii,invoke_iiiii,invoke_iiiiii,invoke_iiiiiii,invoke_iiiiiiii,invoke_iiiiiiiii,invoke_iiiiiiiiii,invoke_iiiiiiiiiii,invoke_iiiiiiiiiiiiii,invoke_iiiiiiiiiiiiiiiiii,invoke_iiiiiji,invoke_iiiij,invoke_iiiijii,invoke_iiij,invoke_iiji,invoke_ij,invoke_ijiiiii,invoke_ijiiiiii,invoke_j,invoke_ji,invoke_jii,invoke_jiiii,invoke_jiiiiii,invoke_jiiiiiiiii,invoke_v,invoke_vi,invoke_vid,invoke_vii,invoke_viii,invoke_viiii,invoke_viiiii,invoke_viiiiii,invoke_viiiiiii,invoke_viiiiiiii,invoke_viiiiiiiii,invoke_viiiiiiiiiiii,invoke_viiiji,invoke_viij,invoke_viiji,invoke_viijii,invoke_viijiiii,invoke_vij,invoke_viji,invoke_vijiji,invoke_vj,invoke_vji,memory:wasmMemory,proc_exit:_proc_exit,setTempRet0:_setTempRet0},wasmExports;createWasm();var _fflush=Module._fflush=e=>(_fflush=Module._fflush=wasmExports.fflush)(e);Module.___errno_location=()=>(Module.___errno_location=wasmExports.__errno_location)(),Module._ProcessInterrupts=()=>(Module._ProcessInterrupts=wasmExports.ProcessInterrupts)(),Module._errstart_cold=(e,r)=>(Module._errstart_cold=wasmExports.errstart_cold)(e,r),Module._errcode=e=>(Module._errcode=wasmExports.errcode)(e),Module._errmsg=(e,r)=>(Module._errmsg=wasmExports.errmsg)(e,r),Module._errfinish=(e,r,M)=>(Module._errfinish=wasmExports.errfinish)(e,r,M),Module._puts=e=>(Module._puts=wasmExports.puts)(e),Module._errstart=(e,r)=>(Module._errstart=wasmExports.errstart)(e,r),Module._errmsg_internal=(e,r)=>(Module._errmsg_internal=wasmExports.errmsg_internal)(e,r),Module._errdetail=(e,r)=>(Module._errdetail=wasmExports.errdetail)(e,r),Module._errhint=(e,r)=>(Module._errhint=wasmExports.errhint)(e,r),Module._pg_parse_query=e=>(Module._pg_parse_query=wasmExports.pg_parse_query)(e),Module._gettimeofday=(e,r)=>(Module._gettimeofday=wasmExports.gettimeofday)(e,r),Module._raw_parser=(e,r)=>(Module._raw_parser=wasmExports.raw_parser)(e,r),Module._initStringInfo=e=>(Module._initStringInfo=wasmExports.initStringInfo)(e),Module._appendStringInfoString=(e,r)=>(Module._appendStringInfoString=wasmExports.appendStringInfoString)(e,r),Module._appendStringInfo=(e,r,M)=>(Module._appendStringInfo=wasmExports.appendStringInfo)(e,r,M),Module._errdetail_internal=(e,r)=>(Module._errdetail_internal=wasmExports.errdetail_internal)(e,r),Module._pfree=e=>(Module._pfree=wasmExports.pfree)(e),Module._list_make1_impl=(e,r)=>(Module._list_make1_impl=wasmExports.list_make1_impl)(e,r),Module._QueryRewrite=e=>(Module._QueryRewrite=wasmExports.QueryRewrite)(e),Module._pg_plan_query=(e,r,M,r0)=>(Module._pg_plan_query=wasmExports.pg_plan_query)(e,r,M,r0),Module._palloc0=e=>(Module._palloc0=wasmExports.palloc0)(e),Module._lappend=(e,r)=>(Module._lappend=wasmExports.lappend)(e,r),Module._GetCurrentTimestamp=()=>(Module._GetCurrentTimestamp=wasmExports.GetCurrentTimestamp)(),Module._pg_prng_double=e=>(Module._pg_prng_double=wasmExports.pg_prng_double)(e),Module._pg_snprintf=(e,r,M,r0)=>(Module._pg_snprintf=wasmExports.pg_snprintf)(e,r,M,r0),Module._die=e=>(Module._die=wasmExports.die)(e),Module._check_stack_depth=()=>(Module._check_stack_depth=wasmExports.check_stack_depth)(),Module._pre_format_elog_string=(e,r)=>(Module._pre_format_elog_string=wasmExports.pre_format_elog_string)(e,r),Module._format_elog_string=(e,r)=>(Module._format_elog_string=wasmExports.format_elog_string)(e,r),Module._pstrdup=e=>(Module._pstrdup=wasmExports.pstrdup)(e),Module._SplitIdentifierString=(e,r,M)=>(Module._SplitIdentifierString=wasmExports.SplitIdentifierString)(e,r,M),Module._list_free=e=>(Module._list_free=wasmExports.list_free)(e),Module._pg_strcasecmp=(e,r)=>(Module._pg_strcasecmp=wasmExports.pg_strcasecmp)(e,r),Module._guc_malloc=(e,r)=>(Module._guc_malloc=wasmExports.guc_malloc)(e,r),Module._SetConfigOption=(e,r,M,r0)=>(Module._SetConfigOption=wasmExports.SetConfigOption)(e,r,M,r0),Module._pg_sprintf=(e,r,M)=>(Module._pg_sprintf=wasmExports.pg_sprintf)(e,r,M),Module._strcmp=(e,r)=>(Module._strcmp=wasmExports.strcmp)(e,r),Module._atoi=e=>(Module._atoi=wasmExports.atoi)(e),Module._pgl_shutdown=()=>(Module._pgl_shutdown=wasmExports.pgl_shutdown)(),Module._pgl_closed=()=>(Module._pgl_closed=wasmExports.pgl_closed)(),Module._MemoryContextReset=e=>(Module._MemoryContextReset=wasmExports.MemoryContextReset)(e),Module._resetStringInfo=e=>(Module._resetStringInfo=wasmExports.resetStringInfo)(e),Module._getc=e=>(Module._getc=wasmExports.getc)(e),Module._appendStringInfoChar=(e,r)=>(Module._appendStringInfoChar=wasmExports.appendStringInfoChar)(e,r),Module._strlen=e=>(Module._strlen=wasmExports.strlen)(e),Module._strncmp=(e,r,M)=>(Module._strncmp=wasmExports.strncmp)(e,r,M),Module._pg_fprintf=(e,r,M)=>(Module._pg_fprintf=wasmExports.pg_fprintf)(e,r,M),Module._pgstat_report_activity=(e,r)=>(Module._pgstat_report_activity=wasmExports.pgstat_report_activity)(e,r),Module._errhidestmt=e=>(Module._errhidestmt=wasmExports.errhidestmt)(e),Module._GetTransactionSnapshot=()=>(Module._GetTransactionSnapshot=wasmExports.GetTransactionSnapshot)(),Module._PushActiveSnapshot=e=>(Module._PushActiveSnapshot=wasmExports.PushActiveSnapshot)(e),Module._AllocSetContextCreateInternal=(e,r,M,r0,s0)=>(Module._AllocSetContextCreateInternal=wasmExports.AllocSetContextCreateInternal)(e,r,M,r0,s0),Module._PopActiveSnapshot=()=>(Module._PopActiveSnapshot=wasmExports.PopActiveSnapshot)(),Module._CreateDestReceiver=e=>(Module._CreateDestReceiver=wasmExports.CreateDestReceiver)(e),Module._CommitTransactionCommand=()=>(Module._CommitTransactionCommand=wasmExports.CommitTransactionCommand)(),Module._CommandCounterIncrement=()=>(Module._CommandCounterIncrement=wasmExports.CommandCounterIncrement)(),Module._MemoryContextDelete=e=>(Module._MemoryContextDelete=wasmExports.MemoryContextDelete)(e),Module._StartTransactionCommand=()=>(Module._StartTransactionCommand=wasmExports.StartTransactionCommand)(),Module.___wasm_setjmp_test=(e,r)=>(Module.___wasm_setjmp_test=wasmExports.__wasm_setjmp_test)(e,r),Module._pg_printf=(e,r)=>(Module._pg_printf=wasmExports.pg_printf)(e,r),Module.___wasm_setjmp=(e,r,M)=>(Module.___wasm_setjmp=wasmExports.__wasm_setjmp)(e,r,M),Module._FlushErrorState=()=>(Module._FlushErrorState=wasmExports.FlushErrorState)(),Module._emscripten_longjmp=(e,r)=>(Module._emscripten_longjmp=wasmExports.emscripten_longjmp)(e,r),Module._enlargeStringInfo=(e,r)=>(Module._enlargeStringInfo=wasmExports.enlargeStringInfo)(e,r);var _malloc=Module._malloc=e=>(_malloc=Module._malloc=wasmExports.malloc)(e);Module._realloc=(e,r)=>(Module._realloc=wasmExports.realloc)(e,r),Module._strspn=(e,r)=>(Module._strspn=wasmExports.strspn)(e,r),Module._memcpy=(e,r,M)=>(Module._memcpy=wasmExports.memcpy)(e,r,M),Module._fileno=e=>(Module._fileno=wasmExports.fileno)(e),Module._strchr=(e,r)=>(Module._strchr=wasmExports.strchr)(e,r),Module._free=e=>(Module._free=wasmExports.free)(e),Module._pg_vsnprintf=(e,r,M,r0)=>(Module._pg_vsnprintf=wasmExports.pg_vsnprintf)(e,r,M,r0),Module._strcpy=(e,r)=>(Module._strcpy=wasmExports.strcpy)(e,r),Module._psprintf=(e,r)=>(Module._psprintf=wasmExports.psprintf)(e,r),Module._stat=(e,r)=>(Module._stat=wasmExports.stat)(e,r),Module._fwrite=(e,r,M,r0)=>(Module._fwrite=wasmExports.fwrite)(e,r,M,r0),Module._strftime=(e,r,M,r0)=>(Module._strftime=wasmExports.strftime)(e,r,M,r0),Module._strstr=(e,r)=>(Module._strstr=wasmExports.strstr)(e,r),Module._strtol=(e,r,M)=>(Module._strtol=wasmExports.strtol)(e,r,M),Module._ferror=e=>(Module._ferror=wasmExports.ferror)(e),Module._set_read_write_cbs=(e,r)=>(Module._set_read_write_cbs=wasmExports.set_read_write_cbs)(e,r),Module._clear_error=()=>(Module._clear_error=wasmExports.clear_error)(),Module._interactive_one=(e,r)=>(Module._interactive_one=wasmExports.interactive_one)(e,r),Module._pq_getmsgint=(e,r)=>(Module._pq_getmsgint=wasmExports.pq_getmsgint)(e,r),Module._palloc=e=>(Module._palloc=wasmExports.palloc)(e),Module._makeParamList=e=>(Module._makeParamList=wasmExports.makeParamList)(e),Module._getTypeInputInfo=(e,r,M)=>(Module._getTypeInputInfo=wasmExports.getTypeInputInfo)(e,r,M),Module._pnstrdup=(e,r)=>(Module._pnstrdup=wasmExports.pnstrdup)(e,r),Module._MemoryContextSetParent=(e,r)=>(Module._MemoryContextSetParent=wasmExports.MemoryContextSetParent)(e,r),Module._pgl_backend=()=>(Module._pgl_backend=wasmExports.pgl_backend)(),Module._pgl_initdb=()=>(Module._pgl_initdb=wasmExports.pgl_initdb)(),Module._main=(e,r)=>(Module._main=wasmExports.__main_argc_argv)(e,r),Module._appendStringInfoStringQuoted=(e,r,M)=>(Module._appendStringInfoStringQuoted=wasmExports.appendStringInfoStringQuoted)(e,r,M),Module._set_errcontext_domain=e=>(Module._set_errcontext_domain=wasmExports.set_errcontext_domain)(e),Module._errcontext_msg=(e,r)=>(Module._errcontext_msg=wasmExports.errcontext_msg)(e,r),Module._memchr=(e,r,M)=>(Module._memchr=wasmExports.memchr)(e,r,M),Module._strrchr=(e,r)=>(Module._strrchr=wasmExports.strrchr)(e,r),Module._xsltFreeStylesheet=e=>(Module._xsltFreeStylesheet=wasmExports.xsltFreeStylesheet)(e),Module._xsltParseStylesheetDoc=e=>(Module._xsltParseStylesheetDoc=wasmExports.xsltParseStylesheetDoc)(e),Module._xsltSaveResultToString=(e,r,M,r0)=>(Module._xsltSaveResultToString=wasmExports.xsltSaveResultToString)(e,r,M,r0),Module._xsltCleanupGlobals=()=>(Module._xsltCleanupGlobals=wasmExports.xsltCleanupGlobals)(),Module._xsltNewTransformContext=(e,r)=>(Module._xsltNewTransformContext=wasmExports.xsltNewTransformContext)(e,r),Module._xsltFreeTransformContext=e=>(Module._xsltFreeTransformContext=wasmExports.xsltFreeTransformContext)(e),Module._xsltApplyStylesheetUser=(e,r,M,r0,s0,a0)=>(Module._xsltApplyStylesheetUser=wasmExports.xsltApplyStylesheetUser)(e,r,M,r0,s0,a0),Module._xsltNewSecurityPrefs=()=>(Module._xsltNewSecurityPrefs=wasmExports.xsltNewSecurityPrefs)(),Module._xsltFreeSecurityPrefs=e=>(Module._xsltFreeSecurityPrefs=wasmExports.xsltFreeSecurityPrefs)(e),Module._xsltSetSecurityPrefs=(e,r,M)=>(Module._xsltSetSecurityPrefs=wasmExports.xsltSetSecurityPrefs)(e,r,M),Module._xsltSetCtxtSecurityPrefs=(e,r)=>(Module._xsltSetCtxtSecurityPrefs=wasmExports.xsltSetCtxtSecurityPrefs)(e,r),Module._xsltSecurityForbid=(e,r,M)=>(Module._xsltSecurityForbid=wasmExports.xsltSecurityForbid)(e,r,M),Module._replace_percent_placeholders=(e,r,M,r0)=>(Module._replace_percent_placeholders=wasmExports.replace_percent_placeholders)(e,r,M,r0),Module._memset=(e,r,M)=>(Module._memset=wasmExports.memset)(e,r,M),Module._MemoryContextAllocZero=(e,r)=>(Module._MemoryContextAllocZero=wasmExports.MemoryContextAllocZero)(e,r),Module._MemoryContextAllocExtended=(e,r,M)=>(Module._MemoryContextAllocExtended=wasmExports.MemoryContextAllocExtended)(e,r,M),Module._hash_bytes=(e,r)=>(Module._hash_bytes=wasmExports.hash_bytes)(e,r),Module._memcmp=(e,r,M)=>(Module._memcmp=wasmExports.memcmp)(e,r,M),Module._repalloc=(e,r)=>(Module._repalloc=wasmExports.repalloc)(e,r),Module._pg_qsort=(e,r,M,r0)=>(Module._pg_qsort=wasmExports.pg_qsort)(e,r,M,r0),Module._OpenTransientFile=(e,r)=>(Module._OpenTransientFile=wasmExports.OpenTransientFile)(e,r),Module._errcode_for_file_access=()=>(Module._errcode_for_file_access=wasmExports.errcode_for_file_access)(),Module._read=(e,r,M)=>(Module._read=wasmExports.read)(e,r,M),Module._CloseTransientFile=e=>(Module._CloseTransientFile=wasmExports.CloseTransientFile)(e),Module._close=e=>(Module._close=wasmExports.close)(e),Module.___multi3=(e,r,M,r0,s0)=>(Module.___multi3=wasmExports.__multi3)(e,r,M,r0,s0),Module._isalnum=e=>(Module._isalnum=wasmExports.isalnum)(e),Module._wait_result_to_str=e=>(Module._wait_result_to_str=wasmExports.wait_result_to_str)(e),Module._float_to_shortest_decimal_bufn=(e,r)=>(Module._float_to_shortest_decimal_bufn=wasmExports.float_to_shortest_decimal_bufn)(e,r),Module._float_to_shortest_decimal_buf=(e,r)=>(Module._float_to_shortest_decimal_buf=wasmExports.float_to_shortest_decimal_buf)(e,r),Module._memmove=(e,r,M)=>(Module._memmove=wasmExports.memmove)(e,r,M),Module._pwrite=(e,r,M,r0)=>(Module._pwrite=wasmExports.pwrite)(e,r,M,r0),Module._hash_bytes_extended=(e,r,M)=>(Module._hash_bytes_extended=wasmExports.hash_bytes_extended)(e,r,M);var _calloc=(e,r)=>(_calloc=wasmExports.calloc)(e,r);Module._IsValidJsonNumber=(e,r)=>(Module._IsValidJsonNumber=wasmExports.IsValidJsonNumber)(e,r),Module._appendBinaryStringInfo=(e,r,M)=>(Module._appendBinaryStringInfo=wasmExports.appendBinaryStringInfo)(e,r,M),Module._makeStringInfo=()=>(Module._makeStringInfo=wasmExports.makeStringInfo)(),Module._GetDatabaseEncodingName=()=>(Module._GetDatabaseEncodingName=wasmExports.GetDatabaseEncodingName)(),Module._ScanKeywordLookup=(e,r)=>(Module._ScanKeywordLookup=wasmExports.ScanKeywordLookup)(e,r),Module._strtoul=(e,r,M)=>(Module._strtoul=wasmExports.strtoul)(e,r,M),Module._sscanf=(e,r,M)=>(Module._sscanf=wasmExports.sscanf)(e,r,M),Module._pg_prng_uint64=e=>(Module._pg_prng_uint64=wasmExports.pg_prng_uint64)(e),Module._pg_prng_uint32=e=>(Module._pg_prng_uint32=wasmExports.pg_prng_uint32)(e),Module._log=e=>(Module._log=wasmExports.log)(e),Module._sin=e=>(Module._sin=wasmExports.sin)(e),Module._forkname_to_number=e=>(Module._forkname_to_number=wasmExports.forkname_to_number)(e),Module._unlink=e=>(Module._unlink=wasmExports.unlink)(e),Module._pg_utf_mblen_private=e=>(Module._pg_utf_mblen_private=wasmExports.pg_utf_mblen_private)(e),Module._bsearch=(e,r,M,r0,s0)=>(Module._bsearch=wasmExports.bsearch)(e,r,M,r0,s0),Module._palloc_extended=(e,r)=>(Module._palloc_extended=wasmExports.palloc_extended)(e,r),Module._appendStringInfoSpaces=(e,r)=>(Module._appendStringInfoSpaces=wasmExports.appendStringInfoSpaces)(e,r),Module._fcntl=(e,r,M)=>(Module._fcntl=wasmExports.fcntl)(e,r,M),Module._pg_popcount_optimized=(e,r)=>(Module._pg_popcount_optimized=wasmExports.pg_popcount_optimized)(e,r),Module._open=(e,r,M)=>(Module._open=wasmExports.open)(e,r,M),Module._pg_usleep=e=>(Module._pg_usleep=wasmExports.pg_usleep)(e),Module._nanosleep=(e,r)=>(Module._nanosleep=wasmExports.nanosleep)(e,r),Module._getpid=()=>(Module._getpid=wasmExports.getpid)(),Module._qsort_arg=(e,r,M,r0,s0)=>(Module._qsort_arg=wasmExports.qsort_arg)(e,r,M,r0,s0),Module._RelationGetNumberOfBlocksInFork=(e,r)=>(Module._RelationGetNumberOfBlocksInFork=wasmExports.RelationGetNumberOfBlocksInFork)(e,r),Module._ExtendBufferedRel=(e,r,M,r0)=>(Module._ExtendBufferedRel=wasmExports.ExtendBufferedRel)(e,r,M,r0),Module._MarkBufferDirty=e=>(Module._MarkBufferDirty=wasmExports.MarkBufferDirty)(e),Module._XLogBeginInsert=()=>(Module._XLogBeginInsert=wasmExports.XLogBeginInsert)(),Module._XLogRegisterData=(e,r)=>(Module._XLogRegisterData=wasmExports.XLogRegisterData)(e,r),Module._XLogInsert=(e,r)=>(Module._XLogInsert=wasmExports.XLogInsert)(e,r),Module._UnlockReleaseBuffer=e=>(Module._UnlockReleaseBuffer=wasmExports.UnlockReleaseBuffer)(e),Module._brin_build_desc=e=>(Module._brin_build_desc=wasmExports.brin_build_desc)(e),Module._EnterParallelMode=()=>(Module._EnterParallelMode=wasmExports.EnterParallelMode)(),Module._CreateParallelContext=(e,r,M)=>(Module._CreateParallelContext=wasmExports.CreateParallelContext)(e,r,M),Module._RegisterSnapshot=e=>(Module._RegisterSnapshot=wasmExports.RegisterSnapshot)(e),Module._table_parallelscan_estimate=(e,r)=>(Module._table_parallelscan_estimate=wasmExports.table_parallelscan_estimate)(e,r),Module._add_size=(e,r)=>(Module._add_size=wasmExports.add_size)(e,r),Module._tuplesort_estimate_shared=e=>(Module._tuplesort_estimate_shared=wasmExports.tuplesort_estimate_shared)(e),Module._InitializeParallelDSM=e=>(Module._InitializeParallelDSM=wasmExports.InitializeParallelDSM)(e),Module._UnregisterSnapshot=e=>(Module._UnregisterSnapshot=wasmExports.UnregisterSnapshot)(e),Module._DestroyParallelContext=e=>(Module._DestroyParallelContext=wasmExports.DestroyParallelContext)(e),Module._ExitParallelMode=()=>(Module._ExitParallelMode=wasmExports.ExitParallelMode)(),Module._shm_toc_allocate=(e,r)=>(Module._shm_toc_allocate=wasmExports.shm_toc_allocate)(e,r),Module._ConditionVariableInit=e=>(Module._ConditionVariableInit=wasmExports.ConditionVariableInit)(e),Module._s_init_lock_sema=(e,r)=>(Module._s_init_lock_sema=wasmExports.s_init_lock_sema)(e,r),Module._table_parallelscan_initialize=(e,r,M)=>(Module._table_parallelscan_initialize=wasmExports.table_parallelscan_initialize)(e,r,M),Module._tuplesort_initialize_shared=(e,r,M)=>(Module._tuplesort_initialize_shared=wasmExports.tuplesort_initialize_shared)(e,r,M),Module._shm_toc_insert=(e,r,M)=>(Module._shm_toc_insert=wasmExports.shm_toc_insert)(e,r,M),Module._LaunchParallelWorkers=e=>(Module._LaunchParallelWorkers=wasmExports.LaunchParallelWorkers)(e),Module._WaitForParallelWorkersToAttach=e=>(Module._WaitForParallelWorkersToAttach=wasmExports.WaitForParallelWorkersToAttach)(e),Module._tas_sema=e=>(Module._tas_sema=wasmExports.tas_sema)(e),Module._s_lock=(e,r,M,r0)=>(Module._s_lock=wasmExports.s_lock)(e,r,M,r0),Module._s_unlock_sema=e=>(Module._s_unlock_sema=wasmExports.s_unlock_sema)(e),Module._ConditionVariableSleep=(e,r)=>(Module._ConditionVariableSleep=wasmExports.ConditionVariableSleep)(e,r),Module._ConditionVariableCancelSleep=()=>(Module._ConditionVariableCancelSleep=wasmExports.ConditionVariableCancelSleep)(),Module._tuplesort_performsort=e=>(Module._tuplesort_performsort=wasmExports.tuplesort_performsort)(e),Module._tuplesort_end=e=>(Module._tuplesort_end=wasmExports.tuplesort_end)(e),Module._brin_deform_tuple=(e,r,M)=>(Module._brin_deform_tuple=wasmExports.brin_deform_tuple)(e,r,M),Module._log_newpage_buffer=(e,r)=>(Module._log_newpage_buffer=wasmExports.log_newpage_buffer)(e,r),Module._LockBuffer=(e,r)=>(Module._LockBuffer=wasmExports.LockBuffer)(e,r),Module._ReleaseBuffer=e=>(Module._ReleaseBuffer=wasmExports.ReleaseBuffer)(e),Module._IndexGetRelation=(e,r)=>(Module._IndexGetRelation=wasmExports.IndexGetRelation)(e,r),Module._table_open=(e,r)=>(Module._table_open=wasmExports.table_open)(e,r),Module._ReadBufferExtended=(e,r,M,r0,s0)=>(Module._ReadBufferExtended=wasmExports.ReadBufferExtended)(e,r,M,r0,s0),Module._table_close=(e,r)=>(Module._table_close=wasmExports.table_close)(e,r),Module._build_reloptions=(e,r,M,r0,s0,a0)=>(Module._build_reloptions=wasmExports.build_reloptions)(e,r,M,r0,s0,a0),Module._RelationGetIndexScan=(e,r,M)=>(Module._RelationGetIndexScan=wasmExports.RelationGetIndexScan)(e,r,M),Module._pgstat_assoc_relation=e=>(Module._pgstat_assoc_relation=wasmExports.pgstat_assoc_relation)(e),Module._index_getprocinfo=(e,r,M)=>(Module._index_getprocinfo=wasmExports.index_getprocinfo)(e,r,M),Module._fmgr_info_copy=(e,r,M)=>(Module._fmgr_info_copy=wasmExports.fmgr_info_copy)(e,r,M),Module._FunctionCall4Coll=(e,r,M,r0,s0,a0)=>(Module._FunctionCall4Coll=wasmExports.FunctionCall4Coll)(e,r,M,r0,s0,a0),Module._FunctionCall1Coll=(e,r,M)=>(Module._FunctionCall1Coll=wasmExports.FunctionCall1Coll)(e,r,M),Module._brin_free_desc=e=>(Module._brin_free_desc=wasmExports.brin_free_desc)(e),Module._WaitForParallelWorkersToFinish=e=>(Module._WaitForParallelWorkersToFinish=wasmExports.WaitForParallelWorkersToFinish)(e),Module._PageGetFreeSpace=e=>(Module._PageGetFreeSpace=wasmExports.PageGetFreeSpace)(e),Module._BufferGetBlockNumber=e=>(Module._BufferGetBlockNumber=wasmExports.BufferGetBlockNumber)(e),Module._BuildIndexInfo=e=>(Module._BuildIndexInfo=wasmExports.BuildIndexInfo)(e),Module._Int64GetDatum=e=>(Module._Int64GetDatum=wasmExports.Int64GetDatum)(e),Module._DirectFunctionCall2Coll=(e,r,M,r0)=>(Module._DirectFunctionCall2Coll=wasmExports.DirectFunctionCall2Coll)(e,r,M,r0),Module._RecoveryInProgress=()=>(Module._RecoveryInProgress=wasmExports.RecoveryInProgress)(),Module._GetUserIdAndSecContext=(e,r)=>(Module._GetUserIdAndSecContext=wasmExports.GetUserIdAndSecContext)(e,r),Module._SetUserIdAndSecContext=(e,r)=>(Module._SetUserIdAndSecContext=wasmExports.SetUserIdAndSecContext)(e,r),Module._NewGUCNestLevel=()=>(Module._NewGUCNestLevel=wasmExports.NewGUCNestLevel)(),Module._RestrictSearchPath=()=>(Module._RestrictSearchPath=wasmExports.RestrictSearchPath)(),Module._index_open=(e,r)=>(Module._index_open=wasmExports.index_open)(e,r),Module._object_ownercheck=(e,r,M)=>(Module._object_ownercheck=wasmExports.object_ownercheck)(e,r,M),Module._aclcheck_error=(e,r,M)=>(Module._aclcheck_error=wasmExports.aclcheck_error)(e,r,M),Module._AtEOXact_GUC=(e,r)=>(Module._AtEOXact_GUC=wasmExports.AtEOXact_GUC)(e,r),Module._relation_close=(e,r)=>(Module._relation_close=wasmExports.relation_close)(e,r),Module._GetUserId=()=>(Module._GetUserId=wasmExports.GetUserId)(),Module._ReadBuffer=(e,r)=>(Module._ReadBuffer=wasmExports.ReadBuffer)(e,r),Module._shm_toc_lookup=(e,r,M)=>(Module._shm_toc_lookup=wasmExports.shm_toc_lookup)(e,r,M),Module._tuplesort_attach_shared=(e,r)=>(Module._tuplesort_attach_shared=wasmExports.tuplesort_attach_shared)(e,r),Module._index_close=(e,r)=>(Module._index_close=wasmExports.index_close)(e,r),Module._table_beginscan_parallel=(e,r)=>(Module._table_beginscan_parallel=wasmExports.table_beginscan_parallel)(e,r),Module._ConditionVariableSignal=e=>(Module._ConditionVariableSignal=wasmExports.ConditionVariableSignal)(e),Module._datumCopy=(e,r,M)=>(Module._datumCopy=wasmExports.datumCopy)(e,r,M),Module._lookup_type_cache=(e,r)=>(Module._lookup_type_cache=wasmExports.lookup_type_cache)(e,r),Module._get_fn_opclass_options=e=>(Module._get_fn_opclass_options=wasmExports.get_fn_opclass_options)(e),Module._pg_detoast_datum=e=>(Module._pg_detoast_datum=wasmExports.pg_detoast_datum)(e),Module._index_getprocid=(e,r,M)=>(Module._index_getprocid=wasmExports.index_getprocid)(e,r,M),Module._init_local_reloptions=(e,r)=>(Module._init_local_reloptions=wasmExports.init_local_reloptions)(e,r),Module._FunctionCall2Coll=(e,r,M,r0)=>(Module._FunctionCall2Coll=wasmExports.FunctionCall2Coll)(e,r,M,r0),Module._SysCacheGetAttrNotNull=(e,r,M)=>(Module._SysCacheGetAttrNotNull=wasmExports.SysCacheGetAttrNotNull)(e,r,M),Module._ReleaseSysCache=e=>(Module._ReleaseSysCache=wasmExports.ReleaseSysCache)(e),Module._fmgr_info_cxt=(e,r,M)=>(Module._fmgr_info_cxt=wasmExports.fmgr_info_cxt)(e,r,M),Module._Float8GetDatum=e=>(Module._Float8GetDatum=wasmExports.Float8GetDatum)(e),Module._numeric_sub=e=>(Module._numeric_sub=wasmExports.numeric_sub)(e),Module._DirectFunctionCall1Coll=(e,r,M)=>(Module._DirectFunctionCall1Coll=wasmExports.DirectFunctionCall1Coll)(e,r,M),Module._pg_detoast_datum_packed=e=>(Module._pg_detoast_datum_packed=wasmExports.pg_detoast_datum_packed)(e),Module._add_local_int_reloption=(e,r,M,r0,s0,a0,i0)=>(Module._add_local_int_reloption=wasmExports.add_local_int_reloption)(e,r,M,r0,s0,a0,i0),Module._getTypeOutputInfo=(e,r,M)=>(Module._getTypeOutputInfo=wasmExports.getTypeOutputInfo)(e,r,M),Module._fmgr_info=(e,r)=>(Module._fmgr_info=wasmExports.fmgr_info)(e,r),Module._OutputFunctionCall=(e,r)=>(Module._OutputFunctionCall=wasmExports.OutputFunctionCall)(e,r),Module._cstring_to_text_with_len=(e,r)=>(Module._cstring_to_text_with_len=wasmExports.cstring_to_text_with_len)(e,r),Module._accumArrayResult=(e,r,M,r0,s0)=>(Module._accumArrayResult=wasmExports.accumArrayResult)(e,r,M,r0,s0),Module._makeArrayResult=(e,r)=>(Module._makeArrayResult=wasmExports.makeArrayResult)(e,r),Module._OidOutputFunctionCall=(e,r)=>(Module._OidOutputFunctionCall=wasmExports.OidOutputFunctionCall)(e,r),Module._cstring_to_text=e=>(Module._cstring_to_text=wasmExports.cstring_to_text)(e),Module._PageGetExactFreeSpace=e=>(Module._PageGetExactFreeSpace=wasmExports.PageGetExactFreeSpace)(e),Module._PageIndexTupleOverwrite=(e,r,M,r0)=>(Module._PageIndexTupleOverwrite=wasmExports.PageIndexTupleOverwrite)(e,r,M,r0),Module._PageInit=(e,r,M)=>(Module._PageInit=wasmExports.PageInit)(e,r,M),Module._PageAddItemExtended=(e,r,M,r0,s0)=>(Module._PageAddItemExtended=wasmExports.PageAddItemExtended)(e,r,M,r0,s0),Module._LockRelationForExtension=(e,r)=>(Module._LockRelationForExtension=wasmExports.LockRelationForExtension)(e,r),Module._UnlockRelationForExtension=(e,r)=>(Module._UnlockRelationForExtension=wasmExports.UnlockRelationForExtension)(e,r),Module._smgropen=(e,r)=>(Module._smgropen=wasmExports.smgropen)(e,r),Module._smgrpin=e=>(Module._smgrpin=wasmExports.smgrpin)(e),Module._ItemPointerEquals=(e,r)=>(Module._ItemPointerEquals=wasmExports.ItemPointerEquals)(e,r),Module._detoast_external_attr=e=>(Module._detoast_external_attr=wasmExports.detoast_external_attr)(e),Module._CreateTemplateTupleDesc=e=>(Module._CreateTemplateTupleDesc=wasmExports.CreateTemplateTupleDesc)(e),Module._TupleDescInitEntry=(e,r,M,r0,s0,a0)=>(Module._TupleDescInitEntry=wasmExports.TupleDescInitEntry)(e,r,M,r0,s0,a0),Module._SearchSysCache1=(e,r)=>(Module._SearchSysCache1=wasmExports.SearchSysCache1)(e,r),Module._SearchSysCacheList=(e,r,M,r0,s0)=>(Module._SearchSysCacheList=wasmExports.SearchSysCacheList)(e,r,M,r0,s0),Module._check_amproc_signature=(e,r,M,r0,s0,a0)=>(Module._check_amproc_signature=wasmExports.check_amproc_signature)(e,r,M,r0,s0,a0),Module._check_amoptsproc_signature=e=>(Module._check_amoptsproc_signature=wasmExports.check_amoptsproc_signature)(e),Module._format_procedure=e=>(Module._format_procedure=wasmExports.format_procedure)(e),Module._format_operator=e=>(Module._format_operator=wasmExports.format_operator)(e),Module._check_amop_signature=(e,r,M,r0)=>(Module._check_amop_signature=wasmExports.check_amop_signature)(e,r,M,r0),Module._identify_opfamily_groups=(e,r)=>(Module._identify_opfamily_groups=wasmExports.identify_opfamily_groups)(e,r),Module._format_type_be=e=>(Module._format_type_be=wasmExports.format_type_be)(e),Module._ReleaseCatCacheList=e=>(Module._ReleaseCatCacheList=wasmExports.ReleaseCatCacheList)(e),Module._format_type_with_typemod=(e,r)=>(Module._format_type_with_typemod=wasmExports.format_type_with_typemod)(e,r),Module._DatumGetEOHP=e=>(Module._DatumGetEOHP=wasmExports.DatumGetEOHP)(e),Module._EOH_get_flat_size=e=>(Module._EOH_get_flat_size=wasmExports.EOH_get_flat_size)(e),Module._EOH_flatten_into=(e,r,M)=>(Module._EOH_flatten_into=wasmExports.EOH_flatten_into)(e,r,M),Module._getmissingattr=(e,r,M)=>(Module._getmissingattr=wasmExports.getmissingattr)(e,r,M),Module._hash_create=(e,r,M,r0)=>(Module._hash_create=wasmExports.hash_create)(e,r,M,r0),Module._hash_search=(e,r,M,r0)=>(Module._hash_search=wasmExports.hash_search)(e,r,M,r0),Module._nocachegetattr=(e,r,M)=>(Module._nocachegetattr=wasmExports.nocachegetattr)(e,r,M),Module._heap_form_tuple=(e,r,M)=>(Module._heap_form_tuple=wasmExports.heap_form_tuple)(e,r,M),Module._heap_modify_tuple=(e,r,M,r0,s0)=>(Module._heap_modify_tuple=wasmExports.heap_modify_tuple)(e,r,M,r0,s0),Module._heap_deform_tuple=(e,r,M,r0)=>(Module._heap_deform_tuple=wasmExports.heap_deform_tuple)(e,r,M,r0),Module._heap_modify_tuple_by_cols=(e,r,M,r0,s0,a0)=>(Module._heap_modify_tuple_by_cols=wasmExports.heap_modify_tuple_by_cols)(e,r,M,r0,s0,a0),Module._heap_freetuple=e=>(Module._heap_freetuple=wasmExports.heap_freetuple)(e),Module._index_form_tuple=(e,r,M)=>(Module._index_form_tuple=wasmExports.index_form_tuple)(e,r,M),Module._nocache_index_getattr=(e,r,M)=>(Module._nocache_index_getattr=wasmExports.nocache_index_getattr)(e,r,M),Module._index_deform_tuple=(e,r,M,r0)=>(Module._index_deform_tuple=wasmExports.index_deform_tuple)(e,r,M,r0),Module._slot_getsomeattrs_int=(e,r)=>(Module._slot_getsomeattrs_int=wasmExports.slot_getsomeattrs_int)(e,r),Module._pg_ltoa=(e,r)=>(Module._pg_ltoa=wasmExports.pg_ltoa)(e,r),Module._relation_open=(e,r)=>(Module._relation_open=wasmExports.relation_open)(e,r),Module._LockRelationOid=(e,r)=>(Module._LockRelationOid=wasmExports.LockRelationOid)(e,r),Module._try_relation_open=(e,r)=>(Module._try_relation_open=wasmExports.try_relation_open)(e,r),Module._relation_openrv=(e,r)=>(Module._relation_openrv=wasmExports.relation_openrv)(e,r),Module._RangeVarGetRelidExtended=(e,r,M,r0,s0)=>(Module._RangeVarGetRelidExtended=wasmExports.RangeVarGetRelidExtended)(e,r,M,r0,s0),Module._add_reloption_kind=()=>(Module._add_reloption_kind=wasmExports.add_reloption_kind)(),Module._register_reloptions_validator=(e,r)=>(Module._register_reloptions_validator=wasmExports.register_reloptions_validator)(e,r),Module._add_int_reloption=(e,r,M,r0,s0,a0,i0)=>(Module._add_int_reloption=wasmExports.add_int_reloption)(e,r,M,r0,s0,a0,i0),Module._MemoryContextStrdup=(e,r)=>(Module._MemoryContextStrdup=wasmExports.MemoryContextStrdup)(e,r),Module._transformRelOptions=(e,r,M,r0,s0,a0)=>(Module._transformRelOptions=wasmExports.transformRelOptions)(e,r,M,r0,s0,a0),Module._deconstruct_array_builtin=(e,r,M,r0,s0)=>(Module._deconstruct_array_builtin=wasmExports.deconstruct_array_builtin)(e,r,M,r0,s0),Module._defGetString=e=>(Module._defGetString=wasmExports.defGetString)(e),Module._defGetBoolean=e=>(Module._defGetBoolean=wasmExports.defGetBoolean)(e),Module._untransformRelOptions=e=>(Module._untransformRelOptions=wasmExports.untransformRelOptions)(e),Module._text_to_cstring=e=>(Module._text_to_cstring=wasmExports.text_to_cstring)(e),Module._makeString=e=>(Module._makeString=wasmExports.makeString)(e),Module._makeDefElem=(e,r,M)=>(Module._makeDefElem=wasmExports.makeDefElem)(e,r,M),Module._heap_reloptions=(e,r,M)=>(Module._heap_reloptions=wasmExports.heap_reloptions)(e,r,M),Module._MemoryContextAlloc=(e,r)=>(Module._MemoryContextAlloc=wasmExports.MemoryContextAlloc)(e,r),Module._parse_bool=(e,r)=>(Module._parse_bool=wasmExports.parse_bool)(e,r),Module._parse_int=(e,r,M,r0)=>(Module._parse_int=wasmExports.parse_int)(e,r,M,r0),Module._parse_real=(e,r,M,r0)=>(Module._parse_real=wasmExports.parse_real)(e,r,M,r0),Module._ScanKeyInit=(e,r,M,r0,s0)=>(Module._ScanKeyInit=wasmExports.ScanKeyInit)(e,r,M,r0,s0),Module._dsm_segment_handle=e=>(Module._dsm_segment_handle=wasmExports.dsm_segment_handle)(e),Module._dsm_create=(e,r)=>(Module._dsm_create=wasmExports.dsm_create)(e,r),Module._dsm_segment_address=e=>(Module._dsm_segment_address=wasmExports.dsm_segment_address)(e),Module._dsm_attach=e=>(Module._dsm_attach=wasmExports.dsm_attach)(e),Module._dsm_detach=e=>(Module._dsm_detach=wasmExports.dsm_detach)(e),Module._ShmemInitStruct=(e,r,M)=>(Module._ShmemInitStruct=wasmExports.ShmemInitStruct)(e,r,M),Module._LWLockAcquire=(e,r)=>(Module._LWLockAcquire=wasmExports.LWLockAcquire)(e,r),Module._LWLockRelease=e=>(Module._LWLockRelease=wasmExports.LWLockRelease)(e),Module._LWLockInitialize=(e,r)=>(Module._LWLockInitialize=wasmExports.LWLockInitialize)(e,r),Module._MemoryContextMemAllocated=(e,r)=>(Module._MemoryContextMemAllocated=wasmExports.MemoryContextMemAllocated)(e,r),Module._GetCurrentCommandId=e=>(Module._GetCurrentCommandId=wasmExports.GetCurrentCommandId)(e),Module._toast_open_indexes=(e,r,M,r0)=>(Module._toast_open_indexes=wasmExports.toast_open_indexes)(e,r,M,r0),Module._RelationGetIndexList=e=>(Module._RelationGetIndexList=wasmExports.RelationGetIndexList)(e),Module._systable_beginscan=(e,r,M,r0,s0,a0)=>(Module._systable_beginscan=wasmExports.systable_beginscan)(e,r,M,r0,s0,a0),Module._systable_getnext=e=>(Module._systable_getnext=wasmExports.systable_getnext)(e),Module._systable_endscan=e=>(Module._systable_endscan=wasmExports.systable_endscan)(e),Module._toast_close_indexes=(e,r,M)=>(Module._toast_close_indexes=wasmExports.toast_close_indexes)(e,r,M),Module._systable_beginscan_ordered=(e,r,M,r0,s0)=>(Module._systable_beginscan_ordered=wasmExports.systable_beginscan_ordered)(e,r,M,r0,s0),Module._systable_getnext_ordered=(e,r)=>(Module._systable_getnext_ordered=wasmExports.systable_getnext_ordered)(e,r),Module._systable_endscan_ordered=e=>(Module._systable_endscan_ordered=wasmExports.systable_endscan_ordered)(e),Module._init_toast_snapshot=e=>(Module._init_toast_snapshot=wasmExports.init_toast_snapshot)(e),Module._convert_tuples_by_position=(e,r,M)=>(Module._convert_tuples_by_position=wasmExports.convert_tuples_by_position)(e,r,M),Module._execute_attr_map_tuple=(e,r)=>(Module._execute_attr_map_tuple=wasmExports.execute_attr_map_tuple)(e,r),Module._ExecStoreVirtualTuple=e=>(Module._ExecStoreVirtualTuple=wasmExports.ExecStoreVirtualTuple)(e),Module._bms_is_member=(e,r)=>(Module._bms_is_member=wasmExports.bms_is_member)(e,r),Module._bms_add_member=(e,r)=>(Module._bms_add_member=wasmExports.bms_add_member)(e,r),Module._CreateTupleDescCopy=e=>(Module._CreateTupleDescCopy=wasmExports.CreateTupleDescCopy)(e),Module._DecrTupleDescRefCount=e=>(Module._DecrTupleDescRefCount=wasmExports.DecrTupleDescRefCount)(e),Module._datumIsEqual=(e,r,M,r0)=>(Module._datumIsEqual=wasmExports.datumIsEqual)(e,r,M,r0),Module._TupleDescInitEntryCollation=(e,r,M)=>(Module._TupleDescInitEntryCollation=wasmExports.TupleDescInitEntryCollation)(e,r,M),Module._stringToNode=e=>(Module._stringToNode=wasmExports.stringToNode)(e),Module._pg_detoast_datum_copy=e=>(Module._pg_detoast_datum_copy=wasmExports.pg_detoast_datum_copy)(e),Module._get_typlenbyvalalign=(e,r,M,r0)=>(Module._get_typlenbyvalalign=wasmExports.get_typlenbyvalalign)(e,r,M,r0),Module._deconstruct_array=(e,r,M,r0,s0,a0,i0,u0)=>(Module._deconstruct_array=wasmExports.deconstruct_array)(e,r,M,r0,s0,a0,i0,u0),Module._tbm_add_tuples=(e,r,M,r0)=>(Module._tbm_add_tuples=wasmExports.tbm_add_tuples)(e,r,M,r0),Module._ginPostingListDecode=(e,r)=>(Module._ginPostingListDecode=wasmExports.ginPostingListDecode)(e,r),Module._ItemPointerCompare=(e,r)=>(Module._ItemPointerCompare=wasmExports.ItemPointerCompare)(e,r),Module._LockPage=(e,r,M)=>(Module._LockPage=wasmExports.LockPage)(e,r,M),Module._UnlockPage=(e,r,M)=>(Module._UnlockPage=wasmExports.UnlockPage)(e,r,M),Module._vacuum_delay_point=()=>(Module._vacuum_delay_point=wasmExports.vacuum_delay_point)(),Module._RecordFreeIndexPage=(e,r)=>(Module._RecordFreeIndexPage=wasmExports.RecordFreeIndexPage)(e,r),Module._IndexFreeSpaceMapVacuum=e=>(Module._IndexFreeSpaceMapVacuum=wasmExports.IndexFreeSpaceMapVacuum)(e),Module._log_newpage_range=(e,r,M,r0,s0)=>(Module._log_newpage_range=wasmExports.log_newpage_range)(e,r,M,r0,s0),Module._GetFreeIndexPage=e=>(Module._GetFreeIndexPage=wasmExports.GetFreeIndexPage)(e),Module._ConditionalLockBuffer=e=>(Module._ConditionalLockBuffer=wasmExports.ConditionalLockBuffer)(e),Module._LockBufferForCleanup=e=>(Module._LockBufferForCleanup=wasmExports.LockBufferForCleanup)(e),Module._gistcheckpage=(e,r)=>(Module._gistcheckpage=wasmExports.gistcheckpage)(e,r),Module._PageIndexMultiDelete=(e,r,M)=>(Module._PageIndexMultiDelete=wasmExports.PageIndexMultiDelete)(e,r,M),Module._smgrnblocks=(e,r)=>(Module._smgrnblocks=wasmExports.smgrnblocks)(e,r),Module._list_free_deep=e=>(Module._list_free_deep=wasmExports.list_free_deep)(e),Module._pairingheap_remove_first=e=>(Module._pairingheap_remove_first=wasmExports.pairingheap_remove_first)(e),Module._pairingheap_add=(e,r)=>(Module._pairingheap_add=wasmExports.pairingheap_add)(e,r),Module._float_overflow_error=()=>(Module._float_overflow_error=wasmExports.float_overflow_error)(),Module._float_underflow_error=()=>(Module._float_underflow_error=wasmExports.float_underflow_error)(),Module._DirectFunctionCall5Coll=(e,r,M,r0,s0,a0,i0)=>(Module._DirectFunctionCall5Coll=wasmExports.DirectFunctionCall5Coll)(e,r,M,r0,s0,a0,i0),Module._pairingheap_allocate=(e,r)=>(Module._pairingheap_allocate=wasmExports.pairingheap_allocate)(e,r),Module._GenerationContextCreate=(e,r,M,r0,s0)=>(Module._GenerationContextCreate=wasmExports.GenerationContextCreate)(e,r,M,r0,s0),Module._pgstat_progress_update_param=(e,r)=>(Module._pgstat_progress_update_param=wasmExports.pgstat_progress_update_param)(e,r),Module.__hash_getbuf=(e,r,M,r0)=>(Module.__hash_getbuf=wasmExports._hash_getbuf)(e,r,M,r0),Module.__hash_relbuf=(e,r)=>(Module.__hash_relbuf=wasmExports._hash_relbuf)(e,r),Module.__hash_get_indextuple_hashkey=e=>(Module.__hash_get_indextuple_hashkey=wasmExports._hash_get_indextuple_hashkey)(e),Module.__hash_getbuf_with_strategy=(e,r,M,r0,s0)=>(Module.__hash_getbuf_with_strategy=wasmExports._hash_getbuf_with_strategy)(e,r,M,r0,s0),Module.__hash_ovflblkno_to_bitno=(e,r)=>(Module.__hash_ovflblkno_to_bitno=wasmExports._hash_ovflblkno_to_bitno)(e,r),Module._list_member_oid=(e,r)=>(Module._list_member_oid=wasmExports.list_member_oid)(e,r),Module._HeapTupleSatisfiesVisibility=(e,r,M)=>(Module._HeapTupleSatisfiesVisibility=wasmExports.HeapTupleSatisfiesVisibility)(e,r,M),Module._read_stream_begin_relation=(e,r,M,r0,s0,a0,i0)=>(Module._read_stream_begin_relation=wasmExports.read_stream_begin_relation)(e,r,M,r0,s0,a0,i0),Module._GetAccessStrategy=e=>(Module._GetAccessStrategy=wasmExports.GetAccessStrategy)(e),Module._FreeAccessStrategy=e=>(Module._FreeAccessStrategy=wasmExports.FreeAccessStrategy)(e),Module._read_stream_end=e=>(Module._read_stream_end=wasmExports.read_stream_end)(e),Module._heap_getnext=(e,r)=>(Module._heap_getnext=wasmExports.heap_getnext)(e,r),Module._HeapTupleSatisfiesVacuum=(e,r,M)=>(Module._HeapTupleSatisfiesVacuum=wasmExports.HeapTupleSatisfiesVacuum)(e,r,M),Module._GetMultiXactIdMembers=(e,r,M,r0)=>(Module._GetMultiXactIdMembers=wasmExports.GetMultiXactIdMembers)(e,r,M,r0),Module._TransactionIdPrecedes=(e,r)=>(Module._TransactionIdPrecedes=wasmExports.TransactionIdPrecedes)(e,r),Module._HeapTupleGetUpdateXid=e=>(Module._HeapTupleGetUpdateXid=wasmExports.HeapTupleGetUpdateXid)(e),Module._visibilitymap_clear=(e,r,M,r0)=>(Module._visibilitymap_clear=wasmExports.visibilitymap_clear)(e,r,M,r0),Module._pgstat_count_heap_insert=(e,r)=>(Module._pgstat_count_heap_insert=wasmExports.pgstat_count_heap_insert)(e,r),Module._ExecFetchSlotHeapTuple=(e,r,M)=>(Module._ExecFetchSlotHeapTuple=wasmExports.ExecFetchSlotHeapTuple)(e,r,M),Module._PageGetHeapFreeSpace=e=>(Module._PageGetHeapFreeSpace=wasmExports.PageGetHeapFreeSpace)(e),Module._visibilitymap_pin=(e,r,M)=>(Module._visibilitymap_pin=wasmExports.visibilitymap_pin)(e,r,M),Module._HeapTupleSatisfiesUpdate=(e,r,M)=>(Module._HeapTupleSatisfiesUpdate=wasmExports.HeapTupleSatisfiesUpdate)(e,r,M),Module._TransactionIdIsCurrentTransactionId=e=>(Module._TransactionIdIsCurrentTransactionId=wasmExports.TransactionIdIsCurrentTransactionId)(e),Module._TransactionIdDidCommit=e=>(Module._TransactionIdDidCommit=wasmExports.TransactionIdDidCommit)(e),Module._TransactionIdIsInProgress=e=>(Module._TransactionIdIsInProgress=wasmExports.TransactionIdIsInProgress)(e),Module._bms_free=e=>(Module._bms_free=wasmExports.bms_free)(e),Module._bms_add_members=(e,r)=>(Module._bms_add_members=wasmExports.bms_add_members)(e,r),Module._bms_next_member=(e,r)=>(Module._bms_next_member=wasmExports.bms_next_member)(e,r),Module._bms_overlap=(e,r)=>(Module._bms_overlap=wasmExports.bms_overlap)(e,r),Module._MultiXactIdPrecedes=(e,r)=>(Module._MultiXactIdPrecedes=wasmExports.MultiXactIdPrecedes)(e,r),Module._heap_tuple_needs_eventual_freeze=e=>(Module._heap_tuple_needs_eventual_freeze=wasmExports.heap_tuple_needs_eventual_freeze)(e),Module._PrefetchBuffer=(e,r,M,r0)=>(Module._PrefetchBuffer=wasmExports.PrefetchBuffer)(e,r,M,r0),Module._XLogRecGetBlockTagExtended=(e,r,M,r0,s0,a0)=>(Module._XLogRecGetBlockTagExtended=wasmExports.XLogRecGetBlockTagExtended)(e,r,M,r0,s0,a0),Module._read_stream_next_buffer=(e,r)=>(Module._read_stream_next_buffer=wasmExports.read_stream_next_buffer)(e,r),Module._smgrexists=(e,r)=>(Module._smgrexists=wasmExports.smgrexists)(e,r),Module._table_slot_create=(e,r)=>(Module._table_slot_create=wasmExports.table_slot_create)(e,r),Module._ExecDropSingleTupleTableSlot=e=>(Module._ExecDropSingleTupleTableSlot=wasmExports.ExecDropSingleTupleTableSlot)(e),Module._CreateExecutorState=()=>(Module._CreateExecutorState=wasmExports.CreateExecutorState)(),Module._MakePerTupleExprContext=e=>(Module._MakePerTupleExprContext=wasmExports.MakePerTupleExprContext)(e),Module._GetOldestNonRemovableTransactionId=e=>(Module._GetOldestNonRemovableTransactionId=wasmExports.GetOldestNonRemovableTransactionId)(e),Module._FreeExecutorState=e=>(Module._FreeExecutorState=wasmExports.FreeExecutorState)(e),Module._MakeSingleTupleTableSlot=(e,r)=>(Module._MakeSingleTupleTableSlot=wasmExports.MakeSingleTupleTableSlot)(e,r),Module._ExecStoreHeapTuple=(e,r,M)=>(Module._ExecStoreHeapTuple=wasmExports.ExecStoreHeapTuple)(e,r,M),Module._visibilitymap_get_status=(e,r,M)=>(Module._visibilitymap_get_status=wasmExports.visibilitymap_get_status)(e,r,M),Module._ExecStoreAllNullTuple=e=>(Module._ExecStoreAllNullTuple=wasmExports.ExecStoreAllNullTuple)(e),Module._XidInMVCCSnapshot=(e,r)=>(Module._XidInMVCCSnapshot=wasmExports.XidInMVCCSnapshot)(e,r),Module._hash_seq_init=(e,r)=>(Module._hash_seq_init=wasmExports.hash_seq_init)(e,r),Module._hash_seq_search=e=>(Module._hash_seq_search=wasmExports.hash_seq_search)(e),Module._ftruncate=(e,r)=>(Module._ftruncate=wasmExports.ftruncate)(e,r),Module._fd_fsync_fname=(e,r)=>(Module._fd_fsync_fname=wasmExports.fd_fsync_fname)(e,r),Module._get_namespace_name=e=>(Module._get_namespace_name=wasmExports.get_namespace_name)(e),Module._GetRecordedFreeSpace=(e,r)=>(Module._GetRecordedFreeSpace=wasmExports.GetRecordedFreeSpace)(e,r),Module._vac_estimate_reltuples=(e,r,M,r0)=>(Module._vac_estimate_reltuples=wasmExports.vac_estimate_reltuples)(e,r,M,r0),Module._WaitLatch=(e,r,M,r0)=>(Module._WaitLatch=wasmExports.WaitLatch)(e,r,M,r0),Module._ResetLatch=e=>(Module._ResetLatch=wasmExports.ResetLatch)(e),Module._clock_gettime=(e,r)=>(Module._clock_gettime=wasmExports.clock_gettime)(e,r),Module._WalUsageAccumDiff=(e,r,M)=>(Module._WalUsageAccumDiff=wasmExports.WalUsageAccumDiff)(e,r,M),Module._BufferUsageAccumDiff=(e,r,M)=>(Module._BufferUsageAccumDiff=wasmExports.BufferUsageAccumDiff)(e,r,M),Module._visibilitymap_prepare_truncate=(e,r)=>(Module._visibilitymap_prepare_truncate=wasmExports.visibilitymap_prepare_truncate)(e,r),Module._pg_class_aclcheck=(e,r,M)=>(Module._pg_class_aclcheck=wasmExports.pg_class_aclcheck)(e,r,M),Module._btboolcmp=e=>(Module._btboolcmp=wasmExports.btboolcmp)(e),Module._btint2cmp=e=>(Module._btint2cmp=wasmExports.btint2cmp)(e),Module._btint4cmp=e=>(Module._btint4cmp=wasmExports.btint4cmp)(e),Module._btint8cmp=e=>(Module._btint8cmp=wasmExports.btint8cmp)(e),Module._btoidcmp=e=>(Module._btoidcmp=wasmExports.btoidcmp)(e),Module._btcharcmp=e=>(Module._btcharcmp=wasmExports.btcharcmp)(e),Module.__bt_form_posting=(e,r,M)=>(Module.__bt_form_posting=wasmExports._bt_form_posting)(e,r,M),Module.__bt_mkscankey=(e,r)=>(Module.__bt_mkscankey=wasmExports._bt_mkscankey)(e,r),Module.__bt_checkpage=(e,r)=>(Module.__bt_checkpage=wasmExports._bt_checkpage)(e,r),Module.__bt_compare=(e,r,M,r0)=>(Module.__bt_compare=wasmExports._bt_compare)(e,r,M,r0),Module.__bt_relbuf=(e,r)=>(Module.__bt_relbuf=wasmExports._bt_relbuf)(e,r),Module.__bt_search=(e,r,M,r0,s0)=>(Module.__bt_search=wasmExports._bt_search)(e,r,M,r0,s0),Module.__bt_binsrch_insert=(e,r)=>(Module.__bt_binsrch_insert=wasmExports._bt_binsrch_insert)(e,r),Module.__bt_freestack=e=>(Module.__bt_freestack=wasmExports._bt_freestack)(e),Module.__bt_metaversion=(e,r,M)=>(Module.__bt_metaversion=wasmExports._bt_metaversion)(e,r,M),Module.__bt_allequalimage=(e,r)=>(Module.__bt_allequalimage=wasmExports._bt_allequalimage)(e,r),Module._before_shmem_exit=(e,r)=>(Module._before_shmem_exit=wasmExports.before_shmem_exit)(e,r),Module._cancel_before_shmem_exit=(e,r)=>(Module._cancel_before_shmem_exit=wasmExports.cancel_before_shmem_exit)(e,r),Module._pg_re_throw=()=>(Module._pg_re_throw=wasmExports.pg_re_throw)(),Module._get_opfamily_member=(e,r,M,r0)=>(Module._get_opfamily_member=wasmExports.get_opfamily_member)(e,r,M,r0),Module.__bt_check_natts=(e,r,M,r0)=>(Module.__bt_check_natts=wasmExports._bt_check_natts)(e,r,M,r0),Module._timestamptz_to_str=e=>(Module._timestamptz_to_str=wasmExports.timestamptz_to_str)(e),Module._XLogRecGetBlockRefInfo=(e,r,M,r0,s0)=>(Module._XLogRecGetBlockRefInfo=wasmExports.XLogRecGetBlockRefInfo)(e,r,M,r0,s0),Module._varstr_cmp=(e,r,M,r0,s0)=>(Module._varstr_cmp=wasmExports.varstr_cmp)(e,r,M,r0,s0),Module._exprType=e=>(Module._exprType=wasmExports.exprType)(e),Module._GetActiveSnapshot=()=>(Module._GetActiveSnapshot=wasmExports.GetActiveSnapshot)(),Module._errdetail_relkind_not_supported=e=>(Module._errdetail_relkind_not_supported=wasmExports.errdetail_relkind_not_supported)(e),Module._table_openrv=(e,r)=>(Module._table_openrv=wasmExports.table_openrv)(e,r),Module._table_slot_callbacks=e=>(Module._table_slot_callbacks=wasmExports.table_slot_callbacks)(e),Module._clamp_row_est=e=>(Module._clamp_row_est=wasmExports.clamp_row_est)(e),Module._estimate_expression_value=(e,r)=>(Module._estimate_expression_value=wasmExports.estimate_expression_value)(e,r),Module._XLogFlush=e=>(Module._XLogFlush=wasmExports.XLogFlush)(e),Module._get_call_result_type=(e,r,M)=>(Module._get_call_result_type=wasmExports.get_call_result_type)(e,r,M),Module._HeapTupleHeaderGetDatum=e=>(Module._HeapTupleHeaderGetDatum=wasmExports.HeapTupleHeaderGetDatum)(e),Module._GenericXLogStart=e=>(Module._GenericXLogStart=wasmExports.GenericXLogStart)(e),Module._GenericXLogRegisterBuffer=(e,r,M)=>(Module._GenericXLogRegisterBuffer=wasmExports.GenericXLogRegisterBuffer)(e,r,M),Module._GenericXLogFinish=e=>(Module._GenericXLogFinish=wasmExports.GenericXLogFinish)(e),Module._GenericXLogAbort=e=>(Module._GenericXLogAbort=wasmExports.GenericXLogAbort)(e),Module._errmsg_plural=(e,r,M,r0)=>(Module._errmsg_plural=wasmExports.errmsg_plural)(e,r,M,r0),Module._ReadNextMultiXactId=()=>(Module._ReadNextMultiXactId=wasmExports.ReadNextMultiXactId)(),Module._ReadMultiXactIdRange=(e,r)=>(Module._ReadMultiXactIdRange=wasmExports.ReadMultiXactIdRange)(e,r),Module._MultiXactIdPrecedesOrEquals=(e,r)=>(Module._MultiXactIdPrecedesOrEquals=wasmExports.MultiXactIdPrecedesOrEquals)(e,r),Module._init_MultiFuncCall=e=>(Module._init_MultiFuncCall=wasmExports.init_MultiFuncCall)(e),Module._TupleDescGetAttInMetadata=e=>(Module._TupleDescGetAttInMetadata=wasmExports.TupleDescGetAttInMetadata)(e),Module._per_MultiFuncCall=e=>(Module._per_MultiFuncCall=wasmExports.per_MultiFuncCall)(e),Module._BuildTupleFromCStrings=(e,r)=>(Module._BuildTupleFromCStrings=wasmExports.BuildTupleFromCStrings)(e,r),Module._end_MultiFuncCall=(e,r)=>(Module._end_MultiFuncCall=wasmExports.end_MultiFuncCall)(e,r),Module._GetCurrentSubTransactionId=()=>(Module._GetCurrentSubTransactionId=wasmExports.GetCurrentSubTransactionId)(),Module._WaitForBackgroundWorkerShutdown=e=>(Module._WaitForBackgroundWorkerShutdown=wasmExports.WaitForBackgroundWorkerShutdown)(e),Module._RegisterDynamicBackgroundWorker=(e,r)=>(Module._RegisterDynamicBackgroundWorker=wasmExports.RegisterDynamicBackgroundWorker)(e,r),Module._BackgroundWorkerUnblockSignals=()=>(Module._BackgroundWorkerUnblockSignals=wasmExports.BackgroundWorkerUnblockSignals)(),Module._BackgroundWorkerInitializeConnectionByOid=(e,r,M)=>(Module._BackgroundWorkerInitializeConnectionByOid=wasmExports.BackgroundWorkerInitializeConnectionByOid)(e,r,M),Module._GetDatabaseEncoding=()=>(Module._GetDatabaseEncoding=wasmExports.GetDatabaseEncoding)(),Module._RmgrNotFound=e=>(Module._RmgrNotFound=wasmExports.RmgrNotFound)(e),Module._InitMaterializedSRF=(e,r)=>(Module._InitMaterializedSRF=wasmExports.InitMaterializedSRF)(e,r),Module._tuplestore_putvalues=(e,r,M,r0)=>(Module._tuplestore_putvalues=wasmExports.tuplestore_putvalues)(e,r,M,r0),Module._AllocateFile=(e,r)=>(Module._AllocateFile=wasmExports.AllocateFile)(e,r),Module._FreeFile=e=>(Module._FreeFile=wasmExports.FreeFile)(e),Module._fd_durable_rename=(e,r,M)=>(Module._fd_durable_rename=wasmExports.fd_durable_rename)(e,r,M),Module._BlessTupleDesc=e=>(Module._BlessTupleDesc=wasmExports.BlessTupleDesc)(e),Module._fstat=(e,r)=>(Module._fstat=wasmExports.fstat)(e,r),Module._superuser_arg=e=>(Module._superuser_arg=wasmExports.superuser_arg)(e),Module._wal_segment_close=e=>(Module._wal_segment_close=wasmExports.wal_segment_close)(e),Module._wal_segment_open=(e,r,M)=>(Module._wal_segment_open=wasmExports.wal_segment_open)(e,r,M),Module._XLogReaderAllocate=(e,r,M,r0)=>(Module._XLogReaderAllocate=wasmExports.XLogReaderAllocate)(e,r,M,r0),Module._XLogReadRecord=(e,r)=>(Module._XLogReadRecord=wasmExports.XLogReadRecord)(e,r),Module._XLogReaderFree=e=>(Module._XLogReaderFree=wasmExports.XLogReaderFree)(e),Module._GetTopFullTransactionId=()=>(Module._GetTopFullTransactionId=wasmExports.GetTopFullTransactionId)(),Module._GetCurrentTransactionNestLevel=()=>(Module._GetCurrentTransactionNestLevel=wasmExports.GetCurrentTransactionNestLevel)(),Module._ResourceOwnerCreate=(e,r)=>(Module._ResourceOwnerCreate=wasmExports.ResourceOwnerCreate)(e,r),Module._RegisterXactCallback=(e,r)=>(Module._RegisterXactCallback=wasmExports.RegisterXactCallback)(e,r),Module._RegisterSubXactCallback=(e,r)=>(Module._RegisterSubXactCallback=wasmExports.RegisterSubXactCallback)(e,r),Module._BeginInternalSubTransaction=e=>(Module._BeginInternalSubTransaction=wasmExports.BeginInternalSubTransaction)(e),Module._ReleaseCurrentSubTransaction=()=>(Module._ReleaseCurrentSubTransaction=wasmExports.ReleaseCurrentSubTransaction)(),Module._ResourceOwnerDelete=e=>(Module._ResourceOwnerDelete=wasmExports.ResourceOwnerDelete)(e),Module._RollbackAndReleaseCurrentSubTransaction=()=>(Module._RollbackAndReleaseCurrentSubTransaction=wasmExports.RollbackAndReleaseCurrentSubTransaction)(),Module._ReleaseExternalFD=()=>(Module._ReleaseExternalFD=wasmExports.ReleaseExternalFD)(),Module._GetFlushRecPtr=e=>(Module._GetFlushRecPtr=wasmExports.GetFlushRecPtr)(e),Module._GetXLogReplayRecPtr=e=>(Module._GetXLogReplayRecPtr=wasmExports.GetXLogReplayRecPtr)(e),Module._TimestampDifferenceMilliseconds=(e,r)=>(Module._TimestampDifferenceMilliseconds=wasmExports.TimestampDifferenceMilliseconds)(e,r),Module._numeric_in=e=>(Module._numeric_in=wasmExports.numeric_in)(e),Module._DirectFunctionCall3Coll=(e,r,M,r0,s0)=>(Module._DirectFunctionCall3Coll=wasmExports.DirectFunctionCall3Coll)(e,r,M,r0,s0),Module._XLogFindNextRecord=(e,r)=>(Module._XLogFindNextRecord=wasmExports.XLogFindNextRecord)(e,r),Module._RestoreBlockImage=(e,r,M)=>(Module._RestoreBlockImage=wasmExports.RestoreBlockImage)(e,r,M),Module._timestamptz_in=e=>(Module._timestamptz_in=wasmExports.timestamptz_in)(e),Module._fscanf=(e,r,M)=>(Module._fscanf=wasmExports.fscanf)(e,r,M),Module._XLogRecStoreStats=(e,r)=>(Module._XLogRecStoreStats=wasmExports.XLogRecStoreStats)(e,r),Module._hash_get_num_entries=e=>(Module._hash_get_num_entries=wasmExports.hash_get_num_entries)(e),Module._read_local_xlog_page_no_wait=(e,r,M,r0,s0)=>(Module._read_local_xlog_page_no_wait=wasmExports.read_local_xlog_page_no_wait)(e,r,M,r0,s0),Module._escape_json=(e,r)=>(Module._escape_json=wasmExports.escape_json)(e,r),Module._list_sort=(e,r)=>(Module._list_sort=wasmExports.list_sort)(e,r),Module._pg_checksum_page=(e,r)=>(Module._pg_checksum_page=wasmExports.pg_checksum_page)(e,r),Module._bbsink_forward_end_archive=e=>(Module._bbsink_forward_end_archive=wasmExports.bbsink_forward_end_archive)(e),Module._bbsink_forward_begin_manifest=e=>(Module._bbsink_forward_begin_manifest=wasmExports.bbsink_forward_begin_manifest)(e),Module._bbsink_forward_end_manifest=e=>(Module._bbsink_forward_end_manifest=wasmExports.bbsink_forward_end_manifest)(e),Module._bbsink_forward_end_backup=(e,r,M)=>(Module._bbsink_forward_end_backup=wasmExports.bbsink_forward_end_backup)(e,r,M),Module._bbsink_forward_cleanup=e=>(Module._bbsink_forward_cleanup=wasmExports.bbsink_forward_cleanup)(e),Module._list_concat=(e,r)=>(Module._list_concat=wasmExports.list_concat)(e,r),Module._bbsink_forward_begin_backup=e=>(Module._bbsink_forward_begin_backup=wasmExports.bbsink_forward_begin_backup)(e),Module._bbsink_forward_archive_contents=(e,r)=>(Module._bbsink_forward_archive_contents=wasmExports.bbsink_forward_archive_contents)(e,r),Module._bbsink_forward_begin_archive=(e,r)=>(Module._bbsink_forward_begin_archive=wasmExports.bbsink_forward_begin_archive)(e,r),Module._bbsink_forward_manifest_contents=(e,r)=>(Module._bbsink_forward_manifest_contents=wasmExports.bbsink_forward_manifest_contents)(e,r),Module._has_privs_of_role=(e,r)=>(Module._has_privs_of_role=wasmExports.has_privs_of_role)(e,r),Module._BaseBackupAddTarget=(e,r,M)=>(Module._BaseBackupAddTarget=wasmExports.BaseBackupAddTarget)(e,r,M),Module._list_copy=e=>(Module._list_copy=wasmExports.list_copy)(e),Module._tuplestore_puttuple=(e,r)=>(Module._tuplestore_puttuple=wasmExports.tuplestore_puttuple)(e,r),Module._makeRangeVar=(e,r,M)=>(Module._makeRangeVar=wasmExports.makeRangeVar)(e,r,M),Module._DefineIndex=(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0)=>(Module._DefineIndex=wasmExports.DefineIndex)(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0),Module._fread=(e,r,M,r0)=>(Module._fread=wasmExports.fread)(e,r,M,r0),Module._clearerr=e=>(Module._clearerr=wasmExports.clearerr)(e),Module._copyObjectImpl=e=>(Module._copyObjectImpl=wasmExports.copyObjectImpl)(e),Module._lappend_oid=(e,r)=>(Module._lappend_oid=wasmExports.lappend_oid)(e,r),Module._makeTypeNameFromNameList=e=>(Module._makeTypeNameFromNameList=wasmExports.makeTypeNameFromNameList)(e),Module._CatalogTupleUpdate=(e,r,M)=>(Module._CatalogTupleUpdate=wasmExports.CatalogTupleUpdate)(e,r,M),Module._get_rel_name=e=>(Module._get_rel_name=wasmExports.get_rel_name)(e),Module._CatalogTupleDelete=(e,r)=>(Module._CatalogTupleDelete=wasmExports.CatalogTupleDelete)(e,r),Module._CatalogTupleInsert=(e,r)=>(Module._CatalogTupleInsert=wasmExports.CatalogTupleInsert)(e,r),Module._recordDependencyOn=(e,r,M)=>(Module._recordDependencyOn=wasmExports.recordDependencyOn)(e,r,M),Module._get_element_type=e=>(Module._get_element_type=wasmExports.get_element_type)(e),Module._object_aclcheck=(e,r,M,r0)=>(Module._object_aclcheck=wasmExports.object_aclcheck)(e,r,M,r0),Module._superuser=()=>(Module._superuser=wasmExports.superuser)(),Module._SearchSysCacheAttName=(e,r)=>(Module._SearchSysCacheAttName=wasmExports.SearchSysCacheAttName)(e,r),Module._new_object_addresses=()=>(Module._new_object_addresses=wasmExports.new_object_addresses)(),Module._free_object_addresses=e=>(Module._free_object_addresses=wasmExports.free_object_addresses)(e),Module._performMultipleDeletions=(e,r,M)=>(Module._performMultipleDeletions=wasmExports.performMultipleDeletions)(e,r,M),Module._recordDependencyOnExpr=(e,r,M,r0)=>(Module._recordDependencyOnExpr=wasmExports.recordDependencyOnExpr)(e,r,M,r0),Module._query_tree_walker_impl=(e,r,M,r0)=>(Module._query_tree_walker_impl=wasmExports.query_tree_walker_impl)(e,r,M,r0),Module._expression_tree_walker_impl=(e,r,M)=>(Module._expression_tree_walker_impl=wasmExports.expression_tree_walker_impl)(e,r,M),Module._add_exact_object_address=(e,r)=>(Module._add_exact_object_address=wasmExports.add_exact_object_address)(e,r),Module._get_rel_relkind=e=>(Module._get_rel_relkind=wasmExports.get_rel_relkind)(e),Module._get_typtype=e=>(Module._get_typtype=wasmExports.get_typtype)(e),Module._list_delete_last=e=>(Module._list_delete_last=wasmExports.list_delete_last)(e),Module._type_is_collatable=e=>(Module._type_is_collatable=wasmExports.type_is_collatable)(e),Module._GetSysCacheOid=(e,r,M,r0,s0,a0)=>(Module._GetSysCacheOid=wasmExports.GetSysCacheOid)(e,r,M,r0,s0,a0),Module._CheckTableNotInUse=(e,r)=>(Module._CheckTableNotInUse=wasmExports.CheckTableNotInUse)(e,r),Module._construct_array=(e,r,M,r0,s0,a0)=>(Module._construct_array=wasmExports.construct_array)(e,r,M,r0,s0,a0),Module._make_parsestate=e=>(Module._make_parsestate=wasmExports.make_parsestate)(e),Module._transformExpr=(e,r,M)=>(Module._transformExpr=wasmExports.transformExpr)(e,r,M),Module._equal=(e,r)=>(Module._equal=wasmExports.equal)(e,r),Module._pull_var_clause=(e,r)=>(Module._pull_var_clause=wasmExports.pull_var_clause)(e,r),Module._get_attname=(e,r,M)=>(Module._get_attname=wasmExports.get_attname)(e,r,M),Module._coerce_to_target_type=(e,r,M,r0,s0,a0,i0,u0)=>(Module._coerce_to_target_type=wasmExports.coerce_to_target_type)(e,r,M,r0,s0,a0,i0,u0),Module._nodeToString=e=>(Module._nodeToString=wasmExports.nodeToString)(e),Module._parser_errposition=(e,r)=>(Module._parser_errposition=wasmExports.parser_errposition)(e,r),Module._exprTypmod=e=>(Module._exprTypmod=wasmExports.exprTypmod)(e),Module._get_base_element_type=e=>(Module._get_base_element_type=wasmExports.get_base_element_type)(e),Module._SystemFuncName=e=>(Module._SystemFuncName=wasmExports.SystemFuncName)(e),Module._CreateTrigger=(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0)=>(Module._CreateTrigger=wasmExports.CreateTrigger)(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0),Module._plan_create_index_workers=(e,r)=>(Module._plan_create_index_workers=wasmExports.plan_create_index_workers)(e,r),Module._get_rel_namespace=e=>(Module._get_rel_namespace=wasmExports.get_rel_namespace)(e),Module._ConditionalLockRelationOid=(e,r)=>(Module._ConditionalLockRelationOid=wasmExports.ConditionalLockRelationOid)(e,r),Module._RelnameGetRelid=e=>(Module._RelnameGetRelid=wasmExports.RelnameGetRelid)(e),Module._get_relkind_objtype=e=>(Module._get_relkind_objtype=wasmExports.get_relkind_objtype)(e),Module._RelationIsVisible=e=>(Module._RelationIsVisible=wasmExports.RelationIsVisible)(e),Module._get_func_arg_info=(e,r,M,r0)=>(Module._get_func_arg_info=wasmExports.get_func_arg_info)(e,r,M,r0),Module._NameListToString=e=>(Module._NameListToString=wasmExports.NameListToString)(e),Module._OpernameGetOprid=(e,r,M)=>(Module._OpernameGetOprid=wasmExports.OpernameGetOprid)(e,r,M),Module._makeRangeVarFromNameList=e=>(Module._makeRangeVarFromNameList=wasmExports.makeRangeVarFromNameList)(e),Module._quote_identifier=e=>(Module._quote_identifier=wasmExports.quote_identifier)(e),Module._GetSearchPathMatcher=e=>(Module._GetSearchPathMatcher=wasmExports.GetSearchPathMatcher)(e),Module._SearchPathMatchesCurrentEnvironment=e=>(Module._SearchPathMatchesCurrentEnvironment=wasmExports.SearchPathMatchesCurrentEnvironment)(e),Module._get_collation_oid=(e,r)=>(Module._get_collation_oid=wasmExports.get_collation_oid)(e,r),Module._CacheRegisterSyscacheCallback=(e,r,M)=>(Module._CacheRegisterSyscacheCallback=wasmExports.CacheRegisterSyscacheCallback)(e,r,M),Module._get_extension_oid=(e,r)=>(Module._get_extension_oid=wasmExports.get_extension_oid)(e,r),Module._get_role_oid=(e,r)=>(Module._get_role_oid=wasmExports.get_role_oid)(e,r),Module._GetForeignServerByName=(e,r)=>(Module._GetForeignServerByName=wasmExports.GetForeignServerByName)(e,r),Module._typeStringToTypeName=(e,r)=>(Module._typeStringToTypeName=wasmExports.typeStringToTypeName)(e,r),Module._list_make2_impl=(e,r,M)=>(Module._list_make2_impl=wasmExports.list_make2_impl)(e,r,M),Module._GetUserNameFromId=(e,r)=>(Module._GetUserNameFromId=wasmExports.GetUserNameFromId)(e,r),Module._format_type_extended=(e,r,M)=>(Module._format_type_extended=wasmExports.format_type_extended)(e,r,M),Module._quote_qualified_identifier=(e,r)=>(Module._quote_qualified_identifier=wasmExports.quote_qualified_identifier)(e,r),Module._get_tablespace_name=e=>(Module._get_tablespace_name=wasmExports.get_tablespace_name)(e),Module._GetForeignServerExtended=(e,r)=>(Module._GetForeignServerExtended=wasmExports.GetForeignServerExtended)(e,r),Module._GetForeignServer=e=>(Module._GetForeignServer=wasmExports.GetForeignServer)(e),Module._construct_empty_array=e=>(Module._construct_empty_array=wasmExports.construct_empty_array)(e),Module._format_type_be_qualified=e=>(Module._format_type_be_qualified=wasmExports.format_type_be_qualified)(e),Module._get_namespace_name_or_temp=e=>(Module._get_namespace_name_or_temp=wasmExports.get_namespace_name_or_temp)(e),Module._list_make3_impl=(e,r,M,r0)=>(Module._list_make3_impl=wasmExports.list_make3_impl)(e,r,M,r0),Module._construct_md_array=(e,r,M,r0,s0,a0,i0,u0,d0)=>(Module._construct_md_array=wasmExports.construct_md_array)(e,r,M,r0,s0,a0,i0,u0,d0),Module._pull_varattnos=(e,r,M)=>(Module._pull_varattnos=wasmExports.pull_varattnos)(e,r,M),Module._get_func_name=e=>(Module._get_func_name=wasmExports.get_func_name)(e),Module._construct_array_builtin=(e,r,M)=>(Module._construct_array_builtin=wasmExports.construct_array_builtin)(e,r,M),Module._makeObjectName=(e,r,M)=>(Module._makeObjectName=wasmExports.makeObjectName)(e,r,M),Module._get_primary_key_attnos=(e,r,M)=>(Module._get_primary_key_attnos=wasmExports.get_primary_key_attnos)(e,r,M),Module._bms_is_subset=(e,r)=>(Module._bms_is_subset=wasmExports.bms_is_subset)(e,r),Module._getExtensionOfObject=(e,r)=>(Module._getExtensionOfObject=wasmExports.getExtensionOfObject)(e,r),Module._find_inheritance_children=(e,r)=>(Module._find_inheritance_children=wasmExports.find_inheritance_children)(e,r),Module._lappend_int=(e,r)=>(Module._lappend_int=wasmExports.lappend_int)(e,r),Module._has_superclass=e=>(Module._has_superclass=wasmExports.has_superclass)(e),Module._CheckFunctionValidatorAccess=(e,r)=>(Module._CheckFunctionValidatorAccess=wasmExports.CheckFunctionValidatorAccess)(e,r),Module._AcquireRewriteLocks=(e,r,M)=>(Module._AcquireRewriteLocks=wasmExports.AcquireRewriteLocks)(e,r,M),Module._function_parse_error_transpose=e=>(Module._function_parse_error_transpose=wasmExports.function_parse_error_transpose)(e),Module._geterrposition=()=>(Module._geterrposition=wasmExports.geterrposition)(),Module._getinternalerrposition=()=>(Module._getinternalerrposition=wasmExports.getinternalerrposition)(),Module._pg_mblen=e=>(Module._pg_mblen=wasmExports.pg_mblen)(e),Module._pg_mbstrlen_with_len=(e,r)=>(Module._pg_mbstrlen_with_len=wasmExports.pg_mbstrlen_with_len)(e,r),Module._errposition=e=>(Module._errposition=wasmExports.errposition)(e),Module._internalerrposition=e=>(Module._internalerrposition=wasmExports.internalerrposition)(e),Module._internalerrquery=e=>(Module._internalerrquery=wasmExports.internalerrquery)(e),Module._list_delete_nth_cell=(e,r)=>(Module._list_delete_nth_cell=wasmExports.list_delete_nth_cell)(e,r),Module._get_array_type=e=>(Module._get_array_type=wasmExports.get_array_type)(e),Module._smgrtruncate2=(e,r,M,r0,s0)=>(Module._smgrtruncate2=wasmExports.smgrtruncate2)(e,r,M,r0,s0),Module._smgrreadv=(e,r,M,r0,s0)=>(Module._smgrreadv=wasmExports.smgrreadv)(e,r,M,r0,s0),Module._NewRelationCreateToastTable=(e,r)=>(Module._NewRelationCreateToastTable=wasmExports.NewRelationCreateToastTable)(e,r),Module._transformStmt=(e,r)=>(Module._transformStmt=wasmExports.transformStmt)(e,r),Module._exprLocation=e=>(Module._exprLocation=wasmExports.exprLocation)(e),Module._ParseFuncOrColumn=(e,r,M,r0,s0,a0,i0)=>(Module._ParseFuncOrColumn=wasmExports.ParseFuncOrColumn)(e,r,M,r0,s0,a0,i0),Module._exprCollation=e=>(Module._exprCollation=wasmExports.exprCollation)(e),Module._transformDistinctClause=(e,r,M,r0)=>(Module._transformDistinctClause=wasmExports.transformDistinctClause)(e,r,M,r0),Module._makeTargetEntry=(e,r,M,r0)=>(Module._makeTargetEntry=wasmExports.makeTargetEntry)(e,r,M,r0),Module._makeAlias=(e,r)=>(Module._makeAlias=wasmExports.makeAlias)(e,r),Module._addRangeTableEntryForSubquery=(e,r,M,r0,s0)=>(Module._addRangeTableEntryForSubquery=wasmExports.addRangeTableEntryForSubquery)(e,r,M,r0,s0),Module._makeVar=(e,r,M,r0,s0,a0)=>(Module._makeVar=wasmExports.makeVar)(e,r,M,r0,s0,a0),Module._makeBoolean=e=>(Module._makeBoolean=wasmExports.makeBoolean)(e),Module._makeInteger=e=>(Module._makeInteger=wasmExports.makeInteger)(e),Module._makeTypeName=e=>(Module._makeTypeName=wasmExports.makeTypeName)(e),Module._makeFuncCall=(e,r,M,r0)=>(Module._makeFuncCall=wasmExports.makeFuncCall)(e,r,M,r0),Module._list_make4_impl=(e,r,M,r0,s0)=>(Module._list_make4_impl=wasmExports.list_make4_impl)(e,r,M,r0,s0),Module._get_sortgroupclause_tle=(e,r)=>(Module._get_sortgroupclause_tle=wasmExports.get_sortgroupclause_tle)(e,r),Module._flatten_join_alias_vars=(e,r,M)=>(Module._flatten_join_alias_vars=wasmExports.flatten_join_alias_vars)(e,r,M),Module._list_member_int=(e,r)=>(Module._list_member_int=wasmExports.list_member_int)(e,r),Module._addRangeTableEntryForENR=(e,r,M)=>(Module._addRangeTableEntryForENR=wasmExports.addRangeTableEntryForENR)(e,r,M),Module._typenameTypeIdAndMod=(e,r,M,r0)=>(Module._typenameTypeIdAndMod=wasmExports.typenameTypeIdAndMod)(e,r,M,r0),Module._get_typcollation=e=>(Module._get_typcollation=wasmExports.get_typcollation)(e),Module._strip_implicit_coercions=e=>(Module._strip_implicit_coercions=wasmExports.strip_implicit_coercions)(e),Module._get_sortgroupref_tle=(e,r)=>(Module._get_sortgroupref_tle=wasmExports.get_sortgroupref_tle)(e,r),Module._contain_aggs_of_level=(e,r)=>(Module._contain_aggs_of_level=wasmExports.contain_aggs_of_level)(e,r),Module._typeidType=e=>(Module._typeidType=wasmExports.typeidType)(e),Module._typeTypeCollation=e=>(Module._typeTypeCollation=wasmExports.typeTypeCollation)(e),Module._typeLen=e=>(Module._typeLen=wasmExports.typeLen)(e),Module._typeByVal=e=>(Module._typeByVal=wasmExports.typeByVal)(e),Module._makeConst=(e,r,M,r0,s0,a0,i0)=>(Module._makeConst=wasmExports.makeConst)(e,r,M,r0,s0,a0,i0),Module._lookup_rowtype_tupdesc=(e,r)=>(Module._lookup_rowtype_tupdesc=wasmExports.lookup_rowtype_tupdesc)(e,r),Module._bms_del_member=(e,r)=>(Module._bms_del_member=wasmExports.bms_del_member)(e,r),Module._list_member=(e,r)=>(Module._list_member=wasmExports.list_member)(e,r),Module._type_is_rowtype=e=>(Module._type_is_rowtype=wasmExports.type_is_rowtype)(e),Module._bit_in=e=>(Module._bit_in=wasmExports.bit_in)(e),Module._bms_union=(e,r)=>(Module._bms_union=wasmExports.bms_union)(e,r),Module._varstr_levenshtein_less_equal=(e,r,M,r0,s0,a0,i0,u0,d0)=>(Module._varstr_levenshtein_less_equal=wasmExports.varstr_levenshtein_less_equal)(e,r,M,r0,s0,a0,i0,u0,d0),Module._errsave_start=(e,r)=>(Module._errsave_start=wasmExports.errsave_start)(e,r),Module._errsave_finish=(e,r,M,r0)=>(Module._errsave_finish=wasmExports.errsave_finish)(e,r,M,r0),Module._makeColumnDef=(e,r,M,r0)=>(Module._makeColumnDef=wasmExports.makeColumnDef)(e,r,M,r0),Module._GetDefaultOpClass=(e,r)=>(Module._GetDefaultOpClass=wasmExports.GetDefaultOpClass)(e,r),Module._scanner_init=(e,r,M,r0)=>(Module._scanner_init=wasmExports.scanner_init)(e,r,M,r0),Module._scanner_finish=e=>(Module._scanner_finish=wasmExports.scanner_finish)(e),Module._core_yylex=(e,r,M)=>(Module._core_yylex=wasmExports.core_yylex)(e,r,M),Module._isxdigit=e=>(Module._isxdigit=wasmExports.isxdigit)(e),Module._scanner_isspace=e=>(Module._scanner_isspace=wasmExports.scanner_isspace)(e),Module._truncate_identifier=(e,r,M)=>(Module._truncate_identifier=wasmExports.truncate_identifier)(e,r,M),Module._pg_database_encoding_max_length=()=>(Module._pg_database_encoding_max_length=wasmExports.pg_database_encoding_max_length)(),Module._namein=e=>(Module._namein=wasmExports.namein)(e),Module._BlockSampler_Init=(e,r,M,r0)=>(Module._BlockSampler_Init=wasmExports.BlockSampler_Init)(e,r,M,r0),Module._reservoir_init_selection_state=(e,r)=>(Module._reservoir_init_selection_state=wasmExports.reservoir_init_selection_state)(e,r),Module._reservoir_get_next_S=(e,r,M)=>(Module._reservoir_get_next_S=wasmExports.reservoir_get_next_S)(e,r,M),Module._sampler_random_fract=e=>(Module._sampler_random_fract=wasmExports.sampler_random_fract)(e),Module._BlockSampler_HasMore=e=>(Module._BlockSampler_HasMore=wasmExports.BlockSampler_HasMore)(e),Module._BlockSampler_Next=e=>(Module._BlockSampler_Next=wasmExports.BlockSampler_Next)(e),Module._Async_Notify=(e,r)=>(Module._Async_Notify=wasmExports.Async_Notify)(e,r),Module._RangeVarCallbackMaintainsTable=(e,r,M,r0)=>(Module._RangeVarCallbackMaintainsTable=wasmExports.RangeVarCallbackMaintainsTable)(e,r,M,r0),Module._make_new_heap=(e,r,M,r0,s0)=>(Module._make_new_heap=wasmExports.make_new_heap)(e,r,M,r0,s0),Module._finish_heap_swap=(e,r,M,r0,s0,a0,i0,u0,d0)=>(Module._finish_heap_swap=wasmExports.finish_heap_swap)(e,r,M,r0,s0,a0,i0,u0,d0),Module._wasm_OpenPipeStream=(e,r)=>(Module._wasm_OpenPipeStream=wasmExports.wasm_OpenPipeStream)(e,r),Module._ClosePipeStream=e=>(Module._ClosePipeStream=wasmExports.ClosePipeStream)(e),Module._BeginCopyFrom=(e,r,M,r0,s0,a0,i0,u0)=>(Module._BeginCopyFrom=wasmExports.BeginCopyFrom)(e,r,M,r0,s0,a0,i0,u0),Module._EndCopyFrom=e=>(Module._EndCopyFrom=wasmExports.EndCopyFrom)(e),Module._ProcessCopyOptions=(e,r,M,r0)=>(Module._ProcessCopyOptions=wasmExports.ProcessCopyOptions)(e,r,M,r0),Module._CopyFromErrorCallback=e=>(Module._CopyFromErrorCallback=wasmExports.CopyFromErrorCallback)(e),Module._NextCopyFrom=(e,r,M,r0)=>(Module._NextCopyFrom=wasmExports.NextCopyFrom)(e,r,M,r0),Module._ExecInitExpr=(e,r)=>(Module._ExecInitExpr=wasmExports.ExecInitExpr)(e,r),Module._tolower=e=>(Module._tolower=wasmExports.tolower)(e),Module._PushCopiedSnapshot=e=>(Module._PushCopiedSnapshot=wasmExports.PushCopiedSnapshot)(e),Module._UpdateActiveSnapshotCommandId=()=>(Module._UpdateActiveSnapshotCommandId=wasmExports.UpdateActiveSnapshotCommandId)(),Module._CreateQueryDesc=(e,r,M,r0,s0,a0,i0,u0)=>(Module._CreateQueryDesc=wasmExports.CreateQueryDesc)(e,r,M,r0,s0,a0,i0,u0),Module._ExecutorStart=(e,r)=>(Module._ExecutorStart=wasmExports.ExecutorStart)(e,r),Module._ExecutorFinish=e=>(Module._ExecutorFinish=wasmExports.ExecutorFinish)(e),Module._ExecutorEnd=e=>(Module._ExecutorEnd=wasmExports.ExecutorEnd)(e),Module._FreeQueryDesc=e=>(Module._FreeQueryDesc=wasmExports.FreeQueryDesc)(e),Module._pg_server_to_any=(e,r,M)=>(Module._pg_server_to_any=wasmExports.pg_server_to_any)(e,r,M),Module._ExecutorRun=(e,r,M,r0)=>(Module._ExecutorRun=wasmExports.ExecutorRun)(e,r,M,r0),Module._CreateTableAsRelExists=e=>(Module._CreateTableAsRelExists=wasmExports.CreateTableAsRelExists)(e),Module._DefineRelation=(e,r,M,r0,s0,a0)=>(Module._DefineRelation=wasmExports.DefineRelation)(e,r,M,r0,s0,a0),Module._oidin=e=>(Module._oidin=wasmExports.oidin)(e),Module._GetCommandTagName=e=>(Module._GetCommandTagName=wasmExports.GetCommandTagName)(e),Module._ExplainBeginOutput=e=>(Module._ExplainBeginOutput=wasmExports.ExplainBeginOutput)(e),Module._NewExplainState=()=>(Module._NewExplainState=wasmExports.NewExplainState)(),Module._ExplainEndOutput=e=>(Module._ExplainEndOutput=wasmExports.ExplainEndOutput)(e),Module._ExplainPrintPlan=(e,r)=>(Module._ExplainPrintPlan=wasmExports.ExplainPrintPlan)(e,r),Module._ExplainPrintTriggers=(e,r)=>(Module._ExplainPrintTriggers=wasmExports.ExplainPrintTriggers)(e,r),Module._ExplainPrintJITSummary=(e,r)=>(Module._ExplainPrintJITSummary=wasmExports.ExplainPrintJITSummary)(e,r),Module._InstrEndLoop=e=>(Module._InstrEndLoop=wasmExports.InstrEndLoop)(e),Module._ExplainPropertyInteger=(e,r,M,r0)=>(Module._ExplainPropertyInteger=wasmExports.ExplainPropertyInteger)(e,r,M,r0),Module._ExplainQueryText=(e,r)=>(Module._ExplainQueryText=wasmExports.ExplainQueryText)(e,r),Module._ExplainPropertyText=(e,r,M)=>(Module._ExplainPropertyText=wasmExports.ExplainPropertyText)(e,r,M),Module._ExplainQueryParameters=(e,r,M)=>(Module._ExplainQueryParameters=wasmExports.ExplainQueryParameters)(e,r,M),Module._get_func_namespace=e=>(Module._get_func_namespace=wasmExports.get_func_namespace)(e),Module._get_rel_type_id=e=>(Module._get_rel_type_id=wasmExports.get_rel_type_id)(e),Module._set_config_option=(e,r,M,r0,s0,a0,i0,u0)=>(Module._set_config_option=wasmExports.set_config_option)(e,r,M,r0,s0,a0,i0,u0),Module._pg_any_to_server=(e,r,M)=>(Module._pg_any_to_server=wasmExports.pg_any_to_server)(e,r,M),Module._DirectFunctionCall4Coll=(e,r,M,r0,s0,a0)=>(Module._DirectFunctionCall4Coll=wasmExports.DirectFunctionCall4Coll)(e,r,M,r0,s0,a0),Module._list_delete_cell=(e,r)=>(Module._list_delete_cell=wasmExports.list_delete_cell)(e,r),Module._GetForeignDataWrapper=e=>(Module._GetForeignDataWrapper=wasmExports.GetForeignDataWrapper)(e),Module._CreateExprContext=e=>(Module._CreateExprContext=wasmExports.CreateExprContext)(e),Module._EnsurePortalSnapshotExists=()=>(Module._EnsurePortalSnapshotExists=wasmExports.EnsurePortalSnapshotExists)(),Module._CheckIndexCompatible=(e,r,M,r0)=>(Module._CheckIndexCompatible=wasmExports.CheckIndexCompatible)(e,r,M,r0),Module._pgstat_count_truncate=e=>(Module._pgstat_count_truncate=wasmExports.pgstat_count_truncate)(e),Module._SPI_connect=()=>(Module._SPI_connect=wasmExports.SPI_connect)(),Module._SPI_exec=(e,r)=>(Module._SPI_exec=wasmExports.SPI_exec)(e,r),Module._SPI_execute=(e,r,M)=>(Module._SPI_execute=wasmExports.SPI_execute)(e,r,M),Module._SPI_getvalue=(e,r,M)=>(Module._SPI_getvalue=wasmExports.SPI_getvalue)(e,r,M),Module._generate_operator_clause=(e,r,M,r0,s0,a0)=>(Module._generate_operator_clause=wasmExports.generate_operator_clause)(e,r,M,r0,s0,a0),Module._SPI_finish=()=>(Module._SPI_finish=wasmExports.SPI_finish)(),Module._CreateTransientRelDestReceiver=e=>(Module._CreateTransientRelDestReceiver=wasmExports.CreateTransientRelDestReceiver)(e),Module._MemoryContextSetIdentifier=(e,r)=>(Module._MemoryContextSetIdentifier=wasmExports.MemoryContextSetIdentifier)(e,r),Module._checkExprHasSubLink=e=>(Module._checkExprHasSubLink=wasmExports.checkExprHasSubLink)(e),Module._SetTuplestoreDestReceiverParams=(e,r,M,r0,s0,a0)=>(Module._SetTuplestoreDestReceiverParams=wasmExports.SetTuplestoreDestReceiverParams)(e,r,M,r0,s0,a0),Module._tuplestore_rescan=e=>(Module._tuplestore_rescan=wasmExports.tuplestore_rescan)(e),Module._MemoryContextDeleteChildren=e=>(Module._MemoryContextDeleteChildren=wasmExports.MemoryContextDeleteChildren)(e),Module._ReleaseCachedPlan=(e,r)=>(Module._ReleaseCachedPlan=wasmExports.ReleaseCachedPlan)(e,r),Module._nextval=e=>(Module._nextval=wasmExports.nextval)(e),Module._textToQualifiedNameList=e=>(Module._textToQualifiedNameList=wasmExports.textToQualifiedNameList)(e),Module._tuplestore_gettupleslot=(e,r,M,r0)=>(Module._tuplestore_gettupleslot=wasmExports.tuplestore_gettupleslot)(e,r,M,r0),Module._list_delete=(e,r)=>(Module._list_delete=wasmExports.list_delete)(e,r),Module._tuplestore_end=e=>(Module._tuplestore_end=wasmExports.tuplestore_end)(e),Module._quote_literal_cstr=e=>(Module._quote_literal_cstr=wasmExports.quote_literal_cstr)(e),Module._contain_mutable_functions=e=>(Module._contain_mutable_functions=wasmExports.contain_mutable_functions)(e),Module._ExecuteTruncateGuts=(e,r,M,r0,s0,a0)=>(Module._ExecuteTruncateGuts=wasmExports.ExecuteTruncateGuts)(e,r,M,r0,s0,a0),Module._bms_make_singleton=e=>(Module._bms_make_singleton=wasmExports.bms_make_singleton)(e),Module._tuplestore_puttupleslot=(e,r)=>(Module._tuplestore_puttupleslot=wasmExports.tuplestore_puttupleslot)(e,r),Module._tuplestore_begin_heap=(e,r,M)=>(Module._tuplestore_begin_heap=wasmExports.tuplestore_begin_heap)(e,r,M),Module._ExecForceStoreHeapTuple=(e,r,M)=>(Module._ExecForceStoreHeapTuple=wasmExports.ExecForceStoreHeapTuple)(e,r,M),Module._strtod=(e,r)=>(Module._strtod=wasmExports.strtod)(e,r),Module._plain_crypt_verify=(e,r,M,r0)=>(Module._plain_crypt_verify=wasmExports.plain_crypt_verify)(e,r,M,r0),Module._ProcessConfigFile=e=>(Module._ProcessConfigFile=wasmExports.ProcessConfigFile)(e),Module._ExecReScan=e=>(Module._ExecReScan=wasmExports.ExecReScan)(e),Module._ExecAsyncResponse=e=>(Module._ExecAsyncResponse=wasmExports.ExecAsyncResponse)(e),Module._ExecAsyncRequestDone=(e,r)=>(Module._ExecAsyncRequestDone=wasmExports.ExecAsyncRequestDone)(e,r),Module._ExecAsyncRequestPending=e=>(Module._ExecAsyncRequestPending=wasmExports.ExecAsyncRequestPending)(e),Module._ExprEvalPushStep=(e,r)=>(Module._ExprEvalPushStep=wasmExports.ExprEvalPushStep)(e,r),Module._ExecInitExprWithParams=(e,r)=>(Module._ExecInitExprWithParams=wasmExports.ExecInitExprWithParams)(e,r),Module._ExecInitExprList=(e,r)=>(Module._ExecInitExprList=wasmExports.ExecInitExprList)(e,r),Module._MakeExpandedObjectReadOnlyInternal=e=>(Module._MakeExpandedObjectReadOnlyInternal=wasmExports.MakeExpandedObjectReadOnlyInternal)(e),Module._tuplesort_puttupleslot=(e,r)=>(Module._tuplesort_puttupleslot=wasmExports.tuplesort_puttupleslot)(e,r),Module._ArrayGetNItems=(e,r)=>(Module._ArrayGetNItems=wasmExports.ArrayGetNItems)(e,r),Module._expanded_record_fetch_tupdesc=e=>(Module._expanded_record_fetch_tupdesc=wasmExports.expanded_record_fetch_tupdesc)(e),Module._expanded_record_fetch_field=(e,r,M)=>(Module._expanded_record_fetch_field=wasmExports.expanded_record_fetch_field)(e,r,M),Module._JsonbValueToJsonb=e=>(Module._JsonbValueToJsonb=wasmExports.JsonbValueToJsonb)(e),Module._boolout=e=>(Module._boolout=wasmExports.boolout)(e),Module._lookup_rowtype_tupdesc_domain=(e,r,M)=>(Module._lookup_rowtype_tupdesc_domain=wasmExports.lookup_rowtype_tupdesc_domain)(e,r,M),Module._MemoryContextGetParent=e=>(Module._MemoryContextGetParent=wasmExports.MemoryContextGetParent)(e),Module._DeleteExpandedObject=e=>(Module._DeleteExpandedObject=wasmExports.DeleteExpandedObject)(e),Module._ExecFindJunkAttributeInTlist=(e,r)=>(Module._ExecFindJunkAttributeInTlist=wasmExports.ExecFindJunkAttributeInTlist)(e,r),Module._standard_ExecutorStart=(e,r)=>(Module._standard_ExecutorStart=wasmExports.standard_ExecutorStart)(e,r),Module._standard_ExecutorRun=(e,r,M,r0)=>(Module._standard_ExecutorRun=wasmExports.standard_ExecutorRun)(e,r,M,r0),Module._standard_ExecutorFinish=e=>(Module._standard_ExecutorFinish=wasmExports.standard_ExecutorFinish)(e),Module._standard_ExecutorEnd=e=>(Module._standard_ExecutorEnd=wasmExports.standard_ExecutorEnd)(e),Module._InstrAlloc=(e,r,M)=>(Module._InstrAlloc=wasmExports.InstrAlloc)(e,r,M),Module._get_typlenbyval=(e,r,M)=>(Module._get_typlenbyval=wasmExports.get_typlenbyval)(e,r,M),Module._InputFunctionCall=(e,r,M,r0)=>(Module._InputFunctionCall=wasmExports.InputFunctionCall)(e,r,M,r0),Module._FreeExprContext=(e,r)=>(Module._FreeExprContext=wasmExports.FreeExprContext)(e,r),Module._ExecOpenScanRelation=(e,r,M)=>(Module._ExecOpenScanRelation=wasmExports.ExecOpenScanRelation)(e,r,M),Module._bms_intersect=(e,r)=>(Module._bms_intersect=wasmExports.bms_intersect)(e,r),Module._ExecGetReturningSlot=(e,r)=>(Module._ExecGetReturningSlot=wasmExports.ExecGetReturningSlot)(e,r),Module._ExecGetResultRelCheckAsUser=(e,r)=>(Module._ExecGetResultRelCheckAsUser=wasmExports.ExecGetResultRelCheckAsUser)(e,r),Module._get_call_expr_argtype=(e,r)=>(Module._get_call_expr_argtype=wasmExports.get_call_expr_argtype)(e,r),Module._tuplestore_clear=e=>(Module._tuplestore_clear=wasmExports.tuplestore_clear)(e),Module._InstrUpdateTupleCount=(e,r)=>(Module._InstrUpdateTupleCount=wasmExports.InstrUpdateTupleCount)(e,r),Module._tuplesort_begin_heap=(e,r,M,r0,s0,a0,i0,u0,d0)=>(Module._tuplesort_begin_heap=wasmExports.tuplesort_begin_heap)(e,r,M,r0,s0,a0,i0,u0,d0),Module._tuplesort_gettupleslot=(e,r,M,r0,s0)=>(Module._tuplesort_gettupleslot=wasmExports.tuplesort_gettupleslot)(e,r,M,r0,s0),Module._AddWaitEventToSet=(e,r,M,r0,s0)=>(Module._AddWaitEventToSet=wasmExports.AddWaitEventToSet)(e,r,M,r0,s0),Module._GetNumRegisteredWaitEvents=e=>(Module._GetNumRegisteredWaitEvents=wasmExports.GetNumRegisteredWaitEvents)(e),Module._get_attstatsslot=(e,r,M,r0,s0)=>(Module._get_attstatsslot=wasmExports.get_attstatsslot)(e,r,M,r0,s0),Module._free_attstatsslot=e=>(Module._free_attstatsslot=wasmExports.free_attstatsslot)(e),Module._tuplesort_reset=e=>(Module._tuplesort_reset=wasmExports.tuplesort_reset)(e),Module._pairingheap_first=e=>(Module._pairingheap_first=wasmExports.pairingheap_first)(e),Module._bms_nonempty_difference=(e,r)=>(Module._bms_nonempty_difference=wasmExports.bms_nonempty_difference)(e,r),Module._SPI_connect_ext=e=>(Module._SPI_connect_ext=wasmExports.SPI_connect_ext)(e),Module._SPI_commit=()=>(Module._SPI_commit=wasmExports.SPI_commit)(),Module._CopyErrorData=()=>(Module._CopyErrorData=wasmExports.CopyErrorData)(),Module._ReThrowError=e=>(Module._ReThrowError=wasmExports.ReThrowError)(e),Module._SPI_commit_and_chain=()=>(Module._SPI_commit_and_chain=wasmExports.SPI_commit_and_chain)(),Module._SPI_rollback=()=>(Module._SPI_rollback=wasmExports.SPI_rollback)(),Module._SPI_rollback_and_chain=()=>(Module._SPI_rollback_and_chain=wasmExports.SPI_rollback_and_chain)(),Module._SPI_freetuptable=e=>(Module._SPI_freetuptable=wasmExports.SPI_freetuptable)(e),Module._SPI_execute_extended=(e,r)=>(Module._SPI_execute_extended=wasmExports.SPI_execute_extended)(e,r),Module._SPI_execute_plan=(e,r,M,r0,s0)=>(Module._SPI_execute_plan=wasmExports.SPI_execute_plan)(e,r,M,r0,s0),Module._SPI_execp=(e,r,M,r0)=>(Module._SPI_execp=wasmExports.SPI_execp)(e,r,M,r0),Module._SPI_execute_plan_extended=(e,r)=>(Module._SPI_execute_plan_extended=wasmExports.SPI_execute_plan_extended)(e,r),Module._SPI_execute_plan_with_paramlist=(e,r,M,r0)=>(Module._SPI_execute_plan_with_paramlist=wasmExports.SPI_execute_plan_with_paramlist)(e,r,M,r0),Module._SPI_prepare=(e,r,M)=>(Module._SPI_prepare=wasmExports.SPI_prepare)(e,r,M),Module._SPI_prepare_extended=(e,r)=>(Module._SPI_prepare_extended=wasmExports.SPI_prepare_extended)(e,r),Module._SPI_keepplan=e=>(Module._SPI_keepplan=wasmExports.SPI_keepplan)(e),Module._SPI_freeplan=e=>(Module._SPI_freeplan=wasmExports.SPI_freeplan)(e),Module._SPI_copytuple=e=>(Module._SPI_copytuple=wasmExports.SPI_copytuple)(e),Module._SPI_returntuple=(e,r)=>(Module._SPI_returntuple=wasmExports.SPI_returntuple)(e,r),Module._SPI_fnumber=(e,r)=>(Module._SPI_fnumber=wasmExports.SPI_fnumber)(e,r),Module._SPI_fname=(e,r)=>(Module._SPI_fname=wasmExports.SPI_fname)(e,r),Module._SPI_getbinval=(e,r,M,r0)=>(Module._SPI_getbinval=wasmExports.SPI_getbinval)(e,r,M,r0),Module._SPI_gettype=(e,r)=>(Module._SPI_gettype=wasmExports.SPI_gettype)(e,r),Module._SPI_gettypeid=(e,r)=>(Module._SPI_gettypeid=wasmExports.SPI_gettypeid)(e,r),Module._SPI_getrelname=e=>(Module._SPI_getrelname=wasmExports.SPI_getrelname)(e),Module._SPI_palloc=e=>(Module._SPI_palloc=wasmExports.SPI_palloc)(e),Module._SPI_datumTransfer=(e,r,M)=>(Module._SPI_datumTransfer=wasmExports.SPI_datumTransfer)(e,r,M),Module._datumTransfer=(e,r,M)=>(Module._datumTransfer=wasmExports.datumTransfer)(e,r,M),Module._SPI_cursor_open_with_paramlist=(e,r,M,r0)=>(Module._SPI_cursor_open_with_paramlist=wasmExports.SPI_cursor_open_with_paramlist)(e,r,M,r0),Module._SPI_cursor_parse_open=(e,r,M)=>(Module._SPI_cursor_parse_open=wasmExports.SPI_cursor_parse_open)(e,r,M),Module._SPI_cursor_find=e=>(Module._SPI_cursor_find=wasmExports.SPI_cursor_find)(e),Module._SPI_cursor_fetch=(e,r,M)=>(Module._SPI_cursor_fetch=wasmExports.SPI_cursor_fetch)(e,r,M),Module._SPI_scroll_cursor_fetch=(e,r,M)=>(Module._SPI_scroll_cursor_fetch=wasmExports.SPI_scroll_cursor_fetch)(e,r,M),Module._SPI_scroll_cursor_move=(e,r,M)=>(Module._SPI_scroll_cursor_move=wasmExports.SPI_scroll_cursor_move)(e,r,M),Module._SPI_cursor_close=e=>(Module._SPI_cursor_close=wasmExports.SPI_cursor_close)(e),Module._SPI_plan_is_valid=e=>(Module._SPI_plan_is_valid=wasmExports.SPI_plan_is_valid)(e),Module._SPI_result_code_string=e=>(Module._SPI_result_code_string=wasmExports.SPI_result_code_string)(e),Module._SPI_plan_get_plan_sources=e=>(Module._SPI_plan_get_plan_sources=wasmExports.SPI_plan_get_plan_sources)(e),Module._SPI_plan_get_cached_plan=e=>(Module._SPI_plan_get_cached_plan=wasmExports.SPI_plan_get_cached_plan)(e),Module._SPI_register_relation=e=>(Module._SPI_register_relation=wasmExports.SPI_register_relation)(e),Module._create_queryEnv=()=>(Module._create_queryEnv=wasmExports.create_queryEnv)(),Module._register_ENR=(e,r)=>(Module._register_ENR=wasmExports.register_ENR)(e,r),Module._SPI_register_trigger_data=e=>(Module._SPI_register_trigger_data=wasmExports.SPI_register_trigger_data)(e),Module._tuplestore_tuple_count=e=>(Module._tuplestore_tuple_count=wasmExports.tuplestore_tuple_count)(e),Module._GetUserMapping=(e,r)=>(Module._GetUserMapping=wasmExports.GetUserMapping)(e,r),Module._GetForeignTable=e=>(Module._GetForeignTable=wasmExports.GetForeignTable)(e),Module._GetForeignColumnOptions=(e,r)=>(Module._GetForeignColumnOptions=wasmExports.GetForeignColumnOptions)(e,r),Module._initClosestMatch=(e,r,M)=>(Module._initClosestMatch=wasmExports.initClosestMatch)(e,r,M),Module._updateClosestMatch=(e,r)=>(Module._updateClosestMatch=wasmExports.updateClosestMatch)(e,r),Module._getClosestMatch=e=>(Module._getClosestMatch=wasmExports.getClosestMatch)(e),Module._GetExistingLocalJoinPath=e=>(Module._GetExistingLocalJoinPath=wasmExports.GetExistingLocalJoinPath)(e),Module._bloom_create=(e,r,M)=>(Module._bloom_create=wasmExports.bloom_create)(e,r,M),Module._bloom_free=e=>(Module._bloom_free=wasmExports.bloom_free)(e),Module._bloom_add_element=(e,r,M)=>(Module._bloom_add_element=wasmExports.bloom_add_element)(e,r,M),Module._bloom_lacks_element=(e,r,M)=>(Module._bloom_lacks_element=wasmExports.bloom_lacks_element)(e,r,M),Module._bloom_prop_bits_set=e=>(Module._bloom_prop_bits_set=wasmExports.bloom_prop_bits_set)(e),Module._socket=(e,r,M)=>(Module._socket=wasmExports.socket)(e,r,M),Module._send=(e,r,M,r0)=>(Module._send=wasmExports.send)(e,r,M,r0),Module._recv=(e,r,M,r0)=>(Module._recv=wasmExports.recv)(e,r,M,r0),Module._be_lo_unlink=e=>(Module._be_lo_unlink=wasmExports.be_lo_unlink)(e),Module._pg_mb2wchar_with_len=(e,r,M)=>(Module._pg_mb2wchar_with_len=wasmExports.pg_mb2wchar_with_len)(e,r,M),Module._pg_regcomp=(e,r,M,r0,s0)=>(Module._pg_regcomp=wasmExports.pg_regcomp)(e,r,M,r0,s0),Module._pg_regerror=(e,r,M,r0)=>(Module._pg_regerror=wasmExports.pg_regerror)(e,r,M,r0),Module._strcat=(e,r)=>(Module._strcat=wasmExports.strcat)(e,r),Module._setsockopt=(e,r,M,r0,s0)=>(Module._setsockopt=wasmExports.setsockopt)(e,r,M,r0,s0),Module._getsockopt=(e,r,M,r0,s0)=>(Module._getsockopt=wasmExports.getsockopt)(e,r,M,r0,s0),Module._getsockname=(e,r,M)=>(Module._getsockname=wasmExports.getsockname)(e,r,M),Module._pq_sendtext=(e,r,M)=>(Module._pq_sendtext=wasmExports.pq_sendtext)(e,r,M),Module._pq_sendfloat4=(e,r)=>(Module._pq_sendfloat4=wasmExports.pq_sendfloat4)(e,r),Module._pq_sendfloat8=(e,r)=>(Module._pq_sendfloat8=wasmExports.pq_sendfloat8)(e,r),Module._pq_begintypsend=e=>(Module._pq_begintypsend=wasmExports.pq_begintypsend)(e),Module._pq_endtypsend=e=>(Module._pq_endtypsend=wasmExports.pq_endtypsend)(e),Module._pq_getmsgfloat4=e=>(Module._pq_getmsgfloat4=wasmExports.pq_getmsgfloat4)(e),Module._pq_getmsgfloat8=e=>(Module._pq_getmsgfloat8=wasmExports.pq_getmsgfloat8)(e),Module._pq_getmsgtext=(e,r,M)=>(Module._pq_getmsgtext=wasmExports.pq_getmsgtext)(e,r,M),Module._pg_strtoint32=e=>(Module._pg_strtoint32=wasmExports.pg_strtoint32)(e),Module._bms_membership=e=>(Module._bms_membership=wasmExports.bms_membership)(e),Module._list_make5_impl=(e,r,M,r0,s0,a0)=>(Module._list_make5_impl=wasmExports.list_make5_impl)(e,r,M,r0,s0,a0),Module._list_insert_nth=(e,r,M)=>(Module._list_insert_nth=wasmExports.list_insert_nth)(e,r,M),Module._list_member_ptr=(e,r)=>(Module._list_member_ptr=wasmExports.list_member_ptr)(e,r),Module._list_append_unique_ptr=(e,r)=>(Module._list_append_unique_ptr=wasmExports.list_append_unique_ptr)(e,r),Module._make_opclause=(e,r,M,r0,s0,a0,i0)=>(Module._make_opclause=wasmExports.make_opclause)(e,r,M,r0,s0,a0,i0),Module._exprIsLengthCoercion=(e,r)=>(Module._exprIsLengthCoercion=wasmExports.exprIsLengthCoercion)(e,r),Module._fix_opfuncids=e=>(Module._fix_opfuncids=wasmExports.fix_opfuncids)(e),Module._CleanQuerytext=(e,r,M)=>(Module._CleanQuerytext=wasmExports.CleanQuerytext)(e,r,M),Module._EnableQueryId=()=>(Module._EnableQueryId=wasmExports.EnableQueryId)(),Module._find_base_rel=(e,r)=>(Module._find_base_rel=wasmExports.find_base_rel)(e,r),Module._add_path=(e,r)=>(Module._add_path=wasmExports.add_path)(e,r),Module._pathkeys_contained_in=(e,r)=>(Module._pathkeys_contained_in=wasmExports.pathkeys_contained_in)(e,r),Module._create_sort_path=(e,r,M,r0,s0)=>(Module._create_sort_path=wasmExports.create_sort_path)(e,r,M,r0,s0),Module._set_baserel_size_estimates=(e,r)=>(Module._set_baserel_size_estimates=wasmExports.set_baserel_size_estimates)(e,r),Module._clauselist_selectivity=(e,r,M,r0,s0)=>(Module._clauselist_selectivity=wasmExports.clauselist_selectivity)(e,r,M,r0,s0),Module._get_tablespace_page_costs=(e,r,M)=>(Module._get_tablespace_page_costs=wasmExports.get_tablespace_page_costs)(e,r,M),Module._cost_qual_eval=(e,r,M)=>(Module._cost_qual_eval=wasmExports.cost_qual_eval)(e,r,M),Module._estimate_num_groups=(e,r,M,r0,s0)=>(Module._estimate_num_groups=wasmExports.estimate_num_groups)(e,r,M,r0,s0),Module._cost_sort=(e,r,M,r0,s0,a0,i0,u0,d0)=>(Module._cost_sort=wasmExports.cost_sort)(e,r,M,r0,s0,a0,i0,u0,d0),Module._get_sortgrouplist_exprs=(e,r)=>(Module._get_sortgrouplist_exprs=wasmExports.get_sortgrouplist_exprs)(e,r),Module._make_restrictinfo=(e,r,M,r0,s0,a0,i0,u0,d0,m0)=>(Module._make_restrictinfo=wasmExports.make_restrictinfo)(e,r,M,r0,s0,a0,i0,u0,d0,m0),Module._generate_implied_equalities_for_column=(e,r,M,r0,s0)=>(Module._generate_implied_equalities_for_column=wasmExports.generate_implied_equalities_for_column)(e,r,M,r0,s0),Module._eclass_useful_for_merging=(e,r,M)=>(Module._eclass_useful_for_merging=wasmExports.eclass_useful_for_merging)(e,r,M),Module._join_clause_is_movable_to=(e,r)=>(Module._join_clause_is_movable_to=wasmExports.join_clause_is_movable_to)(e,r),Module._get_plan_rowmark=(e,r)=>(Module._get_plan_rowmark=wasmExports.get_plan_rowmark)(e,r),Module._update_mergeclause_eclasses=(e,r)=>(Module._update_mergeclause_eclasses=wasmExports.update_mergeclause_eclasses)(e,r),Module._find_join_rel=(e,r)=>(Module._find_join_rel=wasmExports.find_join_rel)(e,r),Module._make_canonical_pathkey=(e,r,M,r0,s0)=>(Module._make_canonical_pathkey=wasmExports.make_canonical_pathkey)(e,r,M,r0,s0),Module._get_sortgroupref_clause_noerr=(e,r)=>(Module._get_sortgroupref_clause_noerr=wasmExports.get_sortgroupref_clause_noerr)(e,r),Module._extract_actual_clauses=(e,r)=>(Module._extract_actual_clauses=wasmExports.extract_actual_clauses)(e,r),Module._change_plan_targetlist=(e,r,M)=>(Module._change_plan_targetlist=wasmExports.change_plan_targetlist)(e,r,M),Module._make_foreignscan=(e,r,M,r0,s0,a0,i0,u0)=>(Module._make_foreignscan=wasmExports.make_foreignscan)(e,r,M,r0,s0,a0,i0,u0),Module._tlist_member=(e,r)=>(Module._tlist_member=wasmExports.tlist_member)(e,r),Module._pull_vars_of_level=(e,r)=>(Module._pull_vars_of_level=wasmExports.pull_vars_of_level)(e,r),Module._IncrementVarSublevelsUp=(e,r,M)=>(Module._IncrementVarSublevelsUp=wasmExports.IncrementVarSublevelsUp)(e,r,M),Module._standard_planner=(e,r,M,r0)=>(Module._standard_planner=wasmExports.standard_planner)(e,r,M,r0),Module._get_relids_in_jointree=(e,r,M)=>(Module._get_relids_in_jointree=wasmExports.get_relids_in_jointree)(e,r,M),Module._add_new_columns_to_pathtarget=(e,r)=>(Module._add_new_columns_to_pathtarget=wasmExports.add_new_columns_to_pathtarget)(e,r),Module._get_agg_clause_costs=(e,r,M)=>(Module._get_agg_clause_costs=wasmExports.get_agg_clause_costs)(e,r,M),Module._grouping_is_sortable=e=>(Module._grouping_is_sortable=wasmExports.grouping_is_sortable)(e),Module._copy_pathtarget=e=>(Module._copy_pathtarget=wasmExports.copy_pathtarget)(e),Module._create_projection_path=(e,r,M,r0)=>(Module._create_projection_path=wasmExports.create_projection_path)(e,r,M,r0),Module._GetSysCacheHashValue=(e,r,M,r0,s0)=>(Module._GetSysCacheHashValue=wasmExports.GetSysCacheHashValue)(e,r,M,r0,s0),Module._get_translated_update_targetlist=(e,r,M,r0)=>(Module._get_translated_update_targetlist=wasmExports.get_translated_update_targetlist)(e,r,M,r0),Module._add_row_identity_var=(e,r,M,r0)=>(Module._add_row_identity_var=wasmExports.add_row_identity_var)(e,r,M,r0),Module._get_rel_all_updated_cols=(e,r)=>(Module._get_rel_all_updated_cols=wasmExports.get_rel_all_updated_cols)(e,r),Module._get_baserel_parampathinfo=(e,r,M)=>(Module._get_baserel_parampathinfo=wasmExports.get_baserel_parampathinfo)(e,r,M),Module._create_foreignscan_path=(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0)=>(Module._create_foreignscan_path=wasmExports.create_foreignscan_path)(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0),Module._create_foreign_join_path=(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0)=>(Module._create_foreign_join_path=wasmExports.create_foreign_join_path)(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0),Module._create_foreign_upper_path=(e,r,M,r0,s0,a0,i0,u0,d0,m0)=>(Module._create_foreign_upper_path=wasmExports.create_foreign_upper_path)(e,r,M,r0,s0,a0,i0,u0,d0,m0),Module._adjust_limit_rows_costs=(e,r,M,r0,s0)=>(Module._adjust_limit_rows_costs=wasmExports.adjust_limit_rows_costs)(e,r,M,r0,s0),Module._add_to_flat_tlist=(e,r)=>(Module._add_to_flat_tlist=wasmExports.add_to_flat_tlist)(e,r),Module._get_fn_expr_argtype=(e,r)=>(Module._get_fn_expr_argtype=wasmExports.get_fn_expr_argtype)(e,r),Module._on_shmem_exit=(e,r)=>(Module._on_shmem_exit=wasmExports.on_shmem_exit)(e,r),Module._SignalHandlerForConfigReload=e=>(Module._SignalHandlerForConfigReload=wasmExports.SignalHandlerForConfigReload)(e),Module._SignalHandlerForShutdownRequest=e=>(Module._SignalHandlerForShutdownRequest=wasmExports.SignalHandlerForShutdownRequest)(e),Module._procsignal_sigusr1_handler=e=>(Module._procsignal_sigusr1_handler=wasmExports.procsignal_sigusr1_handler)(e),Module._RegisterBackgroundWorker=e=>(Module._RegisterBackgroundWorker=wasmExports.RegisterBackgroundWorker)(e),Module._WaitForBackgroundWorkerStartup=(e,r)=>(Module._WaitForBackgroundWorkerStartup=wasmExports.WaitForBackgroundWorkerStartup)(e,r),Module._GetConfigOption=(e,r,M)=>(Module._GetConfigOption=wasmExports.GetConfigOption)(e,r,M),Module._toupper=e=>(Module._toupper=wasmExports.toupper)(e),Module._pg_reg_getinitialstate=e=>(Module._pg_reg_getinitialstate=wasmExports.pg_reg_getinitialstate)(e),Module._pg_reg_getfinalstate=e=>(Module._pg_reg_getfinalstate=wasmExports.pg_reg_getfinalstate)(e),Module._pg_reg_getnumoutarcs=(e,r)=>(Module._pg_reg_getnumoutarcs=wasmExports.pg_reg_getnumoutarcs)(e,r),Module._pg_reg_getoutarcs=(e,r,M,r0)=>(Module._pg_reg_getoutarcs=wasmExports.pg_reg_getoutarcs)(e,r,M,r0),Module._pg_reg_getnumcolors=e=>(Module._pg_reg_getnumcolors=wasmExports.pg_reg_getnumcolors)(e),Module._pg_reg_colorisbegin=(e,r)=>(Module._pg_reg_colorisbegin=wasmExports.pg_reg_colorisbegin)(e,r),Module._pg_reg_colorisend=(e,r)=>(Module._pg_reg_colorisend=wasmExports.pg_reg_colorisend)(e,r),Module._pg_reg_getnumcharacters=(e,r)=>(Module._pg_reg_getnumcharacters=wasmExports.pg_reg_getnumcharacters)(e,r),Module._pg_reg_getcharacters=(e,r,M,r0)=>(Module._pg_reg_getcharacters=wasmExports.pg_reg_getcharacters)(e,r,M,r0),Module._OutputPluginPrepareWrite=(e,r)=>(Module._OutputPluginPrepareWrite=wasmExports.OutputPluginPrepareWrite)(e,r),Module._OutputPluginWrite=(e,r)=>(Module._OutputPluginWrite=wasmExports.OutputPluginWrite)(e,r),Module._array_contains_nulls=e=>(Module._array_contains_nulls=wasmExports.array_contains_nulls)(e),Module._hash_seq_term=e=>(Module._hash_seq_term=wasmExports.hash_seq_term)(e),Module._FreeErrorData=e=>(Module._FreeErrorData=wasmExports.FreeErrorData)(e),Module._RelidByRelfilenumber=(e,r)=>(Module._RelidByRelfilenumber=wasmExports.RelidByRelfilenumber)(e,r),Module._WaitLatchOrSocket=(e,r,M,r0,s0)=>(Module._WaitLatchOrSocket=wasmExports.WaitLatchOrSocket)(e,r,M,r0,s0),Module._get_row_security_policies=(e,r,M,r0,s0,a0,i0)=>(Module._get_row_security_policies=wasmExports.get_row_security_policies)(e,r,M,r0,s0,a0,i0),Module._hash_estimate_size=(e,r)=>(Module._hash_estimate_size=wasmExports.hash_estimate_size)(e,r),Module._ShmemInitHash=(e,r,M,r0,s0)=>(Module._ShmemInitHash=wasmExports.ShmemInitHash)(e,r,M,r0,s0),Module._LockBufHdr=e=>(Module._LockBufHdr=wasmExports.LockBufHdr)(e),Module._EvictUnpinnedBuffer=e=>(Module._EvictUnpinnedBuffer=wasmExports.EvictUnpinnedBuffer)(e),Module._have_free_buffer=()=>(Module._have_free_buffer=wasmExports.have_free_buffer)(),Module._copy_file=(e,r)=>(Module._copy_file=wasmExports.copy_file)(e,r),Module._AcquireExternalFD=()=>(Module._AcquireExternalFD=wasmExports.AcquireExternalFD)(),Module._GetNamedDSMSegment=(e,r,M,r0)=>(Module._GetNamedDSMSegment=wasmExports.GetNamedDSMSegment)(e,r,M,r0),Module._RequestAddinShmemSpace=e=>(Module._RequestAddinShmemSpace=wasmExports.RequestAddinShmemSpace)(e),Module._GetRunningTransactionData=()=>(Module._GetRunningTransactionData=wasmExports.GetRunningTransactionData)(),Module._BackendXidGetPid=e=>(Module._BackendXidGetPid=wasmExports.BackendXidGetPid)(e),Module._LWLockRegisterTranche=(e,r)=>(Module._LWLockRegisterTranche=wasmExports.LWLockRegisterTranche)(e,r),Module._GetNamedLWLockTranche=e=>(Module._GetNamedLWLockTranche=wasmExports.GetNamedLWLockTranche)(e),Module._LWLockNewTrancheId=()=>(Module._LWLockNewTrancheId=wasmExports.LWLockNewTrancheId)(),Module._RequestNamedLWLockTranche=(e,r)=>(Module._RequestNamedLWLockTranche=wasmExports.RequestNamedLWLockTranche)(e,r),Module._standard_ProcessUtility=(e,r,M,r0,s0,a0,i0,u0)=>(Module._standard_ProcessUtility=wasmExports.standard_ProcessUtility)(e,r,M,r0,s0,a0,i0,u0),Module._lookup_ts_dictionary_cache=e=>(Module._lookup_ts_dictionary_cache=wasmExports.lookup_ts_dictionary_cache)(e),Module._get_tsearch_config_filename=(e,r)=>(Module._get_tsearch_config_filename=wasmExports.get_tsearch_config_filename)(e,r),Module._lowerstr=e=>(Module._lowerstr=wasmExports.lowerstr)(e),Module._readstoplist=(e,r,M)=>(Module._readstoplist=wasmExports.readstoplist)(e,r,M),Module._lowerstr_with_len=(e,r)=>(Module._lowerstr_with_len=wasmExports.lowerstr_with_len)(e,r),Module._searchstoplist=(e,r)=>(Module._searchstoplist=wasmExports.searchstoplist)(e,r),Module._tsearch_readline_begin=(e,r)=>(Module._tsearch_readline_begin=wasmExports.tsearch_readline_begin)(e,r),Module._tsearch_readline=e=>(Module._tsearch_readline=wasmExports.tsearch_readline)(e),Module._t_isspace=e=>(Module._t_isspace=wasmExports.t_isspace)(e),Module._tsearch_readline_end=e=>(Module._tsearch_readline_end=wasmExports.tsearch_readline_end)(e),Module._stringToQualifiedNameList=(e,r)=>(Module._stringToQualifiedNameList=wasmExports.stringToQualifiedNameList)(e,r),Module._t_isdigit=e=>(Module._t_isdigit=wasmExports.t_isdigit)(e),Module._t_isalnum=e=>(Module._t_isalnum=wasmExports.t_isalnum)(e),Module._get_restriction_variable=(e,r,M,r0,s0,a0)=>(Module._get_restriction_variable=wasmExports.get_restriction_variable)(e,r,M,r0,s0,a0),Module._MemoryContextAllocHuge=(e,r)=>(Module._MemoryContextAllocHuge=wasmExports.MemoryContextAllocHuge)(e,r),Module._WaitEventExtensionNew=e=>(Module._WaitEventExtensionNew=wasmExports.WaitEventExtensionNew)(e),Module._expand_array=(e,r,M)=>(Module._expand_array=wasmExports.expand_array)(e,r,M),Module._arraycontsel=e=>(Module._arraycontsel=wasmExports.arraycontsel)(e),Module._arraycontjoinsel=e=>(Module._arraycontjoinsel=wasmExports.arraycontjoinsel)(e),Module._initArrayResult=(e,r,M)=>(Module._initArrayResult=wasmExports.initArrayResult)(e,r,M),Module._array_create_iterator=(e,r,M)=>(Module._array_create_iterator=wasmExports.array_create_iterator)(e,r,M),Module._array_iterate=(e,r,M)=>(Module._array_iterate=wasmExports.array_iterate)(e,r,M),Module._ArrayGetIntegerTypmods=(e,r)=>(Module._ArrayGetIntegerTypmods=wasmExports.ArrayGetIntegerTypmods)(e,r),Module._boolin=e=>(Module._boolin=wasmExports.boolin)(e),Module._cash_cmp=e=>(Module._cash_cmp=wasmExports.cash_cmp)(e),Module._int64_to_numeric=e=>(Module._int64_to_numeric=wasmExports.int64_to_numeric)(e),Module._numeric_div=e=>(Module._numeric_div=wasmExports.numeric_div)(e),Module._date_eq=e=>(Module._date_eq=wasmExports.date_eq)(e),Module._date_lt=e=>(Module._date_lt=wasmExports.date_lt)(e),Module._date_le=e=>(Module._date_le=wasmExports.date_le)(e),Module._date_gt=e=>(Module._date_gt=wasmExports.date_gt)(e),Module._date_ge=e=>(Module._date_ge=wasmExports.date_ge)(e),Module._date_cmp=e=>(Module._date_cmp=wasmExports.date_cmp)(e),Module._date_mi=e=>(Module._date_mi=wasmExports.date_mi)(e),Module._time_eq=e=>(Module._time_eq=wasmExports.time_eq)(e),Module._time_lt=e=>(Module._time_lt=wasmExports.time_lt)(e),Module._time_le=e=>(Module._time_le=wasmExports.time_le)(e),Module._time_gt=e=>(Module._time_gt=wasmExports.time_gt)(e),Module._time_ge=e=>(Module._time_ge=wasmExports.time_ge)(e),Module._time_cmp=e=>(Module._time_cmp=wasmExports.time_cmp)(e),Module._time_mi_time=e=>(Module._time_mi_time=wasmExports.time_mi_time)(e),Module._timetz_cmp=e=>(Module._timetz_cmp=wasmExports.timetz_cmp)(e),Module._TransferExpandedObject=(e,r)=>(Module._TransferExpandedObject=wasmExports.TransferExpandedObject)(e,r),Module._numeric_lt=e=>(Module._numeric_lt=wasmExports.numeric_lt)(e),Module._numeric_ge=e=>(Module._numeric_ge=wasmExports.numeric_ge)(e),Module._err_generic_string=(e,r)=>(Module._err_generic_string=wasmExports.err_generic_string)(e,r),Module._domain_check=(e,r,M,r0,s0)=>(Module._domain_check=wasmExports.domain_check)(e,r,M,r0,s0),Module._enum_lt=e=>(Module._enum_lt=wasmExports.enum_lt)(e),Module._enum_le=e=>(Module._enum_le=wasmExports.enum_le)(e),Module._enum_ge=e=>(Module._enum_ge=wasmExports.enum_ge)(e),Module._enum_gt=e=>(Module._enum_gt=wasmExports.enum_gt)(e),Module._enum_cmp=e=>(Module._enum_cmp=wasmExports.enum_cmp)(e),Module._make_expanded_record_from_typeid=(e,r,M)=>(Module._make_expanded_record_from_typeid=wasmExports.make_expanded_record_from_typeid)(e,r,M),Module._make_expanded_record_from_tupdesc=(e,r)=>(Module._make_expanded_record_from_tupdesc=wasmExports.make_expanded_record_from_tupdesc)(e,r),Module._make_expanded_record_from_exprecord=(e,r)=>(Module._make_expanded_record_from_exprecord=wasmExports.make_expanded_record_from_exprecord)(e,r),Module._expanded_record_set_tuple=(e,r,M,r0)=>(Module._expanded_record_set_tuple=wasmExports.expanded_record_set_tuple)(e,r,M,r0),Module._expanded_record_get_tuple=e=>(Module._expanded_record_get_tuple=wasmExports.expanded_record_get_tuple)(e),Module._deconstruct_expanded_record=e=>(Module._deconstruct_expanded_record=wasmExports.deconstruct_expanded_record)(e),Module._expanded_record_lookup_field=(e,r,M)=>(Module._expanded_record_lookup_field=wasmExports.expanded_record_lookup_field)(e,r,M),Module._expanded_record_set_field_internal=(e,r,M,r0,s0,a0)=>(Module._expanded_record_set_field_internal=wasmExports.expanded_record_set_field_internal)(e,r,M,r0,s0,a0),Module._expanded_record_set_fields=(e,r,M,r0)=>(Module._expanded_record_set_fields=wasmExports.expanded_record_set_fields)(e,r,M,r0),Module._float4in_internal=(e,r,M,r0,s0)=>(Module._float4in_internal=wasmExports.float4in_internal)(e,r,M,r0,s0),Module._strtof=(e,r)=>(Module._strtof=wasmExports.strtof)(e,r),Module._float8in_internal=(e,r,M,r0,s0)=>(Module._float8in_internal=wasmExports.float8in_internal)(e,r,M,r0,s0),Module._float8out_internal=e=>(Module._float8out_internal=wasmExports.float8out_internal)(e),Module._btfloat4cmp=e=>(Module._btfloat4cmp=wasmExports.btfloat4cmp)(e),Module._btfloat8cmp=e=>(Module._btfloat8cmp=wasmExports.btfloat8cmp)(e),Module._acos=e=>(Module._acos=wasmExports.acos)(e),Module._asin=e=>(Module._asin=wasmExports.asin)(e),Module._cos=e=>(Module._cos=wasmExports.cos)(e),Module._str_tolower=(e,r,M)=>(Module._str_tolower=wasmExports.str_tolower)(e,r,M),Module._pushJsonbValue=(e,r,M)=>(Module._pushJsonbValue=wasmExports.pushJsonbValue)(e,r,M),Module._numeric_float4=e=>(Module._numeric_float4=wasmExports.numeric_float4)(e),Module._numeric_cmp=e=>(Module._numeric_cmp=wasmExports.numeric_cmp)(e),Module._numeric_eq=e=>(Module._numeric_eq=wasmExports.numeric_eq)(e),Module._numeric_is_nan=e=>(Module._numeric_is_nan=wasmExports.numeric_is_nan)(e),Module._timestamp_cmp=e=>(Module._timestamp_cmp=wasmExports.timestamp_cmp)(e),Module._macaddr_cmp=e=>(Module._macaddr_cmp=wasmExports.macaddr_cmp)(e),Module._macaddr_lt=e=>(Module._macaddr_lt=wasmExports.macaddr_lt)(e),Module._macaddr_le=e=>(Module._macaddr_le=wasmExports.macaddr_le)(e),Module._macaddr_eq=e=>(Module._macaddr_eq=wasmExports.macaddr_eq)(e),Module._macaddr_ge=e=>(Module._macaddr_ge=wasmExports.macaddr_ge)(e),Module._macaddr_gt=e=>(Module._macaddr_gt=wasmExports.macaddr_gt)(e),Module._macaddr8_cmp=e=>(Module._macaddr8_cmp=wasmExports.macaddr8_cmp)(e),Module._macaddr8_lt=e=>(Module._macaddr8_lt=wasmExports.macaddr8_lt)(e),Module._macaddr8_le=e=>(Module._macaddr8_le=wasmExports.macaddr8_le)(e),Module._macaddr8_eq=e=>(Module._macaddr8_eq=wasmExports.macaddr8_eq)(e),Module._macaddr8_ge=e=>(Module._macaddr8_ge=wasmExports.macaddr8_ge)(e),Module._macaddr8_gt=e=>(Module._macaddr8_gt=wasmExports.macaddr8_gt)(e),Module._current_query=e=>(Module._current_query=wasmExports.current_query)(e),Module._unpack_sql_state=e=>(Module._unpack_sql_state=wasmExports.unpack_sql_state)(e),Module._get_fn_expr_rettype=e=>(Module._get_fn_expr_rettype=wasmExports.get_fn_expr_rettype)(e),Module._btnamecmp=e=>(Module._btnamecmp=wasmExports.btnamecmp)(e),Module._inet_in=e=>(Module._inet_in=wasmExports.inet_in)(e),Module._network_cmp=e=>(Module._network_cmp=wasmExports.network_cmp)(e),Module._convert_network_to_scalar=(e,r,M)=>(Module._convert_network_to_scalar=wasmExports.convert_network_to_scalar)(e,r,M),Module._numeric_gt=e=>(Module._numeric_gt=wasmExports.numeric_gt)(e),Module._numeric_le=e=>(Module._numeric_le=wasmExports.numeric_le)(e),Module._numeric_float8_no_overflow=e=>(Module._numeric_float8_no_overflow=wasmExports.numeric_float8_no_overflow)(e),Module._oidout=e=>(Module._oidout=wasmExports.oidout)(e),Module._interval_mi=e=>(Module._interval_mi=wasmExports.interval_mi)(e),Module._quote_ident=e=>(Module._quote_ident=wasmExports.quote_ident)(e),Module._pg_wchar2mb_with_len=(e,r,M)=>(Module._pg_wchar2mb_with_len=wasmExports.pg_wchar2mb_with_len)(e,r,M),Module._pg_get_indexdef_columns_extended=(e,r)=>(Module._pg_get_indexdef_columns_extended=wasmExports.pg_get_indexdef_columns_extended)(e,r),Module._pg_get_querydef=(e,r)=>(Module._pg_get_querydef=wasmExports.pg_get_querydef)(e,r),Module._strcspn=(e,r)=>(Module._strcspn=wasmExports.strcspn)(e,r),Module._generic_restriction_selectivity=(e,r,M,r0,s0,a0)=>(Module._generic_restriction_selectivity=wasmExports.generic_restriction_selectivity)(e,r,M,r0,s0,a0),Module._genericcostestimate=(e,r,M,r0)=>(Module._genericcostestimate=wasmExports.genericcostestimate)(e,r,M,r0),Module._tidin=e=>(Module._tidin=wasmExports.tidin)(e),Module._tidout=e=>(Module._tidout=wasmExports.tidout)(e),Module._timestamp_in=e=>(Module._timestamp_in=wasmExports.timestamp_in)(e),Module._timestamp_eq=e=>(Module._timestamp_eq=wasmExports.timestamp_eq)(e),Module._timestamp_lt=e=>(Module._timestamp_lt=wasmExports.timestamp_lt)(e),Module._timestamp_gt=e=>(Module._timestamp_gt=wasmExports.timestamp_gt)(e),Module._timestamp_le=e=>(Module._timestamp_le=wasmExports.timestamp_le)(e),Module._timestamp_ge=e=>(Module._timestamp_ge=wasmExports.timestamp_ge)(e),Module._interval_eq=e=>(Module._interval_eq=wasmExports.interval_eq)(e),Module._interval_lt=e=>(Module._interval_lt=wasmExports.interval_lt)(e),Module._interval_gt=e=>(Module._interval_gt=wasmExports.interval_gt)(e),Module._interval_le=e=>(Module._interval_le=wasmExports.interval_le)(e),Module._interval_ge=e=>(Module._interval_ge=wasmExports.interval_ge)(e),Module._interval_cmp=e=>(Module._interval_cmp=wasmExports.interval_cmp)(e),Module._timestamp_mi=e=>(Module._timestamp_mi=wasmExports.timestamp_mi)(e),Module._interval_um=e=>(Module._interval_um=wasmExports.interval_um)(e),Module._has_fn_opclass_options=e=>(Module._has_fn_opclass_options=wasmExports.has_fn_opclass_options)(e),Module._uuid_in=e=>(Module._uuid_in=wasmExports.uuid_in)(e),Module._uuid_out=e=>(Module._uuid_out=wasmExports.uuid_out)(e),Module._uuid_cmp=e=>(Module._uuid_cmp=wasmExports.uuid_cmp)(e),Module._varbit_in=e=>(Module._varbit_in=wasmExports.varbit_in)(e),Module._biteq=e=>(Module._biteq=wasmExports.biteq)(e),Module._bitlt=e=>(Module._bitlt=wasmExports.bitlt)(e),Module._bitle=e=>(Module._bitle=wasmExports.bitle)(e),Module._bitgt=e=>(Module._bitgt=wasmExports.bitgt)(e),Module._bitge=e=>(Module._bitge=wasmExports.bitge)(e),Module._bitcmp=e=>(Module._bitcmp=wasmExports.bitcmp)(e),Module._bpchareq=e=>(Module._bpchareq=wasmExports.bpchareq)(e),Module._bpcharlt=e=>(Module._bpcharlt=wasmExports.bpcharlt)(e),Module._bpcharle=e=>(Module._bpcharle=wasmExports.bpcharle)(e),Module._bpchargt=e=>(Module._bpchargt=wasmExports.bpchargt)(e),Module._bpcharge=e=>(Module._bpcharge=wasmExports.bpcharge)(e),Module._bpcharcmp=e=>(Module._bpcharcmp=wasmExports.bpcharcmp)(e),Module._texteq=e=>(Module._texteq=wasmExports.texteq)(e),Module._text_lt=e=>(Module._text_lt=wasmExports.text_lt)(e),Module._text_le=e=>(Module._text_le=wasmExports.text_le)(e),Module._text_gt=e=>(Module._text_gt=wasmExports.text_gt)(e),Module._text_ge=e=>(Module._text_ge=wasmExports.text_ge)(e),Module._bttextcmp=e=>(Module._bttextcmp=wasmExports.bttextcmp)(e),Module._byteaeq=e=>(Module._byteaeq=wasmExports.byteaeq)(e),Module._bytealt=e=>(Module._bytealt=wasmExports.bytealt)(e),Module._byteale=e=>(Module._byteale=wasmExports.byteale)(e),Module._byteagt=e=>(Module._byteagt=wasmExports.byteagt)(e),Module._byteage=e=>(Module._byteage=wasmExports.byteage)(e),Module._byteacmp=e=>(Module._byteacmp=wasmExports.byteacmp)(e),Module._to_hex32=e=>(Module._to_hex32=wasmExports.to_hex32)(e),Module._varstr_levenshtein=(e,r,M,r0,s0,a0,i0,u0)=>(Module._varstr_levenshtein=wasmExports.varstr_levenshtein)(e,r,M,r0,s0,a0,i0,u0),Module._pg_xml_init=e=>(Module._pg_xml_init=wasmExports.pg_xml_init)(e),Module._xmlInitParser=()=>(Module._xmlInitParser=wasmExports.xmlInitParser)(),Module._xml_ereport=(e,r,M,r0)=>(Module._xml_ereport=wasmExports.xml_ereport)(e,r,M,r0),Module._pg_xml_done=(e,r)=>(Module._pg_xml_done=wasmExports.pg_xml_done)(e,r),Module._xmlXPathNewContext=e=>(Module._xmlXPathNewContext=wasmExports.xmlXPathNewContext)(e),Module._xmlXPathFreeContext=e=>(Module._xmlXPathFreeContext=wasmExports.xmlXPathFreeContext)(e),Module._xmlFreeDoc=e=>(Module._xmlFreeDoc=wasmExports.xmlFreeDoc)(e),Module._xmlXPathCtxtCompile=(e,r)=>(Module._xmlXPathCtxtCompile=wasmExports.xmlXPathCtxtCompile)(e,r),Module._xmlXPathCompiledEval=(e,r)=>(Module._xmlXPathCompiledEval=wasmExports.xmlXPathCompiledEval)(e,r),Module._xmlXPathFreeObject=e=>(Module._xmlXPathFreeObject=wasmExports.xmlXPathFreeObject)(e),Module._xmlXPathFreeCompExpr=e=>(Module._xmlXPathFreeCompExpr=wasmExports.xmlXPathFreeCompExpr)(e),Module._xmlStrdup=e=>(Module._xmlStrdup=wasmExports.xmlStrdup)(e),Module._xmlEncodeSpecialChars=(e,r)=>(Module._xmlEncodeSpecialChars=wasmExports.xmlEncodeSpecialChars)(e,r),Module._xmlStrlen=e=>(Module._xmlStrlen=wasmExports.xmlStrlen)(e),Module._xmlBufferCreate=()=>(Module._xmlBufferCreate=wasmExports.xmlBufferCreate)(),Module._xmlBufferFree=e=>(Module._xmlBufferFree=wasmExports.xmlBufferFree)(e),Module._xmlXPathCastNodeToString=e=>(Module._xmlXPathCastNodeToString=wasmExports.xmlXPathCastNodeToString)(e),Module._xmlNodeDump=(e,r,M,r0,s0)=>(Module._xmlNodeDump=wasmExports.xmlNodeDump)(e,r,M,r0,s0),Module._get_typsubscript=(e,r)=>(Module._get_typsubscript=wasmExports.get_typsubscript)(e,r),Module._CachedPlanAllowsSimpleValidityCheck=(e,r,M)=>(Module._CachedPlanAllowsSimpleValidityCheck=wasmExports.CachedPlanAllowsSimpleValidityCheck)(e,r,M),Module._CachedPlanIsSimplyValid=(e,r,M)=>(Module._CachedPlanIsSimplyValid=wasmExports.CachedPlanIsSimplyValid)(e,r,M),Module._GetCachedExpression=e=>(Module._GetCachedExpression=wasmExports.GetCachedExpression)(e),Module._FreeCachedExpression=e=>(Module._FreeCachedExpression=wasmExports.FreeCachedExpression)(e),Module._ReleaseAllPlanCacheRefsInOwner=e=>(Module._ReleaseAllPlanCacheRefsInOwner=wasmExports.ReleaseAllPlanCacheRefsInOwner)(e),Module._in_error_recursion_trouble=()=>(Module._in_error_recursion_trouble=wasmExports.in_error_recursion_trouble)(),Module._GetErrorContextStack=()=>(Module._GetErrorContextStack=wasmExports.GetErrorContextStack)(),Module._find_rendezvous_variable=e=>(Module._find_rendezvous_variable=wasmExports.find_rendezvous_variable)(e),Module._CallerFInfoFunctionCall2=(e,r,M,r0,s0)=>(Module._CallerFInfoFunctionCall2=wasmExports.CallerFInfoFunctionCall2)(e,r,M,r0,s0),Module._FunctionCall0Coll=(e,r)=>(Module._FunctionCall0Coll=wasmExports.FunctionCall0Coll)(e,r),Module._resolve_polymorphic_argtypes=(e,r,M,r0)=>(Module._resolve_polymorphic_argtypes=wasmExports.resolve_polymorphic_argtypes)(e,r,M,r0),Module._pg_bindtextdomain=e=>(Module._pg_bindtextdomain=wasmExports.pg_bindtextdomain)(e),Module._DefineCustomBoolVariable=(e,r,M,r0,s0,a0,i0,u0,d0,m0)=>(Module._DefineCustomBoolVariable=wasmExports.DefineCustomBoolVariable)(e,r,M,r0,s0,a0,i0,u0,d0,m0),Module._DefineCustomIntVariable=(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0)=>(Module._DefineCustomIntVariable=wasmExports.DefineCustomIntVariable)(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0),Module._DefineCustomRealVariable=(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0)=>(Module._DefineCustomRealVariable=wasmExports.DefineCustomRealVariable)(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0),Module._DefineCustomStringVariable=(e,r,M,r0,s0,a0,i0,u0,d0,m0)=>(Module._DefineCustomStringVariable=wasmExports.DefineCustomStringVariable)(e,r,M,r0,s0,a0,i0,u0,d0,m0),Module._DefineCustomEnumVariable=(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0)=>(Module._DefineCustomEnumVariable=wasmExports.DefineCustomEnumVariable)(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0),Module._MarkGUCPrefixReserved=e=>(Module._MarkGUCPrefixReserved=wasmExports.MarkGUCPrefixReserved)(e),Module._sampler_random_init_state=(e,r)=>(Module._sampler_random_init_state=wasmExports.sampler_random_init_state)(e,r),Module._pchomp=e=>(Module._pchomp=wasmExports.pchomp)(e),Module._PinPortal=e=>(Module._PinPortal=wasmExports.PinPortal)(e),Module._UnpinPortal=e=>(Module._UnpinPortal=wasmExports.UnpinPortal)(e),Module._xmlBufferWriteCHAR=(e,r)=>(Module._xmlBufferWriteCHAR=wasmExports.xmlBufferWriteCHAR)(e,r),Module._xmlBufferWriteChar=(e,r)=>(Module._xmlBufferWriteChar=wasmExports.xmlBufferWriteChar)(e,r),Module._xmlReadMemory=(e,r,M,r0,s0)=>(Module._xmlReadMemory=wasmExports.xmlReadMemory)(e,r,M,r0,s0),Module._xmlDocGetRootElement=e=>(Module._xmlDocGetRootElement=wasmExports.xmlDocGetRootElement)(e),Module._xmlXPathIsNaN=e=>(Module._xmlXPathIsNaN=wasmExports.xmlXPathIsNaN)(e),Module._xmlXPathCastToBoolean=e=>(Module._xmlXPathCastToBoolean=wasmExports.xmlXPathCastToBoolean)(e),Module._xmlXPathCastToNumber=e=>(Module._xmlXPathCastToNumber=wasmExports.xmlXPathCastToNumber)(e);var ___dl_seterr=(e,r)=>(___dl_seterr=wasmExports.__dl_seterr)(e,r);Module._gmtime=e=>(Module._gmtime=wasmExports.gmtime)(e);var _htonl=e=>(_htonl=wasmExports.htonl)(e),_htons=e=>(_htons=wasmExports.htons)(e);Module._ioctl=(e,r,M)=>(Module._ioctl=wasmExports.ioctl)(e,r,M);var _emscripten_builtin_memalign=(e,r)=>(_emscripten_builtin_memalign=wasmExports.emscripten_builtin_memalign)(e,r),_ntohs=e=>(_ntohs=wasmExports.ntohs)(e);Module._srand=e=>(Module._srand=wasmExports.srand)(e),Module._rand=()=>(Module._rand=wasmExports.rand)();var __emscripten_timeout=(e,r)=>(__emscripten_timeout=wasmExports._emscripten_timeout)(e,r),_setThrew=(e,r)=>(_setThrew=wasmExports.setThrew)(e,r),__emscripten_tempret_set=e=>(__emscripten_tempret_set=wasmExports._emscripten_tempret_set)(e),__emscripten_tempret_get=()=>(__emscripten_tempret_get=wasmExports._emscripten_tempret_get)(),__emscripten_stack_restore=e=>(__emscripten_stack_restore=wasmExports._emscripten_stack_restore)(e),__emscripten_stack_alloc=e=>(__emscripten_stack_alloc=wasmExports._emscripten_stack_alloc)(e),_emscripten_stack_get_current=()=>(_emscripten_stack_get_current=wasmExports.emscripten_stack_get_current)();Module._InterruptPending=2677872,Module._MyLatch=2678060,Module._CritSectionCount=2677924,Module._MyProc=2647676,Module._pg_global_prng_state=2624272,Module._error_context_stack=2676168,Module._GUC_check_errdetail_string=2681820,Module._IsUnderPostmaster=2677953,Module._CurrentMemoryContext=2683248,Module._stdout=2537152,Module._debug_query_string=2538716,Module._MyProcPort=2678048,Module.___THREW__=2698916,Module.___threwValue=2698920,Module._MyDatabaseId=2677932,Module._TopMemoryContext=2683252,Module._PG_exception_stack=2676172,Module._MyProcPid=2678024,Module._stdin=2537e3,Module._ScanKeywords=2374040,Module._pg_number_of_ones=925120,Module._LocalBufferBlockPointers=2644252,Module._BufferBlocks=2638988,Module._wal_level=2387920,Module._SnapshotAnyData=2474096,Module._maintenance_work_mem=2421576,Module._ParallelWorkerNumber=2379480,Module._MainLWLockArray=2645860,Module._CurrentResourceOwner=2683296,Module._work_mem=2421560,Module._NBuffers=2421584,Module._bsysscan=2625508,Module._CheckXidAlive=2625504,Module._RecentXmin=2474188,Module._XactIsoLevel=2387784,Module._pgWalUsage=2628976,Module._pgBufferUsage=2628848,Module._TTSOpsVirtual=2391608,Module._TransamVariables=2625496,Module._TopTransactionContext=2683272,Module._RmgrTable=2379504,Module._process_shared_preload_libraries_in_progress=2681216,Module._wal_segment_size=2387940,Module._TopTransactionResourceOwner=2683304,Module._arch_module_check_errdetail_string=2638372,Module._object_access_hook=2627616,Module._InvalidObjectAddress=1520620,Module._check_function_bodies=2421750,Module._post_parse_analyze_hook=2627656,Module._ScanKeywordTokens=1551648,Module._SPI_processed=2629e3,Module._SPI_tuptable=2629008,Module._TTSOpsMinimalTuple=2391712,Module._check_password_hook=2627924,Module._ConfigReloadPending=2638360,Module._max_parallel_maintenance_workers=2421580,Module._DateStyle=2421548,Module._ExecutorStart_hook=2628824,Module._ExecutorRun_hook=2628828,Module._ExecutorFinish_hook=2628832,Module._ExecutorEnd_hook=2628836,Module._SPI_result=2629012,Module._ClientAuthentication_hook=2629184,Module._cpu_tuple_cost=2392168,Module._cpu_operator_cost=2392184,Module._seq_page_cost=2392152,Module._planner_hook=2638056,Module._ShutdownRequestPending=2638364,Module._MyStartTime=2678032,Module._cluster_name=2421800,Module._application_name=2682044,Module._BufferDescriptors=2638984,Module._shmem_startup_hook=2644932,Module._ProcessUtility_hook=2647764,Module._IntervalStyle=2677956,Module._extra_float_digits=2411976,Module._pg_crc32_table=2112288,Module._xmlFree=2523400,Module._shmem_request_hook=2681220;function invoke_iii(e,r,M){var r0=stackSave();try{return getWasmTableEntry(e)(r,M)}catch(s0){if(stackRestore(r0),s0!==s0+0)throw s0;_setThrew(1,0)}}function invoke_viiii(e,r,M,r0,s0){var a0=stackSave();try{getWasmTableEntry(e)(r,M,r0,s0)}catch(i0){if(stackRestore(a0),i0!==i0+0)throw i0;_setThrew(1,0)}}function invoke_vi(e,r){var M=stackSave();try{getWasmTableEntry(e)(r)}catch(r0){if(stackRestore(M),r0!==r0+0)throw r0;_setThrew(1,0)}}function invoke_v(e){var r=stackSave();try{getWasmTableEntry(e)()}catch(M){if(stackRestore(r),M!==M+0)throw M;_setThrew(1,0)}}function invoke_j(e){var r=stackSave();try{return getWasmTableEntry(e)()}catch(M){if(stackRestore(r),M!==M+0)throw M;return _setThrew(1,0),0n}}function invoke_viiiiii(e,r,M,r0,s0,a0,i0){var u0=stackSave();try{getWasmTableEntry(e)(r,M,r0,s0,a0,i0)}catch(d0){if(stackRestore(u0),d0!==d0+0)throw d0;_setThrew(1,0)}}function invoke_vii(e,r,M){var r0=stackSave();try{getWasmTableEntry(e)(r,M)}catch(s0){if(stackRestore(r0),s0!==s0+0)throw s0;_setThrew(1,0)}}function invoke_iiiiii(e,r,M,r0,s0,a0){var i0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0)}catch(u0){if(stackRestore(i0),u0!==u0+0)throw u0;_setThrew(1,0)}}function invoke_i(e){var r=stackSave();try{return getWasmTableEntry(e)()}catch(M){if(stackRestore(r),M!==M+0)throw M;_setThrew(1,0)}}function invoke_ii(e,r){var M=stackSave();try{return getWasmTableEntry(e)(r)}catch(r0){if(stackRestore(M),r0!==r0+0)throw r0;_setThrew(1,0)}}function invoke_viii(e,r,M,r0){var s0=stackSave();try{getWasmTableEntry(e)(r,M,r0)}catch(a0){if(stackRestore(s0),a0!==a0+0)throw a0;_setThrew(1,0)}}function invoke_vji(e,r,M){var r0=stackSave();try{getWasmTableEntry(e)(r,M)}catch(s0){if(stackRestore(r0),s0!==s0+0)throw s0;_setThrew(1,0)}}function invoke_iiii(e,r,M,r0){var s0=stackSave();try{return getWasmTableEntry(e)(r,M,r0)}catch(a0){if(stackRestore(s0),a0!==a0+0)throw a0;_setThrew(1,0)}}function invoke_iiiiiiii(e,r,M,r0,s0,a0,i0,u0){var d0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0,i0,u0)}catch(m0){if(stackRestore(d0),m0!==m0+0)throw m0;_setThrew(1,0)}}function invoke_iiiii(e,r,M,r0,s0){var a0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0)}catch(i0){if(stackRestore(a0),i0!==i0+0)throw i0;_setThrew(1,0)}}function invoke_viiiiiiiii(e,r,M,r0,s0,a0,i0,u0,d0,m0){var _0=stackSave();try{getWasmTableEntry(e)(r,M,r0,s0,a0,i0,u0,d0,m0)}catch(f0){if(stackRestore(_0),f0!==f0+0)throw f0;_setThrew(1,0)}}function invoke_viiiii(e,r,M,r0,s0,a0){var i0=stackSave();try{getWasmTableEntry(e)(r,M,r0,s0,a0)}catch(u0){if(stackRestore(i0),u0!==u0+0)throw u0;_setThrew(1,0)}}function invoke_jii(e,r,M){var r0=stackSave();try{return getWasmTableEntry(e)(r,M)}catch(s0){if(stackRestore(r0),s0!==s0+0)throw s0;return _setThrew(1,0),0n}}function invoke_ji(e,r){var M=stackSave();try{return getWasmTableEntry(e)(r)}catch(r0){if(stackRestore(M),r0!==r0+0)throw r0;return _setThrew(1,0),0n}}function invoke_jiiiiiiiii(e,r,M,r0,s0,a0,i0,u0,d0,m0){var _0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0,i0,u0,d0,m0)}catch(f0){if(stackRestore(_0),f0!==f0+0)throw f0;return _setThrew(1,0),0n}}function invoke_jiiiiii(e,r,M,r0,s0,a0,i0){var u0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0,i0)}catch(d0){if(stackRestore(u0),d0!==d0+0)throw d0;return _setThrew(1,0),0n}}function invoke_iiiiiiiiiiiiii(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0,g0,x0){var k0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0,g0,x0)}catch(F0){if(stackRestore(k0),F0!==F0+0)throw F0;_setThrew(1,0)}}function invoke_iiiijii(e,r,M,r0,s0,a0,i0){var u0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0,i0)}catch(d0){if(stackRestore(u0),d0!==d0+0)throw d0;_setThrew(1,0)}}function invoke_vijiji(e,r,M,r0,s0,a0){var i0=stackSave();try{getWasmTableEntry(e)(r,M,r0,s0,a0)}catch(u0){if(stackRestore(i0),u0!==u0+0)throw u0;_setThrew(1,0)}}function invoke_viji(e,r,M,r0){var s0=stackSave();try{getWasmTableEntry(e)(r,M,r0)}catch(a0){if(stackRestore(s0),a0!==a0+0)throw a0;_setThrew(1,0)}}function invoke_iiji(e,r,M,r0){var s0=stackSave();try{return getWasmTableEntry(e)(r,M,r0)}catch(a0){if(stackRestore(s0),a0!==a0+0)throw a0;_setThrew(1,0)}}function invoke_iiiiiiiii(e,r,M,r0,s0,a0,i0,u0,d0){var m0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0,i0,u0,d0)}catch(_0){if(stackRestore(m0),_0!==_0+0)throw _0;_setThrew(1,0)}}function invoke_iiiiiiiiiiiiiiiiii(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0,g0,x0,k0,F0,C0,R0){var y0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0,g0,x0,k0,F0,C0,R0)}catch(w0){if(stackRestore(y0),w0!==w0+0)throw w0;_setThrew(1,0)}}function invoke_iiiij(e,r,M,r0,s0){var a0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0)}catch(i0){if(stackRestore(a0),i0!==i0+0)throw i0;_setThrew(1,0)}}function invoke_iiiiiii(e,r,M,r0,s0,a0,i0){var u0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0,i0)}catch(d0){if(stackRestore(u0),d0!==d0+0)throw d0;_setThrew(1,0)}}function invoke_vj(e,r){var M=stackSave();try{getWasmTableEntry(e)(r)}catch(r0){if(stackRestore(M),r0!==r0+0)throw r0;_setThrew(1,0)}}function invoke_iiiiiiiiii(e,r,M,r0,s0,a0,i0,u0,d0,m0){var _0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0,i0,u0,d0,m0)}catch(f0){if(stackRestore(_0),f0!==f0+0)throw f0;_setThrew(1,0)}}function invoke_viiji(e,r,M,r0,s0){var a0=stackSave();try{getWasmTableEntry(e)(r,M,r0,s0)}catch(i0){if(stackRestore(a0),i0!==i0+0)throw i0;_setThrew(1,0)}}function invoke_viiiiiiii(e,r,M,r0,s0,a0,i0,u0,d0){var m0=stackSave();try{getWasmTableEntry(e)(r,M,r0,s0,a0,i0,u0,d0)}catch(_0){if(stackRestore(m0),_0!==_0+0)throw _0;_setThrew(1,0)}}function invoke_vij(e,r,M){var r0=stackSave();try{getWasmTableEntry(e)(r,M)}catch(s0){if(stackRestore(r0),s0!==s0+0)throw s0;_setThrew(1,0)}}function invoke_ij(e,r){var M=stackSave();try{return getWasmTableEntry(e)(r)}catch(r0){if(stackRestore(M),r0!==r0+0)throw r0;_setThrew(1,0)}}function invoke_viiiiiii(e,r,M,r0,s0,a0,i0,u0){var d0=stackSave();try{getWasmTableEntry(e)(r,M,r0,s0,a0,i0,u0)}catch(m0){if(stackRestore(d0),m0!==m0+0)throw m0;_setThrew(1,0)}}function invoke_viiiji(e,r,M,r0,s0,a0){var i0=stackSave();try{getWasmTableEntry(e)(r,M,r0,s0,a0)}catch(u0){if(stackRestore(i0),u0!==u0+0)throw u0;_setThrew(1,0)}}function invoke_iiij(e,r,M,r0){var s0=stackSave();try{return getWasmTableEntry(e)(r,M,r0)}catch(a0){if(stackRestore(s0),a0!==a0+0)throw a0;_setThrew(1,0)}}function invoke_vid(e,r,M){var r0=stackSave();try{getWasmTableEntry(e)(r,M)}catch(s0){if(stackRestore(r0),s0!==s0+0)throw s0;_setThrew(1,0)}}function invoke_ijiiiiii(e,r,M,r0,s0,a0,i0,u0){var d0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0,i0,u0)}catch(m0){if(stackRestore(d0),m0!==m0+0)throw m0;_setThrew(1,0)}}function invoke_viijii(e,r,M,r0,s0,a0){var i0=stackSave();try{getWasmTableEntry(e)(r,M,r0,s0,a0)}catch(u0){if(stackRestore(i0),u0!==u0+0)throw u0;_setThrew(1,0)}}function invoke_iiiiiji(e,r,M,r0,s0,a0,i0){var u0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0,i0)}catch(d0){if(stackRestore(u0),d0!==d0+0)throw d0;_setThrew(1,0)}}function invoke_viijiiii(e,r,M,r0,s0,a0,i0,u0){var d0=stackSave();try{getWasmTableEntry(e)(r,M,r0,s0,a0,i0,u0)}catch(m0){if(stackRestore(d0),m0!==m0+0)throw m0;_setThrew(1,0)}}function invoke_viij(e,r,M,r0){var s0=stackSave();try{getWasmTableEntry(e)(r,M,r0)}catch(a0){if(stackRestore(s0),a0!==a0+0)throw a0;_setThrew(1,0)}}function invoke_jiiii(e,r,M,r0,s0){var a0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0)}catch(i0){if(stackRestore(a0),i0!==i0+0)throw i0;return _setThrew(1,0),0n}}function invoke_viiiiiiiiiiii(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0,g0){var x0=stackSave();try{getWasmTableEntry(e)(r,M,r0,s0,a0,i0,u0,d0,m0,_0,f0,g0)}catch(k0){if(stackRestore(x0),k0!==k0+0)throw k0;_setThrew(1,0)}}function invoke_di(e,r){var M=stackSave();try{return getWasmTableEntry(e)(r)}catch(r0){if(stackRestore(M),r0!==r0+0)throw r0;_setThrew(1,0)}}function invoke_id(e,r){var M=stackSave();try{return getWasmTableEntry(e)(r)}catch(r0){if(stackRestore(M),r0!==r0+0)throw r0;_setThrew(1,0)}}function invoke_ijiiiii(e,r,M,r0,s0,a0,i0){var u0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0,i0)}catch(d0){if(stackRestore(u0),d0!==d0+0)throw d0;_setThrew(1,0)}}function invoke_iiiiiiiiiii(e,r,M,r0,s0,a0,i0,u0,d0,m0,_0){var f0=stackSave();try{return getWasmTableEntry(e)(r,M,r0,s0,a0,i0,u0,d0,m0,_0)}catch(g0){if(stackRestore(f0),g0!==g0+0)throw g0;_setThrew(1,0)}}Module.addRunDependency=addRunDependency,Module.removeRunDependency=removeRunDependency,Module.addFunction=addFunction,Module.removeFunction=removeFunction,Module.setValue=setValue,Module.getValue=getValue,Module.UTF8ToString=UTF8ToString,Module.stringToNewUTF8=stringToNewUTF8,Module.stringToUTF8OnStack=stringToUTF8OnStack,Module.FS_createPreloadedFile=FS_createPreloadedFile,Module.FS_unlink=FS_unlink,Module.FS_createPath=FS_createPath,Module.FS_createDevice=FS_createDevice,Module.FS=FS,Module.FS_createDataFile=FS_createDataFile,Module.FS_createLazyFile=FS_createLazyFile,Module.MEMFS=MEMFS,Module.IDBFS=IDBFS;var calledRun;dependenciesFulfilled=function e(){calledRun||run(),calledRun||(dependenciesFulfilled=e)};function callMain(e=[]){var r=resolveGlobalSymbol("main").sym;if(r){e.unshift(thisProgram);var M=e.length,r0=stackAlloc((M+1)*4),s0=r0;e.forEach(i0=>{HEAPU32[s0>>2]=stringToUTF8OnStack(i0),s0+=4}),HEAPU32[s0>>2]=0;try{var a0=r(M,r0);return exitJS(a0,!0),a0}catch(i0){return handleException(i0)}}}function run(e=arguments_){if(runDependencies>0||(preRun(),runDependencies>0))return;function r(){var M;calledRun||(calledRun=!0,Module.calledRun=!0,!ABORT&&(initRuntime(),preMain(),readyPromiseResolve(Module),(M=Module.onRuntimeInitialized)==null||M.call(Module),shouldRunNow&&callMain(e),postRun()))}Module.setStatus?(Module.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Module.setStatus(""),1),r()},1)):r()}if(Module.preInit)for(typeof Module.preInit=="function"&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();var shouldRunNow=!0;return Module.noInitialRun&&(shouldRunNow=!1),run(),moduleRtn=readyPromise,moduleRtn}})(),He=pt,je=He,ne,te,re,ie,_e,xe,Se,we,ye,le,fe,he,pe,ae,$,I,se,de,B,Q,K,me,oe,J,O,Z,q,G,C,Ve,Xe,ge,Ke,Ye,L=class ki extends k{constructor(r={},M={}){super(),R$1(this,C),R$1(this,ne,!1),R$1(this,te,!1),R$1(this,re,!1),R$1(this,ie,!1),R$1(this,_e,!1),R$1(this,xe,new Y),R$1(this,Se,new Y),R$1(this,we,new Y),R$1(this,ye,new Y),R$1(this,le,!1),this.debug=0,R$1(this,fe),R$1(this,he,[]),R$1(this,pe,new ye$1),R$1(this,ae),R$1(this,$),R$1(this,I,new Map),R$1(this,se,new Set),R$1(this,de,-1),R$1(this,B,[]),R$1(this,Q,!1),R$1(this,K),R$1(this,me,-1),R$1(this,oe,[]),R$1(this,J,0),R$1(this,O,null),R$1(this,Z,!0),R$1(this,q,new Uint8Array(0)),R$1(this,G,0),typeof r=="string"?M={dataDir:r,...M}:M=r,this.dataDir=M.dataDir,M.parsers!==void 0&&(this.parsers={...this.parsers,...M.parsers}),M.serializers!==void 0&&(this.serializers={...this.serializers,...M.serializers}),(M==null?void 0:M.debug)!==void 0&&(this.debug=M.debug),(M==null?void 0:M.relaxedDurability)!==void 0&&x$3(this,_e,M.relaxedDurability),x$3(this,fe,M.extensions??{}),this.waitReady=T$2(this,C,Ve).call(this,M??{})}static async create(r,M){let r0=typeof r=="string"?{dataDir:r,...M??{}}:r??{},s0=new ki(r0);return await s0.waitReady,s0}get Module(){return this.mod}get ready(){return h$1(this,ne)&&!h$1(this,te)&&!h$1(this,re)}get closed(){return h$1(this,re)}async close(){await this._checkReady(),x$3(this,te,!0);for(let r of h$1(this,he))await r();try{await this.execProtocol(k$1.end()),this.mod._pgl_shutdown(),this.mod.removeFunction(h$1(this,me)),this.mod.removeFunction(h$1(this,de))}catch(r){let M=r;if(!(M.name==="ExitStatus"&&M.status===0))throw r}await this.fs.closeFs(),x$3(this,re,!0),x$3(this,te,!1)}async[Symbol.asyncDispose](){await this.close()}async _handleBlob(r){x$3(this,ae,r?await r.arrayBuffer():void 0)}async _cleanupBlob(){x$3(this,ae,void 0)}async _getWrittenBlob(){if(!h$1(this,$))return;let r=new Blob(h$1(this,$));return x$3(this,$,void 0),r}async _checkReady(){if(h$1(this,te))throw new Error("PGlite is closing");if(h$1(this,re))throw new Error("PGlite is closed");h$1(this,ne)||await this.waitReady}execProtocolRawSync(r){let M=this.mod;return x$3(this,J,0),x$3(this,G,0),x$3(this,oe,r),h$1(this,Z)&&h$1(this,q).length!==ki.DEFAULT_RECV_BUF_SIZE&&x$3(this,q,new Uint8Array(ki.DEFAULT_RECV_BUF_SIZE)),M._interactive_one(r.length,r[0]),x$3(this,oe,[]),h$1(this,Z)&&h$1(this,G)?h$1(this,q).subarray(0,h$1(this,G)):new Uint8Array(0)}async execProtocolRaw(r,{syncToFs:M=!0}={}){let r0=this.execProtocolRawSync(r);return M&&await this.syncToFs(),r0}async execProtocol(r,{syncToFs:M=!0,throwOnError:r0=!0,onNotice:s0}={}){x$3(this,Q,r0),x$3(this,K,s0),x$3(this,B,[]),x$3(this,O,null);let a0=await this.execProtocolRaw(r,{syncToFs:M}),i0=h$1(this,O);x$3(this,Q,!1),x$3(this,K,void 0),x$3(this,O,null);let u0={messages:h$1(this,B),data:a0};if(x$3(this,B,[]),r0&&i0)throw x$3(this,pe,new ye$1),i0;return u0}async execProtocolStream(r,{syncToFs:M,throwOnError:r0=!0,onNotice:s0}={}){x$3(this,Q,r0),x$3(this,K,s0),x$3(this,B,[]),x$3(this,O,null),x$3(this,Z,!1),await this.execProtocolRaw(r,{syncToFs:M}),x$3(this,Z,!0);let a0=h$1(this,O);x$3(this,Q,!1),x$3(this,K,void 0),x$3(this,O,null);let i0=h$1(this,B);if(x$3(this,B,[]),r0&&a0)throw x$3(this,pe,new ye$1),a0;return i0}isInTransaction(){return h$1(this,ie)}async syncToFs(){if(h$1(this,le))return;x$3(this,le,!0);let r=async()=>{await h$1(this,ye).runExclusive(async()=>{x$3(this,le,!1),await this.fs.syncToFs(h$1(this,_e))})};h$1(this,_e)?r():await r()}async listen(r,M,r0){return this._runExclusiveListen(()=>T$2(this,C,Ke).call(this,r,M,r0))}async unlisten(r,M,r0){return this._runExclusiveListen(()=>T$2(this,C,Ye).call(this,r,M,r0))}onNotification(r){return h$1(this,se).add(r),()=>{h$1(this,se).delete(r)}}offNotification(r){h$1(this,se).delete(r)}async dumpDataDir(r){var r0;await this._checkReady();let M=((r0=this.dataDir)==null?void 0:r0.split("/").pop())??"pgdata";return this.fs.dumpTar(M,r)}_runExclusiveQuery(r){return h$1(this,xe).runExclusive(r)}_runExclusiveTransaction(r){return h$1(this,Se).runExclusive(r)}async clone(){let r=await this.dumpDataDir("none");return ki.create({loadDataDir:r})}_runExclusiveListen(r){return h$1(this,we).runExclusive(r)}};ne=new WeakMap,te=new WeakMap,re=new WeakMap,ie=new WeakMap,_e=new WeakMap,xe=new WeakMap,Se=new WeakMap,we=new WeakMap,ye=new WeakMap,le=new WeakMap,fe=new WeakMap,he=new WeakMap,pe=new WeakMap,ae=new WeakMap,$=new WeakMap,I=new WeakMap,se=new WeakMap,de=new WeakMap,B=new WeakMap,Q=new WeakMap,K=new WeakMap,me=new WeakMap,oe=new WeakMap,J=new WeakMap,O=new WeakMap,Z=new WeakMap,q=new WeakMap,G=new WeakMap,C=new WeakSet,Ve=async function(e){if(e.fs)this.fs=e.fs;else{let{dataDir:m0,fsType:_0}=Ge(e.dataDir);this.fs=await Ue(m0,_0)}let r={},M=[],r0=[`PGDATA=${C$2}`,`PREFIX=${Vr}`,`PGUSER=${e.username??"postgres"}`,`PGDATABASE=${e.database??"template1"}`,"MODE=REACT","REPL=N",...this.debug?["-d",this.debug.toString()]:[]];e.wasmModule||Rr();let s0=e.fsBundle?e.fsBundle.arrayBuffer():Er(),a0;s0.then(m0=>{a0=m0});let i0={WASM_PREFIX:Vr,arguments:r0,INITIAL_MEMORY:e.initialMemory,noExitRuntime:!0,...this.debug>0?{print:console.info,printErr:console.error}:{print:()=>{},printErr:()=>{}},instantiateWasm:(m0,_0)=>(Tr(m0,e.wasmModule).then(({instance:f0,module:g0})=>{_0(f0,g0)}),{}),getPreloadedPackage:(m0,_0)=>{if(m0==="pglite.data"){if(a0.byteLength!==_0)throw new Error(`Invalid FS bundle size: ${a0.byteLength} !== ${_0}`);return a0}throw new Error(`Unknown package: ${m0}`)},preRun:[m0=>{let _0=m0.FS.makedev(64,0),f0={open:g0=>{},close:g0=>{},read:(g0,x0,k0,F0,C0)=>{let R0=h$1(this,ae);if(!R0)throw new Error("No /dev/blob File or Blob provided to read from");let y0=new Uint8Array(R0);if(C0>=y0.length)return 0;let w0=Math.min(y0.length-C0,F0);for(let A0=0;A0(h$1(this,$)??x$3(this,$,[]),h$1(this,$).push(x0.slice(k0,k0+F0)),F0),llseek:(g0,x0,k0)=>{let F0=h$1(this,ae);if(!F0)throw new Error("No /dev/blob File or Blob provided to llseek");let C0=x0;if(k0===1?C0+=g0.position:k0===2&&(C0=new Uint8Array(F0).length),C0<0)throw new m0.FS.ErrnoError(28);return C0}};m0.FS.registerDevice(_0,f0),m0.FS.mkdev("/dev/blob",_0)}]},{emscriptenOpts:u0}=await this.fs.init(this,i0);i0=u0;for(let[m0,_0]of Object.entries(h$1(this,fe)))if(_0 instanceof URL)r[m0]=ke(_0);else{let f0=await _0.setup(this,i0);if(f0.emscriptenOpts&&(i0=f0.emscriptenOpts),f0.namespaceObj){let g0=this;g0[m0]=f0.namespaceObj}f0.bundlePath&&(r[m0]=ke(f0.bundlePath)),f0.init&&M.push(f0.init),f0.close&&h$1(this,he).push(f0.close)}if(i0.pg_extensions=r,await s0,this.mod=await je(i0),x$3(this,de,this.mod.addFunction((m0,_0)=>{let f0;try{f0=this.mod.HEAPU8.subarray(m0,m0+_0)}catch(g0){throw console.error("error",g0),g0}if(h$1(this,pe).parse(f0,g0=>{T$2(this,C,Xe).call(this,g0)}),h$1(this,Z)){let g0=f0.slice(),x0=h$1(this,G)+g0.length;if(x0>h$1(this,q).length){let k0=h$1(this,q).length+(h$1(this,q).length>>1)+x0;x0>L.MAX_BUFFER_SIZE&&(x0=L.MAX_BUFFER_SIZE);let F0=new Uint8Array(k0);F0.set(h$1(this,q).subarray(0,h$1(this,G))),x$3(this,q,F0)}return h$1(this,q).set(g0,h$1(this,G)),x$3(this,G,h$1(this,G)+g0.length),h$1(this,q).length}return _0},"iii")),x$3(this,me,this.mod.addFunction((m0,_0)=>{let f0=h$1(this,oe).length-h$1(this,J);f0>_0&&(f0=_0);try{this.mod.HEAP8.set(h$1(this,oe).subarray(h$1(this,J),h$1(this,J)+f0),m0),x$3(this,J,h$1(this,J)+f0)}catch(g0){console.log(g0)}return f0},"iii")),this.mod._set_read_write_cbs(h$1(this,me),h$1(this,de)),await this.fs.initialSyncFs(),e.loadDataDir){if(this.mod.FS.analyzePath(C$2+"/PG_VERSION").exists)throw new Error("Database already exists, cannot load from tarball");T$2(this,C,ge).call(this,"pglite: loading data from tarball"),await ce$2(this.mod.FS,e.loadDataDir,C$2)}this.mod.FS.analyzePath(C$2+"/PG_VERSION").exists?T$2(this,C,ge).call(this,"pglite: found DB, resuming"):T$2(this,C,ge).call(this,"pglite: no db"),await Be(this.mod,(...m0)=>T$2(this,C,ge).call(this,...m0));let d0=this.mod._pgl_initdb();if(!d0)throw new Error("INITDB failed to return value");if(d0&1)throw new Error("INITDB: failed to execute");if(d0&2){let m0=e.username??"postgres",_0=e.database??"template1";if(d0&4){if(!(d0&12))throw new Error(`INITDB: Invalid db ${_0}/user ${m0} combination`)}else if(_0!=="template1"&&m0!=="postgres")throw new Error(`INITDB: created a new datadir ${C$2}, but an alternative db ${_0}/user ${m0} was requested`)}this.mod._pgl_backend(),await this.syncToFs(),x$3(this,ne,!0),await this.exec("SET search_path TO public;"),await this._initArrayTypes();for(let m0 of M)await m0()},Xe=function(e){if(!h$1(this,O)){if(e instanceof C$1)h$1(this,Q)&&x$3(this,O,e);else if(e instanceof te$1)this.debug>0&&console.warn(e),h$1(this,K)&&h$1(this,K).call(this,e);else if(e instanceof Z$1)switch(e.text){case"BEGIN":x$3(this,ie,!0);break;case"COMMIT":case"ROLLBACK":x$3(this,ie,!1);break}else if(e instanceof J$1){let r=h$1(this,I).get(e.channel);r&&r.forEach(M=>{queueMicrotask(()=>M(e.payload))}),h$1(this,se).forEach(M=>{queueMicrotask(()=>M(e.channel,e.payload))})}h$1(this,B).push(e)}},ge=function(...e){this.debug>0&&console.log(...e)},Ke=async function(e,r,M){var a0;let r0=Nr(e),s0=M??this;h$1(this,I).has(r0)||h$1(this,I).set(r0,new Set),h$1(this,I).get(r0).add(r);try{await s0.exec(`LISTEN ${e}`)}catch(i0){throw h$1(this,I).get(r0).delete(r),((a0=h$1(this,I).get(r0))==null?void 0:a0.size)===0&&h$1(this,I).delete(r0),i0}return async i0=>{await this.unlisten(r0,r,i0)}},Ye=async function(e,r,M){var i0,u0;let r0=Nr(e),s0=M??this,a0=async()=>{var d0;await s0.exec(`UNLISTEN ${e}`),((d0=h$1(this,I).get(r0))==null?void 0:d0.size)===0&&h$1(this,I).delete(r0)};r?((i0=h$1(this,I).get(r0))==null||i0.delete(r),((u0=h$1(this,I).get(r0))==null?void 0:u0.size)===0&&await a0()):await a0()},L.DEFAULT_RECV_BUF_SIZE=1*1024*1024,L.MAX_BUFFER_SIZE=Math.pow(2,30);var We=L;u();u();var n=async(e,r)=>({emscriptenOpts:r,bundlePath:new URL("/assets/vector.tar-D1fuLWD0.gz",import.meta.url)}),o={name:"pgvector",setup:n};let dbInstance,dbPromise;async function getDB(){return dbInstance||dbPromise||(dbPromise=(async()=>{try{const e=new We({extensions:{vector:o}});return await e.waitReady,dbInstance=e,e}catch(e){throw dbPromise=null,e}})(),dbPromise)}async function initDB(e){await e.exec(` + CREATE EXTENSION IF NOT EXISTS vector; + CREATE TABLE IF NOT EXISTS embeddings ( + id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, + content TEXT NOT NULL, + question TEXT NOT NULL, + embedding VECTOR(384) + ); + + CREATE INDEX ON EMBEDDINGS USING hnsw ( embedding vector_ip_ops); + `)}const search=async(e,r,M=.6,r0=1)=>(await e.query(` + select * from embeddings + + -- The inner product is negative, so we negate match_threshold + where embeddings.embedding <#> $1 < $2 + + -- Our embeddings are normalized to length 1, so cosine similarity + -- and inner product will produce the same query results. + -- Using inner product which can be computed faster. + -- + -- For the different distance functions, see https://github.com/pgvector/pgvector + order by embeddings.embedding <#> $1 + limit $3; + `,[JSON.stringify(r),-Number(M),Number(r0)])).rows,seedDb=async e=>await e.exec(` + INSERT INTO embeddings (content, question, embedding) VALUES +('Therapeutic communication is the purposeful and patient-centered process that forms the bedrock of the nurse-patient relationship. Unlike social conversation, it is goal-oriented, focusing on understanding the patient''s needs, concerns, and experiences to promote healing and well-being. The primary objective is to build trust and rapport, creating a safe environment where the patient feels comfortable sharing sensitive information. This is achieved through active listening, which involves not just hearing the patient''s words but also interpreting their non-verbal cues, such as body language and tone of voice. A nurse who is actively listening gives their full attention, makes eye contact, and conveys a genuine interest in the patient''s perspective. Key techniques in therapeutic communication include the use of open-ended questions, which encourage the patient to elaborate rather than give a simple yes or no answer. For example, asking "How have you been feeling since your last dose of medication?" is more effective than "Did the medication help?" Other vital techniques are paraphrasing and summarizing. Paraphrasing involves restating the patient''s message in your own words to confirm understanding, while summarizing helps to organize key points of a conversation, ensuring both parties are on the same page. The strategic use of silence can also be powerful, giving the patient time to gather their thoughts and reflect without feeling rushed. Conversely, there are common barriers that can hinder effective communication and damage trust. Giving unsolicited advice, offering false reassurance like "Don''t worry, everything will be fine," or using medical jargon the patient doesn''t understand can create distance and invalidate their feelings. Being judgmental or changing the subject when a patient expresses difficult emotions are also significant roadblocks. The skillful nurse navigates these interactions with empathy, focusing on the patient''s reality and validating their experience, which ultimately leads to more accurate assessments, better patient adherence to treatment plans, and improved health outcomes.', 'What is the primary goal of therapeutic communication in nursing?', '[0.019654231145977974, 0.02728176675736904, -0.05165129527449608, -0.032069459557533264, -0.047723736613988876, 0.014441808685660362, 0.0010012828279286623, 0.020398039370775223, 0.10914112627506256, -0.09972863644361496, -0.09353257715702057, 0.016359765082597733, -0.05620568245649338, 0.06288065016269684, 0.01861458830535412, 0.0010283509036526084, -0.009681017138063908, 0.04752069711685181, 0.04639328643679619, 0.037090931087732315, 0.0030070156790316105, 0.09200771898031235, 0.06786105036735535, 0.070894256234169, -0.032640546560287476, 0.02151753567159176, -0.00826891977339983, -0.04341669753193855, 0.03282732889056206, 0.06194714456796646, -0.01066251564770937, -0.025787578895688057, 0.051036540418863297, 0.08624931424856186, -0.06843095272779465, 0.11291251331567764, -0.003959536552429199, -0.0023922682739794254, -0.0400608591735363, -0.031768910586833954, -0.03601407632231712, -0.023664601147174835, 0.02440122701227665, -0.05007801577448845, 0.04584010690450668, -0.10925094783306122, 0.01191720087081194, 0.031356725841760635, -0.011942395009100437, -0.04604315385222435, -0.05887923017144203, -0.029333792626857758, -0.07324342429637909, 0.09342572093009949, 0.020287713035941124, -0.005456665996462107, -0.01791410520672798, 0.008599687367677689, -0.04247885197401047, 0.027955858036875725, -0.01711503230035305, -0.0046576401218771935, -0.011692490428686142, 0.046388160437345505, 0.062042951583862305, -0.047324467450380325, -0.02210615761578083, 0.05994800850749016, -0.016235273331403732, -0.021791134029626846, -0.01380334235727787, -0.07738672941923141, 0.0791679173707962, 0.02027747593820095, 0.03567732870578766, 0.011161708272993565, 0.0183692779392004, -0.017033983021974564, -0.0077307382598519325, 0.04457047954201698, 0.054397787898778915, 0.020686499774456024, 0.04766283929347992, 0.08192598074674606, 0.010866103693842888, 0.0021600541658699512, 0.021526256576180458, -0.07293001562356949, -0.04953962564468384, 0.0011025811545550823, -0.011751473881304264, -0.03061477467417717, -0.10732779651880264, 0.046397894620895386, -0.1092858836054802, -0.021958770230412483, -0.057601265609264374, -0.05303409695625305, -0.0021857533138245344, 0.030760424211621284, -0.010950993746519089, 0.0218666959553957, -0.02515711449086666, -0.007636751048266888, -0.06423519551753998, -0.05240415781736374, 0.030740298330783844, -0.019102072343230247, -0.05070134624838829, 0.047474849969148636, -0.058732569217681885, 0.0427367277443409, -0.025227002799510956, 0.02454378828406334, 0.04837092384696007, 0.045408379286527634, -0.07380826771259308, -0.030191360041499138, 0.09108419716358185, 0.021043024957180023, -0.005558145698159933, -0.05262349173426628, 0.02264583483338356, 0.0161353200674057, -0.015947865322232246, 0.012555430643260479, 0.009949610568583012, -4.782008364770993e-33, 0.0016635367646813393, 0.03778861463069916, 0.08253371715545654, 0.1101289689540863, 0.04298299551010132, 0.10628660023212433, 0.0012412478681653738, -0.09191308170557022, 0.032697126269340515, -0.024284327402710915, -0.023173462599515915, 0.04699080437421799, 0.0852847769856453, -0.014557267539203167, -0.001406451570801437, -0.04303181543946266, -0.16116800904273987, 0.07916515320539474, 0.03763362392783165, 0.01428395975381136, 0.03299128636717796, -1.305930800299393e-05, -0.059192873537540436, 0.07014308869838715, 0.002843403723090887, 0.006269631441682577, -0.011853540316224098, -0.0249515101313591, 0.0007340070442296565, 0.01663302071392536, -0.0820210725069046, -0.0021646127570420504, -0.04559161141514778, -0.06501143425703049, 0.0048117367550730705, -0.026006130501627922, -0.006227262318134308, -0.08845765143632889, -0.01304040290415287, 0.04500893875956535, 0.041806865483522415, 0.03350141644477844, -0.01795501634478569, 0.021803446114063263, 0.08075405657291412, 0.09310109913349152, -0.04959611967206001, -0.1016031950712204, -0.11496948450803757, -0.02407435141503811, -0.022459793835878372, -0.06403690576553345, -0.04647430032491684, -0.068220354616642, 0.03580412268638611, 0.020810957998037338, -0.02789860963821411, -0.02171209082007408, 0.008136867545545101, 0.040174756199121475, 0.05843479558825493, -0.04296579957008362, -0.05317160487174988, 0.013058565557003021, 0.07962091267108917, 0.010739695280790329, -0.06584318727254868, -0.08498737215995789, 0.09540622681379318, -0.1005866602063179, -0.09292775392532349, 0.014322852715849876, 0.005781521089375019, 0.011935953050851822, -0.05908774584531784, -0.04747543856501579, 0.01938542351126671, -0.045149799436330795, 0.04842375963926315, 0.03008459135890007, 0.001000041957013309, 0.017623065039515495, -0.06944576650857925, 0.10731019079685211, 0.05469120666384697, -0.10672435909509659, -0.06138524413108826, -0.0006750957109034061, -0.08517275750637054, 0.048489801585674286, -0.016454901546239853, 0.08340656012296677, 0.060657352209091187, 0.03611476719379425, -0.015382422134280205, 1.5721707969790225e-33, 0.0473162941634655, 0.08079317212104797, -0.061466868966817856, 0.018720949068665504, 0.03107515163719654, -0.049580980092287064, -0.003981516696512699, -0.016788369044661522, 0.10035170614719391, 0.07797391712665558, 0.03704891353845596, -0.0638529509305954, -0.014500610530376434, 0.05595134571194649, -0.10650629550218582, 0.02321632392704487, 0.025927921757102013, -0.02096269279718399, -0.01221313327550888, -0.06747525185346603, 0.07415670156478882, 0.13081857562065125, -0.06230098009109497, 0.014983597211539745, 0.029800398275256157, -0.0028964888770133257, -0.06172337755560875, 0.007643111515790224, -0.038278840482234955, -0.015030422247946262, 0.06802766025066376, 0.02515460178256035, -0.04003281146287918, 0.00423703296110034, -0.04046718403697014, 0.020228147506713867, 0.07360997796058655, -0.019015494734048843, -0.012550491839647293, 0.014263872057199478, 0.11339584738016129, -0.016698366031050682, -0.04757026955485344, 0.0670531839132309, 0.011079840362071991, -0.00948040559887886, 0.03256633132696152, 0.0089415293186903, -0.007570004556328058, 0.0018927723867818713, 0.03616670146584511, -0.08860396593809128, -0.001192879513837397, -0.029187005013227463, 0.003719246480613947, -0.07365859299898148, 0.01863693818449974, -0.07593613117933273, -0.005829865578562021, -0.0038658601697534323, 0.09769640862941742, 0.06674506515264511, -0.0817941203713417, 0.034378521144390106, 0.06561616063117981, 0.048765022307634354, -0.0026505524292588234, 0.09869891405105591, 0.02138541452586651, 0.01374790444970131, 0.02840130589902401, 0.04564480483531952, 0.0026726152282208204, 0.04595306143164635, -0.035813745111227036, 0.02314029075205326, -0.050948064774274826, -0.11289725452661514, -0.09623046964406967, 0.03236183524131775, -0.11869533360004425, -0.046539828181266785, -0.018649915233254433, -0.054364241659641266, -0.00977031048387289, 0.009983903728425503, 0.03403367102146149, -0.017800666391849518, -0.025413362309336662, -0.07262081652879715, -0.08008703589439392, -0.056589629501104355, -0.0254669189453125, -0.04380377009510994, -0.08475682884454727, -1.9464989620132656e-08, -0.07598097622394562, -0.06186037138104439, -0.015546831302344799, -0.08456943184137344, -0.009106519632041454, 0.007732860278338194, -0.016742218285799026, -0.018178705126047134, -0.007970739156007767, 0.04947188124060631, -0.012660756707191467, 0.019512716680765152, -0.001343191834166646, 0.04658779129385948, 0.13644668459892273, -0.002077273093163967, 0.044834621250629425, -0.0338115356862545, -0.049789175391197205, -0.044533297419548035, 0.04472240433096886, -0.01727660559117794, -0.10234621167182922, -0.02069053053855896, 0.006580105517059565, -0.035727228969335556, 0.038060761988162994, 0.07442951947450638, -0.05620531737804413, -0.024143291637301445, 0.011092386208474636, 0.010641706176102161, 0.08321069926023483, 0.05401139706373215, -0.07324273139238358, -0.01819549687206745, 0.033618804067373276, -0.0550665408372879, 0.0343528687953949, -0.00650562159717083, -0.007085470948368311, 0.04463335499167442, 0.03775797411799431, -0.0007514840108342469, 0.01831703633069992, 0.05073556676506996, 0.003691059770062566, 0.06106650456786156, -0.0056741805747151375, -0.01089479960501194, 0.008476332761347294, -0.00498939398676157, 0.030932627618312836, 0.008274606429040432, 0.005669950507581234, 0.07007640600204468, -0.0064295134507119656, 0.009060959331691265, -0.051291365176439285, -0.007777031976729631, 0.01555740088224411, 0.14277438819408417, 0.05832863971590996, -0.03482259809970856]'), +('Therapeutic communication is the purposeful and patient-centered process that forms the bedrock of the nurse-patient relationship. Unlike social conversation, it is goal-oriented, focusing on understanding the patient''s needs, concerns, and experiences to promote healing and well-being. The primary objective is to build trust and rapport, creating a safe environment where the patient feels comfortable sharing sensitive information. This is achieved through active listening, which involves not just hearing the patient''s words but also interpreting their non-verbal cues, such as body language and tone of voice. A nurse who is actively listening gives their full attention, makes eye contact, and conveys a genuine interest in the patient''s perspective. Key techniques in therapeutic communication include the use of open-ended questions, which encourage the patient to elaborate rather than give a simple yes or no answer. For example, asking "How have you been feeling since your last dose of medication?" is more effective than "Did the medication help?" Other vital techniques are paraphrasing and summarizing. Paraphrasing involves restating the patient''s message in your own words to confirm understanding, while summarizing helps to organize key points of a conversation, ensuring both parties are on the same page. The strategic use of silence can also be powerful, giving the patient time to gather their thoughts and reflect without feeling rushed. Conversely, there are common barriers that can hinder effective communication and damage trust. Giving unsolicited advice, offering false reassurance like "Don''t worry, everything will be fine," or using medical jargon the patient doesn''t understand can create distance and invalidate their feelings. Being judgmental or changing the subject when a patient expresses difficult emotions are also significant roadblocks. The skillful nurse navigates these interactions with empathy, focusing on the patient''s reality and validating their experience, which ultimately leads to more accurate assessments, better patient adherence to treatment plans, and improved health outcomes.', 'Name two key techniques of active listening mentioned in the text.', '[0.003418092615902424, -0.0018822657875716686, -0.07830553501844406, -0.04279983788728714, -0.05144064873456955, 0.022515833377838135, 0.1305283010005951, 0.008760301396250725, 0.014894375577569008, -0.01513164397329092, 0.036953527480363846, 0.07686663419008255, 0.0071741207502782345, -0.04944610595703125, 0.03037911467254162, 0.037507615983486176, 0.03346765413880348, 0.03966055065393448, 0.02256137691438198, -0.08023124188184738, 0.039372432976961136, 0.06331562250852585, 0.004376683384180069, 0.014387455768883228, -0.042525943368673325, -0.006493289023637772, -0.028153717517852783, -0.036069367080926895, 0.042280543595552444, -0.005847596563398838, 0.028742365539073944, 0.05408443138003349, 0.115963876247406, 0.03589613735675812, -0.18999478220939636, 0.028504017740488052, 0.0034906049259006977, 0.02294669672846794, -0.053793977946043015, -0.011012065224349499, 0.039017725735902786, -0.04994240403175354, 0.0046866899356245995, -0.07219333201646805, -0.025674955919384956, -0.020825939252972603, -0.1190204843878746, -0.01896774396300316, -0.0799083262681961, -0.039892327040433884, -0.10008549690246582, -0.023297687992453575, -0.03650594502687454, 0.09899606555700302, -0.04137367382645607, -0.012301766313612461, -0.01724259741604328, 0.040713559836149216, 0.014145313762128353, 0.04875818267464638, 0.0022526641841977835, -0.016604166477918625, -0.09841007739305496, 0.009520582854747772, 0.04148654267191887, -0.026663148775696754, 0.06705763936042786, -0.0006824145093560219, 0.011196673847734928, 0.04731304943561554, -0.06946128606796265, -0.00019607885042205453, -0.00999814085662365, -0.06562800705432892, 0.00993438996374607, -0.06584860384464264, 0.016019070520997047, -0.06574399024248123, 0.03293127194046974, -0.046633146703243256, -0.043015580624341965, -0.05122457817196846, -0.042444609105587006, -0.05423276126384735, 0.030593106523156166, 0.10235659778118134, -0.07510338723659515, -0.1353403776884079, -0.016992511227726936, -0.027260184288024902, -0.07261722534894943, -0.03628227487206459, -0.03951313719153404, 0.057542864233255386, -0.001316866255365312, -0.0014760084450244904, 0.004583956208080053, 0.037181589752435684, 0.03755484148859978, 0.03879160434007645, 0.06383828073740005, 0.044187240302562714, -0.05350838229060173, -0.009451784193515778, -0.0345056988298893, -0.12034871429204941, -0.016071146354079247, 0.0065009454265236855, 0.028556762263178825, 0.007825564593076706, -0.05063309147953987, -0.012261277064681053, -0.02264205738902092, -0.04723897576332092, 0.020348189398646355, 0.12167675048112869, 0.018365032970905304, 0.09103158861398697, 0.07010576874017715, 0.005593739915639162, 0.039506953209638596, -0.03393157571554184, -0.002928640926256776, -0.03703320771455765, 0.003568419022485614, -0.062288373708724976, -0.032581958919763565, -1.698566378064166e-33, 0.007825310342013836, -0.02493247017264366, -0.02131318487226963, 0.04284774139523506, -0.01561276987195015, -0.02721002697944641, -0.06188323348760605, -0.06394062936306, 0.08804585039615631, 0.06678107380867004, 0.015663983300328255, 0.07500961422920227, 0.02643997222185135, 0.04635819047689438, 0.020428985357284546, -0.08599051088094711, -0.08107773214578629, 0.10578818619251251, -0.02103150635957718, 0.0017291313270106912, 0.061510119587183, 0.045960091054439545, 0.05942504480481148, 0.03752562776207924, 0.10307291895151138, -0.024649010971188545, 0.02984088845551014, -0.012639807537198067, 0.0021245472598820925, 0.03948808088898659, 0.03154740110039711, -0.018122009932994843, -0.07693873345851898, 0.019069751724600792, 0.044902194291353226, 0.013650612905621529, -0.020103391259908676, -0.003126367460936308, 0.024916572496294975, -0.07261325418949127, -0.011120719835162163, 0.004697385709732771, 0.012409084476530552, -0.03163021802902222, 0.056464407593011856, -0.007303890306502581, -0.10731865465641022, 0.03549832105636597, 0.05979672074317932, 0.05022082477807999, 0.013691033236682415, -0.014684219844639301, 0.0016983227105811238, 0.0009236743790097535, 0.041183989495038986, 0.03463189676403999, 0.02811148203909397, 0.08947516232728958, -0.006199799943715334, 0.0857735127210617, -0.01101045124232769, 0.03584161028265953, -0.0008367059053853154, -0.026506278663873672, 0.04590127244591713, 0.07714304327964783, -0.05360034853219986, -0.13345132768154144, 0.05825034901499748, -0.06672099232673645, -0.019524117931723595, 0.08817093819379807, 0.014916820451617241, 0.04766938462853432, -0.02569161355495453, -0.0031095168087631464, -0.028406372293829918, -0.0161367766559124, 0.012011715210974216, 0.0266665518283844, -0.06964308023452759, 0.00556587241590023, -0.03848518058657646, 0.12635278701782227, -0.061736032366752625, 0.026524236425757408, -0.038862019777297974, -0.06468147039413452, -0.073839470744133, -0.012462313286960125, -0.062008194625377655, 0.11087177693843842, -0.041021477431058884, -0.01275123655796051, 0.02591242454946041, 1.9333075202724955e-35, 0.018664486706256866, 0.07198190689086914, -0.052022818475961685, 0.06284480541944504, -0.04116319492459297, 0.026202697306871414, 0.011351085267961025, -0.04579199105501175, -0.0051986039616167545, 0.0004549347795546055, 0.033440131694078445, -0.01248047687113285, -0.004343399312347174, 0.021242476999759674, -0.014780846424400806, -0.06702431291341782, -0.02051522210240364, 0.012222537770867348, -0.0048741186037659645, 0.11667173355817795, -5.6768563808873296e-05, 0.02491314336657524, 0.022125793620944023, -0.007213993463665247, 0.0013940383214503527, -0.03663353621959686, -0.02114398032426834, 0.017307382076978683, -0.04750385507941246, -0.03566550090909004, -0.04735211282968521, 0.007245514541864395, -0.050730302929878235, -0.05286439135670662, -0.01115918718278408, 0.04128549247980118, 0.08967749029397964, 0.03814009204506874, 0.006751025561243296, 0.015716996043920517, 0.04992112144827843, 0.048141203820705414, 0.07857917994260788, -0.051390934735536575, -0.001249605556949973, 0.014509334228932858, -0.078241266310215, 0.06936538964509964, -0.15870881080627441, -0.044174812734127045, 0.09148197621107101, -0.09598071873188019, 0.015780052170157433, -0.03617412969470024, -0.02291039377450943, 0.13511425256729126, 0.016487937420606613, -0.018259352073073387, -0.01066189631819725, 0.0007881562341935933, 0.05332469940185547, 0.022005120292305946, -0.036478035151958466, 0.019521990790963173, -0.043064139783382416, 0.05385183170437813, 0.03309747204184532, 0.0019059586338698864, 0.0022013504058122635, 0.038157738745212555, 0.06575606763362885, 0.022489480674266815, -0.003616778878495097, -0.012212888337671757, -0.03258742764592171, 0.012752686627209187, -0.08887287974357605, -0.10902831703424454, -0.08970168232917786, -0.011829043738543987, -0.02057958021759987, 0.031186020001769066, -0.032196369022130966, -0.0025349182542413473, -0.05372841656208038, 0.06030239164829254, 0.03706080839037895, -0.08737178146839142, -0.02453150972723961, -0.0747639387845993, 0.01281204167753458, 0.06099209934473038, -0.06207343935966492, 0.060192931443452835, -0.05778667330741882, -1.7563827725552983e-08, -0.029327601194381714, -0.04210301861166954, 0.052951425313949585, -0.06996318697929382, 0.055985208600759506, 0.0008521881536580622, -0.006544728763401508, -0.03698725253343582, -0.012008516117930412, -0.04238785430788994, 0.011969706043601036, 0.029591595754027367, -0.004729787353426218, -0.008298133499920368, 0.11771994829177856, 0.005682069342583418, -0.022059811279177666, 0.018049174919724464, -0.09621851146221161, -0.05625387653708458, 0.10517504066228867, 0.01933559961616993, 0.010725744999945164, 0.02611301653087139, 0.031931377947330475, 0.004549948964267969, 0.1261385679244995, 0.07883373647928238, 0.02741236425936222, 0.008545750752091408, 0.00828170869499445, 0.05215039104223251, -0.019816849380731583, -0.045176830142736435, -0.031949061900377274, 0.023940904065966606, 0.0006682435050606728, -0.07033142447471619, -0.018218519166111946, 0.048551224172115326, -0.01869395561516285, -0.033844344317913055, -0.04436618462204933, 0.06118081137537956, 0.05557727441191673, 0.045983899384737015, 0.020287256687879562, -0.027130000293254852, 0.02720853127539158, -0.015549441799521446, -0.03589252382516861, 0.021739881485700607, 0.06967214494943619, -0.012100531719624996, -0.03309221565723419, 0.09393349289894104, 0.037387728691101074, -0.04533468559384346, -0.034131065011024475, 0.03711788356304169, -0.009091343730688095, 0.13874030113220215, -0.01765952818095684, 0.058198753744363785]'), +('Therapeutic communication is the purposeful and patient-centered process that forms the bedrock of the nurse-patient relationship. Unlike social conversation, it is goal-oriented, focusing on understanding the patient''s needs, concerns, and experiences to promote healing and well-being. The primary objective is to build trust and rapport, creating a safe environment where the patient feels comfortable sharing sensitive information. This is achieved through active listening, which involves not just hearing the patient''s words but also interpreting their non-verbal cues, such as body language and tone of voice. A nurse who is actively listening gives their full attention, makes eye contact, and conveys a genuine interest in the patient''s perspective. Key techniques in therapeutic communication include the use of open-ended questions, which encourage the patient to elaborate rather than give a simple yes or no answer. For example, asking "How have you been feeling since your last dose of medication?" is more effective than "Did the medication help?" Other vital techniques are paraphrasing and summarizing. Paraphrasing involves restating the patient''s message in your own words to confirm understanding, while summarizing helps to organize key points of a conversation, ensuring both parties are on the same page. The strategic use of silence can also be powerful, giving the patient time to gather their thoughts and reflect without feeling rushed. Conversely, there are common barriers that can hinder effective communication and damage trust. Giving unsolicited advice, offering false reassurance like "Don''t worry, everything will be fine," or using medical jargon the patient doesn''t understand can create distance and invalidate their feelings. Being judgmental or changing the subject when a patient expresses difficult emotions are also significant roadblocks. The skillful nurse navigates these interactions with empathy, focusing on the patient''s reality and validating their experience, which ultimately leads to more accurate assessments, better patient adherence to treatment plans, and improved health outcomes.', 'Why are open-ended questions generally preferred over closed-ended questions in patient interviews?', '[0.005508371628820896, 0.12316865473985672, 0.013447928242385387, 0.04385153204202652, 0.0479954369366169, -0.002976509742438793, -0.007285348605364561, 0.06951303035020828, 0.06503313779830933, -0.029318740591406822, -0.07774318754673004, 0.03807809576392174, -0.11258142441511154, -0.03812689334154129, 0.03313411399722099, 0.0068157208152115345, -0.000142111093737185, -0.1063970997929573, -0.016896920278668404, 0.0929800495505333, -0.03942755237221718, 0.05274511128664017, 0.050255388021469116, -0.0213517677038908, -0.03610708564519882, -0.06399445235729218, 0.034862540662288666, -0.06326492130756378, 0.04281198978424072, 0.11001076549291611, 0.010108904913067818, 0.029227174818515778, 0.000767935998737812, -0.02251708321273327, 0.02325044572353363, -0.004925912246108055, -0.043198924511671066, 0.07435103505849838, -0.10353588312864304, 0.04962786287069321, 0.019224179908633232, -0.0025335391983389854, -0.001405109534971416, 0.025576990097761154, -0.018282830715179443, -0.15299363434314728, -0.011751423589885235, -0.012113791890442371, 0.0025188876315951347, -0.010448602959513664, -0.09296908229589462, -0.11618997901678085, -0.06462699919939041, -0.013120323419570923, 0.009472116827964783, -0.040652740746736526, -0.03869413584470749, -0.027094000950455666, -0.07042215764522552, 0.06851939111948013, -0.05522027239203453, -0.05156761780381203, -0.0661136656999588, 0.0744757279753685, 0.05886145681142807, -0.03866061568260193, 0.006468117702752352, -0.04098347947001457, 0.014846354722976685, -0.020435519516468048, -0.11711539328098297, -0.010654131881892681, 0.0024312164168804884, 0.0438498929142952, -0.03990260884165764, -0.0038270249497145414, -0.06237130984663963, -0.048543013632297516, -0.006989113986492157, 0.08140134811401367, 0.06030565872788429, -0.11352648586034775, 0.0009183200891129673, 0.05184581130743027, 0.03058823198080063, 0.03301771730184555, -0.026952069252729416, -0.006709210574626923, -0.06828922033309937, -0.06241561099886894, 0.010650363750755787, 0.03357958793640137, -0.01489716675132513, 0.0012456108815968037, 0.11677844822406769, -0.005766790360212326, -0.018777241930365562, 0.06114240735769272, -0.0017320133047178388, -0.025858018547296524, 0.05563708022236824, -0.01651155948638916, 0.016833771020174026, 0.021621795371174812, -0.0583425909280777, 0.016700617969036102, 0.0036033443175256252, -0.02231452614068985, 0.01186689455062151, -0.009224291890859604, 0.0020435331389307976, -0.040429387241601944, 0.11696092784404755, -0.09480864554643631, -0.007778818719089031, 0.002549267839640379, -0.05272199958562851, 0.04677943140268326, -0.002319153631106019, 0.017530888319015503, 0.014955155551433563, -0.005143914837390184, -0.0013474635779857635, -0.06484095752239227, 0.036399587988853455, 0.03300601989030838, -0.007448683958500624, -2.3254668825783e-33, -0.0027739391662180424, -0.04772863909602165, 0.043097611516714096, 0.006029988639056683, 0.011399243958294392, 0.08178861439228058, -0.050479792058467865, 0.025197410956025124, 0.0247956495732069, 0.005215468816459179, 0.02373475953936577, 0.04750160127878189, 0.01859881356358528, -0.016488032415509224, 0.034909214824438095, 0.07982110232114792, -0.06520189344882965, 0.1068282276391983, -0.04759015142917633, 0.09459622949361801, 0.03867806866765022, 0.03211880475282669, 0.02677260898053646, 0.08690652251243591, -0.031264301389455795, -0.03115115500986576, -0.003598945215344429, -0.01712685264647007, 0.038446713238954544, -0.03319637104868889, -0.06357378512620926, -0.07301198691129684, 0.05352034419775009, 0.024832826107740402, 0.0029721218161284924, 0.12510861456394196, -0.02453937940299511, -0.029861686751246452, 0.005025963764637709, -0.09081250429153442, 0.0009024563478305936, 0.00839370395988226, 0.04957780987024307, 0.09060904383659363, 0.047901593148708344, -0.04587516188621521, -0.08200062066316605, -0.07642875611782074, -0.055383555591106415, -0.02297261729836464, -0.029290566220879555, -0.009463107213377953, -0.07905887812376022, -0.006854617036879063, 0.03818091005086899, 0.07425718009471893, 0.02442384697496891, 0.004448386840522289, -0.09815492480993271, 0.09303212910890579, 0.013620266690850258, 0.06120633706450462, 0.08055203408002853, -0.11110195517539978, -0.006236311048269272, 0.005993626546114683, -0.03130083158612251, -0.04272092878818512, 0.0497804656624794, 0.0034179023932665586, -0.011508590541779995, 0.029840368777513504, -0.04000445082783699, -0.026012621819972992, 0.0190464835613966, 0.046928536146879196, -0.061524614691734314, 0.06888139992952347, 0.10342544317245483, -0.03102736733853817, 0.10736387223005295, -0.0040137022733688354, -0.0487816147506237, 0.06066427007317543, -0.019120503216981888, -0.043383240699768066, -0.0478656068444252, 0.11039730161428452, -0.044068071991205215, 0.0366215817630291, -0.04358223080635071, -0.0058671277947723866, 0.04915810748934746, 0.03172849863767624, 0.018305042758584023, 2.7857891387456135e-34, 0.005576943513005972, -0.01693785935640335, -0.08474671840667725, 0.05955886095762253, 0.035587068647146225, -0.011766528710722923, -0.010873962193727493, -0.09343883395195007, 0.10936354100704193, 0.03781472146511078, 0.036028902977705, 0.032354824244976044, 0.0251784585416317, -0.027997305616736412, -0.03348840773105621, -0.029881462454795837, -0.055875830352306366, -0.05310645326972008, -0.01720883697271347, -0.012644888833165169, 0.019781770184636116, 0.10127799957990646, -0.021874045953154564, 0.018453089520335197, 0.05004855990409851, 0.037636805325746536, -0.10138995200395584, -0.05705462768673897, -0.019093208014965057, -0.028583569452166557, -0.051054686307907104, -0.0742112323641777, -0.013840142637491226, 0.02752016671001911, 0.04156981036067009, 0.09202732890844345, 0.008009356446564198, -0.06037024408578873, 0.08692511916160583, 0.03346030414104462, -0.033272456377744675, -0.08639755845069885, -0.06999020278453827, -0.04156649112701416, 0.02758168615400791, -0.08033743500709534, -0.03242217376828194, 0.005869708955287933, 0.011903999373316765, -0.03674435243010521, -0.08846502751111984, -0.00869812723249197, 0.021170971915125847, 0.005832521244883537, -0.06597341597080231, -0.0712018683552742, -0.043729018419981, 0.042125921696424484, -0.023887550458312035, -0.026752116158604622, 0.04789471998810768, 0.0262418482452631, 0.0221236702054739, -0.01857503317296505, 0.020560242235660553, -0.005586849991232157, 0.05729932337999344, 0.03269411623477936, -0.08525204658508301, -0.05610558018088341, -0.11606017500162125, -0.03503146767616272, 0.07088698446750641, 0.07024221122264862, 0.04614175856113434, 0.04708121716976166, 0.05874395743012428, -0.09286592155694962, -0.02568809688091278, 0.007213827222585678, -0.029509995132684708, -0.0986495092511177, 0.06653058528900146, 0.10157634317874908, -0.04736337810754776, 0.0476774200797081, 0.03350779414176941, 0.0056452201679348946, 0.03555650636553764, 0.04853379353880882, -0.00047493891906924546, -0.022797970101237297, -0.04453777149319649, -0.054538529366254807, -0.04598525911569595, -2.099968021695986e-08, -0.04644465073943138, -0.019991466775536537, 0.028857730329036713, -0.011029249988496304, 0.0005979714915156364, -0.07760200649499893, -0.07049635797739029, 0.0563938207924366, 0.0032750668469816446, 0.048176176846027374, -0.03241740167140961, 0.024233706295490265, -0.03331418335437775, 0.04448995366692543, -0.010255158878862858, 0.08291877806186676, -0.03547251224517822, -0.011705897748470306, 0.02252531237900257, -0.014839684590697289, -0.04315200448036194, 0.009892893955111504, -0.06643376499414444, 0.03934784233570099, -0.019254449754953384, 0.089712955057621, -0.059010133147239685, 0.05465879663825035, -0.06599292159080505, 0.022293534129858017, 0.0503033772110939, 0.0180532094091177, 0.036200493574142456, 0.07606606185436249, 0.0006879675784148276, -0.008113084360957146, 0.05079574137926102, 0.04146493598818779, 0.0012873400701209903, -0.04377557337284088, 0.00764420535415411, 0.05269959196448326, 0.029712501913309097, 0.002436539623886347, -0.006207569502294064, -0.045096054673194885, -0.011978555470705032, 0.11465990543365479, -0.09889671951532364, 0.022396519780158997, -0.01870943419635296, -0.054343219846487045, 0.06944161653518677, -0.027487965300679207, 0.029071589931845665, 0.0007280689897015691, 0.02661236748099327, 0.03737984597682953, -0.04955392703413963, 0.06892994791269302, 0.010618112049996853, 0.06611362844705582, -0.012913908809423447, 0.0002882876724470407]'), +('Therapeutic communication is the purposeful and patient-centered process that forms the bedrock of the nurse-patient relationship. Unlike social conversation, it is goal-oriented, focusing on understanding the patient''s needs, concerns, and experiences to promote healing and well-being. The primary objective is to build trust and rapport, creating a safe environment where the patient feels comfortable sharing sensitive information. This is achieved through active listening, which involves not just hearing the patient''s words but also interpreting their non-verbal cues, such as body language and tone of voice. A nurse who is actively listening gives their full attention, makes eye contact, and conveys a genuine interest in the patient''s perspective. Key techniques in therapeutic communication include the use of open-ended questions, which encourage the patient to elaborate rather than give a simple yes or no answer. For example, asking "How have you been feeling since your last dose of medication?" is more effective than "Did the medication help?" Other vital techniques are paraphrasing and summarizing. Paraphrasing involves restating the patient''s message in your own words to confirm understanding, while summarizing helps to organize key points of a conversation, ensuring both parties are on the same page. The strategic use of silence can also be powerful, giving the patient time to gather their thoughts and reflect without feeling rushed. Conversely, there are common barriers that can hinder effective communication and damage trust. Giving unsolicited advice, offering false reassurance like "Don''t worry, everything will be fine," or using medical jargon the patient doesn''t understand can create distance and invalidate their feelings. Being judgmental or changing the subject when a patient expresses difficult emotions are also significant roadblocks. The skillful nurse navigates these interactions with empathy, focusing on the patient''s reality and validating their experience, which ultimately leads to more accurate assessments, better patient adherence to treatment plans, and improved health outcomes.', 'What is one common barrier to effective communication that nurses should avoid?', '[0.037978433072566986, -0.006764780264347792, -0.01640886627137661, -0.0027710741851478815, -0.02994091808795929, 0.024669377133250237, -0.02877853624522686, -0.0008128017652779818, 0.05752389132976532, -0.11008162051439285, -0.03408852592110634, 0.04418011009693146, -0.0693415179848671, 0.03728843107819557, 0.02388559840619564, -0.021356115117669106, 0.07700379192829132, 0.061143066734075546, -0.017909901216626167, -0.012913443148136139, -0.008722689934074879, 0.05705580115318298, 0.06368234008550644, 0.09456980228424072, -0.03309301286935806, -0.05717334523797035, 0.007977182045578957, -0.031233565881848335, 0.03307493031024933, 0.031120043247938156, -0.04374799132347107, -0.04910657927393913, 0.033721186220645905, 0.04580027982592583, -0.1298852264881134, 0.0903172716498375, 0.009275645017623901, 0.04225746914744377, -0.009485267102718353, -0.02915797010064125, -0.05632957071065903, 0.0010839173337444663, 0.02089354395866394, -0.06629359722137451, 0.06133685261011124, -0.09451533854007721, 0.05968799814581871, 0.05527954921126366, -0.049151670187711716, -0.051463790237903595, -0.06595901399850845, -0.039770592004060745, -0.03235836327075958, 0.08404969424009323, 0.07480014860630035, -0.08141987770795822, -0.034087687730789185, 0.03524794057011604, -0.03253990784287453, 0.030394578352570534, -0.03148827701807022, -0.03435494005680084, 0.000333423784468323, 0.02158493548631668, -0.02363472804427147, 0.04045264795422554, -0.042870860546827316, 0.06273611634969711, -0.002940779784694314, 0.08569779247045517, -0.026029979810118675, -0.05077202618122101, 0.008156233467161655, 0.055094510316848755, 0.018004579469561577, 0.032209839671850204, 0.008428733795881271, -0.04657776281237602, 0.007600089069455862, 0.057864800095558167, 0.004550601821392775, -0.020855002105236053, 0.009476101957261562, 0.09018569439649582, 0.005556799937039614, -0.038652945309877396, 0.02284426800906658, -0.031765181571245193, -0.05433185398578644, -0.07213002443313599, 0.009801163338124752, 0.0071951160207390785, -0.04263875260949135, 0.014859601855278015, -0.02726968191564083, -0.022505324333906174, -0.046372074633836746, -0.07458877563476562, -0.044936858117580414, 0.01017030980437994, 0.006704025436192751, 0.046519383788108826, -0.02385995350778103, 0.06946853548288345, -0.0569620244204998, -0.019205402582883835, 0.06324923038482666, -0.1062789112329483, -0.12140671163797379, 0.05233140289783478, -0.04919670522212982, 0.09409239143133163, -0.0943254828453064, -0.03191448375582695, -0.023756936192512512, -0.022658444941043854, 0.04049677774310112, -0.01145468931645155, 0.041230879724025726, 0.05650672689080238, -0.01685010828077793, -0.03410041332244873, 0.027453221380710602, -0.011271587572991848, 0.04732728749513626, 0.026669899001717567, 0.006079183891415596, -2.850228315607501e-33, 0.009149766527116299, 0.06746336817741394, 0.030499184504151344, 0.10051144659519196, 0.07650674879550934, 0.0848807543516159, 0.01885472983121872, -0.07174830883741379, 0.09732795506715775, 0.03228769451379776, -0.026566630229353905, 0.04168389365077019, 0.07008258998394012, -0.07123751938343048, 0.036806393414735794, -0.012330823577940464, -0.10008443892002106, 0.03270954638719559, -0.002037166152149439, 0.04498185217380524, 0.038019467145204544, -0.06881667673587799, -0.06642638146877289, 0.09413991868495941, 0.015038968995213509, -0.049745362251996994, 0.015392917208373547, -0.06949205696582794, 0.08111221343278885, 0.024016451090574265, -0.060943979769945145, -0.014210469089448452, -0.01360318809747696, -0.05421717092394829, 0.0008534321677871048, 0.003573841182515025, -0.07884041965007782, -0.07763209939002991, 0.014479968696832657, 0.02780883014202118, -0.020442459732294083, 0.00041323769255541265, 0.03135163336992264, 0.00395524688065052, 0.12463726103305817, 0.08462727069854736, -0.02656397968530655, -0.07150141149759293, -0.12090972810983658, -0.02014409750699997, -0.024856967851519585, -0.021575018763542175, -0.034724749624729156, -0.0370868444442749, -0.0006466396152973175, -0.0687590166926384, 0.038299452513456345, -0.043800100684165955, -0.0032734309788793325, 0.06058138236403465, -0.008943424560129642, -0.01071210764348507, -0.048944953829050064, -0.007542054634541273, 0.0993548333644867, -0.008710093796253204, -0.14099639654159546, -0.05859522521495819, 0.06010037660598755, -0.10191354900598526, -0.028642289340496063, 0.0401756577193737, -0.04168832302093506, 0.010495776310563087, -0.06237871199846268, -0.029554201290011406, -0.009531164541840553, -0.0609622560441494, 0.11599202454090118, -0.05871225520968437, 0.0028667254373431206, -0.005788254085928202, -0.04404133930802345, 0.047701396048069, -0.006331239826977253, -0.03464353829622269, -0.028246773406863213, 0.05435919389128685, -0.04142175614833832, 0.0510113425552845, -0.017926212400197983, 0.06639803200960159, 0.08182086795568466, 0.021320777013897896, -0.03235689923167229, 4.286818512517642e-34, 0.014970699325203896, 0.09237354248762131, -0.05793410912156105, 0.03889782726764679, -0.01935659535229206, 0.000530279241502285, 0.03674023970961571, -0.005950186401605606, 0.0713764950633049, 0.025073377415537834, 0.015203902497887611, -0.040053434669971466, -0.02444169484078884, 0.027370242401957512, -0.06023798882961273, -0.016030052676796913, 0.10254847258329391, -0.023542607203125954, 0.049173448234796524, -0.07392517477273941, 0.0634487122297287, 0.04077279567718506, -0.04595979303121567, 0.045931730419397354, -0.006320773623883724, 0.022200526669621468, -0.1128922700881958, -0.03215041756629944, -0.03325733542442322, -0.04166032373905182, -0.03468364477157593, 0.09864478558301926, 0.06329700350761414, -0.002849830547347665, -0.06144557520747185, 0.07475639879703522, -0.008686893619596958, -0.006376602221280336, -0.012495869770646095, 0.03050406090915203, 0.08647092431783676, 0.01048178132623434, -0.04830864444375038, 0.03510524705052376, 0.03827038034796715, -0.02637004479765892, -0.025682855397462845, -0.07497977465391159, -0.057508908212184906, 0.0085249412804842, -0.008983287028968334, -0.07875695824623108, -0.037199195474386215, -0.026532180607318878, -0.012457688339054585, -0.016845345497131348, 0.03452387824654579, -0.044900082051754, 0.0036273663863539696, 0.04062559828162193, 0.08971592038869858, 0.014193838462233543, -0.037765637040138245, 0.003089824691414833, 0.038256801664829254, -0.018697556108236313, 0.023263201117515564, 0.07955557107925415, 0.12912729382514954, -0.004494424909353256, 0.032966576516628265, 0.05222798511385918, 0.0024016248062253, -0.02033989131450653, -0.018356049433350563, 0.04816451296210289, -0.03297712653875351, -0.10913106054067612, -0.09027165174484253, 0.0336269736289978, -0.07596640288829803, 0.014477106742560863, -0.029080798849463463, -0.05951952189207077, -0.02154841087758541, 0.03201283887028694, -0.01512976549565792, -0.07234428077936172, -0.023515425622463226, -0.07071647047996521, -0.09260129183530807, -0.0404394194483757, -0.013564776629209518, -0.06414136290550232, -0.0846015140414238, -1.9827423258789167e-08, -0.03694979473948479, -0.04507659003138542, 0.05545371398329735, -0.05861222371459007, 0.05010818690061569, -0.05668334290385246, -0.031265322118997574, 0.0429893434047699, -0.005405576433986425, 0.014880125410854816, 0.01876877062022686, 0.020765051245689392, 0.023947803303599358, 0.03889017924666405, 0.15505127608776093, 0.051437314599752426, 0.023528490215539932, -0.016612332314252853, -0.057927925139665604, -0.05680526793003082, 0.039218563586473465, 0.004840480629354715, -0.11983750015497208, -0.03377332538366318, 0.03408411517739296, -0.02412305772304535, 0.01688418537378311, 0.07781939953565598, -0.025579508394002914, 0.03317166119813919, -0.01526740100234747, -0.04477477818727493, 0.07958246022462845, 0.0528392419219017, -0.07078644633293152, 0.011330408975481987, 0.08264109492301941, -0.0548788383603096, 0.013161160983145237, 0.006565242074429989, -0.01679355837404728, -0.017686575651168823, 0.009115064516663551, 0.05498437583446503, 0.05650241672992706, 0.048567403107881546, -0.0010329951765015721, 0.02616562508046627, -0.045898374170064926, -0.03401723876595497, 0.05923710763454437, -0.018516678363084793, 0.07865040749311447, 0.034829940646886826, -0.015122453682124615, 0.07816102355718613, -0.012652433477342129, -0.009813233278691769, -0.018915176391601562, 0.026851855218410492, -0.002357551595196128, 0.11221544444561005, -0.02033870667219162, 0.05081089586019516]'), +('Therapeutic communication is the purposeful and patient-centered process that forms the bedrock of the nurse-patient relationship. Unlike social conversation, it is goal-oriented, focusing on understanding the patient''s needs, concerns, and experiences to promote healing and well-being. The primary objective is to build trust and rapport, creating a safe environment where the patient feels comfortable sharing sensitive information. This is achieved through active listening, which involves not just hearing the patient''s words but also interpreting their non-verbal cues, such as body language and tone of voice. A nurse who is actively listening gives their full attention, makes eye contact, and conveys a genuine interest in the patient''s perspective. Key techniques in therapeutic communication include the use of open-ended questions, which encourage the patient to elaborate rather than give a simple yes or no answer. For example, asking "How have you been feeling since your last dose of medication?" is more effective than "Did the medication help?" Other vital techniques are paraphrasing and summarizing. Paraphrasing involves restating the patient''s message in your own words to confirm understanding, while summarizing helps to organize key points of a conversation, ensuring both parties are on the same page. The strategic use of silence can also be powerful, giving the patient time to gather their thoughts and reflect without feeling rushed. Conversely, there are common barriers that can hinder effective communication and damage trust. Giving unsolicited advice, offering false reassurance like "Don''t worry, everything will be fine," or using medical jargon the patient doesn''t understand can create distance and invalidate their feelings. Being judgmental or changing the subject when a patient expresses difficult emotions are also significant roadblocks. The skillful nurse navigates these interactions with empathy, focusing on the patient''s reality and validating their experience, which ultimately leads to more accurate assessments, better patient adherence to treatment plans, and improved health outcomes.', 'Besides verbal language, what other form of communication plays a crucial role in patient interaction?', '[0.03701237589120865, 0.016877958551049232, -0.007134707178920507, -0.044098127633333206, -0.11370526999235153, 0.023039693012833595, 0.02157662622630596, 0.027862606570124626, 0.09834648668766022, -0.09126847982406616, -0.0255194753408432, 0.06308551132678986, -0.07645727694034576, 0.07130637019872665, 0.07895722985267639, -0.026552116498351097, 0.023278141394257545, 0.0005046604783274233, 0.024461355060338974, 0.028215399011969566, -0.008143153972923756, 0.06420758366584778, 0.03958291560411453, 0.002551601268351078, -0.045112013816833496, -0.004961767233908176, -0.01166228111833334, -0.035947903990745544, 0.0551033616065979, 0.025715075433254242, 0.007837632670998573, 0.006433975882828236, 0.08039786666631699, 0.04582739248871803, -0.1592760533094406, 0.1119077205657959, 0.01946430839598179, 0.01461588405072689, -0.06593203544616699, -0.03382037952542305, -0.06348922848701477, 0.005317308474332094, 0.0386650376021862, 0.006705737207084894, 0.09466015547513962, -0.10867392271757126, -0.0051951841451227665, 0.04070625454187393, -0.08580417186021805, 0.010631877928972244, -0.1215716302394867, 0.015103782527148724, -0.002079553436487913, 0.1498412936925888, 0.005630568601191044, -0.02395247481763363, -0.04581473395228386, 0.028893882408738136, -0.04023494943976402, -0.006411885377019644, -0.01906924694776535, -0.01676151156425476, 0.03687293455004692, 0.04979315027594566, -0.025911016389727592, 0.0350988395512104, 0.009593894705176353, -0.020647799596190453, -0.03994258865714073, 0.00843745842576027, -0.014773542992770672, -0.04779485985636711, 0.025127936154603958, 0.05028495937585831, -0.015356688760221004, -0.026702197268605232, 0.028221989050507545, -0.072056844830513, 0.01399242877960205, 0.02745216153562069, 0.03357626125216484, 0.04807085543870926, -0.011048668995499611, 0.036606062203645706, -0.04034539684653282, -0.006217075977474451, 0.002828394528478384, -0.06118012219667435, -0.10987139493227005, -0.03639417514204979, -0.01906411536037922, -0.027501607313752174, -0.06584901362657547, -0.04532614350318909, -0.05104723945260048, -0.03631993383169174, -0.008803097531199455, -0.02364574559032917, -0.0031580680515617132, 0.005973902065306902, 0.01815049722790718, 0.009334737434983253, 0.0025904339272528887, 0.03438848257064819, -0.07369362562894821, 0.027867190539836884, -0.054547861218452454, -0.0896233320236206, -0.09145574271678925, 0.02119426056742668, -0.07345296442508698, -0.009590337052941322, -0.08248399198055267, 0.003657976631075144, 0.04454728588461876, 0.04090462252497673, -0.03266669064760208, 0.0013449117541313171, 0.09723444283008575, 0.019644884392619133, 0.027033038437366486, -0.04564027488231659, 0.014508838765323162, -0.02854842133820057, 0.025619911029934883, -0.02688455581665039, 0.00871624331921339, -2.3424153070652496e-33, 0.04651844874024391, -0.00585778197273612, 0.016107309609651566, 0.13561104238033295, 0.07148487865924835, 0.10223439335823059, 0.01507033035159111, -0.061944883316755295, 0.08589284867048264, -0.06159426271915436, -0.03591783717274666, 0.01707269623875618, 0.13629630208015442, 0.05930543318390846, -0.029526297003030777, 0.040367491543293, -0.12034378200769424, 0.14352643489837646, -0.03869771584868431, 0.018671799451112747, 0.025904666632413864, 0.02478211000561714, -0.013671237044036388, 0.06255073100328445, 0.003653523977845907, -0.010364476591348648, 0.009478702209889889, -0.04405473172664642, 0.06929094344377518, -0.025154607370495796, -0.06845337897539139, 0.018458297476172447, -0.01914566196501255, -0.04243004694581032, 0.024636095389723778, 0.04999163746833801, -0.023422054946422577, -0.11583079397678375, 0.056373778730630875, 0.017283476889133453, 0.03821154311299324, 0.02993268519639969, -0.048908110707998276, 0.004756569396704435, 0.035350970923900604, 0.01569434441626072, -0.03986944630742073, -0.06693423539400101, -0.11130766570568085, -0.02468833699822426, -0.07458995282649994, -0.018542073667049408, -0.01733434572815895, -0.021457158029079437, 0.052502501755952835, 0.06736605614423752, 0.028185561299324036, -0.023841766640543938, -0.060439176857471466, 0.015965823084115982, 0.05195358023047447, 0.057334285229444504, 0.03400305286049843, -0.029025962576270103, 0.10092562437057495, -0.03425760939717293, -0.09890387952327728, -0.08908746391534805, 0.06252780556678772, -0.09448406100273132, -0.07698551565408707, 0.08374155312776566, -0.03302709385752678, 0.027502600103616714, -0.08437545597553253, -0.06217712536454201, -0.027431238442659378, -0.10641863197088242, 0.03463589772582054, 0.08896558731794357, -0.019198771566152573, -0.1346987783908844, -0.02683006227016449, 0.08108240365982056, -0.0016788096399977803, -0.02785528264939785, -0.01644613966345787, 0.015257989056408405, -0.026899131014943123, -0.042300865054130554, -0.06623995304107666, 0.020167579874396324, 0.043376557528972626, 0.024530107155442238, 0.024004563689231873, -1.0203769428072439e-33, -0.017822101712226868, 0.0478721521794796, -0.02517998404800892, 0.006242851261049509, -0.004048718139529228, 0.01199595257639885, 0.08180908858776093, -0.04435962811112404, 0.07445952296257019, 0.026865897700190544, 0.005961000919342041, 0.03337987884879112, -0.0022882113698869944, 0.00636302400380373, -0.043089114129543304, 0.04489481449127197, 0.01141527108848095, 0.004226013086736202, 0.06602457165718079, -0.03137122839689255, 0.04242369160056114, 0.074301578104496, -0.01783880405128002, 0.02501043863594532, -0.01684405654668808, -0.014565983787178993, -0.03612307831645012, -0.07345720380544662, -0.05710085853934288, -0.004193947184830904, 0.004051108844578266, 0.0469498373568058, 0.012719493359327316, -0.011181159876286983, -0.0033673683647066355, 0.062190085649490356, 0.018690815195441246, -0.0300145260989666, -0.04469814896583557, -0.04597562551498413, 0.07600146532058716, 0.02263067103922367, 0.008109991438686848, 0.02738681435585022, 0.04884998872876167, -0.014080973342061043, -0.03694121912121773, -0.03968274965882301, -0.04512333869934082, 0.04455064982175827, 0.025467969477176666, -0.044605351984500885, -0.05919284746050835, -0.033652231097221375, -0.06297019869089127, -0.018776047974824905, 0.014354478567838669, -0.07529178261756897, -0.036650363355875015, -0.04505138099193573, 0.018104614689946175, 0.007793160155415535, -0.01898602396249771, -0.022292504087090492, 0.05425536260008812, 0.009451428428292274, 0.014994527213275433, 0.029220949858427048, 0.07957977056503296, -0.029385406523942947, 0.08727672696113586, -0.00085086515173316, 0.02910008281469345, 0.02464991994202137, 0.03351212665438652, -0.0026696280110627413, -0.0386568121612072, -0.06659257411956787, -0.06364540010690689, -0.03332052007317543, -0.047416605055332184, 0.015935169532895088, 0.05314815044403076, -0.02386104129254818, -0.07098066061735153, 0.0773685872554779, -0.06538732349872589, -0.06498641520738602, -0.008557106368243694, -0.07042218744754791, -0.07384667545557022, 0.05002506077289581, -0.030416807159781456, -0.056267186999320984, -0.07626879960298538, -2.378060592889142e-08, -0.04269278049468994, -0.034444522112607956, 0.06266670674085617, -0.08811654895544052, 0.029353925958275795, -0.05326174572110176, -0.00023092234914656729, 0.05789567530155182, -0.05615110322833061, 0.05779453366994858, -0.011288291774690151, 0.07363374531269073, 0.0643039271235466, -0.010433352552354336, 0.11331649124622345, 0.06435255706310272, 0.00020678617875091732, -0.019785357639193535, -0.051600173115730286, -0.06196226552128792, 0.051042113453149796, -0.0677749514579773, -0.06488753110170364, 0.040723271667957306, 0.029668597504496574, 0.006675915792584419, 0.022293509915471077, 0.09746096283197403, -0.03244873881340027, 0.007775170728564262, 0.0001254473318113014, 0.018076706677675247, 0.06956074386835098, 0.01990499347448349, -0.01896822638809681, -0.005628339014947414, 0.0513426773250103, -0.05551925674080849, 0.019769836217164993, 0.027239764109253883, 0.02122684195637703, 0.032305434346199036, -0.007397772744297981, 0.029936067759990692, 0.11169023811817169, 0.022316187620162964, -0.04319082200527191, -0.008344506844878197, -0.02875639498233795, -0.051380522549152374, -0.05049491673707962, 0.03514278680086136, 0.03442328795790672, 0.02839958481490612, -0.03048734925687313, 0.12075191736221313, -0.0022658940870314837, 0.0566244013607502, 0.011851705610752106, 0.0430518314242363, 0.02685014344751835, 0.1231687143445015, -0.01472074817866087, -0.03186943382024765]'), +('Patient safety is a core tenet of nursing care and a primary responsibility of every healthcare provider. A foundational principle is the creation of a "culture of safety," where the focus is on preventing errors through system-wide vigilance rather than placing blame on individuals. For nursing students, this begins with consistently performing basic safety checks. One of the most critical routines is accurate patient identification. Before any procedure, intervention, or medication administration, the patient must be identified using at least two distinct identifiers, such as their full name and date of birth, which are cross-referenced with their wristband and medical record. This simple step prevents a vast number of potential errors. Medication administration is a high-risk activity that demands meticulous attention to detail. Nurses adhere to the "Rights of Medication Administration," which minimally include the right patient, right drug, right dose, right route, and right time. Each step requires verification, from checking the physician''s order to confirming patient allergies and monitoring for adverse reactions after the dose is given. Similarly, preventing healthcare-associated infections (HAIs) is paramount. The single most effective measure to combat the spread of infection is proper hand hygiene, performed before and after every patient contact, after contact with contaminated surfaces, and before performing any aseptic procedure. Another major area of concern is fall prevention. A fall can significantly worsen a patient''s condition and extend their hospital stay. Nurses conduct fall risk assessments on all patients upon admission and regularly thereafter. Interventions are then tailored to the patient''s specific risk level and may include keeping the bed in the lowest position, ensuring call lights are within reach, using bed alarms for high-risk individuals, and maintaining a clutter-free environment. Reporting any errors or near-misses is also a vital component of safety culture, as it allows the institution to identify and correct system vulnerabilities to protect future patients.', 'What is the fundamental principle behind a ''culture of safety'' in healthcare?', '[0.03909296914935112, 0.07189465314149857, -0.09151638299226761, -0.06634499877691269, 0.05486152321100235, 0.06874444335699081, 0.03784872964024544, 0.01938733085989952, -0.0019914351869374514, 0.015966182574629784, 0.025831544771790504, -0.0028013265691697598, 0.04897596314549446, -0.016475537791848183, -0.08720755577087402, -0.11995791643857956, 0.018464304506778717, -0.004315619822591543, -0.11087442934513092, 0.06483805179595947, -0.03812863677740097, 0.013913610018789768, 0.10888040065765381, 0.07264241576194763, -0.12658029794692993, -0.0013763750903308392, 0.04084673896431923, 0.0020857001654803753, -0.0047505139373242855, 0.005105968564748764, 0.020072029903531075, -0.01321139931678772, 0.07672964036464691, -0.043935030698776245, -0.0421973280608654, 0.051053404808044434, -0.0008204071200452745, -0.017970630899071693, -0.0200542900711298, 0.04488539323210716, -0.06773220002651215, -0.06615383923053741, -0.016937656328082085, 0.0009250663570128381, 0.03183188661932945, 0.018198316916823387, -0.006047662813216448, -0.0006737714866176248, 0.0010162084363400936, -0.029852835461497307, -0.039876051247119904, 0.036027777940034866, 0.02456394024193287, 0.024437420070171356, 0.04617602750658989, -0.06737835705280304, 0.027029911056160927, -0.005454154685139656, -0.12608949840068817, 0.05159713327884674, -0.005786257330328226, -0.0350193977355957, -0.033763401210308075, 0.041887711733579636, 0.025421537458896637, 0.02067977376282215, -0.04180847108364105, 0.0027792134787887335, -0.03185433894395828, -0.002226341748610139, -0.06458701193332672, -0.0668429285287857, 0.0846264585852623, 0.0686139166355133, -0.012836004607379436, -0.009802870452404022, -0.007888775318861008, -0.05471757799386978, -0.03644026815891266, -0.0036852017510682344, 0.08462667465209961, -0.014444644562900066, 0.09424294531345367, 0.08803164213895798, 0.046035878360271454, 0.04581853374838829, -0.020973166450858116, -0.033711161464452744, 0.027291974052786827, -0.012304989621043205, -0.07522367686033249, -0.011064667254686356, 0.05986538529396057, -0.01605973206460476, 0.116946280002594, -0.0010770048247650266, -0.0730586051940918, 0.02295605093240738, 0.031715601682662964, -0.034364309161901474, 0.03902886435389519, -0.017208460718393326, 0.00860139075666666, 0.10298286378383636, 0.037609491497278214, -0.057645704597234726, -0.015929706394672394, -0.02360263280570507, -0.0285339318215847, 0.0629727691411972, 0.003021016949787736, 0.087124302983284, 0.00795702263712883, -0.01354309543967247, 0.002458662260323763, -0.03939959034323692, -0.03217369690537453, -0.10260570049285889, 0.007391337770968676, -0.025189518928527832, 0.03414218872785568, -0.04559757933020592, -0.015696009621024132, -0.08297539502382278, 0.006002064794301987, 0.028301704674959183, 0.018643774092197418, -7.000274570658116e-33, -0.04048902168869972, 0.002200564369559288, 0.0037791840732097626, -0.01049929391592741, -0.027864564210176468, -0.01933852583169937, -0.03694460168480873, -0.08295509219169617, 0.07472123950719833, 0.010985058732330799, 0.033878810703754425, 0.022220121696591377, 0.04437308758497238, -0.06260282546281815, 0.054337307810783386, 0.009663820266723633, -0.11665817350149155, 0.04504362493753433, -0.04842890053987503, 0.03814496099948883, 0.021423274651169777, -0.03731469810009003, 0.02568627893924713, 0.01919211819767952, -0.05846456065773964, 0.011368520557880402, -0.024438288062810898, 0.033979468047618866, 0.04479467496275902, 0.017259079962968826, -0.05397394299507141, 0.01039497833698988, -0.015019269660115242, -0.06128928065299988, 0.06261171400547028, 0.03897601366043091, -0.11413980275392532, -0.0037659357767552137, -0.03077639266848564, -0.027462130412459373, -0.018435731530189514, -0.06045391783118248, -0.009020961821079254, 0.04907518997788429, 0.09360837936401367, 0.11035540699958801, -0.050601471215486526, -0.08984795212745667, -0.1152171716094017, -0.05186781287193298, -0.06796512752771378, 0.025908008217811584, 0.1003468707203865, -0.07133276760578156, 0.004930178634822369, 0.029237067326903343, 0.03965812548995018, 0.04495815187692642, -0.04493909701704979, -0.056286826729774475, -0.04836491122841835, 0.06391430646181107, 0.00038495182525366545, 0.038291677832603455, -0.014844926074147224, -0.011694292537868023, -0.009966217912733555, -0.034320540726184845, 0.05736155062913895, -0.012818647548556328, -0.030535653233528137, 0.07376319169998169, -0.08260297030210495, 0.026875630021095276, -0.07961773872375488, 0.01620442420244217, 0.002777002053335309, -0.002751871244981885, 0.0034746702294796705, -0.10629044473171234, -0.02104169689118862, 0.03793107718229294, -0.023827150464057922, 0.08567643910646439, 0.004632114432752132, -0.03244708478450775, 0.016777334734797478, 0.09225815534591675, -0.05813293904066086, 0.025370607152581215, -0.024710603058338165, -0.0644751489162445, 0.07229489833116531, 0.08784352242946625, -0.029402516782283783, 2.100155104910392e-33, 0.0827803760766983, -0.06727703660726547, -0.0467611700296402, 0.043778520077466965, -0.01641053706407547, -0.03202195093035698, -0.03979448601603508, 0.031534381210803986, 0.041584406048059464, 0.06009615585207939, 0.0002829489822033793, -0.04125199466943741, -0.008503892458975315, 0.03862271085381508, -0.015977265313267708, -0.06929392367601395, 0.019905464723706245, 0.042947422713041306, -0.017051005735993385, -0.06060006842017174, 0.09547949582338333, 0.05492997542023659, -0.11626281589269638, 0.08391071110963821, -0.0814390629529953, 0.06963592022657394, -0.10776255279779434, -0.06483586877584457, -0.03627286106348038, -0.04657047614455223, -0.05200187861919403, 0.013319523073732853, 0.043206796050071716, 0.07525569200515747, -0.01258064340800047, 0.0030989227816462517, 0.020225442945957184, -0.028375128284096718, 0.005097746849060059, -0.004497922491282225, -0.022805338725447655, 0.022441832348704338, -0.06872067600488663, 0.0029908569995313883, 0.010730667039752007, 0.017285078763961792, -0.00940341129899025, -0.03929700329899788, -0.06593553721904755, -0.047933079302310944, 0.01983432099223137, -0.054972726851701736, 0.0438656322658062, -0.05251632258296013, 0.01684834063053131, -0.001742663560435176, 0.05305194854736328, -0.08490242809057236, -0.05553605407476425, 0.039581142365932465, 0.03644469007849693, -0.04734077677130699, -0.07043195515871048, 0.03272293880581856, -0.07250804454088211, 0.07339673489332199, -0.018128616735339165, 0.0038879411295056343, 0.05460154637694359, -0.024568671360611916, 0.0013490287819877267, 0.040270835161209106, -0.05780872702598572, -0.016101881861686707, -0.04959970340132713, 0.012624398805201054, -0.00036586838541552424, -0.07390427589416504, -0.03739244490861893, 0.0050348020158708096, -0.005744969937950373, -0.10983415693044662, -0.02155367098748684, 0.0815640389919281, -0.00515032047405839, 0.04642195999622345, -0.013234213925898075, -0.0482870414853096, -0.05521974340081215, -0.080465167760849, -0.10017356276512146, -0.04105326905846596, -0.1498749703168869, -0.04593740031123161, -0.05820058658719063, -2.2975653379830874e-08, -0.02724231407046318, 0.009575300849974155, 0.02929658256471157, -0.015761831775307655, 0.0025904153008013964, -0.044560957700014114, 0.0054206824861466885, -0.027893681079149246, -0.0034239781089127064, 0.14015628397464752, -0.019576989114284515, 0.05280439928174019, 0.04016115888953209, 0.05670543387532234, -0.02668059431016445, 0.052033908665180206, -0.02662160061299801, 0.1316411942243576, -0.04767666757106781, 0.01948900707066059, 0.05598173663020134, -0.004288776777684689, 0.014323565177619457, -0.03746850788593292, 0.03295299410820007, 0.027319172397255898, -0.008312270045280457, 0.04351363331079483, 0.0051850127056241035, 0.057701658457517624, 0.022197917103767395, -0.02459939755499363, -0.04214910417795181, 0.07418575882911682, -0.07921809703111649, 0.0005412452737800777, 0.06277183443307877, 0.004084710031747818, 0.09654994308948517, -0.06126249209046364, 0.024051200598478317, 0.004626611713320017, 0.04644851014018059, 0.06403839588165283, -0.011570046655833721, 0.01902230642735958, -0.0054871574975550175, 0.1457512527704239, -0.04391343146562576, 0.04892157390713692, 0.029269689694046974, -0.005343672353774309, 0.04673561453819275, 0.07815174013376236, -0.025974977761507034, 0.0004817293374799192, 0.06354448199272156, 0.015794772654771805, 0.057386692613363266, 0.03348510339856148, -0.015302550978958607, 0.05631602182984352, 0.09246417880058289, -0.015176577493548393]'), +('Patient safety is a core tenet of nursing care and a primary responsibility of every healthcare provider. A foundational principle is the creation of a "culture of safety," where the focus is on preventing errors through system-wide vigilance rather than placing blame on individuals. For nursing students, this begins with consistently performing basic safety checks. One of the most critical routines is accurate patient identification. Before any procedure, intervention, or medication administration, the patient must be identified using at least two distinct identifiers, such as their full name and date of birth, which are cross-referenced with their wristband and medical record. This simple step prevents a vast number of potential errors. Medication administration is a high-risk activity that demands meticulous attention to detail. Nurses adhere to the "Rights of Medication Administration," which minimally include the right patient, right drug, right dose, right route, and right time. Each step requires verification, from checking the physician''s order to confirming patient allergies and monitoring for adverse reactions after the dose is given. Similarly, preventing healthcare-associated infections (HAIs) is paramount. The single most effective measure to combat the spread of infection is proper hand hygiene, performed before and after every patient contact, after contact with contaminated surfaces, and before performing any aseptic procedure. Another major area of concern is fall prevention. A fall can significantly worsen a patient''s condition and extend their hospital stay. Nurses conduct fall risk assessments on all patients upon admission and regularly thereafter. Interventions are then tailored to the patient''s specific risk level and may include keeping the bed in the lowest position, ensuring call lights are within reach, using bed alarms for high-risk individuals, and maintaining a clutter-free environment. Reporting any errors or near-misses is also a vital component of safety culture, as it allows the institution to identify and correct system vulnerabilities to protect future patients.', 'According to the text, what is a crucial first step in safe medication administration?', '[-0.0021122577600181103, 0.025763053447008133, -0.039147742092609406, -0.03057611733675003, -0.010059178806841373, 0.03954236954450607, -0.023671021685004234, 0.11140260845422745, -0.037573929876089096, 0.006659392267465591, -0.006736932788044214, 0.08067435771226883, 0.032693590968847275, 0.008079865016043186, -0.05477342754602432, -0.009676326997578144, -0.0036679862532764673, 0.0001224220759468153, -0.03713439032435417, 0.010927394963800907, 0.025525489822030067, 0.04063760116696358, 0.06072906404733658, 0.05023238807916641, -0.09182077646255493, 0.10140572488307953, -0.011154291220009327, 0.02131044492125511, 0.07247862219810486, -0.010234661400318146, 0.06500852853059769, -0.01653176359832287, 0.10830216854810715, -0.00696662999689579, -0.07123210281133652, 0.1317034214735031, -0.02170102298259735, -0.027175990864634514, 0.04023187980055809, 0.05017663165926933, -0.019098617136478424, -0.09526388347148895, -0.04947679489850998, 0.03499164059758186, 0.04038769006729126, -0.059275854378938675, 0.0014443014515563846, 0.011983782052993774, 0.007357539609074593, 0.004921083338558674, -0.05538952723145485, -0.03771593049168587, -0.041434481739997864, 0.08197923004627228, -0.030794069170951843, 0.06619782745838165, -0.02427806332707405, -0.01663772016763687, -0.06431964784860611, 0.03547960892319679, -0.04589478299021721, 0.023539377376437187, -0.012653643265366554, 0.03330611810088158, 0.015936492010951042, 0.02020774781703949, 0.04462386667728424, -0.04605910927057266, 0.07783864438533783, 0.05963126942515373, -0.039893895387649536, -0.0954027771949768, 0.04291486740112305, -0.003764557186514139, -0.04417051002383232, -0.04650713875889778, 0.03779248148202896, -0.05632505938410759, 0.00021409969485830516, -0.05175003036856651, 0.06226852536201477, 0.036354344338178635, 0.05344707891345024, 0.12179578840732574, 0.020876558497548103, 0.049504056572914124, -0.0024793599732220173, -0.07244980335235596, 0.021493110805749893, 0.021479111164808273, 0.08967752009630203, 0.005578402895480394, 0.019375968724489212, -0.005911241751164198, 0.03618200495839119, -0.010818621143698692, -0.06861267983913422, -0.016072800382971764, -0.0263264961540699, -0.013867292553186417, 0.013298697769641876, -0.05199344456195831, 0.021235940977931023, 0.01692083291709423, -0.04445282742381096, -0.08777903765439987, 0.05110662430524826, -0.05873842164874077, -0.019261835142970085, 0.03929660841822624, -0.04042835533618927, -0.018258346244692802, 0.02052675187587738, 0.054958123713731766, -0.020625922828912735, 0.03886587545275688, 0.011788985691964626, 0.009403428994119167, 0.056709617376327515, 0.023345835506916046, -0.00041037643677555025, -0.012867165729403496, 0.06691588461399078, -0.06689556688070297, -0.03703964501619339, 0.042470768094062805, 0.051300209015607834, -4.8341723959566706e-33, 0.04974682256579399, 0.0606611892580986, 0.007454355247318745, 0.090721495449543, -0.07818190008401871, 0.07763337343931198, -0.030770935118198395, -0.07503096014261246, 0.0012910692021250725, 0.051681067794561386, 0.020996684208512306, -0.056456558406353, -0.013292082585394382, 0.07706667482852936, -0.028976937755942345, -0.06248260661959648, -0.08838561922311783, 0.019523005932569504, -0.0074069323018193245, -0.02199486643075943, 0.07167929410934448, -0.06588836014270782, -0.0035764749627560377, -0.016404811292886734, -0.02762444131076336, 0.056346695870161057, 0.01991305686533451, 0.05587833747267723, 0.016318416222929955, -0.009202677756547928, -0.09447219222784042, -0.00753172067925334, -0.07259538769721985, -0.047281600534915924, 0.008316236548125744, 0.06670628488063812, -0.07186241447925568, -0.06286042928695679, -0.0069045149721205235, -0.006450312677770853, -0.014996418729424477, 0.042903196066617966, 0.060296107083559036, 0.024071834981441498, 0.13183648884296417, 0.07486022263765335, -0.16560640931129456, 0.021359004080295563, -0.006315391976386309, 0.040543198585510254, -0.03698575496673584, -0.07818035036325455, 0.04582680016756058, -0.022192947566509247, -0.07644718140363693, 0.0439642034471035, -0.045102715492248535, -0.05506119504570961, 0.009002448990941048, -0.004248717799782753, 0.03256446123123169, 0.043537434190511703, -0.03220127150416374, 0.07167468219995499, 0.013708592392504215, -0.016240278258919716, -0.027373190969228745, -0.09479033946990967, -0.002935713389888406, -0.04862460121512413, -0.11356005817651749, 0.016202129423618317, 0.006674107629805803, 0.053363136947155, -0.04492414370179176, -0.012541518546640873, -0.01997806318104267, -0.0315217562019825, 0.004426299128681421, -0.057505249977111816, -0.020513635128736496, -0.06041692942380905, -0.008723204024136066, 0.13906939327716827, -0.016340192407369614, -0.03597075864672661, 0.03151876851916313, 0.03704461827874184, -0.0940140038728714, -0.013961796648800373, 0.012269166298210621, -0.05070558562874794, 0.036683086305856705, 0.09008210897445679, 0.001486866269260645, 1.1615981708856449e-33, 0.048140302300453186, -0.027888981625437737, 0.024575769901275635, -0.009696862660348415, -0.04638339579105377, 0.0502738319337368, -0.023394685238599777, -0.07109662890434265, 0.14881831407546997, -0.021663038060069084, -0.04020543769001961, 0.035520315170288086, 0.033906687051057816, -0.08412250876426697, -0.060379136353731155, -0.012263055890798569, 0.007114794105291367, -0.021453093737363815, -0.046624455600976944, 0.0006743413978256285, 0.029772035777568817, -0.017705200240015984, -0.048777174204587936, 0.08939407020807266, -0.008580387569963932, -0.020939700305461884, 0.031910575926303864, 0.003716881852596998, -0.06227070465683937, 0.01576998084783554, 0.03962042182683945, 0.0055990563705563545, -0.0390155129134655, 0.016767611727118492, -0.1050984263420105, 0.03085874766111374, 0.019829697906970978, -0.08669827878475189, 0.012114922516047955, -0.05188225954771042, 0.08291976898908615, 0.06140585616230965, -0.06395269930362701, -0.00889183022081852, -0.011816990561783314, 0.03193560242652893, 0.00406739953905344, 0.026883266866207123, -0.12117742747068405, -0.009060552343726158, -0.01360730268061161, -0.021906761452555656, 0.01229566428810358, -0.008927581831812859, 0.04864721745252609, 0.008911002427339554, 0.06496044248342514, -0.057740721851587296, 0.012264659628272057, 0.004915827885270119, -0.033954814076423645, 0.018317662179470062, -0.04196589067578316, 0.050747212022542953, -0.05647304281592369, 0.001473987358622253, 0.0015895048854872584, 0.06298210471868515, 0.09164132177829742, -0.057383690029382706, -0.031798429787158966, 0.017845364287495613, 0.06113991141319275, -0.036554768681526184, -0.018093407154083252, -0.07637035846710205, -0.03658417612314224, -0.11750758439302444, -0.001328574726358056, -0.08772189170122147, 0.004914425779134035, -0.06946758925914764, -0.05738850310444832, 0.01684187538921833, -0.02664841152727604, -0.03949872776865959, 0.05010741204023361, -0.13030226528644562, -0.0337059386074543, -0.06116345152258873, -0.10539235174655914, -0.04550708457827568, -0.05650072917342186, 0.06398677080869675, -0.015566005371510983, -2.077128868904765e-08, -0.01548126619309187, -0.048885028809309006, 0.014898741617798805, 0.011083935387432575, 0.025057977065443993, 0.015294009819626808, -0.03546745330095291, 0.015948042273521423, -0.017624348402023315, -0.010032307356595993, 0.06697547435760498, 0.07114791870117188, 0.0065263258293271065, -0.015367976389825344, -0.011562497355043888, 0.0726914256811142, -0.014868256635963917, 0.07268217206001282, -0.04978415369987488, -0.04259807989001274, -0.05908118560910225, -0.030255191028118134, 0.022181963548064232, -0.030137216672301292, 0.15187223255634308, 0.014058190397918224, 0.11419660598039627, 0.07658064365386963, 0.014234294183552265, 0.05525919422507286, 0.02258439175784588, -0.03669748827815056, 0.05317869037389755, 0.03762466832995415, -0.07457653433084488, 0.06986016035079956, 0.03277630731463432, 0.03706955909729004, 0.11944709718227386, -0.061019524931907654, -0.025017086416482925, 0.06943470239639282, 0.004461243748664856, 0.016289472579956055, -0.05092215538024902, -0.04814165458083153, -0.007883249782025814, 0.07148008793592453, 0.013781075365841389, -0.09646261483430862, 0.0026440154761075974, 0.03998695686459541, 0.06314513832330704, 0.036788541823625565, -0.05077040195465088, 0.003274346934631467, -0.005661266855895519, -0.05166298896074295, 0.053899142891168594, -0.02736244536936283, -0.030382761731743813, 0.04521223530173302, 0.08595987409353256, -0.04662087559700012]'), +('Patient safety is a core tenet of nursing care and a primary responsibility of every healthcare provider. A foundational principle is the creation of a "culture of safety," where the focus is on preventing errors through system-wide vigilance rather than placing blame on individuals. For nursing students, this begins with consistently performing basic safety checks. One of the most critical routines is accurate patient identification. Before any procedure, intervention, or medication administration, the patient must be identified using at least two distinct identifiers, such as their full name and date of birth, which are cross-referenced with their wristband and medical record. This simple step prevents a vast number of potential errors. Medication administration is a high-risk activity that demands meticulous attention to detail. Nurses adhere to the "Rights of Medication Administration," which minimally include the right patient, right drug, right dose, right route, and right time. Each step requires verification, from checking the physician''s order to confirming patient allergies and monitoring for adverse reactions after the dose is given. Similarly, preventing healthcare-associated infections (HAIs) is paramount. The single most effective measure to combat the spread of infection is proper hand hygiene, performed before and after every patient contact, after contact with contaminated surfaces, and before performing any aseptic procedure. Another major area of concern is fall prevention. A fall can significantly worsen a patient''s condition and extend their hospital stay. Nurses conduct fall risk assessments on all patients upon admission and regularly thereafter. Interventions are then tailored to the patient''s specific risk level and may include keeping the bed in the lowest position, ensuring call lights are within reach, using bed alarms for high-risk individuals, and maintaining a clutter-free environment. Reporting any errors or near-misses is also a vital component of safety culture, as it allows the institution to identify and correct system vulnerabilities to protect future patients.', 'What is described as the single most effective way to prevent the spread of infection?', '[-0.003047361271455884, 0.08526775240898132, 0.028288135305047035, -0.014276891946792603, -0.014475533738732338, 0.02848929539322853, -0.017749981954693794, 0.08907083421945572, -0.0002521753776818514, 0.022381240501999855, 0.07737704366445541, 0.04662920534610748, 0.03467664122581482, 0.09691908210515976, -0.06381624937057495, -0.01091793179512024, -0.007769422139972448, 0.045367274433374405, 0.0059195151552557945, -0.03747423738241196, -0.00782163068652153, 0.022012004628777504, 0.007711488753557205, -0.030706748366355896, -0.074575275182724, 0.01253460068255663, -0.013177631422877312, -0.008957025595009327, 0.014606835320591927, -0.030836086720228195, 0.040681518614292145, -0.018521860241889954, -0.013409415259957314, -0.03145013749599457, -0.13546881079673767, 0.029606249183416367, -0.005294241476804018, -0.01081217359751463, 0.07858732342720032, 0.05738060176372528, -0.00838699284940958, -0.026731252670288086, -0.0047394754365086555, -0.07452195137739182, 0.012691738083958626, 0.010384817607700825, 0.04286399483680725, 0.08572091907262802, 0.06639105826616287, -0.046341098845005035, -0.008128865621984005, 0.0275955218821764, -0.062254615128040314, 0.11033062636852264, -0.04656129330396652, -0.07916167378425598, -0.07467611879110336, -0.04621472209692001, -0.013388962484896183, -0.02017110399901867, -0.030499916523694992, 0.0052165980450809, -0.0037700561806559563, 0.045507196336984634, -0.10459764301776886, -0.06900625675916672, -0.02264471724629402, 0.08274952322244644, 0.034161973744630814, 0.14483022689819336, 0.004133258014917374, 0.030911091715097427, -0.06814031302928925, 0.04451502114534378, 0.03292408585548401, -0.013593041338026524, 0.0057967049069702625, -0.14475584030151367, 0.01886361464858055, 0.08483231067657471, 0.020001430064439774, 0.013361875899136066, 0.10037042945623398, 0.09992408752441406, 0.06097300723195076, 0.06875494867563248, 0.07230693846940994, -0.04188675060868263, -0.029147028923034668, -0.02340065874159336, 0.0004161002580076456, 0.014511511661112309, 0.006823316216468811, 0.02277766354382038, -0.008964752778410912, 0.014397122897207737, 0.0006661364459432662, -0.053485531359910965, -0.021239524707198143, 0.030086880549788475, -0.07918134331703186, -0.14792700111865997, -0.008532236330211163, -0.051352012902498245, -0.01514420285820961, -0.06510362774133682, 0.03962451592087746, -0.05555342510342598, 0.005668776575475931, 0.004092492163181305, 0.007428829092532396, 0.024795088917016983, -0.09407567977905273, -0.018924597650766373, -0.04464685544371605, -0.007301023229956627, 0.11865866929292679, 0.0006802644347772002, 0.03236209228634834, -0.034303005784749985, 0.008995396085083485, -0.021743416786193848, 0.05110698193311691, -0.031747639179229736, 0.03548451513051987, -0.0003742707194760442, 0.07061295211315155, -3.7861181631528275e-33, -0.05681437999010086, -0.037636756896972656, 0.023427803069353104, 0.03450183942914009, 0.010763443075120449, 0.04080047458410263, -0.012673994526267052, -0.020412858575582504, 0.08061385899782181, 0.012847598642110825, -0.009865778498351574, -0.014908138662576675, 0.013885938562452793, 0.0392896868288517, 0.009736457839608192, -0.026618201285600662, -0.0685734897851944, 0.06162191927433014, -0.051779843866825104, 0.011430639773607254, 0.06843382865190506, -0.06428362429141998, 0.0356828048825264, -0.01447890792042017, 0.06058363616466522, -0.028986455872654915, -0.012856506742537022, -0.02823648601770401, 0.04469844698905945, 0.010388161055743694, 0.019588828086853027, 0.017022408545017242, -0.024022497236728668, 0.016941014677286148, -0.047989241778850555, 0.07002011686563492, -0.12572617828845978, -0.07776861637830734, 0.022015824913978577, -0.0029176967218518257, -0.07310578972101212, 0.017798999324440956, 0.007585329003632069, 0.01507691852748394, 0.1341698318719864, 0.04705597832798958, -0.16314458847045898, 0.00629518972709775, -0.04263516515493393, -0.02763000875711441, 0.07114756852388382, 0.03699639067053795, 0.007932813838124275, -0.0706811249256134, -0.04146305471658707, -0.06819739192724228, 0.015459002926945686, -0.021775947883725166, 0.005073974374681711, 0.07002957910299301, 0.012239496223628521, -0.0331832580268383, -0.05155499652028084, 0.04333971440792084, 0.0194818414747715, -0.03153299540281296, 0.02964177541434765, -0.04850681498646736, -0.030599527060985565, -0.0669531524181366, -0.025546330958604813, 0.03447427228093147, -0.04636355862021446, 0.002481405856087804, -0.14034613966941833, -0.0669243261218071, -0.004125908017158508, 0.037813931703567505, 0.085207998752594, -0.02236107923090458, -0.06095966696739197, -0.044807709753513336, -0.004580496810376644, 0.08177713304758072, -0.021491430699825287, 0.062242865562438965, -0.037673406302928925, 0.08443334698677063, 0.0012485694605857134, -0.005372113082557917, 0.013504022732377052, 0.020830292254686356, -0.020451877266168594, -0.004310354590415955, -0.016008803620934486, 1.4511219703156935e-33, 0.053716834634542465, -0.02645597793161869, 0.024144796654582024, 0.06669092178344727, -0.04621126875281334, 0.1012466549873352, 0.041297055780887604, -0.004815338645130396, 0.05462212115526199, 0.024745287373661995, -0.055301483720541, 0.019814059138298035, 0.02446427196264267, -0.017754115164279938, -0.04643440246582031, 0.017992211505770683, 0.05095106363296509, 0.007847407832741737, -0.09023024886846542, -0.0118807852268219, -0.06382890045642853, 0.05505242198705673, 0.04130833223462105, -0.006595141254365444, 0.03169221431016922, -0.021319400519132614, -0.07899672538042068, 0.045619163662195206, -0.05600453540682793, 0.0006515303975902498, 0.0062512787990272045, 0.020696820691227913, -0.0034714345820248127, -0.11775584518909454, -0.042128968983888626, 0.12563328444957733, 0.07765130698680878, -0.006608374882489443, 0.03143012523651123, 0.02820340357720852, 0.0396631620824337, -0.028294449672102928, -0.025440111756324768, 0.0750422477722168, 0.010369379073381424, 0.11226393282413483, -0.02788352221250534, 0.024794936180114746, -0.01315400656312704, 0.028538530692458153, -0.020869845524430275, -0.035223424434661865, -0.025469375774264336, -0.020755164325237274, -0.015227500349283218, -0.04573984444141388, 0.008078666403889656, -0.0718718096613884, -0.05611012130975723, 0.0240633524954319, -0.03686922416090965, -0.06930185109376907, -0.0019524721428751945, -0.008341899141669273, -0.055192336440086365, 0.027334213256835938, -0.003660102840512991, 0.10038101673126221, 0.03605596348643303, -0.07799851894378662, -0.02290644869208336, 0.040095485746860504, 0.005315783899277449, -0.07510379701852798, -0.0993804857134819, -0.025417059659957886, -0.007463710382580757, -0.08390367776155472, 0.021421054378151894, 0.06357047706842422, -0.07460318505764008, -0.062309909611940384, -0.011197966523468494, -0.041888996958732605, -0.00288778985850513, -0.03960973396897316, 0.05016214773058891, -0.09165210276842117, -0.006450067739933729, 0.013857977464795113, -0.10645810514688492, -0.012704221531748772, -0.023496851325035095, -0.023644382134079933, -0.032102521508932114, -2.0845003945169083e-08, 0.02635812759399414, -0.04427457973361015, 0.013598453253507614, -0.01131720282137394, -0.0211865846067667, 0.009913910180330276, -0.05109303072094917, 0.05386435613036156, 0.06769377738237381, -0.04415496066212654, -0.03135010227560997, 0.10459892451763153, 0.056656364351511, 0.06050148233771324, 0.07671693712472916, -0.01584019884467125, -0.0367850586771965, -0.00599606242030859, -0.09040340781211853, -0.10185782611370087, -0.024282056838274002, -0.04031507298350334, -0.025274083018302917, -0.0148231852799654, 0.08983290195465088, 0.00298708351328969, 0.09114383906126022, 0.008129136636853218, 0.0022409288212656975, -0.012431751005351543, -0.0036018765531480312, -0.04607212916016579, -0.032877951860427856, 0.048929084092378616, -0.06133713573217392, 0.06716052442789078, 0.06713087856769562, 0.01061334926635027, 0.0730520486831665, -0.010222533717751503, 0.04409404098987579, -0.027299726381897926, -0.0013775852276012301, 0.04655580595135689, -0.034043654799461365, 0.044454388320446014, -0.02558095194399357, 0.09610877186059952, -0.0403096005320549, -0.023304713889956474, 0.005794554948806763, -0.0340537391602993, 0.05002305284142494, 0.07453586906194687, -0.07641453295946121, -0.0007675050874240696, 0.004091559909284115, -0.056358080357313156, 0.10991934686899185, 0.020637692883610725, -0.08029326051473618, 0.023777127265930176, 0.06471668183803558, 0.09873315691947937]'), +('Patient safety is a core tenet of nursing care and a primary responsibility of every healthcare provider. A foundational principle is the creation of a "culture of safety," where the focus is on preventing errors through system-wide vigilance rather than placing blame on individuals. For nursing students, this begins with consistently performing basic safety checks. One of the most critical routines is accurate patient identification. Before any procedure, intervention, or medication administration, the patient must be identified using at least two distinct identifiers, such as their full name and date of birth, which are cross-referenced with their wristband and medical record. This simple step prevents a vast number of potential errors. Medication administration is a high-risk activity that demands meticulous attention to detail. Nurses adhere to the "Rights of Medication Administration," which minimally include the right patient, right drug, right dose, right route, and right time. Each step requires verification, from checking the physician''s order to confirming patient allergies and monitoring for adverse reactions after the dose is given. Similarly, preventing healthcare-associated infections (HAIs) is paramount. The single most effective measure to combat the spread of infection is proper hand hygiene, performed before and after every patient contact, after contact with contaminated surfaces, and before performing any aseptic procedure. Another major area of concern is fall prevention. A fall can significantly worsen a patient''s condition and extend their hospital stay. Nurses conduct fall risk assessments on all patients upon admission and regularly thereafter. Interventions are then tailored to the patient''s specific risk level and may include keeping the bed in the lowest position, ensuring call lights are within reach, using bed alarms for high-risk individuals, and maintaining a clutter-free environment. Reporting any errors or near-misses is also a vital component of safety culture, as it allows the institution to identify and correct system vulnerabilities to protect future patients.', 'Name two environmental strategies to help prevent patient falls.', '[0.0036098260898143053, 0.06729045510292053, 0.06691961735486984, 0.024325693026185036, 0.00976217444986105, 0.08086010813713074, 0.000973694899585098, 0.08324496448040009, -0.04131978005170822, 0.008983205072581768, 0.027735520154237747, -0.007782116066664457, -0.016109280288219452, 0.05952439829707146, -0.05539475381374359, -0.01918792724609375, -0.033078067004680634, 0.11974061280488968, 0.03234732151031494, 0.050819557160139084, -0.01392750721424818, 0.029936082661151886, 0.047351446002721786, 0.037487179040908813, -0.19855807721614838, 0.04531124606728554, -0.0397765189409256, 0.008276956155896187, 0.04231244698166847, -0.01682167872786522, 0.09108781814575195, 0.009514509700238705, 0.007333354093134403, -0.015271997079253197, -0.06401851773262024, 0.05626610666513443, 0.03949490562081337, 0.016881396993994713, -0.061176057904958725, 0.07011668384075165, -0.06383953988552094, -0.06932920217514038, -0.02482876554131508, -0.03535867854952812, 0.09333555400371552, 0.030676547437906265, 0.0563010610640049, 0.004282563924789429, -0.003079867223277688, -0.020443145185709, 0.02263580821454525, 0.06084904819726944, -0.028413686901330948, 0.045726388692855835, -0.038378942757844925, -0.06193353608250618, -0.0686975046992302, 0.024551941081881523, -0.030800674110651016, -0.010206835344433784, 0.11428701877593994, -0.006256406661123037, -0.07556931674480438, 0.05149565637111664, -0.009997337125241756, 0.040078990161418915, -0.040212482213974, 0.039055101573467255, 0.05265432223677635, 0.07044944912195206, 0.021265925839543343, -0.038098931312561035, 0.024998251348733902, -0.010746913030743599, -0.09949439764022827, -0.019297605380415916, 0.013160609640181065, -0.08788303285837173, 0.008610118180513382, 0.04726138710975647, 0.04786257818341255, -0.008390326052904129, 0.04871383681893349, 0.04204928129911423, -0.054815784096717834, 0.10597649961709976, 0.003097027074545622, -0.03666200116276741, -0.053434666246175766, -0.08325733989477158, 0.016857275739312172, 0.008305391296744347, 0.008534292690455914, 0.013843577355146408, -0.012718340381979942, 0.11537519097328186, -0.06749796867370605, -0.13327530026435852, 0.00580746540799737, -0.03184078633785248, 0.025407034903764725, -0.05312417447566986, 0.024827279150485992, 0.06695582717657089, 0.06413166224956512, -0.14274929463863373, 0.004392825532704592, -0.06501015275716782, 0.06534237414598465, 0.11251115798950195, -0.022193551063537598, 0.017509840428829193, -0.0062478347681462765, 0.0525936633348465, -0.04588044434785843, 0.056467197835445404, -0.022437328472733498, -0.014682763256132603, 0.04055904597043991, 0.011274171061813831, 0.031269144266843796, 0.03823433816432953, 0.049666184931993484, -0.04432489350438118, 0.04886208102107048, -0.05605772137641907, -0.034419797360897064, -2.71342244634888e-33, 0.06019860506057739, -0.06069193407893181, 0.03765518590807915, 0.010983728803694248, 0.06596265733242035, -0.016849681735038757, -0.07175588607788086, -0.0715414434671402, 0.014360837638378143, 0.0027231958229094744, -0.02891061268746853, -0.04613287001848221, 0.06480175256729126, 0.00461299205198884, 0.015545187518000603, -0.07912803441286087, -0.07261203974485397, 0.012868691235780716, -0.06269330531358719, 0.02833872102200985, 0.0012862493749707937, -0.07440818101167679, 0.04877607896924019, 0.12967878580093384, 0.04446999356150627, -0.010781918652355671, -0.02236136421561241, 0.006748640909790993, 0.03585139662027359, 0.0017396174371242523, -0.029570885002613068, -0.017260193824768066, -0.03438565507531166, -0.05241570994257927, -0.0019247954478487372, 0.029377564787864685, -0.04243338108062744, -0.0008463453268632293, -0.04503078758716583, -0.05908762291073799, -0.09156559407711029, 0.045478455722332, 0.044977378100156784, 0.027459023520350456, 0.14149931073188782, -0.08280391991138458, -0.012485155835747719, -0.014142305590212345, -0.029289843514561653, -0.015623563900589943, 0.03549507260322571, 0.039154067635536194, -0.008405285887420177, -0.05488603562116623, 0.011863719671964645, -0.0018395662773400545, 0.018985074013471603, 0.011877160519361496, -0.033983733505010605, 0.06127190962433815, -0.021882319822907448, -0.018933584913611412, -0.03855225816369057, -0.050129976123571396, 0.10392332822084427, -0.062422189861536026, 0.03164839744567871, -0.047721102833747864, -0.057004738599061966, -0.06811781227588654, -0.08053478598594666, 0.06816940009593964, 0.007469382602721453, 0.03238295763731003, -0.10741808265447617, -0.021618260070681572, -0.007311435882002115, 0.003930211532860994, 0.05357427895069122, -0.00756207387894392, 0.0046953135170042515, 0.03416355326771736, 0.015549244359135628, 0.0005801403312943876, -1.5539490050286986e-05, 0.037921130657196045, 0.008609484881162643, -0.02301262505352497, -0.047370631247758865, -0.03271586820483208, -0.02361794002354145, 0.002926118904724717, 0.004499508999288082, -0.04420721158385277, 0.03722991794347763, 2.587413676373554e-34, -0.0014467490836977959, -0.015309491194784641, -0.009912431240081787, 0.011803200468420982, 0.05980759114027023, -0.015473539009690285, -0.07014309614896774, -0.09023770689964294, 0.05449261888861656, 0.000785086362157017, -0.046734970062971115, 0.08187025040388107, 0.003527270397171378, 0.0473746694624424, 0.013905414380133152, -0.005596695002168417, -0.011129898019134998, 0.05331224948167801, -0.04476795345544815, -0.004058796912431717, 0.041443705558776855, 0.08015184104442596, -0.017870930954813957, 0.03741240128874779, -0.010519052855670452, 0.04894743114709854, -0.01688634417951107, -0.05198414623737335, 0.017805373296141624, -0.05715461075305939, -0.04948131740093231, 0.02504347264766693, -0.04229611158370972, -0.010856278240680695, -0.036870233714580536, 0.06233895942568779, -0.03861594572663307, -0.042425815016031265, -0.10478230565786362, 0.0020805427338927984, 0.09010878950357437, -0.012057889252901077, 0.09150391072034836, 0.02014879696071148, 0.0009937882423400879, 0.00899617001414299, -0.021254941821098328, 0.0365321971476078, -0.04655895382165909, -0.05177799239754677, -0.01783379539847374, -0.048873767256736755, -0.10229326039552689, 0.06547856330871582, 0.12237673252820969, -0.053140878677368164, 0.03872980549931526, -0.09772855043411255, -0.08884584903717041, -0.022123131901025772, 0.030345045030117035, -0.007427149917930365, -0.05384735390543938, 0.07527139037847519, -0.028631607070565224, 0.03678063675761223, -0.03661051392555237, 0.08265848457813263, -0.0740298256278038, -0.019445126876235008, -0.03180643543601036, 0.02317412570118904, 0.0239668320864439, -0.11154744029045105, -0.04217185452580452, -0.03007471188902855, -0.036047518253326416, 0.00911269523203373, -0.048925723880529404, -0.013197585940361023, -0.0219768974930048, -0.011083196848630905, 0.009121929295361042, 0.030844205990433693, -0.07267177104949951, -0.02336694300174713, -0.05410631746053696, -0.0741189494729042, -0.04328850284218788, 0.012671048752963543, -0.10659519582986832, 0.00729840062558651, -0.008790403604507446, 0.07429420202970505, -0.025001399219036102, -1.7728323697951964e-08, -0.03147224709391594, -0.012399453669786453, 0.03335198760032654, -0.04570364952087402, -0.07236082851886749, -0.00983951985836029, 0.01789676584303379, 0.054478343576192856, 0.04961847513914108, -0.011029326356947422, -0.08288301527500153, 0.06376297771930695, 0.08966618776321411, 0.11089757084846497, 0.03738986700773239, -0.05265502631664276, 0.032399170100688934, 0.05641861632466316, -0.08295249193906784, 0.006705785635858774, -0.03742574155330658, -0.06740511953830719, 0.011611280962824821, -0.0034769487101584673, 0.010901284404098988, 0.006364297587424517, 0.028989318758249283, 0.01263129711151123, -0.009789464063942432, 0.07711002975702286, 0.03720618411898613, 0.017156269401311874, 0.005397839937359095, 0.008267190307378769, -0.05921350419521332, -0.02762071043252945, 0.13828355073928833, 0.017690565437078476, 0.01199011318385601, 0.023843634873628616, 0.006640465930104256, 0.017482589930295944, -0.05495097115635872, 0.07282385230064392, 0.038127925246953964, -0.038593094795942307, 0.048852164298295975, 0.09861787408590317, 0.08105860650539398, -0.004989905282855034, -0.031532712280750275, -0.0672389566898346, 0.029132302850484848, 0.07623445987701416, -0.028955359011888504, 0.06299693137407303, -0.006739829201251268, -0.019601233303546906, 0.040204968303442, 0.029171375557780266, -0.0868375152349472, -0.006946963723748922, 0.06981144100427628, 0.07870713621377945]'), +('Patient safety is a core tenet of nursing care and a primary responsibility of every healthcare provider. A foundational principle is the creation of a "culture of safety," where the focus is on preventing errors through system-wide vigilance rather than placing blame on individuals. For nursing students, this begins with consistently performing basic safety checks. One of the most critical routines is accurate patient identification. Before any procedure, intervention, or medication administration, the patient must be identified using at least two distinct identifiers, such as their full name and date of birth, which are cross-referenced with their wristband and medical record. This simple step prevents a vast number of potential errors. Medication administration is a high-risk activity that demands meticulous attention to detail. Nurses adhere to the "Rights of Medication Administration," which minimally include the right patient, right drug, right dose, right route, and right time. Each step requires verification, from checking the physician''s order to confirming patient allergies and monitoring for adverse reactions after the dose is given. Similarly, preventing healthcare-associated infections (HAIs) is paramount. The single most effective measure to combat the spread of infection is proper hand hygiene, performed before and after every patient contact, after contact with contaminated surfaces, and before performing any aseptic procedure. Another major area of concern is fall prevention. A fall can significantly worsen a patient''s condition and extend their hospital stay. Nurses conduct fall risk assessments on all patients upon admission and regularly thereafter. Interventions are then tailored to the patient''s specific risk level and may include keeping the bed in the lowest position, ensuring call lights are within reach, using bed alarms for high-risk individuals, and maintaining a clutter-free environment. Reporting any errors or near-misses is also a vital component of safety culture, as it allows the institution to identify and correct system vulnerabilities to protect future patients.', 'Why is reporting errors and near misses important in a healthcare setting?', '[0.035383883863687515, 0.09252327680587769, 0.007614021189510822, 0.019443722441792488, 0.04066195338964462, 0.03355185315012932, -0.0030533168464899063, 0.07029321789741516, 0.06691603362560272, -0.0136027866974473, 0.013882547616958618, 0.0657796859741211, 0.04016328975558281, -0.02479337342083454, -0.06855093687772751, -0.1049913838505745, 0.05710894614458084, -0.018489046022295952, -0.04651113599538803, 0.0024881772696971893, -0.06597606837749481, 0.1087728962302208, 0.022157300263643265, 0.10930513590574265, -0.05451727285981178, 0.016848528757691383, -0.09223765879869461, -0.034085046499967575, -0.03092314302921295, -0.013229832984507084, 0.005631050560623407, -0.021206336095929146, 0.024461666122078896, 0.013152494095265865, -0.03179824352264404, -0.0075718555599451065, 0.01223373506218195, 0.021916961297392845, -0.03816431760787964, -0.011045028455555439, 0.030710041522979736, -0.023021157830953598, 0.03702228516340256, 0.027022473514080048, -0.050950538367033005, -0.06192146614193916, -0.016051698476076126, -0.01755429431796074, 0.01743665151298046, 0.034729860723018646, -0.061198849231004715, -0.0047064716927707195, 0.06535665690898895, 0.022722775116562843, 0.04104112088680267, 0.00021933505195192993, -0.03442153334617615, 0.005375766661018133, -0.08038900792598724, 0.023072585463523865, -0.007838024757802486, -0.029166733846068382, -0.023378726094961166, -0.00941480603069067, 0.06225629150867462, 0.028949962928891182, 0.04162965342402458, -0.11016178876161575, 0.0036678952164947987, 0.06731941550970078, -0.07998096942901611, -0.05013153329491615, 0.0024390972685068846, 0.10711279511451721, -0.032530784606933594, -0.0090209124609828, -0.02120734378695488, -0.028816381469368935, 0.004143823869526386, -0.02062666229903698, 0.005154605954885483, -0.043142031878232956, -0.02488866075873375, 0.11548634618520737, 0.08951547741889954, -0.034078262746334076, 0.0366138331592083, 0.004269053228199482, -0.05171157792210579, -0.09723811596632004, 0.0542319156229496, -0.050747066736221313, 0.03219977021217346, 0.05466308072209358, 0.060827501118183136, 0.010219085030257702, -0.017293361946940422, 0.010572049766778946, 0.016702428460121155, -0.0014717662706971169, 0.07513310760259628, 0.014807083643972874, 0.02808303013443947, 0.032713379710912704, 0.0029638500418514013, -0.06808511912822723, -0.03252800926566124, 8.277362212538719e-05, -0.041127026081085205, 0.03349941223859787, 0.01358463242650032, 0.06514955312013626, 0.017037363722920418, -0.05019604042172432, 0.05028581619262695, 0.007364129181951284, -0.07886609435081482, 0.023670518770813942, -0.014208902604877949, 0.0541972890496254, -0.03690344840288162, -0.061327867209911346, 5.88936272833962e-05, -0.021938662976026535, 0.09001416712999344, 0.00010067159018944949, 0.020984377712011337, -4.518926851585211e-33, 0.01582556962966919, -0.018971726298332214, 0.01862579956650734, -0.0227467380464077, -0.005833735689520836, 0.03191044181585312, -0.08552540093660355, -0.100670725107193, 0.14127087593078613, -0.04378082975745201, -0.002514137886464596, 0.006499761715531349, 0.08874963223934174, -0.0436696782708168, -0.04372701793909073, 0.07540971040725708, -0.02721618488430977, 0.10399406403303146, -0.09535637497901917, 0.08375760912895203, 0.017053578048944473, -0.14480368793010712, 0.010587713681161404, -0.009270355105400085, -0.009913652203977108, 0.09236990660429001, 0.009307214990258217, 0.05790722742676735, 0.046928100287914276, -0.014190168119966984, -0.00649861479178071, 0.015689225867390633, 0.05300971865653992, -0.04796186834573746, 0.02037768065929413, -0.0034104385413229465, -0.008404219523072243, -0.049063120037317276, 0.020992467179894447, 0.0026501663960516453, -0.0272291861474514, 0.06669557094573975, -0.05976313352584839, -0.0003814983647316694, 0.08899179100990295, 0.016785617917776108, 0.003473641350865364, -0.04543676972389221, -0.023249948397278786, -0.0018314352491870522, -0.01974070444703102, 0.043622735887765884, 0.03754371404647827, 9.473103273194283e-05, -0.004572736565023661, 0.012644097208976746, 0.03726397082209587, -0.10382702201604843, -0.027701525017619133, -0.029964936897158623, 0.07792197167873383, -0.03210879862308502, -0.006488074082881212, -0.030865369364619255, 0.010377530939877033, 0.07044421136379242, 0.03249277174472809, 0.0201236754655838, 0.005849417764693499, -0.030421199277043343, -0.0026639821007847786, 0.006674175150692463, -0.004149416461586952, 0.031070154160261154, 0.0011806734837591648, -0.00886168796569109, 0.028384177014231682, -0.020449180155992508, 0.07942564785480499, -0.07288894057273865, 0.06627154350280762, -0.06832412630319595, -0.02163376472890377, 0.05759485065937042, -0.022179508581757545, -0.009626524522900581, 0.03318023309111595, 0.05806140974164009, -0.14448605477809906, 0.029013579711318016, -0.014236701652407646, 0.023899026215076447, 0.0027450155466794968, 0.06782763451337814, -0.04375610500574112, 1.0476813806894417e-33, -0.08919685333967209, 0.0342090018093586, 0.010076288133859634, -0.047491904348134995, -0.03569285571575165, -0.03294328972697258, 0.022646509110927582, -0.09106701612472534, 0.062445465475320816, 0.045963533222675323, -0.05262249708175659, -0.06059408560395241, -0.10374945402145386, -0.004024434369057417, -0.07726488262414932, 0.04388497769832611, 0.012431183829903603, -0.13813476264476776, -0.024195538833737373, -0.010170376859605312, 0.13389432430267334, 0.04172368347644806, -0.02768014557659626, 0.053484298288822174, -0.06348670274019241, 0.09809646010398865, -0.02047230489552021, -0.06348895281553268, -0.0902821496129036, -0.17491978406906128, 0.008822324685752392, -0.016701972112059593, 1.6528661944903433e-05, 0.010087293572723866, 0.05241598188877106, -0.02214658632874489, 0.004389751702547073, -0.00200793263502419, -0.046733297407627106, 0.022240659222006798, 0.08696300536394119, 0.059725940227508545, -0.03913240134716034, 0.001002269797027111, -0.00028707453748211265, -0.008981117978692055, -0.0005926152807660401, 0.028976812958717346, -0.008431557565927505, 0.02598482556641102, 0.00042373372707515955, -0.021323105320334435, -0.023927180096507072, 0.05113261193037033, -0.07984175533056259, 0.037009235471487045, -0.028755037114024162, -0.029177511110901833, -0.09787184000015259, 0.08290278166532516, -0.040033042430877686, -0.014692055992782116, -0.06482715159654617, -0.0018895823741331697, -0.026186546310782433, 0.04924765229225159, 0.05271739140152931, -0.03199657425284386, 0.11978653073310852, -0.019395900890231133, -0.034928735345602036, -0.03583219647407532, -0.050114940851926804, -0.07904986292123795, 0.03376716375350952, 0.04059819132089615, -0.06341603398323059, -0.03589607775211334, -0.07707394659519196, 0.02217334881424904, -0.026108089834451675, -0.10362178832292557, 0.05214211717247963, 0.02529124915599823, -0.042713046073913574, 0.029137171804904938, 0.017879335209727287, -0.06860397756099701, -0.02173224464058876, -0.021601615473628044, -0.0735703781247139, 0.03828364610671997, -0.060009442269802094, -0.0037320188712328672, -0.03921227902173996, -1.950670380779229e-08, -0.07383639365434647, 0.028841258957982063, 0.05186200514435768, -0.032862886786460876, 0.004172055516391993, -0.13838815689086914, -0.020493311807513237, 0.05236366018652916, -0.027519308030605316, 0.029164301231503487, -0.018589885905385017, -0.04630224034190178, -0.04093214124441147, -0.03520836681127548, 0.13272696733474731, -0.009835210628807545, -0.03585764393210411, 0.04487362131476402, -0.07080942392349243, 0.020287219434976578, -0.0026651944499462843, 0.017869379371404648, -0.01813058741390705, -0.022029822692275047, 0.029479939490556717, 0.003979808650910854, 0.02923021838068962, 0.12077242136001587, -0.024223534390330315, 0.011274662800133228, 0.020995011553168297, 0.007354808505624533, 0.12840673327445984, 0.021777188405394554, -0.04540037736296654, -0.007297877222299576, 0.13390617072582245, -0.003847255138680339, 0.01129704900085926, -0.0794713944196701, -0.01118195615708828, -0.032021913677453995, 0.026156997308135033, 0.10513076186180115, -0.01298995316028595, -0.04606416076421738, -0.038464441895484924, 0.03939652070403099, -0.033544719219207764, -0.1038232147693634, 0.027655206620693207, -0.014610311016440392, 0.0447942279279232, 0.0726592093706131, 0.02262752875685692, 0.05330394580960274, 0.02753995917737484, -0.08331280201673508, -0.04242495819926262, -0.0030185282230377197, 0.03795940428972244, 0.01951003447175026, -0.026373501867055893, 0.025667458772659302]'), +('The nursing process is a systematic, problem-solving framework that guides all nursing actions. It provides a structured and logical method for delivering patient-centered care. This process is comprised of five distinct but interconnected steps: Assessment, Diagnosis, Planning, Implementation, and Evaluation. By following these steps, nurses can ensure that the care they provide is organized, individualized, and effective. The process is not linear but cyclical, meaning the evaluation of one care plan often leads to a new assessment and a revised plan, reflecting the dynamic nature of a patient''s health status. The first step, Assessment, is the collection of comprehensive data about the patient. This includes both subjective data, which is what the patient says about their symptoms and feelings, and objective data, which is observable and measurable information like vital signs, lab results, and physical examination findings. The second step, Diagnosis, involves analyzing the assessment data to identify actual or potential health problems. These are formulated as nursing diagnoses, which focus on the patient''s response to their health condition, such as "Impaired Gas Exchange" or "Risk for Infection." Following the diagnosis, the nurse moves to the Planning phase. Here, patient-centered goals and expected outcomes are established, and specific nursing interventions are selected to help achieve those goals. These goals should be specific, measurable, achievable, relevant, and time-bound (SMART). The fourth step, Implementation, is the action phase where the planned interventions are carried out. This could involve administering medication, providing wound care, educating the patient, or coordinating with other healthcare team members. Finally, the Evaluation phase determines whether the patient''s goals were met. The nurse assesses the patient''s response to the interventions and decides if the plan of care should be continued, modified, or terminated.', 'What are the five steps of the nursing process in order?', '[-0.020808426663279533, -0.023517007008194923, -0.016885649412870407, -0.036599013954401016, -0.01715167984366417, 0.02118430659174919, -0.10767322778701782, -0.019962342455983162, -0.03374635428190231, 0.014785033650696278, -0.0160235445946455, 0.02733873575925827, -0.050087954849004745, 0.007007126696407795, -0.06811418384313583, -0.05210387334227562, -0.10648678988218307, 0.03274480998516083, 0.014566821977496147, 0.00567843159660697, 0.03597604110836983, -0.0252856258302927, -0.010545342229306698, -0.021049030125141144, -0.017925959080457687, -0.002648233436048031, 0.008596375584602356, -0.04442647472023964, 0.10167568922042847, 0.009378665126860142, 0.034916821867227554, -0.010467136278748512, 0.04666851833462715, 0.0289462897926569, -0.061271604150533676, 0.038028132170438766, 0.04350496083498001, -0.009719615802168846, -0.026530764997005463, 0.03980152681469917, 0.04067113250494003, -0.10647670179605484, -0.024866845458745956, 0.0004522231174632907, 0.08725232630968094, -0.011626369319856167, -0.01862037554383278, -0.013219809159636497, -0.03884327411651611, -0.06549998372793198, -0.11282449960708618, -0.08268795907497406, -0.1389436423778534, 0.11031997948884964, -0.06642933934926987, -0.014617787674069405, 0.07983075827360153, -0.07801971584558487, -0.04526055231690407, -0.006618334911763668, -0.037244684994220734, 0.0413578525185585, -0.05720668286085129, 0.05266480892896652, 0.05256394296884537, -0.018311593681573868, -0.0018815905787050724, -0.06374634802341461, 0.08531435579061508, 0.028107918798923492, -0.002785956021398306, -0.08965981006622314, -0.010953349992632866, 0.011153636500239372, -0.020038889721035957, -0.035955727100372314, 0.03168172016739845, -0.02853023260831833, -0.0364779531955719, -0.014789288863539696, -0.039327964186668396, 0.05654391646385193, 0.021022530272603035, 0.06711780279874802, -0.017052946612238884, 0.02326994761824608, -0.015051649883389473, -0.03582758828997612, -0.042586877942085266, -0.01884610205888748, 0.05933201685547829, 0.012713500298559666, -0.12617188692092896, -0.037526585161685944, 0.004608523100614548, 0.061852987855672836, -0.04718336835503578, -0.04839572310447693, 0.07828385382890701, -0.026986723765730858, -0.005698453169316053, -0.011183768510818481, 0.03305143117904663, 0.006547129712998867, -0.03206321969628334, -0.05684942752122879, 0.0411013662815094, -0.024462485685944557, -0.011312595568597317, 0.024582648649811745, -0.120058573782444, 0.020862586796283722, 0.012374130077660084, 0.010190795175731182, 0.01903511956334114, 0.04556141421198845, -0.009009224362671375, -0.029267404228448868, 0.036110930144786835, 0.055872030556201935, -0.005302810110151768, 0.0496705025434494, 0.022438617423176765, -0.04537084326148033, -0.06540180742740631, -0.004628491122275591, 0.00360698439180851, -4.432227531056344e-33, 0.016822312027215958, -0.002311407122761011, 0.06676946580410004, 0.08289673179388046, 0.006040474865585566, 0.04776547849178314, -0.005254330579191446, -0.06277401000261307, 0.04334677383303642, 0.06221791356801987, 0.04164605587720871, -0.0006892717792652547, -0.025967860594391823, -0.03075454942882061, -0.02176104299724102, -0.0789271742105484, -0.08480297774076462, 0.08026210963726044, -0.05190019682049751, 0.09136088192462921, 0.06258530914783478, -0.021213995292782784, -0.01105586253106594, 0.07544928044080734, 0.02434989996254444, 0.013126312755048275, -0.06083289161324501, 0.02573722042143345, -0.03170522302389145, 0.014351807534694672, 0.023372596129775047, -0.05294979736208916, -0.12073977291584015, -0.03725169971585274, 0.0036359671503305435, 0.002787166042253375, 0.03215593844652176, -0.02736479789018631, 0.019934922456741333, -0.038408901542425156, -0.05969444662332535, -0.015540242195129395, -0.007196404039859772, 0.06744750589132309, 0.08062279969453812, 0.08404985070228577, -0.0497906319797039, -0.03604522719979286, 0.036506831645965576, 0.03438643738627434, 0.024694720283150673, -0.07358377426862717, 0.02879023179411888, -0.05452929809689522, 0.037320781499147415, 0.011841829866170883, -0.005766803398728371, -0.07298599928617477, -0.01033875159919262, 0.05526607483625412, 0.0699705109000206, -0.0020699049346148968, -0.06538060307502747, 0.04449455440044403, 0.06595815718173981, -0.05114653334021568, -0.028260184451937675, -0.08649969100952148, 0.15777622163295746, -0.08351223915815353, -0.11008300632238388, -0.0003072301624342799, 0.027789976447820663, -0.012070073746144772, -0.026301521807909012, 0.04793776199221611, -0.004516231827437878, -0.06607552617788315, 0.009223771281540394, -0.0631362646818161, -0.048225365579128265, 0.057215698063373566, -0.05758875980973244, 0.07102455943822861, 0.08044398576021194, -0.010095568373799324, -0.024701926857233047, 0.05929873511195183, -0.0611807182431221, -0.021722061559557915, -0.01759231463074684, 0.0673462525010109, 0.0949990451335907, -0.02003372460603714, 0.03299350664019585, 9.965225808447095e-34, 0.02812783047556877, 0.021374324336647987, -0.048817187547683716, 0.0412009060382843, 0.038838841021060944, -0.06552471220493317, -0.058016128838062286, -0.03633766621351242, 0.15524084866046906, 0.01015906035900116, -0.018681662157177925, -0.06096374988555908, 0.022991780191659927, 0.03759574145078659, -0.09682963043451309, 0.033892251551151276, 0.06320959329605103, -0.0005168367642909288, 0.028290092945098877, 0.02895970456302166, 0.008501443080604076, 0.0631260871887207, -0.044348567724227905, 0.03496827185153961, -0.014487076550722122, 0.05064814165234566, 0.05330785736441612, 0.0204057265073061, 0.010437149554491043, -0.034823037683963776, 0.027069946750998497, -0.018161555752158165, -0.007960359565913677, 0.08156373351812363, -0.05610615760087967, -0.03534060716629028, 0.04016774520277977, 0.050765134394168854, -0.0015315430937334895, -0.006778341718018055, 0.09872207790613174, 0.0026876493357121944, -0.04172736033797264, 0.020647486671805382, -0.009676294401288033, -0.07866505533456802, 0.0054769013077020645, 0.0222947858273983, -0.07479237020015717, -0.042484331876039505, -0.00590964499861002, -0.03804266080260277, -0.05735358968377113, 0.03307488188147545, 0.011518570594489574, 0.000333218282321468, 0.09289371967315674, -0.08619018644094467, -0.003785062115639448, 0.024249199777841568, 0.06240404397249222, 0.0487203486263752, -0.011363978497684002, -0.03655798360705376, 0.005774192977696657, -0.03313474357128143, 0.04615107551217079, 0.022269079461693764, -0.027587231248617172, -0.027684740722179413, -0.0637010782957077, 0.04235026612877846, 0.052342720329761505, 0.00459635304287076, 0.032669056206941605, -0.03672841191291809, 0.0318039208650589, -0.07769092917442322, -0.002495942637324333, -0.05080816522240639, -0.12403982877731323, -0.07700757682323456, -0.022288057953119278, -0.020573509857058525, -0.08466760814189911, -0.038533713668584824, 0.08266879618167877, -0.08496534079313278, 0.044348735362291336, -0.055043596774339676, -0.05119684711098671, -0.011682949960231781, 0.07506563514471054, 0.0029408344998955727, -0.02965352311730385, -1.7716471845119486e-08, -0.06138192489743233, -0.05284567549824715, 0.09397071599960327, -0.030970772728323936, 0.03860140219330788, 0.015956789255142212, -0.038529735058546066, 0.10956985503435135, 0.0608796589076519, 0.01562763936817646, -0.014716111123561859, 0.07635211944580078, 0.05820878595113754, 0.032418396323919296, 0.09781374782323837, 0.017728231847286224, 0.030284443870186806, 0.07602112740278244, -0.05854878947138786, -0.07297797501087189, -0.05922830477356911, -0.06164846941828728, -0.03857901692390442, -0.015402587130665779, 0.08498929440975189, 0.0062073348090052605, 0.07675259560346603, 0.05806448683142662, -0.03127294033765793, 0.04404408857226372, 0.047931306064128876, 0.057620804756879807, 0.08742858469486237, 0.04981979355216026, -0.10442328453063965, -0.008957972750067711, 0.08915107697248459, 0.004613623023033142, 0.07203331589698792, -0.07575790584087372, -0.0315869078040123, 0.07231754809617996, 0.03636586666107178, 0.0064342631958425045, 0.008615714497864246, -0.0381757877767086, -0.028357699513435364, 0.002543748589232564, -0.006527115125209093, -0.0531749464571476, 0.009350375272333622, -0.06816592812538147, 0.03589034453034401, 0.036702241748571396, -0.013384614139795303, 0.07417786866426468, 0.05392917990684509, -0.04571942985057831, 0.03393545001745224, 0.038947150111198425, 0.0063515957444906235, 0.05658573657274246, 0.1141495332121849, -0.021876143291592598]'), +('The nursing process is a systematic, problem-solving framework that guides all nursing actions. It provides a structured and logical method for delivering patient-centered care. This process is comprised of five distinct but interconnected steps: Assessment, Diagnosis, Planning, Implementation, and Evaluation. By following these steps, nurses can ensure that the care they provide is organized, individualized, and effective. The process is not linear but cyclical, meaning the evaluation of one care plan often leads to a new assessment and a revised plan, reflecting the dynamic nature of a patient''s health status. The first step, Assessment, is the collection of comprehensive data about the patient. This includes both subjective data, which is what the patient says about their symptoms and feelings, and objective data, which is observable and measurable information like vital signs, lab results, and physical examination findings. The second step, Diagnosis, involves analyzing the assessment data to identify actual or potential health problems. These are formulated as nursing diagnoses, which focus on the patient''s response to their health condition, such as "Impaired Gas Exchange" or "Risk for Infection." Following the diagnosis, the nurse moves to the Planning phase. Here, patient-centered goals and expected outcomes are established, and specific nursing interventions are selected to help achieve those goals. These goals should be specific, measurable, achievable, relevant, and time-bound (SMART). The fourth step, Implementation, is the action phase where the planned interventions are carried out. This could involve administering medication, providing wound care, educating the patient, or coordinating with other healthcare team members. Finally, the Evaluation phase determines whether the patient''s goals were met. The nurse assesses the patient''s response to the interventions and decides if the plan of care should be continued, modified, or terminated.', 'What is the difference between subjective and objective data collected during the Assessment phase?', '[0.06562886387109756, 0.009262735024094582, -0.09453807771205902, 0.0024231765419244766, 0.0007324354955926538, -0.015832871198654175, 0.02301589399576187, 0.011078692972660065, 0.01792791858315468, 0.0891043096780777, 0.027484411373734474, -0.03770328685641289, 0.006380161736160517, 0.0695476084947586, -0.06369498372077942, 0.0429314523935318, 0.08423423022031784, -0.07813713699579239, 0.040060605853796005, 0.03340241312980652, 0.0752682238817215, 0.05331611633300781, -0.030306128785014153, 0.03261468559503555, 0.03249602019786835, 0.10556186735630035, 0.0027506505139172077, 0.01744307391345501, 0.030551545321941376, 0.023972928524017334, 0.016794467344880104, 0.05783320963382721, 0.08325674384832382, 0.04518995061516762, -0.02717394195497036, 0.013774913735687733, 0.0457552969455719, 0.004364077467471361, -0.030491095036268234, -0.01340777613222599, -0.04678906127810478, -0.05695010721683502, -0.03302726522088051, -0.02069029025733471, 0.01627338118851185, 0.014890449121594429, -0.0449652262032032, -0.057422347366809845, -0.026937538757920265, 0.09955144673585892, -0.057685449719429016, 0.03486251458525658, -0.04731691628694534, 0.02267785742878914, 0.0012023051967844367, 0.06643857806921005, -0.011100102216005325, -0.03053934872150421, 0.013689263723790646, 0.07763071358203888, -0.1572197526693344, -0.030267732217907906, -0.04758436232805252, 0.053261857479810715, 0.08117698132991791, -0.027421655133366585, -0.09898851066827774, -0.0477784238755703, -0.043634314090013504, -0.05040697753429413, 0.035176679491996765, -0.02640836127102375, 0.10469365119934082, -0.0507345125079155, 0.05315615236759186, 0.004759632050991058, 0.012884661555290222, -0.02759629115462303, -0.042462058365345, -0.01036952156573534, -0.033181581646203995, 0.05384206026792526, 0.07981443405151367, 0.02702762372791767, 0.04280078038573265, -0.06563670933246613, 0.06391385942697525, 0.043236467987298965, -0.12273845076560974, 0.06435450166463852, -0.016048312187194824, -0.013710921630263329, -0.051039017736911774, 0.028681304305791855, 0.06471402943134308, -0.0032421171199530363, -0.040411729365587234, -0.005499460268765688, 0.04768512770533562, -0.03910277411341667, -0.0024403699208050966, 0.012570380233228207, -0.12292987108230591, 0.01031484641134739, -0.04697474464774132, -0.02947734296321869, 0.026144614443182945, -0.03266633301973343, 0.019549014046788216, -0.012913178652524948, -0.09041432291269302, 0.04217226430773735, 0.006392924580723047, -0.04685422405600548, 0.055595528334379196, -0.017749197781085968, -0.025286534801125526, 0.14700324833393097, 0.03109736740589142, -0.011688454076647758, -0.07402171939611435, -0.08337773382663727, 0.11602580547332764, -0.012999829836189747, 0.05662864074110985, 0.0148080512881279, 0.0010636873776093125, -5.338063845141983e-33, -0.023532472550868988, -0.0798281729221344, -0.07633762806653976, -0.021897926926612854, -0.13371680676937103, -0.038584694266319275, -0.032552871853113174, 0.026639685034751892, 0.0896090641617775, -0.009981006383895874, 0.030198736116290092, 0.1363336145877838, 0.02521287277340889, -0.02319527603685856, 0.1146225780248642, -0.02367877960205078, -0.10661519318819046, 0.11421240121126175, -0.12134838104248047, 0.03756327927112579, -0.012103027664124966, 0.02566535584628582, 0.07896681129932404, -0.0008981983992271125, 0.062171902507543564, -0.02847004123032093, 0.08339445292949677, 0.022160951048135757, -0.09620136022567749, 0.03719073906540871, -0.005522190593183041, 0.005555590149015188, 0.011300386860966682, -0.0031838412396609783, -0.011464416049420834, 0.10226532816886902, 0.047113534063100815, 0.04062173515558243, -0.06490180641412735, -0.002337441546842456, 0.014695646241307259, 0.04850245267152786, 0.08744432032108307, 0.012005859054625034, -0.05981571227312088, 0.002966090105473995, -0.013966008089482784, -0.061044663190841675, 0.018773553892970085, -0.004624553024768829, -0.044766865670681, -0.05518617480993271, 0.02400202304124832, -0.05521215870976448, -0.017824426293373108, 0.05092711001634598, -0.006440401542931795, -0.04434599354863167, -0.008128752931952477, -0.037879735231399536, -0.024441184476017952, 0.03607366606593132, -0.037438295781612396, -0.11906084418296814, 0.04742811620235443, 0.054287202656269073, -0.04201333597302437, 0.011347157880663872, 0.05319572612643242, -0.03795956075191498, -0.020981281995773315, 0.04184013977646828, 0.00903679896146059, -0.02545471116900444, 0.004238349851220846, -0.0030841140542179346, -0.012087085284292698, 0.09665446728467941, -0.054305944591760635, -0.07111044228076935, 0.006649254821240902, 0.05265643075108528, -0.024990471079945564, -0.11649779230356216, 0.00041575124487280846, 0.007195077836513519, 0.008463558740913868, -0.022982574999332428, -0.0434890016913414, 0.011937250383198261, -0.10747335106134415, 0.013656399212777615, -0.06177103891968727, 0.06950300931930542, -0.03189156949520111, 1.4597601089198103e-33, -0.06581152230501175, -0.00703217601403594, -0.11427146941423416, 0.12395711243152618, 0.04226122051477432, -0.020664416253566742, 0.010052942670881748, 0.005598523188382387, 0.07945983111858368, 0.08011440932750702, -0.04777708277106285, -0.048102788627147675, -0.06458237767219543, 0.005629496183246374, -0.03429333120584488, -0.015127100981771946, -0.08030644804239273, -0.050082314759492874, -0.04037254676222801, -0.023506080731749535, -0.0171480905264616, 0.12569648027420044, 0.008698146790266037, -0.04114178940653801, -0.02787126414477825, 0.025980496779084206, 0.002954325871542096, -0.0122566819190979, 0.08365099877119064, 0.017486026510596275, 0.06143276393413544, -0.005707454401999712, -0.07030924409627914, 0.012869813479483128, -0.02070710062980652, -0.044881999492645264, -0.009853590279817581, -0.12303177267313004, 0.029682964086532593, 0.08951036632061005, 0.0071707055903971195, 0.08420376479625702, -0.08390466123819351, 0.022714689373970032, 0.00492577301338315, -0.026882462203502655, 0.04669411852955818, 0.005491367541253567, -0.0016046796226873994, -0.042707301676273346, 0.03716232627630234, 0.050729263573884964, 0.006303410977125168, 0.04381402209401131, -0.006901113782078028, -0.10196314007043839, 0.024586740881204605, -0.056075528264045715, 0.016317445784807205, 0.06303390860557556, 0.08303739130496979, 0.035750679671764374, 0.015806689858436584, -0.0455208383500576, -0.04811428487300873, 0.04024317488074303, 0.07852575927972794, -0.052063580602407455, -0.023818977177143097, 0.04960287734866142, -0.03724972531199455, 0.00715265516191721, -0.01994858682155609, -0.018571481108665466, 0.04189612716436386, -0.00783436931669712, 0.029051627963781357, 0.055462244898080826, -0.05961500108242035, -0.061578843742609024, 0.02323230169713497, -0.02010411024093628, -0.012479898519814014, -0.012000343762338161, -0.028406178578734398, -0.014640034176409245, 0.00532524986192584, -0.04938865080475807, -0.0494668185710907, 0.017735885456204414, 0.04837118461728096, 0.0158893633633852, -0.03637833520770073, -0.02661042846739292, -0.0630912035703659, -2.152872546901108e-08, -0.046359021216630936, -0.08638739585876465, 0.04287891462445259, 0.10108776390552521, -0.04008178040385246, -0.010389790870249271, -0.04242421314120293, 0.026542965322732925, -0.015232622623443604, 0.000174027489265427, 0.05145667493343353, 0.006941533647477627, -0.10377683490514755, -0.032298438251018524, -0.015495343133807182, -0.019416073337197304, 0.058296311646699905, -0.03848212957382202, 0.05204296112060547, 0.016245339065790176, 0.04048203304409981, -0.055348172783851624, -0.060696057975292206, -0.00890682078897953, 0.03742258995771408, 0.0005806682747788727, 0.0072752549313008785, -0.04564988613128662, -0.06628727912902832, -0.020122980698943138, 0.014241674914956093, 0.07934655249118805, -0.031241392716765404, -0.01245172694325447, -0.01953749544918537, -0.028197072446346283, 0.04238514229655266, 0.00838539283722639, -0.0030802080873399973, 0.03837069869041443, -0.019473105669021606, 0.020276397466659546, -0.028976423665881157, -0.0012873599771410227, 0.017369568347930908, 0.03011433035135269, -0.029989419505000114, 0.03008696809411049, -0.018205618485808372, -0.020612934604287148, -0.014588256366550922, -0.03585343435406685, 0.01772928610444069, 0.008148095570504665, 0.07694767415523529, -0.007470020093023777, 0.01973627135157585, -0.09929579496383667, -0.016410281881690025, 0.02101675234735012, 0.12563301622867584, 0.022685457020998, -0.04166373237967491, -0.03106273151934147]'), +('The nursing process is a systematic, problem-solving framework that guides all nursing actions. It provides a structured and logical method for delivering patient-centered care. This process is comprised of five distinct but interconnected steps: Assessment, Diagnosis, Planning, Implementation, and Evaluation. By following these steps, nurses can ensure that the care they provide is organized, individualized, and effective. The process is not linear but cyclical, meaning the evaluation of one care plan often leads to a new assessment and a revised plan, reflecting the dynamic nature of a patient''s health status. The first step, Assessment, is the collection of comprehensive data about the patient. This includes both subjective data, which is what the patient says about their symptoms and feelings, and objective data, which is observable and measurable information like vital signs, lab results, and physical examination findings. The second step, Diagnosis, involves analyzing the assessment data to identify actual or potential health problems. These are formulated as nursing diagnoses, which focus on the patient''s response to their health condition, such as "Impaired Gas Exchange" or "Risk for Infection." Following the diagnosis, the nurse moves to the Planning phase. Here, patient-centered goals and expected outcomes are established, and specific nursing interventions are selected to help achieve those goals. These goals should be specific, measurable, achievable, relevant, and time-bound (SMART). The fourth step, Implementation, is the action phase where the planned interventions are carried out. This could involve administering medication, providing wound care, educating the patient, or coordinating with other healthcare team members. Finally, the Evaluation phase determines whether the patient''s goals were met. The nurse assesses the patient''s response to the interventions and decides if the plan of care should be continued, modified, or terminated.', 'What is the main purpose of the Planning phase?', '[0.012175621464848518, 0.09239532053470612, 0.03297059237957001, 0.00420809630304575, 0.04079991579055786, 0.04019763320684433, -0.07252544909715652, -0.032370489090681076, 0.03128363937139511, 0.06075883284211159, -0.06948738545179367, 0.020279433578252792, -0.03397460654377937, -0.030622629448771477, 0.03304377198219299, -0.06070296838879585, -0.007297144271433353, -0.087163545191288, 0.022075572982430458, -0.001566278631798923, 0.012028073891997337, -0.0015142285265028477, 0.021188629791140556, -0.007677182089537382, -0.09148449450731277, 0.06640409678220749, 0.05597192421555519, 0.009528490714728832, 0.045955054461956024, 0.012624374590814114, 0.08151200413703918, 0.13708604872226715, 0.006188867148011923, -0.016037117689847946, -0.043195243924856186, 0.0941641554236412, 0.05413198471069336, -0.04197809472680092, 0.011014324612915516, -0.03170788660645485, -0.022696278989315033, -0.02588568814098835, -0.01606738194823265, 0.04578947648406029, 0.05516309663653374, 0.06802283972501755, 0.01541183888912201, -0.011330182664096355, -0.02336837910115719, -0.08564946800470352, 0.002103417878970504, -0.015505331568419933, 0.018076451495289803, -0.00555403484031558, -0.006068367511034012, 0.02385270968079567, 0.03926314413547516, -0.047221388667821884, 0.025986898690462112, -0.02349778264760971, -0.0387389175593853, -0.026548337191343307, -0.06653343141078949, -0.027267107740044594, 0.04057100787758827, -0.02958105318248272, 0.034334369003772736, -0.00017599514103494585, 0.019333086907863617, -0.022595010697841644, 0.03476821258664131, -0.07423916459083557, 0.0347454771399498, -0.06240447983145714, 0.04898591339588165, -0.02766101434826851, 0.006299466826021671, -0.00032518713851459324, 0.02801557071506977, -0.013583359308540821, 0.04050830006599426, 0.04091760143637657, 0.006489693187177181, 0.08630929887294769, -0.0007214873330667615, -0.037098079919815063, -0.009027264080941677, -0.01648932322859764, 0.04491288214921951, -0.03954667970538139, -0.033979207277297974, -0.0407501719892025, -0.036441609263420105, -0.012005116790533066, -0.04323110729455948, 0.10477543622255325, -0.07636063545942307, -0.09220362454652786, 0.05801740288734436, 0.004728648345917463, 0.032977622002363205, -0.013276812620460987, 0.07997522503137589, -0.03520170599222183, -0.05365198105573654, -0.11938297748565674, -0.004964752588421106, -0.007111605256795883, 0.006514759734272957, -0.03483111038804054, -0.056545838713645935, -0.06559184193611145, 0.11081422120332718, -0.016817009076476097, 0.06613823771476746, 0.05034774914383888, -0.04420272633433342, 0.04078654944896698, 0.047870438545942307, -0.014730915427207947, -0.0017735029105097055, -0.056780844926834106, -0.005988410674035549, 0.04179694131016731, -0.04128943011164665, -0.08255177736282349, -0.0533258393406868, -7.184476739483876e-33, -0.01583210937678814, -0.05151180550456047, 0.012488518841564655, 0.04569847509264946, -0.01658269204199314, 0.005837061442434788, -0.019247259944677353, -0.047893982380628586, 0.0446237176656723, -0.010843927972018719, 0.038679517805576324, -0.03512580320239067, -0.021316977217793465, 0.09658559411764145, 0.08048350363969803, -0.1295156627893448, -0.03921877220273018, 0.12314799427986145, 0.004204624332487583, 0.0074959127232432365, -0.0027221397031098604, 0.033276788890361786, 0.056779034435749054, -0.0738811269402504, 0.10218272358179092, 0.0874621570110321, 0.0033251780550926924, -0.006797746755182743, -0.03473546728491783, 0.01399694848805666, 0.03631436824798584, 0.06570827960968018, -0.14624299108982086, 0.03684700280427933, -0.016385866329073906, 0.09979404509067535, -0.037752121686935425, -0.07047616690397263, -0.015178230591118336, -0.007089151535183191, -0.002598630031570792, -0.020343948155641556, -0.007431259378790855, 0.057610008865594864, 0.0929911881685257, 0.01373858842998743, -0.0040915715508162975, -0.02421352081000805, -0.04804343730211258, 0.020231060683727264, 0.017780493944883347, 0.0002113115187967196, -0.0012998401653021574, -0.0837443396449089, 0.0464484766125679, 0.024930382147431374, -0.016243087127804756, -0.12873029708862305, -0.022769251838326454, 0.060889095067977905, 0.010716491378843784, -0.06731079518795013, -0.07787404209375381, 0.08681725710630417, 0.04455297067761421, 0.06934188306331635, 0.01917605847120285, -0.03229399397969246, 0.1357627958059311, -0.04290788993239403, -0.02673220820724964, 0.00274349725805223, 0.061495743691921234, 0.015447108075022697, -0.04527262598276138, 0.0014440655941143632, 0.0008813540334813297, 0.0609283484518528, -0.005012577399611473, -0.0007991689490154386, -0.06600788980722427, 0.005457049701362848, -0.03817128762602806, -0.015256362967193127, 0.07635250687599182, 0.007059487979859114, 0.07810970395803452, 0.021026859059929848, -0.05856502801179886, -0.017594439908862114, -0.056119490414857864, 0.042512934654951096, -0.032637424767017365, 0.14929896593093872, -0.02173531986773014, 4.01618628483775e-33, 0.022704726085066795, -0.06678241491317749, -0.06403932720422745, -0.03819135203957558, 0.004817022476345301, -0.040082916617393494, -0.0012261481024324894, -0.1872050017118454, 0.058673128485679626, 0.05637733265757561, -0.0931742787361145, -0.08301291614770889, 0.04413913935422897, -0.01422272901982069, -0.02581292763352394, -0.024143215268850327, 0.10627251863479614, -0.04150158166885376, 0.03147793933749199, -0.022786350920796394, -0.013407350517809391, 0.0036758198402822018, -0.10966484248638153, -0.009774072095751762, 0.008268341422080994, -0.0012648634146898985, -0.049178339540958405, -0.058352332562208176, -0.01873026043176651, 0.03769984841346741, -0.03580914065241814, -0.08153001219034195, -0.117282435297966, 0.01116346474736929, -0.07479509711265564, 0.05038229376077652, 0.01677151396870613, 0.04061445593833923, -0.009192400611937046, 0.015187508426606655, 0.05017724633216858, -0.011756950058043003, -0.006048772484064102, 0.020789364352822304, -0.060744430869817734, 0.05461619794368744, 0.08436239510774612, 0.11897359043359756, -0.0603097565472126, 0.0002244442148366943, 0.03155481070280075, 0.026701968163251877, -0.022212345153093338, -0.07982490956783295, 0.022151067852973938, 0.03441854938864708, -0.04036726430058479, -0.019960403442382812, 0.02985461615025997, 0.04468255862593651, 0.022862685844302177, 0.09517285227775574, -0.03152760490775108, 0.05023301765322685, 0.002242204500362277, 0.03228049352765083, -0.0031260810792446136, -0.026867642998695374, 0.07799752801656723, -0.03660482168197632, -0.000536193314474076, 0.0005086039891466498, -0.0035501744132488966, 0.011927666142582893, -0.00814414769411087, -0.029226159676909447, -0.017497548833489418, 0.009588033892214298, -0.05653301253914833, 0.0058648716658353806, -0.07222426682710648, -0.02489762008190155, -0.0708303302526474, 0.015407335013151169, -0.05169471725821495, -0.005993379279971123, -0.050427015870809555, 0.021466420963406563, 0.04485555738210678, -0.02393939346075058, -0.05894535034894943, -0.030543681234121323, 0.012503543868660927, 0.05838068574666977, -0.04383948817849159, -1.9293569408773692e-08, -0.004714890383183956, 0.03100711852312088, 0.013341229408979416, -0.08085531741380692, 0.046900101006031036, -0.03822889178991318, -0.016551513224840164, 0.02890358678996563, 0.021399671211838722, 0.05758710578083992, 0.029774131253361702, 0.05002228915691376, -0.01841849461197853, 0.034980420023202896, -0.004746946971863508, -0.001679814886301756, 0.11100087314844131, -0.007664922624826431, -0.034358419477939606, -0.029773861169815063, 0.019620325416326523, -0.0635126605629921, -0.10936932265758514, -0.018694061785936356, 0.07647466659545898, 0.021825063973665237, 0.019770929589867592, 0.059378836303949356, 0.042805977165699005, 0.07215798646211624, -0.002643589861690998, 0.0077167837880551815, -0.006849874742329121, 0.08599608391523361, -0.017825322225689888, 0.033337146043777466, 0.0038727805949747562, 0.01278156228363514, 0.07261285185813904, -0.0906209722161293, 0.008714328519999981, 0.10192529112100601, 0.0007481620414182544, 0.029991965740919113, -0.02088274247944355, 0.03839796781539917, -0.07614140212535858, 0.02646406553685665, -0.007457633037120104, -0.09696915000677109, -0.10447113960981369, 0.036044951528310776, 0.058429960161447525, 0.07283010333776474, 0.10028369724750519, 0.05097583308815956, 0.027184894308447838, -0.09630286693572998, 0.02333097532391548, 0.008942036889493465, -0.020010175183415413, 0.08293905854225159, -0.03860079497098923, -0.009824777953326702]'), +('The nursing process is a systematic, problem-solving framework that guides all nursing actions. It provides a structured and logical method for delivering patient-centered care. This process is comprised of five distinct but interconnected steps: Assessment, Diagnosis, Planning, Implementation, and Evaluation. By following these steps, nurses can ensure that the care they provide is organized, individualized, and effective. The process is not linear but cyclical, meaning the evaluation of one care plan often leads to a new assessment and a revised plan, reflecting the dynamic nature of a patient''s health status. The first step, Assessment, is the collection of comprehensive data about the patient. This includes both subjective data, which is what the patient says about their symptoms and feelings, and objective data, which is observable and measurable information like vital signs, lab results, and physical examination findings. The second step, Diagnosis, involves analyzing the assessment data to identify actual or potential health problems. These are formulated as nursing diagnoses, which focus on the patient''s response to their health condition, such as "Impaired Gas Exchange" or "Risk for Infection." Following the diagnosis, the nurse moves to the Planning phase. Here, patient-centered goals and expected outcomes are established, and specific nursing interventions are selected to help achieve those goals. These goals should be specific, measurable, achievable, relevant, and time-bound (SMART). The fourth step, Implementation, is the action phase where the planned interventions are carried out. This could involve administering medication, providing wound care, educating the patient, or coordinating with other healthcare team members. Finally, the Evaluation phase determines whether the patient''s goals were met. The nurse assesses the patient''s response to the interventions and decides if the plan of care should be continued, modified, or terminated.', 'The act of administering medication or changing a dressing falls under which step of the nursing process?', '[-0.06708161532878876, -0.017707062885165215, -0.012652670964598656, 0.002909405156970024, -0.027093548327684402, 0.013916983269155025, -0.015714259818196297, 0.02698705345392227, -0.027393298223614693, 0.027640823274850845, 0.04931953176856041, 0.04795040190219879, -0.01824459806084633, 0.061313971877098083, -0.039206087589263916, -0.051626842468976974, -0.02595461905002594, 0.032380856573581696, -0.01545583177357912, 0.06583662331104279, 0.04503459483385086, 0.023364519700407982, 0.014266565442085266, 0.06760213524103165, -0.033052410930395126, -0.015493213199079037, -0.020488383248448372, -0.05319875851273537, 0.09750992804765701, -0.0004928978742100298, 0.032043080776929855, 0.005193570163100958, 0.043828416615724564, 0.032626453787088394, -0.059448372572660446, 0.06001148372888565, 0.03421836346387863, 0.0040056342259049416, -0.021055852994322777, 0.06316636502742767, 0.05294462665915489, -0.08026804029941559, -0.0716424435377121, 0.00282002380117774, 0.12074315547943115, 0.03211282566189766, 0.04064319655299187, -0.00956208910793066, -0.06418180465698242, 0.023309698328375816, -0.09083706140518188, -0.03595134615898132, -0.07727789878845215, 0.10661570727825165, -0.07513954490423203, 0.029135705903172493, 0.05038725957274437, -0.029873846098780632, -0.02250051684677601, 0.04340085759758949, -0.07552041113376617, 0.04477958753705025, -0.024144167080521584, 0.08646948635578156, -0.00031746740569360554, -0.046237021684646606, 0.036995574831962585, -0.06971883028745651, 0.05065719038248062, -0.009668615646660328, -0.03551885113120079, -0.05592137202620506, 0.0550236850976944, 0.05148583650588989, 0.01601318269968033, -0.10081508010625839, 0.046351075172424316, -0.04083208367228508, -0.0482369028031826, -0.012723637744784355, 0.017514312639832497, 0.019580522552132607, 0.018443968147039413, 0.07490579038858414, -0.03251419588923454, -0.02498464845120907, -0.026027610525488853, -0.11340703070163727, 0.041389599442481995, -0.0314222052693367, 0.030901990830898285, -0.007532797288149595, -0.044950954616069794, -0.05352335795760155, 0.013484302908182144, 0.03194873034954071, -0.08065779507160187, 0.006405170075595379, 0.05212918296456337, 0.011015989817678928, -0.07215242832899094, -0.01678444631397724, -0.0414440780878067, 0.029416212812066078, -0.03281455859541893, -0.11449497193098068, 0.03811867535114288, -0.07121196389198303, -0.051410041749477386, 0.04938570782542229, -0.04254399612545967, -0.010304809547960758, 0.005732350517064333, -0.01981622911989689, 0.0012964382767677307, 0.05158497765660286, 0.04692598432302475, -0.02732797898352146, -0.024492662400007248, 0.051547374576330185, -0.00739070400595665, 0.038620851933956146, 0.02262086048722267, -0.05262220278382301, -0.08428207784891129, 0.007039254996925592, 0.060173213481903076, -4.6123279592817036e-33, 0.018863312900066376, -0.05900036171078682, 0.039681658148765564, 0.0455632321536541, 0.058659106492996216, 0.04655969887971878, -0.02385707199573517, -0.11579165607690811, 0.07435901463031769, 0.0494089275598526, 0.06201457977294922, 0.0073854513466358185, -0.06767277419567108, 0.01986030302941799, -0.009022552520036697, -0.047165390104055405, -0.03786400333046913, 0.07526635378599167, 0.024200690910220146, 0.07363813370466232, -0.0010870792903006077, 0.017447413876652718, -0.04782402515411377, 0.06009531766176224, -0.035880427807569504, 0.05582345277070999, -0.06041969731450081, 0.024359483271837234, 0.01472439430654049, 0.004166864790022373, 0.06531301140785217, -0.06089571863412857, -0.07391483336687088, 0.010547557845711708, -0.04832456633448601, 0.01043831929564476, -0.004163258243352175, -0.024599337950348854, 0.017975255846977234, -0.04372594505548477, -0.06809860467910767, 0.025536056607961655, 0.04789514094591141, 0.04316138103604317, -0.001971315825358033, 0.01770521141588688, -0.04680464416742325, 0.030494818463921547, 0.0022826564963907003, 0.03538838401436806, 0.1041034460067749, -0.015090628527104855, 0.08912713080644608, -0.08326243609189987, 0.031792283058166504, 0.06367269158363342, 0.027826203033328056, -0.00915620382875204, 0.015670930966734886, 0.0398879274725914, 0.040969058871269226, 0.020087551325559616, -0.04209039732813835, 0.050114549696445465, 0.09527468681335449, -0.03987976163625717, 0.01254069060087204, -0.06418399512767792, 0.05913209542632103, -0.10354309529066086, -0.13169866800308228, 0.06411410868167877, -0.048664312809705734, 0.01426884438842535, -0.007092206738889217, 0.003480154788121581, -0.0113774249330163, -0.03194764629006386, 0.013717305846512318, -0.11754504591226578, -0.0549185685813427, -0.0035647123586386442, -0.03827517852187157, 0.10447296500205994, 0.03769203647971153, -0.032451432198286057, -0.029665231704711914, 0.07891227304935455, -0.03304782137274742, -0.03843022882938385, -0.01877686381340027, 0.004021259490400553, 0.05521737039089203, 0.027257246896624565, 0.07941731810569763, 1.1080485257339356e-33, 0.040566641837358475, 0.014996812678873539, -0.07470441609621048, 0.07869815081357956, 0.03220497444272041, -0.04548310860991478, -0.036242760717868805, -0.02156994305551052, 0.11466842889785767, 0.03587214648723602, -0.042983103543519974, -0.051116906106472015, -0.06162042170763016, 0.011426887474954128, -0.08532249182462692, 0.042522601783275604, 0.017999060451984406, 0.028531121090054512, -0.05381782352924347, -0.0007608719752170146, -0.031386833637952805, 0.1031755730509758, 0.0213145911693573, 0.004844567272812128, -0.0517282709479332, 0.029707960784435272, 0.04056740552186966, 0.0871572270989418, -0.05944402143359184, -0.04657254368066788, -0.03194348141551018, -0.042258214205503464, -0.030564233660697937, 0.06326987594366074, -0.09141071140766144, 0.02144106850028038, 0.0022626668214797974, -0.013721493072807789, -0.04572523012757301, -0.05970871075987816, 0.10727470368146896, -0.040328532457351685, 0.009416303597390652, 0.11238399893045425, -0.001596877002157271, -0.03981955721974373, -0.05060427635908127, -0.041587792336940765, -0.06626035273075104, -0.06725819408893585, -0.10546354949474335, -0.002246745163574815, 0.04389533773064613, -0.009026131592690945, 0.02867252193391323, 0.07932776212692261, 0.007459576707333326, -0.12606413662433624, -0.052171267569065094, 0.012459996156394482, 0.11291936039924622, 0.050249140709638596, -0.07340274006128311, -0.02422488108277321, -0.00932371523231268, 0.005796537268906832, 0.012643159367144108, -0.03122762404382229, 0.012900084257125854, -0.019921639934182167, 0.06958231329917908, -0.0032596951350569725, 0.04496068134903908, -0.06726966798305511, 0.016569221392273903, -0.07075616717338562, 0.010246560908854008, -0.06649700552225113, -0.05849691480398178, -0.014169096946716309, -0.053992077708244324, -0.11203811317682266, -0.021699894219636917, -0.05364129692316055, -0.09671010822057724, -0.042291294783353806, 0.014107982628047466, -0.0066694412380456924, -0.021423671394586563, -0.027334485203027725, -0.05284697189927101, -0.005280576646327972, 0.02664201892912388, -0.0029547885060310364, -0.060432594269514084, -2.1293301344371685e-08, -0.017189793288707733, -0.018010616302490234, 0.08088880777359009, -0.027260906994342804, 0.025749370455741882, -0.020004285499453545, -0.0467408262193203, 0.018498528748750687, 0.0012907000491395593, 0.043701913207769394, -0.02500283531844616, 0.11011547595262527, 0.08761470764875412, 0.02736625447869301, 0.04713497310876846, -0.007961985655128956, -0.0006715374765917659, 0.03274354711174965, -0.10288318246603012, -0.05607229471206665, -0.05875064805150032, -0.0024734160397201777, -0.010905305854976177, 0.021494342014193535, 0.0847666934132576, -0.010868802666664124, 0.02110014483332634, 0.07930167764425278, -0.08055087178945541, 0.09943369030952454, 0.08771485090255737, 0.05414040759205818, 0.05737246200442314, 0.0460737980902195, -0.10882052779197693, -0.04919659346342087, 0.08129394054412842, -0.0363227017223835, 0.08761294931173325, -0.044425301253795624, 0.013745537959039211, 0.008234838955104351, 0.02544073387980461, 0.04185790196061134, -0.022686652839183807, 0.009713591076433659, 0.014909876510500908, 0.024291522800922394, 0.03457659110426903, -0.02821921743452549, 0.03092154487967491, -0.029362963512539864, -0.013743589632213116, 0.04736267030239105, 0.0016586004057899117, 0.019513051956892014, 0.02396135963499546, -0.02296604961156845, 0.011246418580412865, 0.038386259227991104, -0.08463146537542343, 0.008799071423709393, 0.14216884970664978, -0.025602858513593674]'), +('The nursing process is a systematic, problem-solving framework that guides all nursing actions. It provides a structured and logical method for delivering patient-centered care. This process is comprised of five distinct but interconnected steps: Assessment, Diagnosis, Planning, Implementation, and Evaluation. By following these steps, nurses can ensure that the care they provide is organized, individualized, and effective. The process is not linear but cyclical, meaning the evaluation of one care plan often leads to a new assessment and a revised plan, reflecting the dynamic nature of a patient''s health status. The first step, Assessment, is the collection of comprehensive data about the patient. This includes both subjective data, which is what the patient says about their symptoms and feelings, and objective data, which is observable and measurable information like vital signs, lab results, and physical examination findings. The second step, Diagnosis, involves analyzing the assessment data to identify actual or potential health problems. These are formulated as nursing diagnoses, which focus on the patient''s response to their health condition, such as "Impaired Gas Exchange" or "Risk for Infection." Following the diagnosis, the nurse moves to the Planning phase. Here, patient-centered goals and expected outcomes are established, and specific nursing interventions are selected to help achieve those goals. These goals should be specific, measurable, achievable, relevant, and time-bound (SMART). The fourth step, Implementation, is the action phase where the planned interventions are carried out. This could involve administering medication, providing wound care, educating the patient, or coordinating with other healthcare team members. Finally, the Evaluation phase determines whether the patient''s goals were met. The nurse assesses the patient''s response to the interventions and decides if the plan of care should be continued, modified, or terminated.', 'Why is the nursing process described as cyclical?', '[-0.06219138950109482, -0.053560275584459305, -0.061119355261325836, 0.016343455761671066, 0.013680923730134964, 0.013319027610123158, -0.081910640001297, -0.02198648825287819, 0.12309019267559052, 0.026067441329360008, 0.005022760946303606, 0.09798666089773178, 0.008643107488751411, 0.005913314875215292, -0.04449181631207466, -0.06087489426136017, -0.11108200997114182, -0.03211875632405281, 0.04989013820886612, 0.06500469148159027, -0.0005211690440773964, 0.003419118467718363, 0.012655368074774742, 0.0470699667930603, -0.01853199303150177, -0.013212618418037891, -0.07134959846735, -0.04987526312470436, 0.09069547802209854, 0.0533190555870533, -0.010435688309371471, 0.11025289446115494, 0.016298217698931694, 0.010376771911978722, -0.043934036046266556, 0.04545236751437187, -0.020589662715792656, 0.049233097583055496, -0.033945947885513306, 0.0196079071611166, 0.03932853415608406, -0.03617408126592636, -0.014688718132674694, -0.004265854600816965, 0.031041806563735008, -0.001698042149655521, -0.04719669744372368, -0.04671934247016907, -0.04951416328549385, -0.017821550369262695, -0.08216118067502975, -0.08869442343711853, -0.06202470883727074, 0.0931105762720108, -0.004811775870621204, 0.01874256320297718, 0.07688132673501968, -0.022436173632740974, -0.07652847468852997, -0.029846424236893654, 0.0018613504944369197, 0.04048824682831764, -0.05929088592529297, 0.06349800527095795, 0.06870932877063751, -0.008519806899130344, 0.0029001636430621147, -0.02507248893380165, 0.03292233496904373, -0.08973424136638641, 0.03514280170202255, -0.07309383153915405, 0.026597902178764343, 0.022449329495429993, -0.00016657703963574022, -0.0005467347800731659, 0.02424304001033306, -0.04281863942742348, -0.022475972771644592, -0.0582856647670269, -0.002450041938573122, 0.0332036018371582, 0.048184219747781754, -0.01576785184442997, -0.03184758126735687, -0.019211795181035995, 0.029401622712612152, -0.033699262887239456, -0.004378009121865034, -0.021964389830827713, 0.028020154684782028, 0.08330173790454865, -0.0567970871925354, -0.023362737149000168, -0.03977745771408081, 0.02100568823516369, -0.002640599850565195, 0.05366966873407364, 0.03298700228333473, -0.0017719564493745565, 0.006685703527182341, 0.06058373302221298, 0.011500146239995956, 0.04012267664074898, -0.027960006147623062, -0.07529015094041824, 0.006430438719689846, -0.08625666797161102, -0.040084224194288254, -0.0070759146474301815, -0.10358370095491409, 0.03927097097039223, 0.03578603267669678, 0.022204458713531494, -0.030933823436498642, 0.030950933694839478, -0.04680202528834343, -0.005402314011007547, 0.11419264227151871, 0.07973385602235794, 0.04976874217391014, -0.01249613892287016, -0.0384955108165741, -0.017800645902752876, 0.009708731435239315, 0.008213374763727188, 0.0424533411860466, -4.7736348042313074e-33, 0.017713170498609543, -0.05698227137327194, 0.10134000331163406, 0.0005099513800814748, 0.005072027910500765, 0.021984579041600227, -0.056940097361803055, -0.06558216363191605, 0.09167484939098358, -0.07704000920057297, 0.03397034853696823, 0.023488733917474747, -0.016387537121772766, -0.06925872713327408, 0.007185088470578194, -0.05614769086241722, -0.10045605897903442, 0.018786810338497162, 0.0658702552318573, 0.049095410853624344, -0.011866122484207153, 0.026046257466077805, -0.07882914692163467, 0.03690124303102493, -0.030862512066960335, -0.025121351704001427, -0.009228339418768883, 0.03686034679412842, -0.029879629611968994, 0.030562015250325203, 0.02556013874709606, -0.009884800761938095, -0.10867266356945038, -0.01720958948135376, 0.0022533033043146133, 0.01568496972322464, 0.012375783175230026, 0.007234619930386543, 0.0015223091468214989, 0.029223598539829254, -0.09561803936958313, -0.04625682532787323, 0.003290971042588353, 0.04787357896566391, 0.08275313675403595, 0.019329264760017395, 0.009701361879706383, -0.011001711711287498, -0.08075689524412155, -0.01822996325790882, 0.06335198134183884, -0.034948449581861496, 0.021079163998365402, -0.09540341794490814, -0.012364678084850311, 0.05105080455541611, 0.019278012216091156, -0.04260678216814995, -0.08629355579614639, 0.07178604602813721, 0.10559061169624329, 5.302304634824395e-05, -0.010266916826367378, 0.03165674954652786, 0.04341667518019676, 0.002852367702871561, -0.10679037123918533, -0.042637258768081665, 0.12034754455089569, -0.003765055211260915, -0.04906586557626724, -0.01893782429397106, -0.004348272457718849, -0.015612293966114521, 0.03464600816369057, -0.001798913348466158, 0.06254962086677551, -0.026651622727513313, -0.014690727926790714, -0.04599221423268318, -0.010012962855398655, -0.010485883802175522, -0.044504180550575256, 0.04125402495265007, 0.0652882382273674, -0.06108569726347923, -0.03469466045498848, 0.07475067675113678, -0.07486830651760101, 0.01869053579866886, 0.0014476203359663486, 0.048670295625925064, 0.12976042926311493, 0.05065317824482918, 0.024284902960062027, 1.48751555092364e-33, -0.02937605045735836, -0.0015393521171063185, -0.06906034052371979, 0.028709519654512405, 0.09921013563871384, -0.07805242389440536, -0.08638442307710648, -0.03184227645397186, 0.053663164377212524, 0.015608039684593678, 0.039831846952438354, -0.054273154586553574, -0.005314429756253958, 0.08451148867607117, -0.0018996577709913254, 0.003991730976849794, 0.0356193371117115, 0.014304322190582752, -0.028387287631630898, 0.04051590710878372, 0.023050758987665176, 0.08587606996297836, -0.06764846295118332, -0.019843660295009613, 0.03549296036362648, 0.060174912214279175, -0.08855176717042923, 0.04449616000056267, 0.054979488253593445, 0.04531412199139595, -0.06050945818424225, -0.05361932888627052, 0.027087073773145676, 0.06583618372678757, 0.00802699290215969, -0.00066164112649858, -0.04507138952612877, -0.04212496429681778, -0.004995931405574083, -0.024385670199990273, 0.021014761179685593, -0.03718484565615654, 0.0012918022694066167, 0.018404919654130936, 0.04555872455239296, -0.006475439760833979, 0.027994953095912933, 0.020936891436576843, -0.012772866524755955, -0.028305334970355034, 0.017439857125282288, -0.004701456055045128, -0.03646828234195709, -0.0025799258146435022, -0.004196554888039827, 0.006939088460057974, 0.06298863887786865, -0.05226847156882286, -0.010788899846374989, 0.023624366149306297, 0.09026597440242767, 0.04085415229201317, -0.021234940737485886, -0.013811740092933178, -0.004601546563208103, -0.0016692542703822255, 0.00856183934956789, -0.026608724147081375, -0.034079261124134064, -0.0015399373369291425, 0.04312882572412491, 0.11255043745040894, -0.0659605860710144, 0.020477285608649254, -0.02396932616829872, 0.0365389809012413, 0.03395815193653107, -0.1170504167675972, -0.10433769971132278, -0.06431931257247925, -0.1604263335466385, -0.03734103590250015, -0.005377453286200762, -0.003392194863408804, -0.16395844519138336, -0.08417471498250961, 0.019046198576688766, -0.03791330009698868, -0.004468967206776142, -0.05627434328198433, 0.027148455381393433, -0.07909543067216873, -0.027025775983929634, 0.050222158432006836, -0.05470502749085426, -1.7250400219381845e-08, -0.00040549266850575805, -0.02589453011751175, 0.05435522645711899, -0.04233746975660324, 0.09262699633836746, -0.12224561721086502, 0.0507134310901165, -0.023624278604984283, 0.05319540202617645, 0.03891950100660324, -0.02795799821615219, 0.05573556199669838, 0.07996799051761627, 0.04244939610362053, 0.1050022691488266, 0.05999419465661049, -0.003920598886907101, 0.007155491504818201, -0.04932956397533417, -0.017182013019919395, 0.030747827142477036, -0.071828193962574, -0.0635824054479599, -0.00776784960180521, -0.03249768167734146, 0.019861727952957153, -0.018111703917384148, 0.08633610606193542, -0.009025485254824162, -0.0443640872836113, 0.05518803745508194, 0.06823422759771347, 0.044101789593696594, 0.059657540172338486, -0.12515851855278015, -0.035013649612665176, 0.06847704201936722, -0.014173796400427818, -0.014069365337491035, -0.07624559104442596, 0.010496562346816063, 0.00727450056001544, -0.03325538709759712, 0.0466303788125515, 0.043780624866485596, -0.045123107731342316, -0.0021012090146541595, 0.034303538501262665, -0.013012073002755642, -0.032481785863637924, -0.009641162119805813, -0.03437524288892746, 0.06951916962862015, 0.027494892477989197, 0.035994354635477066, 0.06923792511224747, 0.06180163100361824, -0.07334728538990021, -0.012270660139620304, 0.015632305294275284, -0.05665203183889389, 0.06980564445257187, 0.17523832619190216, -0.022145256400108337]'), +('Holistic nursing care is a philosophy that emphasizes treating the patient as a whole person, not merely as a collection of symptoms or a medical diagnosis. This approach recognizes the interconnectedness of the physical, psychological, social, and spiritual dimensions of an individual''s health and well-being. To provide holistic care, a nurse must look beyond the immediate illness and consider the patient’s lifestyle, culture, belief system, family relationships, and emotional state. This comprehensive view allows for a deeper understanding of the patient''s needs and leads to a more personalized and effective plan of care. A cornerstone of holistic care is empathy, which is the ability to understand and share the feelings of another person. It differs from sympathy, which is feeling pity or sorrow for someone else''s misfortune. An empathetic nurse strives to see the situation from the patient''s perspective, validating their emotions and experiences without judgment. This fosters a strong therapeutic relationship built on trust and respect. Furthermore, cultural competence is essential. Nurses must be aware of and sensitive to the diverse backgrounds of their patients, recognizing that cultural beliefs can significantly influence health practices, dietary preferences, and communication styles. Ultimately, patient-centered care positions the patient as an active partner in their own healthcare journey. This involves including them in decision-making, respecting their values and preferences, and providing them with the education needed to manage their condition effectively. When patients feel heard, respected, and involved, they are more likely to adhere to their treatment plans, report satisfaction with their care, and experience better overall health outcomes. It is the nurse''s role to advocate for the patient, ensuring their voice is central to every discussion about their health.', 'What does the concept of ''holistic care'' entail beyond treating a patient''s physical symptoms?', '[0.005433638114482164, 0.059027716517448425, -0.01033454854041338, 0.0765039324760437, -0.041128408163785934, -0.061488520354032516, -0.03174971789121628, -0.05233105644583702, -0.06173061206936836, -0.07304898649454117, 0.03731158748269081, 0.05917365849018097, -0.030900897458195686, -0.03600090369582176, 0.035689689218997955, -0.018127141520380974, -0.012376567348837852, -0.03733767941594124, 0.00886914785951376, 0.07403703778982162, -0.0735202357172966, 0.01275895070284605, -0.008608231320977211, 0.07415477931499481, -0.04484957829117775, 0.037002742290496826, -0.0062402584590017796, -0.036164216697216034, -0.03927389159798622, 0.044833313673734665, 0.06982319802045822, 0.08278673887252808, -0.031142937019467354, 0.04806465283036232, -0.07750619202852249, 0.15961989760398865, -0.022908803075551987, 0.00939437747001648, -0.06985614448785782, -0.023734549060463905, -0.03612961620092392, 0.008180773817002773, -0.010985788889229298, 0.08180326968431473, 0.059687212109565735, -0.014192928560078144, -0.013614611700177193, -0.005084895994514227, -0.02527792751789093, -0.028791118413209915, -0.12273099273443222, 0.02833274006843567, 0.02040669322013855, 0.02829679846763611, -0.03877801448106766, 0.0225040465593338, -0.022188987582921982, -0.0578436553478241, -0.11035975813865662, 0.06973614543676376, 0.004510661121457815, -0.07881540060043335, 0.005428456701338291, 0.04308522865176201, 0.06363920122385025, -0.04409471154212952, -0.02973862923681736, -0.05164935067296028, 0.010297413915395737, -0.058320920914411545, -0.003401365363970399, -0.03309015929698944, 0.03898532688617706, 0.08960887044668198, 0.04653079807758331, -0.031501248478889465, -0.06745370477437973, -0.0424429289996624, -0.005503979045897722, 0.01874726451933384, 0.06290030479431152, 0.1356642097234726, 0.07418637722730637, 0.03650730475783348, 0.005681025795638561, 0.029042882844805717, 0.02949109487235546, -0.004167067818343639, -0.061464253813028336, -0.034443411976099014, -0.02106689289212227, -0.032777633517980576, -0.06943434476852417, -0.06490841507911682, 0.020614629611372948, 0.01966836303472519, -0.03410327434539795, 0.03816808760166168, -0.09873355180025101, -0.02907520905137062, -0.0024375151842832565, -0.057189784944057465, 0.038178641349077225, 0.0900612473487854, 0.02901521697640419, 0.015797320753335953, 0.008053210563957691, 0.02404230833053589, -0.029278025031089783, -0.03900286182761192, -0.031601425260305405, 0.007271942682564259, -0.00040203126263804734, -0.07114984840154648, 0.0030402401462197304, 0.03283672407269478, 0.06840738654136658, -0.070735864341259, -0.0013942945515736938, -0.08467306941747665, 0.04943586140871048, -0.05160066857933998, 0.09454212337732315, -0.08929967880249023, -0.03384352847933769, -0.009942226111888885, 0.04260971397161484, -4.5360299270476906e-33, 0.01587255299091339, 0.014803027734160423, 0.020390024408698082, 0.011367020197212696, -0.00626372592523694, 0.06160375475883484, 0.025400398299098015, -0.03480071201920509, 0.10351229459047318, 0.037340838462114334, 0.05260300636291504, 0.09403079748153687, 0.0791073888540268, 0.0657273381948471, -0.04794355481863022, -0.007196062710136175, -0.13021063804626465, 0.09279501438140869, 0.005750591866672039, -0.01109218131750822, -0.04720933735370636, 0.05910670384764671, -0.06136634945869446, 0.02743045799434185, -0.06472314894199371, -0.040548719465732574, 0.048853129148483276, 0.01563679613173008, 0.017915382981300354, -0.02587764896452427, 0.03485984727740288, 0.08459945768117905, -0.019325537607073784, -0.032426681369543076, -0.030558530241250992, 0.027388932183384895, -0.048219818621873856, -0.008485020138323307, 0.025424819439649582, -0.07893820106983185, 0.04077586904168129, -0.007128085009753704, 0.04547407850623131, 0.02905454859137535, 0.01167396828532219, 0.0697924941778183, -0.03078862838447094, -0.0960320308804512, -0.13062188029289246, 0.0006608288385905325, 0.006182360928505659, -0.017604485154151917, 0.006486664060503244, 0.04789133369922638, 0.008846098557114601, 0.03776107355952263, 0.08730220049619675, 0.03891400620341301, 0.0037796683609485626, -0.03128329664468765, 0.07246407866477966, -0.08879615366458893, -0.08569616824388504, -0.0014629691140726209, -0.014963557943701744, -0.04196769744157791, -0.005709988065063953, -0.06310240924358368, -0.049819670617580414, 0.06386285275220871, -0.051384422928094864, -0.0017347014509141445, -0.08775094151496887, 0.053941622376441956, -0.04891934245824814, -0.058019183576107025, -0.055236343294382095, -0.04914693534374237, -0.0918712168931961, 0.038210224360227585, -0.03480922430753708, 0.021515978500247, 0.011918185278773308, 0.17482474446296692, 0.043953053653240204, 0.04974972829222679, -0.08405778557062149, 0.07758195698261261, -0.02848156914114952, -0.09715213626623154, 0.0045708222314715385, 0.07415234297513962, 0.04022089019417763, 0.0355130136013031, -0.018981844186782837, 1.7107780883714046e-34, 0.09328622370958328, 0.016933364793658257, -0.00480645103380084, 0.09028708189725876, 0.03935035690665245, 0.003732240293174982, -0.03584430366754532, 0.015642521902918816, 0.03012637235224247, 0.018665481358766556, 0.033781908452510834, 0.015621989034116268, -0.05201134458184242, -0.0001820103352656588, -0.06281092017889023, 0.03381473571062088, -0.08094508945941925, -0.010020626708865166, 0.005866728723049164, 0.05742768198251724, -0.014041850343346596, 0.0909552127122879, -0.009191416203975677, -0.018442263826727867, 0.010687810368835926, 0.03878598287701607, 0.09285695105791092, -0.02725047618150711, -2.6438365239300765e-05, -0.07063319534063339, 0.015149972401559353, 0.012801580131053925, 0.026308760046958923, 0.003884757636114955, -0.03550492972135544, 0.007312492933124304, 0.015798980370163918, -0.006968495901674032, -0.05310870707035065, 0.013152522966265678, 0.03379765897989273, -0.044002316892147064, -0.02911016345024109, 0.0654740184545517, -0.012325456365942955, 0.012743378058075905, -0.0055972435511648655, 7.517462654504925e-05, -0.09986519813537598, 0.012148660607635975, 0.0582314170897007, 0.01137025561183691, -0.04614919796586037, -0.026158446446061134, 0.001501934020780027, -0.03803461790084839, -0.03903597593307495, -0.09826040267944336, -0.054139282554388046, -0.06474307924509048, 0.09781607985496521, -0.02014145627617836, -0.028129007667303085, 0.02010725438594818, -0.08784559369087219, 0.08802882581949234, 0.025354992598295212, 0.027922077104449272, -0.015907716006040573, 0.040766336023807526, -0.07691456377506256, -0.033309176564216614, -0.04155258461833, -0.033015839755535126, 0.047172561287879944, 0.026523908600211143, -0.06684670597314835, -0.03911973163485527, 0.005668724421411753, 0.029120322316884995, -0.08827878534793854, -0.13649867475032806, 0.04645878076553345, -0.04820618778467178, -0.014772123657166958, -0.011771355755627155, -0.039847150444984436, -0.03917520120739937, -0.06798161566257477, -0.009826873429119587, -0.039891455322504044, 0.01499239169061184, -0.11121518909931183, 0.011133400723338127, -0.02980703115463257, -2.533348819611092e-08, -0.007605355232954025, 0.0061142174527049065, 0.014103076420724392, -0.06744447350502014, -0.04517633095383644, -0.0054293000139296055, 0.02286769449710846, 0.07695716619491577, -0.029042666777968407, 0.1466786414384842, -0.03347950428724289, 0.0795554667711258, -0.004955979995429516, 0.05645282566547394, 0.015493934042751789, -0.07192017883062363, -0.008896611630916595, 0.06143547594547272, -0.0540209598839283, -0.00996850524097681, 0.03917746618390083, -0.023626388981938362, 0.022845691069960594, -0.0077372766099870205, 0.051911648362874985, -0.0583290196955204, -0.012066219933331013, 0.08492988348007202, -0.008026543073356152, -0.05186669901013374, 0.025446817278862, 0.0463561974465847, 0.0013266286114230752, 0.015272635966539383, -0.034566789865493774, -0.026351185515522957, -0.00013865884102415293, -0.08372466266155243, 0.030590848997235298, -0.062227703630924225, -0.03952814266085625, 0.07758955657482147, -0.027937451377511024, 0.040033116936683655, 0.023444104939699173, -0.06765662133693695, 0.07838334888219833, 0.04907264932990074, 0.022210652008652687, -0.03063151426613331, 0.045190270990133286, 0.06291843950748444, 0.06983233243227005, 0.007759337313473225, -0.08006003499031067, 0.05340496450662613, 0.040609367191791534, 0.017804795876145363, -0.03861255198717117, -0.02246273308992386, 0.02663550339639187, 0.0006013691890984774, 0.016052816063165665, -0.03130929172039032]'), +('Holistic nursing care is a philosophy that emphasizes treating the patient as a whole person, not merely as a collection of symptoms or a medical diagnosis. This approach recognizes the interconnectedness of the physical, psychological, social, and spiritual dimensions of an individual''s health and well-being. To provide holistic care, a nurse must look beyond the immediate illness and consider the patient’s lifestyle, culture, belief system, family relationships, and emotional state. This comprehensive view allows for a deeper understanding of the patient''s needs and leads to a more personalized and effective plan of care. A cornerstone of holistic care is empathy, which is the ability to understand and share the feelings of another person. It differs from sympathy, which is feeling pity or sorrow for someone else''s misfortune. An empathetic nurse strives to see the situation from the patient''s perspective, validating their emotions and experiences without judgment. This fosters a strong therapeutic relationship built on trust and respect. Furthermore, cultural competence is essential. Nurses must be aware of and sensitive to the diverse backgrounds of their patients, recognizing that cultural beliefs can significantly influence health practices, dietary preferences, and communication styles. Ultimately, patient-centered care positions the patient as an active partner in their own healthcare journey. This involves including them in decision-making, respecting their values and preferences, and providing them with the education needed to manage their condition effectively. When patients feel heard, respected, and involved, they are more likely to adhere to their treatment plans, report satisfaction with their care, and experience better overall health outcomes. It is the nurse''s role to advocate for the patient, ensuring their voice is central to every discussion about their health.', 'Why is cultural competence essential for providing effective nursing care?', '[0.04892979562282562, 0.0025941082276403904, -0.06484168022871017, 0.02809750847518444, -0.04280642792582512, 0.03658784553408623, -0.026890954002738, -0.036378756165504456, 0.028394047170877457, -0.09890635311603546, -0.02258268930017948, 0.004862186964601278, -0.010091383010149002, 0.061744946986436844, -0.02435333840548992, -0.038876693695783615, -0.005679538007825613, -0.006688210181891918, -0.004226990509778261, 0.00483633391559124, -0.08338793367147446, -0.019996028393507004, 0.05874127149581909, 0.03919447213411331, -0.024306396022439003, -0.017589716240763664, 0.004014463163912296, -0.06431008130311966, 0.11979088932275772, 0.05953221023082733, 0.01870282180607319, 0.02397167682647705, 0.010156982578337193, 0.021676218137145042, -0.08857350796461105, 0.1071726381778717, -0.01956029422581196, -0.015821954235434532, -0.023819582536816597, -0.015274272300302982, -0.001466612913645804, -0.0036790347658097744, 0.03386840969324112, -0.035748448222875595, 0.0705873891711235, -0.010431259870529175, 0.008022289723157883, 0.09650371968746185, -0.04551709443330765, -0.028566161170601845, -0.08732753247022629, -0.0038808330427855253, 0.0037900335155427456, -0.00296099204570055, 0.018226206302642822, -0.017324503511190414, 0.04903775826096535, -0.03581814095377922, -0.054758939892053604, 0.030391875654459, -0.050448354333639145, -0.010143346153199673, -0.025348851457238197, 0.04902023449540138, 0.033881958574056625, -0.024703625589609146, -0.06264408677816391, -0.025353115051984787, 0.0024912755470722914, -0.09191922098398209, -0.01708347722887993, -0.04706611484289169, 0.06922930479049683, 0.1281784474849701, 0.03526980057358742, 0.0010683677392080426, 0.04427771270275116, -0.10712770372629166, -0.05825989320874214, 0.001734931138344109, 0.09318006783723831, 0.07787379622459412, 0.044117603451013565, 0.0028275244403630495, 0.03296123445034027, 0.025245053693652153, 0.026619860902428627, -0.08263217657804489, -0.03642901033163071, -0.0027584268245846033, 0.09490553289651871, 0.0639897957444191, -0.06422869861125946, -0.028658835217356682, -0.03518707677721977, 0.0027285709511488676, -0.031791843473911285, 0.028537286445498466, -0.03980116918683052, -0.03258778899908066, 0.052814286202192307, 0.0150303291156888, -0.00866029318422079, 0.04985010623931885, -0.052657365798950195, -0.05809885263442993, 0.07847202569246292, -0.011516950093209743, -0.05800825357437134, 0.003227289766073227, -0.05294864624738693, 0.06264739483594894, -0.08277815580368042, 0.03701871261000633, 0.012105032801628113, -0.01631181500852108, 0.013871436007320881, -0.1046312004327774, 0.005117517895996571, -0.03772974759340286, -0.0025602735113352537, 0.0028066362719982862, -0.03829260915517807, -0.0592009611427784, 0.010974093340337276, -0.047724783420562744, 0.009784235619008541, -3.474706567074972e-33, -0.010001827962696552, 0.02608838491141796, 0.05103045701980591, 0.02721814624965191, 0.04247158765792847, -0.013210245408117771, 0.000979888834990561, -0.08082804083824158, 0.003599878866225481, 0.00011346334940753877, -0.010084071196615696, 0.06476534903049469, 0.005208267830312252, -0.038621556013822556, 0.009997791610658169, 0.06529054790735245, -0.10854267328977585, -0.0054892078042030334, -0.0005734767182730138, 0.10406862199306488, 0.09196046739816666, 0.007006541360169649, 0.016579506918787956, -0.024460045620799065, -0.08023083209991455, -0.035552363842725754, 0.03888890892267227, 0.048021018505096436, 0.055984772741794586, 0.019499555230140686, 0.011720621958374977, -0.05096689239144325, -0.08693571388721466, -0.01727432757616043, 0.011184840463101864, 0.024919714778661728, -0.016082389280200005, -0.01002628356218338, 0.003436372149735689, 0.024194542318582535, -0.009377303533256054, 0.04798223450779915, -0.02251531556248665, 0.07827895134687424, 0.07386147230863571, 0.03117380291223526, 0.07466667890548706, -0.08954993635416031, -0.10875538736581802, 0.03608706220984459, -0.00018628450925461948, -0.056751031428575516, -0.014035494066774845, -0.07786951214075089, 0.08512664586305618, 0.03813399374485016, 0.08314798772335052, 0.0693877637386322, 0.009297906421124935, -0.019829511642456055, -0.021182380616664886, -0.08159919828176498, -0.08667350560426712, 0.08539701998233795, 0.0731954500079155, -0.028295833617448807, 0.03012022376060486, -0.04380057752132416, 0.029516298323869705, -0.0690520629286766, 0.0010919241467490792, -0.043945830315351486, 0.004051958676427603, 0.013135875575244427, -0.06674245744943619, 0.0020814549643546343, -0.016314731910824776, -0.09424596279859543, 0.09085305780172348, -0.027910929173231125, -0.03833726793527603, 0.04858594760298729, -0.041312821209430695, 0.08996260911226273, -0.020813308656215668, -0.03379685804247856, 0.004940273240208626, 0.036469716578722, 0.004076160024851561, 0.01288212463259697, 0.019900977611541748, 0.039224229753017426, 0.10099979490041733, -0.05022170767188072, 0.01018523145467043, 6.972048012558996e-34, 0.09662111848592758, -0.003504060907289386, -0.037755127996206284, 0.06291086226701736, 0.011989807710051537, -0.037654031068086624, 0.005475678015500307, 0.009823506698012352, 0.046256013214588165, 0.002468273276463151, 0.017463319003582, -0.09294429421424866, 0.04930536448955536, 0.11807090789079666, -0.0350574254989624, -0.008506678976118565, -0.019452093169093132, 0.014798282645642757, -0.006570666097104549, 0.020502757281064987, 0.05259283259510994, 0.1718299239873886, -0.05481547489762306, 0.05625046417117119, -0.048232682049274445, 0.012520506978034973, -0.11761392652988434, -0.013644389808177948, -0.026212552562355995, 0.006786248181015253, -0.012227710336446762, 0.029268257319927216, 0.03260175883769989, 0.06453700363636017, -0.03513520583510399, 0.0056179361417889595, 0.00826822780072689, -0.006356360390782356, -0.023034576326608658, 0.06655582785606384, -0.01726241037249565, 0.03133189305663109, -0.11191697418689728, 0.05879160389304161, -0.0051504019647836685, -0.020884009078145027, 0.044131290167570114, -0.04451968893408775, -0.02161663956940174, -0.05694563686847687, -0.012894946150481701, -0.13045327365398407, -0.017377162352204323, -0.050679828971624374, -0.006895072292536497, -0.01703782193362713, 0.05578109994530678, -0.08149249851703644, 0.02157220058143139, 0.0037655094638466835, 0.10185755044221878, 0.05940741300582886, -0.07259643077850342, -0.03847702592611313, -0.013547993265092373, -0.058598924428224564, 0.039210762828588486, 0.09498810023069382, 0.04095753654837608, -0.029173079878091812, 0.0036582285538315773, 0.057437535375356674, -0.020718883723020554, -0.05005323141813278, -0.08705493807792664, 0.08551110327243805, 0.01799609325826168, -0.05099119246006012, -0.02425352856516838, 0.020113883540034294, -0.08712897449731827, -0.06991671025753021, -0.02727484703063965, -0.08165618032217026, -0.032947782427072525, 0.05168033763766289, -0.03661021217703819, -0.032390251755714417, 0.0077310227788984776, -0.03962711989879608, -0.06228553503751755, -0.0606183260679245, -0.04036962613463402, -0.030636202543973923, -0.08217005431652069, -1.861022624893849e-08, -0.08699645102024078, -0.028953764587640762, 0.00768900103867054, -0.05281498283147812, -0.028561091050505638, -0.03722080960869789, -0.07370534539222717, 0.06520318984985352, 0.025593530386686325, 0.11750190705060959, -0.06291361898183823, -0.024946322664618492, 0.016202041879296303, -0.005092328414320946, 0.0712423026561737, 0.032397348433732986, 0.04919181391596794, 0.11053062975406647, -0.05939245969057083, 0.03928719088435173, 0.055749304592609406, -0.005506042391061783, -0.061205729842185974, -0.06392599642276764, -0.0130069050937891, 0.024779781699180603, -0.10922695696353912, 0.01986544020473957, -0.0855247974395752, -0.04027821496129036, 0.06645667552947998, 0.001338472357019782, 0.050721585750579834, 0.03197089210152626, -0.023172346875071526, -0.0028338187839835882, 0.042207807302474976, -0.01984275132417679, 0.06035342067480087, -0.08398787677288055, 0.015250429511070251, 0.010434593074023724, 0.021229952573776245, 0.008828368037939072, -0.014027944765985012, -0.013363976962864399, 0.003660164773464203, 0.1052468866109848, -0.02748969756066799, 0.05483337119221687, 0.02461358532309532, -0.07600031793117523, 0.007275276817381382, -0.0003022183373104781, 0.04182541370391846, 0.06022913381457329, 0.0318743996322155, 0.032118991017341614, -0.019229618832468987, 0.04391249641776085, -0.016075393185019493, 0.09430238604545593, 0.12569034099578857, -0.04189901426434517]'), +('Holistic nursing care is a philosophy that emphasizes treating the patient as a whole person, not merely as a collection of symptoms or a medical diagnosis. This approach recognizes the interconnectedness of the physical, psychological, social, and spiritual dimensions of an individual''s health and well-being. To provide holistic care, a nurse must look beyond the immediate illness and consider the patient’s lifestyle, culture, belief system, family relationships, and emotional state. This comprehensive view allows for a deeper understanding of the patient''s needs and leads to a more personalized and effective plan of care. A cornerstone of holistic care is empathy, which is the ability to understand and share the feelings of another person. It differs from sympathy, which is feeling pity or sorrow for someone else''s misfortune. An empathetic nurse strives to see the situation from the patient''s perspective, validating their emotions and experiences without judgment. This fosters a strong therapeutic relationship built on trust and respect. Furthermore, cultural competence is essential. Nurses must be aware of and sensitive to the diverse backgrounds of their patients, recognizing that cultural beliefs can significantly influence health practices, dietary preferences, and communication styles. Ultimately, patient-centered care positions the patient as an active partner in their own healthcare journey. This involves including them in decision-making, respecting their values and preferences, and providing them with the education needed to manage their condition effectively. When patients feel heard, respected, and involved, they are more likely to adhere to their treatment plans, report satisfaction with their care, and experience better overall health outcomes. It is the nurse''s role to advocate for the patient, ensuring their voice is central to every discussion about their health.', 'How can a nurse actively involve a patient in their own care?', '[0.013009044341742992, -0.0419403500854969, -0.03609926253557205, 0.03810810297727585, -0.06424707174301147, -0.0056242267601192, 0.0017759059555828571, 0.023703904822468758, 0.0047218394465744495, -0.053543925285339355, -0.05668995901942253, 0.05300750583410263, -0.07560354471206665, 0.06273669004440308, 0.008944201283156872, -0.03955531120300293, -0.030413469299674034, -0.017289310693740845, -0.0021655759774148464, 0.05478071793913841, -0.09715023636817932, -0.057313092052936554, 0.018667323514819145, 0.016732560470700264, -0.0086270896717906, -0.03780962526798248, 0.027818815782666206, -0.042012546211481094, 0.04434135928750038, 0.05805274844169617, 0.027184434235095978, -0.03534586355090141, 0.00046474451664835215, 0.07209289819002151, -0.06886844336986542, 0.058448564261198044, -0.029235288500785828, 0.07497568428516388, -0.057067420333623886, -0.001997410086914897, 0.03750613331794739, -0.01497634407132864, 0.03847217187285423, 0.03336434066295624, 0.06381535530090332, -0.03888602927327156, 0.0211171917617321, 0.0839555561542511, -0.003879108000546694, -0.04617190733551979, -0.09065673500299454, -0.07129081338644028, -0.042120903730392456, 0.029817042872309685, 0.03385750204324722, -0.014753193594515324, 0.06451206654310226, -0.048331353813409805, -0.04557206109166145, 0.004207120276987553, -0.012625024653971195, 0.04753575846552849, 0.0030897215474396944, 0.011847395449876785, 0.022908493876457214, 0.0013620645040646195, -0.02880926802754402, 0.04486323148012161, 0.015899959951639175, -0.058957088738679886, 0.01815894804894924, -0.07111597061157227, 0.03555314242839813, 0.053660422563552856, 0.03762587159872055, -0.00929485633969307, 0.021829040721058846, -0.011832194402813911, 0.04117722064256668, 0.010656715370714664, -0.02592753991484642, 0.015541436150670052, 0.06749462336301804, 0.039911750704050064, -0.024809356778860092, 0.038695525377988815, 0.027793986722826958, -0.028203589841723442, 0.013333617709577084, -0.03420388698577881, 0.006915931589901447, 0.0540749616920948, -0.08271056413650513, -0.09479031711816788, -0.007002366706728935, 0.03426849842071533, 0.020705699920654297, -0.001440318301320076, -0.05439664423465729, 0.019567904993891716, -0.005404255352914333, 0.002277029911056161, 0.0012342437403276563, 0.07323600351810455, -0.05201263353228569, 0.06992843002080917, 0.016418833285570145, -0.08713602274656296, -0.04684191197156906, 0.04279636964201927, -0.04697522521018982, 0.03738149255514145, 0.0037252893671393394, -0.028138697147369385, 0.004666945897042751, 0.052840087562799454, -0.052340153604745865, -0.04467976093292236, -0.011666099540889263, 0.04031731188297272, -0.047987647354602814, -0.009633470326662064, -0.023714782670140266, -0.023315895348787308, 0.05836285650730133, 0.06079268828034401, 0.025736240670084953, -4.1823662885554816e-33, 0.045446544885635376, 0.048841770738363266, 0.040930964052677155, 0.09290558844804764, 0.0537557490170002, 0.06137234345078468, -0.024893049150705338, -0.01960313878953457, 0.010648527182638645, 0.010880150832235813, 0.01788078062236309, 0.0748474970459938, 0.0617976076900959, -0.04152073338627815, -0.034375403076410294, 0.008359711617231369, -0.12746398150920868, 0.010964694432914257, -0.04447471722960472, 0.0822872519493103, -0.004724808968603611, 0.014274301007390022, -0.10545197874307632, 0.09250552952289581, -0.04138537123799324, -0.013541657477617264, 0.022492606192827225, 0.021071653813123703, 0.0361170656979084, 0.010830561630427837, 0.04845626652240753, 0.024154342710971832, -0.09695472568273544, -0.021267637610435486, 0.01837944984436035, 0.004981726873666048, -0.023666279390454292, 0.02887445129454136, -0.009484479203820229, 0.013103910721838474, -0.05996792018413544, 0.026687197387218475, 0.05991930142045021, 0.04509145766496658, -0.05621040239930153, 0.007316801697015762, 0.008015738800168037, -0.11062067002058029, -0.08581623435020447, -0.020235048606991768, 0.04073652997612953, -0.07532280683517456, -0.09726733714342117, -0.017121557146310806, 0.03305816650390625, -0.01065306831151247, 0.04165267571806908, 0.023924993351101875, 0.07639555633068085, 0.022109441459178925, 0.1287643015384674, -0.05182500556111336, -0.02390224300324917, 0.09663926064968109, 0.05627033859491348, -0.005913334898650646, 0.010081792250275612, -0.03179169446229935, 0.08762209117412567, -0.07116301357746124, -0.09481781721115112, 0.033087339252233505, -0.027242064476013184, -0.07883893698453903, -0.11249541491270065, 0.009398684836924076, -0.012691104784607887, -0.06582944095134735, 0.02541891112923622, 0.0037837736308574677, -0.008872165344655514, -0.02932843379676342, -0.0076550813391804695, 0.10080624371767044, -0.007005649618804455, -0.036563001573085785, -0.12318581342697144, 0.023489952087402344, -0.07156269997358322, -0.03162647783756256, -0.013688875362277031, 0.05342932790517807, 0.0577540248632431, -0.021126750856637955, 0.016715683043003082, 1.2190611101996385e-33, -0.0006678779027424753, 0.08511164784431458, -0.06916511803865433, 0.004588331561535597, 0.06859894096851349, -0.10112766921520233, -0.013990094885230064, -0.043930284678936005, 0.13600923120975494, 0.059800516813993454, -0.10929834097623825, -0.05907411128282547, -0.0050493525341153145, 0.10558333247900009, -0.08464513719081879, -0.00155915436334908, -0.008998407982289791, -0.013233124278485775, -0.06200981140136719, -0.04656340554356575, -0.03816227987408638, 0.055761586874723434, 0.04411587119102478, 0.028580326586961746, 0.059517402201890945, 0.06644061952829361, -0.043923281133174896, 0.06234356388449669, -0.045054513961076736, -0.0585530661046505, 0.0040696668438613415, -0.005061758682131767, 0.04509081691503525, -0.01396117266267538, -0.09655708819627762, 0.04264266788959503, -0.014028584584593773, -7.949041901156306e-05, -0.014440754428505898, -0.047634560614824295, 0.10853550583124161, -0.08762757480144501, -0.044743649661540985, 0.0332382507622242, -0.004617899656295776, -0.024665245786309242, -0.02618313767015934, -0.03496088460087776, -0.030695222318172455, -0.03392643481492996, -0.10211116075515747, -0.04582832753658295, 0.011818848550319672, 0.0021135832648724318, -0.0006595668382942677, -0.03387965261936188, 0.07509250938892365, -0.04583326727151871, -0.021276533603668213, 0.007210109382867813, 0.14128965139389038, -0.006002506706863642, -0.026299038901925087, 0.03346677124500275, -0.003939043264836073, -0.05952875688672066, 0.0175312552601099, -0.007458216976374388, 0.025290189310908318, 0.016584651544690132, -0.011232617311179638, 0.06407417356967926, 0.018334876745939255, -0.011620678938925266, -0.0014672556426376104, 0.02303837426006794, 0.014784526079893112, -0.10431268066167831, -0.012455543503165245, -0.00871212873607874, -0.11529652029275894, -0.08689392358064651, 0.04696580395102501, -0.07166672497987747, -0.07335840165615082, 0.012676888145506382, 0.06459809839725494, 0.01449709665030241, -0.03407156839966774, -0.060907114297151566, -0.02495458535850048, -0.0234256312251091, 0.00371284456923604, -0.06102919951081276, -0.058085847645998, -1.9698939368595347e-08, -0.05637156963348389, -0.012939702719449997, 0.07117582857608795, -0.011561867780983448, 0.03759622201323509, -0.06575609743595123, -0.04458961263298988, 0.030566412955522537, 0.021128550171852112, 0.1277497410774231, -0.012587947770953178, -0.04697714373469353, 0.045737359672784805, -0.019881172105669975, 0.17937126755714417, 0.003937985748052597, 0.025033636018633842, 0.04445476830005646, -0.11900284886360168, -0.0034854160621762276, -0.03428173065185547, 0.006462967023253441, -0.05247265100479126, -0.0322435200214386, -0.008911269716918468, 0.01716557890176773, -0.09664254635572433, 0.017621668055653572, -0.03154477849602699, 0.07688868790864944, 0.002029593801125884, 0.0374501533806324, 0.08385217189788818, 0.031431231647729874, -0.08547771722078323, -0.04429013654589653, 0.06386567652225494, -0.017806904390454292, 0.0036358293145895004, -0.1117262914776802, -0.020419148728251457, 0.02758960984647274, -0.02775331772863865, 0.037060778588056564, 0.028638891875743866, 0.02703416347503662, 0.04956623166799545, -0.020474784076213837, 0.01743929646909237, -4.860169065068476e-05, 0.10820990055799484, -0.08136005699634552, 0.059700559824705124, -0.0008024016278795898, -0.02024996094405651, 0.07769021391868591, 0.013972606509923935, 0.0648929551243782, -0.01367483101785183, 0.05661621317267418, -0.08588823676109314, 0.040521133691072464, 0.07251883298158646, 0.020481277257204056]'), +('Holistic nursing care is a philosophy that emphasizes treating the patient as a whole person, not merely as a collection of symptoms or a medical diagnosis. This approach recognizes the interconnectedness of the physical, psychological, social, and spiritual dimensions of an individual''s health and well-being. To provide holistic care, a nurse must look beyond the immediate illness and consider the patient’s lifestyle, culture, belief system, family relationships, and emotional state. This comprehensive view allows for a deeper understanding of the patient''s needs and leads to a more personalized and effective plan of care. A cornerstone of holistic care is empathy, which is the ability to understand and share the feelings of another person. It differs from sympathy, which is feeling pity or sorrow for someone else''s misfortune. An empathetic nurse strives to see the situation from the patient''s perspective, validating their emotions and experiences without judgment. This fosters a strong therapeutic relationship built on trust and respect. Furthermore, cultural competence is essential. Nurses must be aware of and sensitive to the diverse backgrounds of their patients, recognizing that cultural beliefs can significantly influence health practices, dietary preferences, and communication styles. Ultimately, patient-centered care positions the patient as an active partner in their own healthcare journey. This involves including them in decision-making, respecting their values and preferences, and providing them with the education needed to manage their condition effectively. When patients feel heard, respected, and involved, they are more likely to adhere to their treatment plans, report satisfaction with their care, and experience better overall health outcomes. It is the nurse''s role to advocate for the patient, ensuring their voice is central to every discussion about their health.', 'What is the primary difference between sympathy and empathy in a clinical context?', '[-0.0126288291066885, -0.017818592488765717, -0.019086206331849098, -0.0027866056188941, 0.008338235318660736, -0.02100210264325142, -0.048186756670475006, 0.07626799494028091, 0.08424689620733261, -0.03284646198153496, 0.037805430591106415, 0.047804947942495346, -0.02241053432226181, 0.06341654062271118, -0.03771965950727463, 0.04677551984786987, 0.07855157554149628, -0.06647220999002457, -0.01744813285768032, 0.0852653980255127, -0.005177774000912905, -0.058143358677625656, -0.0501028411090374, 0.01233519334346056, -0.0377018004655838, 0.01565353386104107, 0.014195378869771957, 0.0199770275503397, -0.0585496686398983, 0.03380044922232628, -0.010347574017941952, -0.11041401326656342, 0.03920569643378258, 0.01165578793734312, 0.024046696722507477, 0.04614374414086342, -0.029425332322716713, 0.05556903034448624, -0.06539242714643478, -0.06668423861265182, -0.052128616720438004, -0.01784384436905384, 0.01423354260623455, -0.015588958747684956, 0.0683579221367836, -0.004315513651818037, -0.019600963220000267, 0.047121312469244, -0.02234092354774475, -0.11937952041625977, -0.1186065822839737, 0.026399215683341026, -0.11864964663982391, 0.016725579276680946, -0.013079743832349777, 0.015088861808180809, -0.052672892808914185, 0.02489594928920269, -0.04833976924419403, 0.03316353261470795, -0.010109862312674522, 0.005189322866499424, 0.005611898377537727, 0.02683291584253311, 0.04306508228182793, 0.03345797210931778, -0.00840192474424839, -0.06300350278615952, -0.03896738961338997, -0.020921766757965088, -0.057606738060712814, 0.013421263545751572, 0.10243332386016846, 0.010831157676875591, -0.013485257513821125, 0.031274136155843735, 0.036337822675704956, -0.06595878303050995, -0.036365486681461334, -0.01917530968785286, -0.03256522864103317, 0.1248164027929306, -0.00843282975256443, 0.017858972772955894, -0.02142881602048874, -0.013857192359864712, 0.04826794192194939, -0.03900245204567909, -0.04728156700730324, 0.09581582993268967, 0.019697586074471474, -0.0576506070792675, -0.03782331943511963, 0.017018046230077744, -0.07206682860851288, 0.0280988160520792, -0.05958285927772522, 0.12373777478933334, -0.05561944842338562, 0.009980911388993263, -0.00604002270847559, 0.035176604986190796, -0.02793688140809536, -0.04724444821476936, 0.06832367181777954, 0.04599447548389435, -0.0992489606142044, -0.06877250224351883, -0.05928507819771767, 0.013953217305243015, -0.11021146923303604, 0.04197947308421135, -0.029429348185658455, -0.012474491260945797, 0.09231120347976685, 0.012980102561414242, -0.033924128860235214, 0.019548486918210983, 0.07233926653862, 0.06118391826748848, 0.10049119591712952, -0.05378900095820427, -0.0065749455243349075, 0.03825961425900459, 0.04900049790740013, -0.008500554598867893, -0.04730823636054993, -3.993989278074379e-33, 0.06401243805885315, -0.0746958926320076, 0.02971426397562027, 0.013857805170118809, -0.047377705574035645, -0.005856313277035952, 0.002743014832958579, 0.03877997770905495, -0.005144008435308933, 0.053243350237607956, 0.03376161679625511, 0.04495840519666672, 0.09363508224487305, -0.0265896487981081, -0.05822001397609711, 0.027413951233029366, -0.1272820085287094, 0.011655738577246666, -0.04589990898966789, 0.04172499105334282, -0.05906883627176285, 0.056068118661642075, -0.02969750389456749, 0.05602816864848137, -0.09417246282100677, -0.14204752445220947, 0.04468366131186485, 0.06349403411149979, -0.016406742855906487, -0.02216511406004429, -0.019549869000911713, 0.027724498882889748, 0.03735750541090965, 0.013306967914104462, 0.003999347332865, 0.03179348632693291, 0.0030402704142034054, -0.06538631021976471, 0.06287284940481186, -0.03028576821088791, 0.0205206461250782, 0.10147351771593094, 0.001032177358865738, -0.010303894989192486, 0.04767805337905884, -0.01575089432299137, -0.03872029483318329, -0.09488769620656967, -0.00695956451818347, -0.025586577132344246, 0.029095947742462158, 0.006311726290732622, 0.015314641408622265, -0.02124115452170372, -0.011764737777411938, -0.002132300054654479, 0.12485391646623611, 0.06908056885004044, -0.008131911046802998, -0.07331692427396774, 0.035303473472595215, -0.018071414902806282, -0.02058691345155239, -0.11112349480390549, 0.03088768944144249, 0.026548361405730247, 0.05126550793647766, -0.06698348373174667, -0.04841265827417374, -0.045802757143974304, -0.043484967201948166, 0.09801336377859116, 0.0055997674353420734, 0.02431565709412098, -0.06120135635137558, -0.02303912676870823, -0.010282393544912338, -0.03670644015073776, 0.020802365615963936, -0.03969482704997063, -0.1076015830039978, 0.056406475603580475, -0.02772199921309948, 0.06735343486070633, 0.005935641471296549, -0.05103854089975357, -0.08210809528827667, -0.008483448065817356, 0.006049206480383873, -0.009990503080189228, 0.007019324693828821, -0.025189928710460663, -0.04013003408908844, 0.011503951624035835, -0.0529722161591053, 1.7160295864248292e-34, 0.022879496216773987, -0.03320395201444626, 0.0018469140632078052, 0.09024795144796371, -0.012701814994215965, -0.015121972188353539, -0.024576302617788315, -0.013710319995880127, 0.043867867439985275, 0.07548106461763382, -0.035196613520383835, -0.03980667516589165, 0.03297518193721771, 0.05803714692592621, -0.02738996222615242, 0.003749310737475753, -0.027937527745962143, -0.01798408292233944, -0.05551185458898544, -0.04025450721383095, -0.02148032933473587, 0.13219715654850006, 0.10271043330430984, -0.018827179446816444, 0.03777041658759117, -0.026385903358459473, 0.015498735941946507, -0.011032894253730774, -0.025919431820511818, -0.09861228615045547, 0.09969925135374069, 0.08078375458717346, -0.03758234903216362, -0.002516884123906493, -0.061646901071071625, 0.05194862186908722, -0.007810561452060938, -0.01824214681982994, -0.04654480889439583, -0.03674289956688881, -0.0017904815031215549, 0.025087781250476837, -0.005289928987622261, 0.040014009922742844, -0.031357746571302414, 0.026951881125569344, 0.06698397547006607, -0.023943135514855385, 0.033722031861543655, -0.02366538904607296, -0.048063721507787704, -0.04118528589606285, 0.029297886416316032, 0.0171656496822834, -0.0002458712551742792, -0.03510922193527222, 0.04904597997665405, -0.07016653567552567, -0.03248455375432968, -0.04833857715129852, 0.10066455602645874, -0.039494454860687256, -0.03386886417865753, 0.05495443940162659, -0.05132444575428963, 0.07313638180494308, 0.02746007964015007, -0.03423761948943138, -0.03648864105343819, 0.029383402317762375, 0.02489953488111496, 0.02360847406089306, -0.016365952789783478, -0.027901947498321533, 0.03609918802976608, 0.034116484224796295, -0.028405068442225456, 0.009903213009238243, -0.06854411214590073, -0.01327795535326004, -0.07468370348215103, -0.08964905142784119, 0.05197206884622574, -0.0021987520158290863, -0.13476914167404175, -0.008623833768069744, 0.10842138528823853, -0.005854669027030468, -0.047907233238220215, -0.013390802778303623, -0.04831084609031677, 0.04479010030627251, 0.04307439550757408, -0.014512402936816216, -0.014054707251489162, -2.0493283514610994e-08, 0.007519584149122238, 0.0006316258804872632, -0.012387300841510296, 0.00819255132228136, -0.03161017969250679, 0.00262863258831203, 0.013262691907584667, 0.02108604647219181, -0.09457836300134659, 0.19260872900485992, -0.0031756197568029165, -0.0006968159577809274, -0.06873659044504166, 0.013741287402808666, 0.048725590109825134, -0.021451435983181, 0.05209679901599884, -0.02419566549360752, 0.011533302254974842, 0.05497264862060547, 0.05908758565783501, -0.004571691155433655, -0.06361155211925507, 0.00039786327397450805, 0.08064554631710052, -0.05477841570973396, -0.0852130874991417, 0.040739793330430984, -0.10821186751127243, -0.05609775334596634, 0.027631297707557678, 0.03431391343474388, -0.009093919768929482, -0.07773146778345108, -0.04148872569203377, -0.042197659611701965, 0.06552459299564362, -0.07186304032802582, 0.0019513795850798488, 0.019829988479614258, 0.1305171698331833, -0.016630124300718307, -0.0040747132152318954, 0.0016850755782797933, 0.10476187616586685, -0.02447018399834633, 0.06266966462135315, -0.013880384154617786, -0.006189315114170313, 0.022866910323500633, 0.0318743959069252, -0.027819765731692314, -0.03179146721959114, -0.04254491254687309, 0.01638934202492237, 0.0037258267402648926, 0.05139700695872307, 0.08697470277547836, 0.021656451746821404, 0.03711165860295296, 0.05575292184948921, 0.11181453615427017, 0.02989841066300869, -0.05322529748082161]'), +('Holistic nursing care is a philosophy that emphasizes treating the patient as a whole person, not merely as a collection of symptoms or a medical diagnosis. This approach recognizes the interconnectedness of the physical, psychological, social, and spiritual dimensions of an individual''s health and well-being. To provide holistic care, a nurse must look beyond the immediate illness and consider the patient’s lifestyle, culture, belief system, family relationships, and emotional state. This comprehensive view allows for a deeper understanding of the patient''s needs and leads to a more personalized and effective plan of care. A cornerstone of holistic care is empathy, which is the ability to understand and share the feelings of another person. It differs from sympathy, which is feeling pity or sorrow for someone else''s misfortune. An empathetic nurse strives to see the situation from the patient''s perspective, validating their emotions and experiences without judgment. This fosters a strong therapeutic relationship built on trust and respect. Furthermore, cultural competence is essential. Nurses must be aware of and sensitive to the diverse backgrounds of their patients, recognizing that cultural beliefs can significantly influence health practices, dietary preferences, and communication styles. Ultimately, patient-centered care positions the patient as an active partner in their own healthcare journey. This involves including them in decision-making, respecting their values and preferences, and providing them with the education needed to manage their condition effectively. When patients feel heard, respected, and involved, they are more likely to adhere to their treatment plans, report satisfaction with their care, and experience better overall health outcomes. It is the nurse''s role to advocate for the patient, ensuring their voice is central to every discussion about their health.', 'Treating the patient as a partner in their care helps to improve what aspects of their experience?', '[-0.03646000102162361, 0.13910435140132904, -0.025379979982972145, 0.02040933631360531, -0.11542181670665741, 0.05471878871321678, -0.024342339485883713, 0.002438665833324194, -0.00944530125707388, -0.06740786135196686, 0.0016902647912502289, 0.10018585622310638, -0.05120484530925751, 0.02266833931207657, 0.03657058998942375, 0.012963368557393551, 0.048868097364902496, 0.03242256119847298, -0.0649905651807785, 0.023531880229711533, -0.1144338920712471, -0.08488199859857559, 0.01992204412817955, -0.014890027232468128, -0.0624568834900856, -0.04892018064856529, -0.010723778046667576, -0.05259926989674568, 0.09459710866212845, -0.012527846731245518, -0.009121415205299854, 0.024042785167694092, 0.05351585894823074, -0.001977108186110854, -0.09842777252197266, 0.10658863186836243, -0.029697813093662262, 0.07714621722698212, -0.029766909778118134, 0.006222166586667299, 0.016114305704832077, -0.0010060282656922936, 0.025302298367023468, 0.012433098629117012, 0.029919685795903206, -0.07219401001930237, 0.030511213466525078, -0.0208557341247797, 0.015841379761695862, -0.04509894549846649, -0.13655787706375122, -0.007054595276713371, -0.07024834305047989, 0.018425246700644493, -0.008593658916652203, 0.03862754628062248, 0.006877172738313675, -0.027022061869502068, -0.09094102680683136, 0.0132446913048625, 0.027968375012278557, 0.034240853041410446, -0.01423825602978468, 0.0716516301035881, -0.01537728775292635, -0.09489286690950394, -0.011283563449978828, 0.002836851868778467, -0.010216770693659782, -0.008180982433259487, -0.07590880990028381, -0.03555721417069435, 0.03590814024209976, 0.008841644041240215, -0.022410398349165916, -0.004080567508935928, 0.01590270735323429, -0.07709084451198578, 0.05159543454647064, -0.05200279876589775, 0.04740389436483383, 0.02888629212975502, 0.0186722781509161, 0.03880593553185463, -0.05314076319336891, -0.02109796367585659, 0.01761377789080143, -0.08825691789388657, -0.06279768794775009, -0.037084128707647324, 0.0038922554813325405, 0.004163973964750767, -0.02022031880915165, -0.08212558180093765, 0.007766997907310724, 0.09738357365131378, -0.04066792502999306, 0.0008698449819348752, -0.039155248552560806, 0.07523848116397858, 0.012880499474704266, 0.05288516357541084, 0.013370868749916553, 0.023735813796520233, -0.0317063070833683, 0.05035141855478287, -0.01660945639014244, -0.03848875313997269, -0.029921436682343483, 0.02947349101305008, -0.033045873045921326, -0.02276037447154522, -0.056595057249069214, -0.04358522593975067, 0.04439825937151909, 0.026504410430788994, -0.016556642949581146, -0.007846147753298283, 0.04110471531748772, -0.01967780292034149, 0.02724723517894745, -0.06533124297857285, 0.04344452917575836, -0.03453121334314346, -0.012155109085142612, -0.04350549727678299, 0.07064095884561539, -3.8957631334097456e-33, 0.05420238897204399, 0.0214522872120142, -0.01669531874358654, 0.040842656046152115, 0.0331803560256958, 0.1054503470659256, 0.005062682554125786, -0.058822665363550186, 0.022803544998168945, -0.0012594008585438132, 0.030405184254050255, 0.04167575016617775, 0.07963086664676666, 0.020329009741544724, -0.06707105040550232, -0.027088308706879616, -0.16536131501197815, 0.08440588414669037, -0.08615457266569138, 0.07735875993967056, -0.019189760088920593, 0.02718445658683777, -0.05041378736495972, 0.05090506002306938, -0.035952333360910416, -0.09271392226219177, 0.026517819613218307, 0.06641442328691483, -0.0020725049544125795, -0.014167645014822483, 0.015533886849880219, 0.08535982668399811, -0.05350114777684212, -0.06007450819015503, -0.0313267707824707, 0.08738622814416885, -0.05971188843250275, -0.052592933177948, 0.0034806786570698023, -0.00964027363806963, -0.0567554347217083, 0.02248506434261799, 0.005990810692310333, 0.013310481794178486, -0.032019298523664474, 0.017635218799114227, -0.01367934513837099, -0.09967391192913055, -0.10906243324279785, -0.013187992386519909, 0.0044137160293757915, 0.028526941314339638, -0.057826243340969086, 0.007435350213199854, -0.0013897785684093833, 0.09015212208032608, 0.06296239048242569, -0.02048727497458458, -0.0011098093818873167, 0.0012488526990637183, 0.10746646672487259, -0.09656480699777603, -0.017074106261134148, -0.031857576221227646, 0.021653730422258377, -0.0334441177546978, 0.04113687202334404, -0.08799998462200165, -0.05981963500380516, -0.04423875734210014, -0.14596912264823914, 0.03941180184483528, -0.004956576973199844, -0.016647491604089737, -0.10513469576835632, -0.06275578588247299, -0.05255991965532303, -0.04919826239347458, 0.03540724143385887, -0.0010762900346890092, -0.034123025834560394, -0.022563960403203964, 0.06292928755283356, 0.05809282511472702, -0.036889445036649704, -0.012039980851113796, -0.02782486006617546, 0.03648468852043152, 0.006174304056912661, 0.03999589756131172, -0.01821431703865528, 0.010896545834839344, 0.019068840891122818, 0.037302374839782715, 0.07802856713533401, -1.4008467197794974e-34, -0.012934466823935509, 0.015026267617940903, -0.015006761066615582, 0.07186494022607803, 0.06020774692296982, -0.034093186259269714, 0.02275838889181614, -0.06874069571495056, 0.0325712114572525, 0.08558695018291473, -0.03561442717909813, 0.005935170222073793, 0.03991633653640747, 0.033459365367889404, -0.0763896033167839, -0.0035953721962869167, -0.054633717983961105, -0.03900742903351784, 0.03955728933215141, 0.023022592067718506, 0.03603668138384819, 0.13486352562904358, 0.060573235154151917, 0.06318242847919464, 0.034069497138261795, 0.028888104483485222, 0.043779995292425156, -0.044508472084999084, -0.03543688729405403, -0.08321426808834076, -0.005910469219088554, 0.02818983979523182, -0.05830420181155205, -0.0030149880331009626, 0.009735766798257828, 0.05940183997154236, 0.012057715095579624, -0.04842374473810196, -0.009655793197453022, -0.0027769587468355894, 0.06030992418527603, -0.017032109200954437, -0.07334441691637039, 0.06388413161039352, 0.05804182216525078, -0.03150569647550583, 0.024680571630597115, -0.039733633399009705, 0.004855753853917122, -0.0046750265173614025, 0.008862942457199097, -0.029804188758134842, -0.03659597784280777, -0.028656598180532455, 0.04907780885696411, -0.08778111636638641, 0.075833261013031, -0.07438783347606659, -0.032406315207481384, -0.012414254248142242, 0.057123951613903046, 0.01914542354643345, -0.026075368747115135, 0.05061091110110283, 0.000889292627107352, 0.005421984475106001, 0.02520781382918358, 0.07842941582202911, 0.016139023005962372, 0.0013393282424658537, -0.011048514395952225, -0.04930400475859642, -0.036258354783058167, -0.039906859397888184, 0.02338349260389805, -0.04295273870229721, -0.007034068927168846, -0.13140538334846497, -0.025798972696065903, -0.0037402634043246508, -0.1199723333120346, -0.0682409256696701, 0.10053320229053497, 0.00908577535301447, -0.08499015867710114, -0.0005685014184564352, 0.05236366391181946, -0.02232297882437706, -0.013123787939548492, -0.02753971889615059, -0.05778360739350319, 0.03594448044896126, -0.06445418298244476, -0.10415887832641602, -0.045051515102386475, -2.3398179394007457e-08, -0.05417753756046295, -0.02031356655061245, -0.017830152064561844, -0.06020474061369896, -0.016415201127529144, -0.06732913851737976, -0.043868839740753174, 0.06065628305077553, -0.03958301618695259, 0.08844874799251556, -0.026164421811699867, 0.013509562239050865, 0.03190650790929794, 0.03935537487268448, 0.1857336163520813, 0.014329161494970322, 0.028356092050671577, 0.07855948060750961, -0.0883425772190094, -0.03461132198572159, 0.017761575058102608, 0.04677315056324005, -0.038414351642131805, -0.02231554500758648, 0.0009803525172173977, 0.08093584328889847, 0.03955812007188797, 0.06877569854259491, -0.04302634671330452, 0.0017211161321029067, 0.014063437469303608, 0.05679549649357796, 0.05765599384903908, 0.017065877094864845, -0.008661369793117046, -0.015874691307544708, 0.08796561509370804, 0.009098516777157784, 0.060892254114151, -0.033909764140844345, -0.02105649933218956, 0.07621656358242035, 0.021244358271360397, 0.061296578496694565, -0.021952275186777115, -0.0194901954382658, 0.017812984064221382, 0.09560426324605942, -0.09607160836458206, -0.02283479832112789, 0.04064204916357994, 0.024514000862836838, 0.028425078839063644, -0.013485088013112545, -0.030731115490198135, 0.04092975705862045, 0.04513813927769661, 0.01229061745107174, 0.014601525850594044, 0.02724587172269821, -0.04591779783368111, 0.06101587042212486, 0.04572179168462753, -0.04211479052901268]'), +('Effective communication is a cornerstone of safe and collaborative patient care. In a complex healthcare environment where a patient is cared for by multiple providers across different shifts, unstructured communication can lead to critical information being missed, resulting in medical errors. To mitigate this risk, standardized communication tools have been developed to ensure that information is conveyed in a clear, concise, and predictable manner. These tools provide a framework that helps organize a clinician’s thoughts and ensures all vital components of a patient’s status are communicated effectively, especially during critical situations or handoffs. One of the most widely adopted and effective of these tools is the SBAR framework, which stands for Situation, Background, Assessment, and Recommendation. This evidence-based model is used for urgent communications, such as when a nurse needs to report a change in a patient’s condition to a physician, as well as for routine shift-to-shift reports. The S is for Situation, a brief statement of the problem. The B is for Background, which provides relevant context and clinical history. The A is for Assessment, which is the nurse’s clinical conclusion or what they believe the problem is. Finally, the R is for Recommendation, the nurse''s stated request for action. Using SBAR organizes the conversation logically. For example, a nurse would start by stating the immediate issue ("Situation: Mr. Jones in room 302 has a new onset of chest pain."), followed by relevant history ("Background: He is a 2-day post-op patient from a hip replacement."). The nurse then offers their clinical judgment ("Assessment: His heart rate is 110, and he is diaphoretic. I am concerned about a cardiac event."). The communication concludes with a clear request ("Recommendation: I need you to come and see him immediately. Should I get an EKG and draw cardiac enzymes while I wait?"). Mastering the SBAR framework is a vital skill for nursing students, as it promotes confidence, enhances clarity, and ultimately improves patient safety by ensuring nothing gets lost in translation.', 'What is the primary reason for using standardized communication tools in healthcare?', '[-0.030880652368068695, 0.04311295971274376, -0.005270146764814854, -0.08478022366762161, -0.057063762098550797, -0.021746668964624405, -0.049506716430187225, 0.0688880905508995, 0.1180235892534256, -0.0289350263774395, -0.007621349301189184, 0.09556099027395248, -0.03337482362985611, 0.06153717264533043, 0.03190082684159279, -0.09455917775630951, 0.06282036751508713, -0.07855521887540817, -0.020265014842152596, 0.01865175925195217, -0.025419719517230988, 0.06983816623687744, 0.03864961490035057, 0.06728148460388184, 0.021738920360803604, -0.01158775482326746, -0.07080931216478348, -0.05208367481827736, -0.008113155141472816, 0.023130342364311218, 0.014933625236153603, -0.004087976645678282, 0.13742603361606598, -0.0047863018698990345, -0.13055488467216492, 0.02430250681936741, 0.06773724406957626, -0.013733770698308945, -0.09074942767620087, -0.018677253276109695, -0.03792166709899902, -0.0797354131937027, -0.005846381187438965, 0.0009585068910382688, -0.0006330158794298768, -0.04649391397833824, -0.03309336677193642, 0.008863426744937897, -0.033849701285362244, 0.007170991972088814, -0.019118910655379295, -0.01759934425354004, 0.002094538416713476, 0.062420014292001724, 0.03879589959979057, -0.03493784740567207, -0.06421206891536713, 0.017699114978313446, -0.03924962505698204, -0.004287088755518198, -0.05027388781309128, -0.000731846084818244, -0.051098860800266266, 0.050576839596033096, -0.008376393467187881, 0.005196713376790285, 0.04918600991368294, -0.03969400376081467, -0.023808564990758896, -0.036244962364435196, -0.09388402849435806, -0.08023399114608765, 0.10014351457357407, 0.09507927298545837, 0.025333980098366737, -0.006504551041871309, -0.009658878669142723, -0.03277808055281639, -0.008948949165642262, -0.02534610405564308, 0.02024802193045616, 0.024655042216181755, 0.04589342698454857, 0.10281761735677719, 0.10846365988254547, 0.033215709030628204, -0.012443461455404758, -0.07087717950344086, -0.05567723885178566, -0.06967148184776306, 0.03167254105210304, -0.03827427327632904, -0.004736308474093676, -0.0017597457626834512, -0.034202661365270615, -0.05711670592427254, -0.05297008156776428, 0.004933779127895832, 0.005426465068012476, 0.0016788493376225233, 0.03568168729543686, -0.02762635238468647, -0.0020214656833559275, -0.0009313987102359533, -0.028070662170648575, -0.08202161639928818, 0.016907857730984688, -0.04071129485964775, 0.02003447711467743, 0.022203069180250168, -0.05493439733982086, 0.0004525991389527917, -0.02865275926887989, -0.06150032952427864, 0.048348136246204376, -0.021660801023244858, -0.03759976476430893, -0.009345266036689281, 0.07241286337375641, 0.013153914362192154, -0.04224654659628868, -0.10119786113500595, -0.0671338215470314, -0.052616603672504425, 0.06553639471530914, 0.10016539692878723, -0.004719758406281471, -4.26496717456181e-33, 0.0016766610788181424, 0.046851370483636856, 0.038638126105070114, 0.04838977009057999, -0.019864674657583237, 0.06351368874311447, -0.06055247411131859, -0.03444425016641617, 0.07095050811767578, -0.041639406234025955, 0.019593659788370132, 0.126808762550354, 0.06511757522821426, 0.007526802830398083, 0.04668877646327019, 0.006657069083303213, -0.07578802108764648, 0.11466249823570251, 0.01714983582496643, 0.044972967356443405, 0.04530103877186775, -0.06474213302135468, 0.02721705660223961, 0.08415604382753372, 0.01795952580869198, 0.03178270161151886, 0.0029514487832784653, 0.01262871827930212, 0.09273126721382141, -0.001140232547186315, -0.06709492206573486, -0.03518577292561531, 0.0630837008357048, -0.048758234828710556, 0.026061752811074257, 0.05139628425240517, -0.015085402876138687, -0.08518550544977188, -0.0005874872440472245, -0.002001676708459854, 0.03586508706212044, -0.00411428464576602, -0.055152490735054016, -0.012553361244499683, 0.0989900603890419, 0.07557040452957153, -0.06511787325143814, -0.03849569708108902, -0.05284680798649788, -0.060443684458732605, -0.05728713423013687, 0.048921212553977966, 0.01326067466288805, -0.005302373319864273, 0.09350250661373138, 0.022061802446842194, 0.036545004695653915, -0.03991793468594551, -0.02453022263944149, 0.04757421836256981, -0.035170119255781174, 0.06991257518529892, -0.007975094020366669, 0.018987491726875305, 0.0659031867980957, 0.011432401835918427, -0.019276123493909836, -0.03308757394552231, 0.008848867379128933, -0.030287351459264755, -0.01314028725028038, 0.06263059377670288, -0.0885620266199112, -0.025893360376358032, 0.016437198966741562, -0.03949735686182976, -0.0024134269915521145, 0.0055300407111644745, 0.0723329409956932, -0.019760772585868835, -0.05824647098779678, -0.01655653677880764, -0.021552765741944313, 0.06410623341798782, 0.01704094000160694, -0.03900842368602753, -0.017507271841168404, 0.035170987248420715, -0.10324858874082565, 0.04647437110543251, -0.05236342176795006, 0.07562126964330673, 0.012845274992287159, 0.11406489461660385, 0.02011353150010109, 9.08203557670104e-34, -0.0052074105478823185, 0.04052828997373581, -0.058513350784778595, 0.07280537486076355, -0.008725659921765327, -0.0016999321524053812, 0.0687522366642952, -0.08777615427970886, 0.07155456393957138, 0.006775521207600832, 0.058035094290971756, -0.05326353386044502, -0.04640451818704605, 0.007660279516130686, 0.03212859854102135, 0.01743953861296177, -0.06221848353743553, -0.12562118470668793, 0.0033729535061866045, -0.018911436200141907, 0.08433160185813904, 0.0651080384850502, -0.058834511786699295, 0.05849408358335495, -0.013850976713001728, -0.044995859265327454, -0.1435803771018982, -0.04771997034549713, 0.007493693847209215, -0.09733226895332336, -0.04497440531849861, 0.03238098695874214, 0.018314436078071594, -0.005460302345454693, -0.021665511652827263, 0.0014451573370024562, -0.015460625290870667, 0.026649849489331245, -0.010030074045062065, 0.006575804203748703, 0.0529036819934845, 0.04346993938088417, -0.06628526002168655, -0.007795689627528191, 0.022554993629455566, 0.025390729308128357, -0.044779252260923386, -0.04250263795256615, -0.028186582028865814, -0.004041855223476887, 0.06566023826599121, -0.03666376322507858, 0.017371907830238342, -0.04467525705695152, -0.10683474689722061, 0.021753331646323204, -0.005137104541063309, -0.049309711903333664, -0.08901959657669067, 0.016161197796463966, 0.07562410086393356, -0.00969590712338686, -0.042859263718128204, 0.03345898166298866, 0.017982233315706253, 0.05609460175037384, 0.128595232963562, 0.050194598734378815, -0.0027251127175986767, -0.008069454692304134, 0.04065708816051483, -0.05338972806930542, 0.03228144720196724, -0.045233104377985, -0.01654997281730175, 0.037267088890075684, -0.056047964841127396, -0.07246489822864532, -0.14021630585193634, 0.040582284331321716, -0.030825840309262276, -0.013827531598508358, 0.04654025658965111, 0.008524784818291664, -0.015285293571650982, 0.07162758708000183, -0.003411733079701662, -0.06373078376054764, -0.016017606481909752, 0.006873423233628273, -0.07798265665769577, -0.017214594408869743, -0.05391952022910118, 0.05136597156524658, -0.07586007565259933, -1.9543962892498712e-08, -0.07574255764484406, -0.021860569715499878, 0.006779617164283991, -0.041835885494947433, -0.005523578263819218, -0.026094194501638412, -0.03945660963654518, 0.07520577311515808, 0.019306987524032593, 0.10863077640533447, -0.01078435406088829, -0.011267055757343769, -0.06852707266807556, 0.05084288492798805, 0.17530936002731323, 0.030326174572110176, -0.04663438722491264, -0.023147111758589745, -0.05679125338792801, -0.03044920228421688, 0.025235898792743683, -0.02399822697043419, -0.0926337018609047, -0.0003945830394513905, 0.00761211896315217, 0.0026985243894159794, -0.004214998334646225, 0.09395457059144974, -0.022115927189588547, 0.01189263816922903, -0.020291142165660858, -0.013346291147172451, 0.07321243733167648, 0.1038329005241394, -0.05344036966562271, -0.03073941543698311, 0.00598095403984189, -0.004717662464827299, 0.07259680330753326, 0.005624684505164623, 0.026480332016944885, -0.012428111396729946, -0.013858368620276451, 0.028782669454813004, 0.02256784215569496, 0.02224131114780903, -0.0568951740860939, 0.09495531022548676, -0.052049484103918076, 0.028289474546909332, -0.03546654060482979, 0.029422475025057793, 0.07930028438568115, 0.013554329052567482, 0.02690490335226059, 0.04173918813467026, 0.05593617260456085, -0.04287038743495941, -0.034854888916015625, 0.019545014947652817, 0.032645247876644135, 0.0647958517074585, -0.0009787848684936762, 0.0019621653482317924]'), +('Effective communication is a cornerstone of safe and collaborative patient care. In a complex healthcare environment where a patient is cared for by multiple providers across different shifts, unstructured communication can lead to critical information being missed, resulting in medical errors. To mitigate this risk, standardized communication tools have been developed to ensure that information is conveyed in a clear, concise, and predictable manner. These tools provide a framework that helps organize a clinician’s thoughts and ensures all vital components of a patient’s status are communicated effectively, especially during critical situations or handoffs. One of the most widely adopted and effective of these tools is the SBAR framework, which stands for Situation, Background, Assessment, and Recommendation. This evidence-based model is used for urgent communications, such as when a nurse needs to report a change in a patient’s condition to a physician, as well as for routine shift-to-shift reports. The S is for Situation, a brief statement of the problem. The B is for Background, which provides relevant context and clinical history. The A is for Assessment, which is the nurse’s clinical conclusion or what they believe the problem is. Finally, the R is for Recommendation, the nurse''s stated request for action. Using SBAR organizes the conversation logically. For example, a nurse would start by stating the immediate issue ("Situation: Mr. Jones in room 302 has a new onset of chest pain."), followed by relevant history ("Background: He is a 2-day post-op patient from a hip replacement."). The nurse then offers their clinical judgment ("Assessment: His heart rate is 110, and he is diaphoretic. I am concerned about a cardiac event."). The communication concludes with a clear request ("Recommendation: I need you to come and see him immediately. Should I get an EKG and draw cardiac enzymes while I wait?"). Mastering the SBAR framework is a vital skill for nursing students, as it promotes confidence, enhances clarity, and ultimately improves patient safety by ensuring nothing gets lost in translation.', 'What do the letters in the SBAR acronym stand for?', '[-0.05750862509012222, -0.06625773012638092, -0.10173369944095612, -0.007528405170887709, -0.012696033343672752, 0.045052334666252136, 0.04907141625881195, 0.03158089518547058, 0.051014602184295654, -0.038235895335674286, 0.02891901321709156, 0.07319172471761703, -0.03616999089717865, -0.046383049339056015, -0.006838778965175152, 0.08728954195976257, -0.02253139205276966, -0.06904622167348862, 0.046286337077617645, -0.06425143778324127, 0.022468725219368935, 0.10907187312841415, 0.031186070293188095, 0.03790244460105896, -0.03909981995820999, 0.08068303763866425, -0.02923193760216236, -0.007240822538733482, -0.00793924368917942, -0.016617529094219208, 0.01517272088676691, 0.07123787701129913, 0.11395841091871262, -0.00529293529689312, -0.038190800696611404, 0.02124015800654888, -0.023451879620552063, 0.03873177245259285, -0.019549446180462837, 0.029664143919944763, -0.06039855629205704, -0.12508739531040192, 0.018890898674726486, 0.0357414186000824, 0.02841905504465103, -0.013586945831775665, -0.05443228408694267, 0.029602909460663795, -0.017935175448656082, 0.047796133905649185, 0.07430775463581085, -0.07259172946214676, -0.0617329403758049, 0.04083159565925598, 0.042950551956892014, -0.042284756898880005, -0.06490690261125565, -0.007813193835318089, -0.018469206988811493, 0.0455639511346817, -0.031166857108473778, 0.040629271417856216, -0.045136384665966034, 0.07611384987831116, 0.04969986528158188, -0.0310197826474905, 0.03742107003927231, 0.01450159028172493, -0.0185518991202116, -0.027796629816293716, -0.03386397659778595, -0.033655595034360886, -0.06278680264949799, 0.04250580817461014, -0.024465106427669525, -0.048973359167575836, 0.11043819785118103, 0.037622809410095215, 0.06595630198717117, -0.043443839997053146, -0.005958999041467905, -0.014580334536731243, -0.045291587710380554, 0.0016319927526637912, -0.036383409053087234, 0.04639536514878273, -0.07175055146217346, -0.02071205899119377, -0.02519821934401989, 0.007758250925689936, 0.0023474956396967173, -0.09341062605381012, 0.031097548082470894, -0.044683750718832016, -0.050561871379613876, 0.00168285658583045, -0.03225988149642944, -0.0742001011967659, -0.027982674539089203, 0.05656757950782776, 0.0064443983137607574, -0.009321172721683979, -0.0503719262778759, 0.04530477151274681, -0.08163287490606308, -0.05971940606832504, -0.0010814998531714082, -0.03887951001524925, 0.057998523116111755, 0.022790612652897835, -0.017543016001582146, 0.03297824412584305, 0.026754530146718025, -0.008938630111515522, -0.08632440119981766, -0.04416108876466751, -0.0546455942094326, 0.0672152191400528, 0.18584313988685608, -0.04169890284538269, -0.05850367620587349, 0.02389627881348133, -0.04179011285305023, 0.0005716167506761849, -0.041651010513305664, -0.01127925980836153, -0.07727590948343277, -5.968570362248257e-33, 0.06026756390929222, 0.02127140574157238, 0.0388326458632946, -0.04275902733206749, -0.023855915293097496, -0.029797131195664406, 0.03822746127843857, -0.03860964998602867, -0.05185724049806595, 0.07207991927862167, 0.03557705134153366, 0.06328608840703964, 0.027521587908267975, -0.010983004234731197, 0.08086161315441132, -0.007671576924622059, -0.015131084248423576, 0.007932579144835472, -0.03580639138817787, -0.09689593315124512, -0.024226048961281776, 0.09545499086380005, 0.045329559594392776, 0.043012797832489014, 0.028477318584918976, -0.006259183865040541, 0.06006564199924469, -0.008497047238051891, -0.04303007200360298, 0.04880917817354202, 0.025902003049850464, 0.04180982708930969, -0.03095732443034649, 0.004425741732120514, 0.019382255151867867, -0.06838782876729965, -0.04535142332315445, -0.06479419767856598, -0.1034584566950798, -0.027101382613182068, 0.019069045782089233, -0.048524368554353714, -0.12047910690307617, 0.045325107872486115, 0.03146125003695488, 0.026112092658877373, -0.016309503465890884, 0.020229674875736237, 0.009816759265959263, 0.04317459464073181, -0.018767746165394783, -0.007111881859600544, -0.009687862358987331, -0.0465090312063694, 0.02812095358967781, -0.015610950998961926, 0.021027352660894394, 0.04421446844935417, -0.014743375591933727, -0.02097329869866371, 0.04772830009460449, 0.0578482560813427, 0.04834223911166191, 0.01691836677491665, -0.0021352863404899836, -0.040110424160957336, 0.024373603984713554, 0.011711068451404572, 0.028872046619653702, 0.01802012138068676, 0.043554022908210754, 0.0031927567906677723, 0.06565237790346146, 0.007227720692753792, -0.01963687315583229, -0.010297741740942001, -0.03186815604567528, 0.08881613612174988, -0.00010043129441328347, -0.001969641540199518, -0.08989328891038895, 0.021459229290485382, 0.010004849173128605, 0.03024647757411003, -0.0051615736447274685, 0.03375400975346565, 0.05595564469695091, -0.11266768723726273, -0.09424714744091034, -0.04510107263922691, -0.1095614954829216, 0.037132833153009415, -0.010092763230204582, 0.0457039512693882, -0.059914834797382355, 2.1826391761656072e-33, 0.027414046227931976, -0.04604417458176613, -0.03396850824356079, 0.03382782265543938, -0.014387762174010277, -0.06769192218780518, 0.11844734102487564, -0.0333789624273777, 0.06876301020383835, 0.024746356531977654, -0.030444316565990448, 0.013113145716488361, -0.028550338000059128, -0.10226090252399445, 0.14329300820827484, -0.07392631471157074, 0.03041638806462288, 0.005207066889852285, -0.08947169780731201, 0.05171923711895943, -0.005493261385709047, 0.0447339229285717, 0.06252942979335785, 0.026347143575549126, 0.005552242510020733, -0.08091524243354797, 0.07761648297309875, 0.03890278935432434, -0.10222272574901581, -0.04326152428984642, 0.03075294755399227, -0.02242271788418293, 0.003419900545850396, 0.08280730247497559, -0.12065807729959488, -0.015754088759422302, 0.05194837227463722, -0.0441364087164402, -0.05637836456298828, 0.011262519285082817, -0.0031432602554559708, 0.06581117957830429, -0.04561176896095276, 0.06977495551109314, -0.04492409899830818, -0.004124392289668322, -0.0522143729031086, -0.04451235383749008, 0.009523162618279457, -0.07530896365642548, 0.0025485067162662745, -0.06221860647201538, 0.00827009230852127, 0.06559422612190247, 0.004069068469107151, 0.03433427959680557, -0.0811256542801857, -0.005881968419998884, -0.04936922714114189, 0.035847898572683334, 0.06424728035926819, -0.022482404485344887, 0.07076823711395264, 0.10386386513710022, 0.04281804710626602, -0.04476297274231911, 0.010019566863775253, 0.008206728845834732, 0.0454360730946064, -0.021819688379764557, 0.11238105595111847, 0.009354191832244396, -0.011747274547815323, 0.07753953337669373, -0.0364321731030941, -0.04366537928581238, -0.014576838351786137, -0.07815204560756683, -0.08088143169879913, -0.0096974428743124, -0.11092878878116608, 8.569347119191661e-05, -0.06622590869665146, 0.13288913667201996, -0.022792935371398926, -0.071809783577919, 0.05628396198153496, 0.0439545102417469, 0.03492816537618637, 0.047278016805648804, 0.05711761862039566, 0.011554921045899391, -0.00590616324916482, 0.07937411218881607, -0.044797103852033615, -1.9561394282163747e-08, -0.04004673287272453, 0.019049424678087234, -0.04440564289689064, -0.004074148368090391, 0.043010812252759933, -0.0590842068195343, 0.014138496480882168, -0.05930156260728836, -0.01624084636569023, 0.008813154883682728, -0.0006238949717953801, -0.010109899565577507, -0.04861972853541374, -0.012987695634365082, 0.04559551924467087, -0.014891346916556358, -0.010807083919644356, 0.06365437060594559, -0.034135885536670685, -0.01179712824523449, 0.0475706048309803, 0.02800787426531315, 0.005718234460800886, -0.03187229484319687, -0.04753582552075386, 0.002083802130073309, -0.03285856544971466, 0.003540473524481058, 0.13621360063552856, -0.014779523015022278, -0.02357117459177971, 0.04287584125995636, 0.07133994251489639, -0.06855782121419907, 5.872011024621315e-05, 0.06138845533132553, 0.07898721843957901, -0.029003998264670372, 0.055233001708984375, 0.049651794135570526, -0.032678451389074326, -0.0546790212392807, 0.021491749212145805, 0.03339754417538643, -0.027875561267137527, 0.05395219847559929, -0.11155743151903152, 0.08137992769479752, -0.02608795091509819, -0.09607681632041931, 0.0904964804649353, 0.014716600067913532, -0.023319318890571594, 0.04687907174229622, 0.016644591465592384, 0.0014706981601193547, -0.0036255097948014736, -0.06026632711291313, 0.02681909129023552, -0.03961091488599777, 0.11938967555761337, -0.004180321004241705, 0.031675372272729874, -0.02899070270359516]'), +('Effective communication is a cornerstone of safe and collaborative patient care. In a complex healthcare environment where a patient is cared for by multiple providers across different shifts, unstructured communication can lead to critical information being missed, resulting in medical errors. To mitigate this risk, standardized communication tools have been developed to ensure that information is conveyed in a clear, concise, and predictable manner. These tools provide a framework that helps organize a clinician’s thoughts and ensures all vital components of a patient’s status are communicated effectively, especially during critical situations or handoffs. One of the most widely adopted and effective of these tools is the SBAR framework, which stands for Situation, Background, Assessment, and Recommendation. This evidence-based model is used for urgent communications, such as when a nurse needs to report a change in a patient’s condition to a physician, as well as for routine shift-to-shift reports. The S is for Situation, a brief statement of the problem. The B is for Background, which provides relevant context and clinical history. The A is for Assessment, which is the nurse’s clinical conclusion or what they believe the problem is. Finally, the R is for Recommendation, the nurse''s stated request for action. Using SBAR organizes the conversation logically. For example, a nurse would start by stating the immediate issue ("Situation: Mr. Jones in room 302 has a new onset of chest pain."), followed by relevant history ("Background: He is a 2-day post-op patient from a hip replacement."). The nurse then offers their clinical judgment ("Assessment: His heart rate is 110, and he is diaphoretic. I am concerned about a cardiac event."). The communication concludes with a clear request ("Recommendation: I need you to come and see him immediately. Should I get an EKG and draw cardiac enzymes while I wait?"). Mastering the SBAR framework is a vital skill for nursing students, as it promotes confidence, enhances clarity, and ultimately improves patient safety by ensuring nothing gets lost in translation.', 'In which part of the SBAR framework does the nurse state what they believe the problem is?', '[-0.037314314395189285, -0.04874153062701225, -0.07657913863658905, 0.025853650644421577, 0.034918151795864105, 0.06872104853391647, -0.018309475854039192, 0.03067709691822529, -0.013700268231332302, -0.017706403508782387, -0.051353149116039276, 0.1357121467590332, -0.07689358294010162, 0.01295674778521061, -0.008003600873053074, 0.04854491353034973, -0.024154232814908028, -0.06092624366283417, 0.034501589834690094, 0.10013793408870697, -0.02573157474398613, 0.040912091732025146, -0.009232640266418457, 0.08985942602157593, -0.08704348653554916, 0.014976241625845432, 0.04359781742095947, -0.06016340106725693, 0.044994425028562546, 0.02584557607769966, 0.00769053865224123, 0.05412530153989792, 0.026566531509160995, 0.006484189070761204, -0.003907809033989906, 0.05335000157356262, 0.01962803117930889, 0.04631010815501213, -0.07442747801542282, 0.006271032150834799, 0.014785232953727245, -0.10119723528623581, -0.027676520869135857, -0.0030284272506833076, 0.06799422204494476, -0.058065321296453476, -0.010531810112297535, 0.021958718076348305, -0.010812931694090366, -0.019245756790041924, -0.07731186598539352, -0.1444685459136963, -0.018145903944969177, 0.028817320242524147, 0.01835031807422638, -0.054913152009248734, 0.03069787658751011, -0.03764728084206581, -0.070348359644413, 0.03691980615258217, -0.006141542457044125, 0.06467321515083313, -0.04452280327677727, 0.053726863116025925, 0.16071274876594543, 0.04929724335670471, -0.004168112762272358, -0.0412587933242321, -0.0014475805219262838, -0.015496883541345596, -0.0009252729942090809, -0.05769753456115723, -0.03886880725622177, 0.04931440204381943, 0.026123715564608574, -0.023803384974598885, 0.05253573879599571, 0.049141816794872284, 0.09979011118412018, -0.021023131906986237, 0.033918190747499466, -0.040707267820835114, 0.006047741509974003, 0.05343973636627197, -0.0031294727232307196, -0.02581716515123844, -0.016630711033940315, -0.05439299717545509, 0.0017312201671302319, -0.041278157383203506, 0.07148508727550507, -0.026418017223477364, -0.028040364384651184, -0.02942061983048916, 0.0379054956138134, 0.06665341556072235, -0.035193949937820435, -0.029157986864447594, 0.020616494119167328, 0.009142200462520123, -0.06285859644412994, 0.03943506255745888, -0.003518736455589533, 0.06336220353841782, -0.07624039798974991, -0.04977722838521004, 0.022982565686106682, -0.11725565046072006, -0.0393025241792202, 0.009036051109433174, 0.015677152201533318, 0.05543425306677818, 0.052307989448308945, 0.03380054607987404, -0.006623419001698494, -0.02324477583169937, -0.0017648081993684173, 0.009346913546323776, 0.05597919225692749, 0.020432181656360626, -0.08909513801336288, 0.0192533228546381, -0.02102069929242134, -0.010545877739787102, 0.012692321091890335, 0.017705654725432396, -0.07705963402986526, -3.816168206863661e-33, 0.05198799818754196, -0.00044785276986658573, 0.08887221664190292, -0.010578803718090057, 0.056410472840070724, 0.017378002405166626, -0.0005880793323740363, -0.06817792356014252, 0.056934256106615067, 0.0462476871907711, -0.01235230453312397, 0.015039747580885887, 0.06413150578737259, -0.026835735887289047, 0.04425269365310669, -0.06665942817926407, -0.0933428406715393, 0.03978179767727852, -0.023901045322418213, 0.07241745293140411, 0.0404558926820755, -0.017418570816516876, -0.06217218562960625, 0.06333497911691666, 0.012700559571385384, 0.022698374465107918, 0.04337301105260849, 0.0630551129579544, -0.02635848894715309, 0.04752974584698677, -0.038678716868162155, 0.012838739901781082, -0.047615692019462585, -0.013074862770736217, -0.042523179203271866, -0.048889487981796265, 0.029683975502848625, -0.003866520244628191, -0.11944552510976791, -0.06369664520025253, -0.05818187817931175, 0.005873906426131725, -0.011508425697684288, 0.0709502100944519, 0.05599323660135269, -0.027406850829720497, 0.013260054402053356, -0.04996773228049278, -0.08434141427278519, 0.009527528658509254, -0.04197046160697937, -0.0024207148235291243, -0.03821592777967453, -0.0926695242524147, 0.044682588428258896, -0.021940022706985474, -0.02663162536919117, 0.012430062517523766, 0.02539806254208088, 0.02625202387571335, 0.10941548645496368, -0.029391616582870483, 0.004757895600050688, -0.016937240958213806, 0.07304016500711441, 0.04214153066277504, -0.02267790399491787, -0.10140635073184967, 0.06365416198968887, -0.036150190979242325, -0.01734515279531479, 0.012082151137292385, 0.020237276330590248, 0.0027705298271030188, -0.06147012487053871, -0.02119264379143715, -0.005160029977560043, 0.09131313115358353, 0.028579777106642723, -0.0794808492064476, -0.04477149248123169, 0.022719010710716248, 0.06307270377874374, 0.10521396994590759, -0.023442529141902924, -0.026807254180312157, 0.015981819480657578, 0.018633736297488213, -0.10594002902507782, -0.019348440691828728, -0.037642013281583786, 0.06624776124954224, 0.0837404653429985, 0.06055520102381706, 0.017670098692178726, 7.161197451398283e-34, -0.04242565482854843, 0.005203817505389452, -0.10015881806612015, -0.014580871909856796, 0.003543631639331579, -0.06728681176900864, 0.03603855520486832, -0.047805894166231155, 0.1300850659608841, 0.008092829026281834, -0.01018557045608759, -0.05554470047354698, -0.04511646553874016, -0.0048587326891720295, -0.02717829868197441, -0.033334918320178986, 0.004345813300460577, -0.08778820186853409, -0.05722619965672493, -0.006560053210705519, 0.03727307915687561, 0.08662201464176178, 0.058097220957279205, 0.022446434944868088, 0.045352909713983536, 0.021517692133784294, -0.04418008774518967, 0.0109527837485075, -0.07961030304431915, -0.0775083601474762, 0.022491639479994774, -0.012653960846364498, -0.0033519561402499676, 0.03916697949171066, -0.14578406512737274, -0.004564471542835236, -0.020421994850039482, -0.013565442524850368, 0.014752277173101902, -0.04891921207308769, 0.10864602774381638, 0.0012454823590815067, -0.11956117302179337, 0.030496269464492798, 0.03463031351566315, -0.04791288077831268, 0.03255077078938484, -0.04959556832909584, 0.03220434859395027, -0.084989033639431, -0.03999013453722, -0.0737881064414978, 0.011982121504843235, 0.05626823008060455, 0.008255456574261189, 0.009312460198998451, 0.04305784031748772, -0.08230805397033691, -0.023690812289714813, 0.08793715387582779, 0.10189905017614365, 0.03249850869178772, -0.025317493826150894, 0.052804119884967804, 0.07714533060789108, -0.03676597401499748, 0.027962949126958847, -0.0048150960355997086, 0.12787291407585144, -0.019487373530864716, 0.057678889483213425, -0.0048469784669578075, -0.005999929271638393, 0.09492099285125732, 0.019226543605327606, 0.01623043417930603, -0.04307786375284195, -0.05804372578859329, -0.08177638798952103, -0.02181992679834366, -0.06827947497367859, -0.10314041376113892, -0.01610928401350975, 0.01873987913131714, -0.03367646783590317, -0.07892037183046341, 0.05617702379822731, -0.044823236763477325, 0.013367517851293087, -0.0021170026157051325, -0.08360602706670761, -0.026993807405233383, -0.06721898913383484, 0.014286852441728115, -0.039547912776470184, -2.339555926766934e-08, -0.011324244551360607, -0.00699612544849515, -0.0010566649725660682, -0.04065568745136261, 0.016429852694272995, -0.08376552909612656, -0.0020856575574725866, 0.007216688245534897, -0.020176777616143227, 0.09452491998672485, -0.04140011966228485, 0.057044047862291336, -0.020841043442487717, -0.04076668620109558, 0.053184688091278076, 0.041034143418073654, 0.007909411564469337, 0.0317397266626358, -0.10246304422616959, -0.07172954827547073, 0.07847748696804047, 0.008914634585380554, -0.05455007404088974, -0.03537008538842201, 0.015609522350132465, 0.0067329974845051765, -0.05399094894528389, 0.08556314557790756, 0.02564326487481594, 0.024739189073443413, -0.04294799268245697, 0.06372229754924774, 0.09504398703575134, 0.04785351827740669, -0.08407824486494064, 0.031810179352760315, 0.08013793081045151, 0.01620812714099884, 0.04883824661374092, -0.0538758710026741, -0.046188779175281525, -0.024918043985962868, -0.006183816120028496, 0.030808746814727783, -0.005192974116653204, -0.01914989948272705, -0.08836490660905838, 0.06700153648853302, 0.007010872941464186, -0.03852929174900055, 0.08001356571912766, -0.011538141407072544, 0.04738911986351013, 0.07420327514410019, 0.02971671335399151, 0.05760845169425011, -0.022233977913856506, -0.06519293040037155, -0.01745663583278656, -0.003626971272751689, 0.031125081703066826, 0.02877068519592285, 0.05278536304831505, -0.012105283327400684]'), +('Effective communication is a cornerstone of safe and collaborative patient care. In a complex healthcare environment where a patient is cared for by multiple providers across different shifts, unstructured communication can lead to critical information being missed, resulting in medical errors. To mitigate this risk, standardized communication tools have been developed to ensure that information is conveyed in a clear, concise, and predictable manner. These tools provide a framework that helps organize a clinician’s thoughts and ensures all vital components of a patient’s status are communicated effectively, especially during critical situations or handoffs. One of the most widely adopted and effective of these tools is the SBAR framework, which stands for Situation, Background, Assessment, and Recommendation. This evidence-based model is used for urgent communications, such as when a nurse needs to report a change in a patient’s condition to a physician, as well as for routine shift-to-shift reports. The S is for Situation, a brief statement of the problem. The B is for Background, which provides relevant context and clinical history. The A is for Assessment, which is the nurse’s clinical conclusion or what they believe the problem is. Finally, the R is for Recommendation, the nurse''s stated request for action. Using SBAR organizes the conversation logically. For example, a nurse would start by stating the immediate issue ("Situation: Mr. Jones in room 302 has a new onset of chest pain."), followed by relevant history ("Background: He is a 2-day post-op patient from a hip replacement."). The nurse then offers their clinical judgment ("Assessment: His heart rate is 110, and he is diaphoretic. I am concerned about a cardiac event."). The communication concludes with a clear request ("Recommendation: I need you to come and see him immediately. Should I get an EKG and draw cardiac enzymes while I wait?"). Mastering the SBAR framework is a vital skill for nursing students, as it promotes confidence, enhances clarity, and ultimately improves patient safety by ensuring nothing gets lost in translation.', 'According to the text, what are two instances when a nurse might use SBAR?', '[-0.07272902131080627, -0.06505727767944336, -0.07242954522371292, 0.002743617631494999, 0.006249973550438881, 0.027129707857966423, 0.008756300434470177, 0.052850980311632156, 0.037899989634752274, -0.06346458941698074, -0.034847572445869446, 0.1323079913854599, -0.060677528381347656, 0.03308643773198128, -0.0024078725837171078, 0.0610414482653141, 0.01349975261837244, -0.07055340707302094, 0.06966008991003036, 0.05699893832206726, 0.07450717687606812, 0.0550478957593441, -0.0032516855280846357, 0.09283795207738876, -0.055754873901605606, 0.00798549223691225, 0.03611472249031067, -0.02972722053527832, 0.05413968116044998, 0.024242348968982697, -0.0040925294160842896, 0.07204731553792953, 0.04491034150123596, 0.006600154563784599, -0.06604590266942978, 0.0193198062479496, -0.018964990973472595, 0.09610940515995026, -0.07156109809875488, 0.04382380098104477, -0.005054643377661705, -0.11477594077587128, -0.012815230526030064, 0.0048422738909721375, 0.07095060497522354, -0.06645318865776062, -0.04187485948204994, 0.01776035875082016, -0.026754144579172134, 0.047912973910570145, -0.016314193606376648, -0.09249693155288696, -0.028426360338926315, 0.06282971054315567, 0.015403513796627522, -0.059086933732032776, -0.04866940528154373, -0.03804703801870346, -0.07668124884366989, 0.05701830983161926, -0.050706662237644196, 0.08426985144615173, -0.012961680069565773, 0.025724150240421295, 0.10531143099069595, -0.0020808065310120583, 0.0020610452629625797, -0.03566586598753929, 0.052302539348602295, -0.005405132193118334, -0.007907360792160034, -0.04839848726987839, -0.02732546441257, 0.07142972201108932, -0.03154534101486206, -0.03806515038013458, 0.09726973623037338, 0.01597793959081173, 0.04239662364125252, -0.023835349828004837, -0.04534709081053734, -0.03710653632879257, -0.01179437804967165, 0.012712950818240643, -0.03780025243759155, 0.03278433158993721, -0.057375166565179825, -0.04223541170358658, 0.006919242441654205, -0.035433851182460785, 0.1115185096859932, -0.007734742946922779, -0.04084080085158348, -0.04444214329123497, 0.045839883387088776, 0.025018945336341858, -0.07565978169441223, -0.040305592119693756, 0.007534914184361696, 0.012489395216107368, -0.042265553027391434, -0.0009757959051057696, -0.04636858403682709, 0.0828581228852272, -0.0644233301281929, -0.05131024122238159, 0.013081573881208897, -0.15028879046440125, -0.003959926776587963, 0.009156212210655212, 0.03510753810405731, 0.07326322048902512, 0.026009539142251015, 0.04248548299074173, -0.058907926082611084, 0.005490198731422424, -0.027990760281682014, 0.03611011058092117, 0.09961443394422531, 0.04099799692630768, -0.08988560736179352, 0.016200652346014977, 0.018027765676379204, -0.04004644602537155, -0.0220493134111166, 0.005242789164185524, -0.033967118710279465, -3.413228579868951e-33, 0.052104461938142776, 0.0020945845171809196, 0.07391194254159927, -0.008014467544853687, 0.0564139299094677, 0.005681131966412067, 0.009094493463635445, -0.036401595920324326, 0.060032881796360016, 0.029700906947255135, -0.004749505314975977, 0.010446577332913876, 0.06838608533143997, 0.007219079416245222, 0.05238852649927139, 0.015172253362834454, -0.036203984171152115, 0.026919757947325706, 0.0017719385214149952, 0.03324880823493004, 0.04164006561040878, 0.027727918699383736, -0.02964676357805729, 0.07568013668060303, -0.0011137225665152073, 0.009464876726269722, 0.0692644715309143, 0.05164206773042679, -0.014112379401922226, 0.03481210023164749, -0.0061720083467662334, -0.01804032362997532, -0.038226302713155746, -0.03480522707104683, -0.015004536136984825, -0.03157790005207062, -0.008821981959044933, -0.0321195125579834, -0.1289430856704712, -0.07183697819709778, -0.03141175955533981, 0.01643984206020832, -0.023937422782182693, 0.04244527965784073, 0.04407117888331413, -0.03353628143668175, -0.04495327174663544, -0.006024190224707127, -0.04986385628581047, 0.011603085324168205, -0.023859862238168716, -0.0073285154066979885, -0.04188463091850281, -0.08241628110408783, 0.05776233226060867, 0.01595289260149002, 0.008068191818892956, 0.045572370290756226, 0.03760728985071182, 0.01809706725180149, 0.07136368751525879, 0.0026338426396250725, 0.02361762523651123, 0.004141092766076326, 0.03967541456222534, 0.00755525566637516, 0.015336115844547749, -0.06649550795555115, 0.053384631872177124, -0.02462603710591793, -0.0011956017697229981, 0.0225533414632082, -0.006868545897305012, -0.02613442949950695, -0.05213224142789841, -0.026974383741617203, 0.0019712995272129774, 0.07873855531215668, 0.0396190769970417, -0.053288113325834274, -0.042661942541599274, 0.00961819663643837, 0.039325956255197525, 0.1366714984178543, -0.024795204401016235, 0.041377078741788864, 0.03429367020726204, -0.06692230701446533, -0.11057011038064957, 0.002274345373734832, 0.008016016334295273, 0.05644393339753151, 0.01614164188504219, 0.02775384858250618, -0.007580004632472992, 3.911860610189295e-34, -0.0324782133102417, 0.03396819531917572, -0.07487580180168152, 0.06295853853225708, 0.012458880431950092, -0.07719205319881439, 0.09945697337388992, -0.06172535568475723, 0.10513738542795181, -0.028863977640867233, -0.022852826863527298, -0.030500320717692375, -0.034135159105062485, -0.06407543271780014, 0.02619747817516327, 0.003911264706403017, -0.03437498211860657, -0.06889063864946365, -0.1086425930261612, 0.03449145704507828, 0.008093640208244324, 0.08015361428260803, 0.13567975163459778, 0.0011544158915057778, 0.04073266312479973, -0.05474001169204712, -0.054042842239141464, 0.07405675947666168, -0.10201413929462433, -0.08630380779504776, 0.05183517932891846, 0.004814231302589178, 0.047043800354003906, -0.004971508868038654, -0.1494845598936081, -0.007163797505199909, 0.003977327607572079, -0.024272000417113304, 0.0040960959158837795, -0.04546070471405983, 0.0826263353228569, 0.027343450114130974, -0.041721709072589874, 0.039721276611089706, -0.01695942133665085, -0.027987148612737656, 0.001036542234942317, -0.09492114931344986, 0.0416063591837883, -0.08572399616241455, -0.034104492515325546, -0.08971790224313736, -0.026393037289381027, 0.05579216778278351, 0.017466755583882332, -0.026864273473620415, -0.0013299157144501805, -0.06468338519334793, -0.04480419680476189, 0.041025664657354355, 0.07831908762454987, -0.013156503438949585, -0.02721010334789753, 0.05943691357970238, 0.012349969707429409, -0.040438368916511536, 0.07534069567918777, -0.0006573052378371358, 0.06859040260314941, -0.015404791571199894, 0.06886813789606094, 0.025165565311908722, 0.027117060497403145, 0.08854056149721146, -0.02336215227842331, -0.004340584389865398, 0.008093149401247501, -0.09060664474964142, -0.1020762175321579, -0.04760764539241791, -0.13518203794956207, -0.0671149343252182, -0.07245088368654251, 0.06589613854885101, -0.035871315747499466, -0.10002890974283218, 0.06518252193927765, -0.02548185922205448, -0.006093848031014204, 0.005522756837308407, -0.016453910619020462, 0.014113601297140121, -0.05614679306745529, -0.01062572468072176, -0.032456882297992706, -2.2619817130475894e-08, -0.035773199051618576, 0.0015245449030771852, 0.03267879784107208, -0.0064810486510396, 0.019222047179937363, -0.1018807515501976, 0.01795308291912079, 0.024863287806510925, -0.04448936507105827, 0.042925603687763214, -0.053228698670864105, 0.057309675961732864, -0.009238384664058685, -0.02062695287168026, 0.07417866587638855, 0.042771536856889725, 0.009174530394375324, 0.025119958445429802, -0.07640723139047623, -0.052566252648830414, 0.03411279618740082, -0.02165300026535988, -0.0309374388307333, -0.02076745219528675, -0.028419509530067444, 0.03177852928638458, -0.041577961295843124, 0.06822898983955383, 0.0688890665769577, -0.027398403733968735, -0.014876366592943668, 0.05499516427516937, 0.13100096583366394, 0.027258262038230896, -0.06614638864994049, 0.020812295377254486, 0.07475753873586655, 0.009412160143256187, 0.0468391552567482, 0.06007327884435654, -0.028137503191828728, -0.07700618356466293, -0.013888668268918991, 0.03077121637761593, -0.0001078436107491143, -0.028853584080934525, -0.08234620839357376, 0.0254902895539999, -0.0047576939687132835, -0.02582693286240101, 0.10651066154241562, -0.05009021982550621, 0.07519722729921341, 0.03879382088780403, 0.007603754289448261, 0.07602118700742722, -0.02512168139219284, -0.0968480333685875, 0.030391326174139977, -0.0036964514292776585, 0.0771811306476593, 0.021520722657442093, 0.033382847905159, -0.02433536946773529]'), +('Effective communication is a cornerstone of safe and collaborative patient care. In a complex healthcare environment where a patient is cared for by multiple providers across different shifts, unstructured communication can lead to critical information being missed, resulting in medical errors. To mitigate this risk, standardized communication tools have been developed to ensure that information is conveyed in a clear, concise, and predictable manner. These tools provide a framework that helps organize a clinician’s thoughts and ensures all vital components of a patient’s status are communicated effectively, especially during critical situations or handoffs. One of the most widely adopted and effective of these tools is the SBAR framework, which stands for Situation, Background, Assessment, and Recommendation. This evidence-based model is used for urgent communications, such as when a nurse needs to report a change in a patient’s condition to a physician, as well as for routine shift-to-shift reports. The S is for Situation, a brief statement of the problem. The B is for Background, which provides relevant context and clinical history. The A is for Assessment, which is the nurse’s clinical conclusion or what they believe the problem is. Finally, the R is for Recommendation, the nurse''s stated request for action. Using SBAR organizes the conversation logically. For example, a nurse would start by stating the immediate issue ("Situation: Mr. Jones in room 302 has a new onset of chest pain."), followed by relevant history ("Background: He is a 2-day post-op patient from a hip replacement."). The nurse then offers their clinical judgment ("Assessment: His heart rate is 110, and he is diaphoretic. I am concerned about a cardiac event."). The communication concludes with a clear request ("Recommendation: I need you to come and see him immediately. Should I get an EKG and draw cardiac enzymes while I wait?"). Mastering the SBAR framework is a vital skill for nursing students, as it promotes confidence, enhances clarity, and ultimately improves patient safety by ensuring nothing gets lost in translation.', 'How does the SBAR framework contribute to a nurse''s professional development and patient safety?', '[-0.03511269763112068, -0.0742814764380455, -0.11746115237474442, -0.031078074127435684, 0.06693640351295471, 0.08397132158279419, -0.037281136959791183, 0.06231985613703728, 0.011982155963778496, 0.006323227658867836, -0.0764864832162857, 0.1307515650987625, -0.05934669449925423, 0.01671227440237999, -0.03312069550156593, 0.036857374012470245, -0.03648338094353676, -0.017802651971578598, -0.002435686532407999, 0.06029842793941498, -0.03624734655022621, 0.06725648045539856, 0.03287789970636368, 0.09070125967264175, -0.09525290876626968, 0.004049849230796099, 0.0331258587539196, -0.03706446290016174, 0.04952828958630562, 0.03321342170238495, 0.01342183817178011, -0.018333610147237778, 0.07015006989240646, 0.0001195466029457748, -0.06257035583257675, 0.017991280183196068, 0.02053334191441536, 0.06481363624334335, -0.05994991585612297, 0.018590372055768967, -0.06754288822412491, -0.07250438630580902, -0.026053572073578835, -0.0011811255244538188, 0.06844647228717804, -0.11640961468219757, -0.0068418290466070175, -0.019732236862182617, 0.004396950360387564, -0.03489390015602112, -0.051173750311136246, -0.09850042313337326, -0.019747287034988403, -0.02912786230444908, 0.011359292082488537, 0.003226866712793708, 0.02594122663140297, -0.030710848048329353, -0.07222995162010193, 0.03822164237499237, -0.024788765236735344, 0.04371325671672821, -0.038336511701345444, 0.02267155423760414, 0.12199342250823975, 0.01865249127149582, -0.04366534575819969, 0.010746557265520096, 0.065090611577034, -0.041505713015794754, -0.05102093890309334, -0.07445083558559418, -0.017746729776263237, 0.027431176975369453, 0.04245683178305626, -0.009259347803890705, 0.05566512048244476, 0.04742753878235817, 0.08407820016145706, -0.004097880329936743, 0.05870640277862549, -0.010327114723622799, 0.025727596133947372, 0.08910202234983444, -0.021545689553022385, 0.01823902502655983, 0.004148983396589756, -0.05157123878598213, -0.013199570588767529, -0.051866963505744934, 0.06124107912182808, -0.00752514973282814, -0.013678692281246185, -0.038212187588214874, 0.0044378419406712055, 0.04889357089996338, -0.07425231486558914, -0.06244577094912529, 0.03297368809580803, 0.007240452338010073, -0.025185275822877884, 0.0015456845285370946, -0.004930868744850159, 0.060998909175395966, -0.04293349012732506, -0.038125570863485336, 0.053531747311353683, -0.09086257964372635, -0.03194624185562134, 0.0437624417245388, 0.02120053768157959, 0.07625913619995117, 0.022136783227324486, 0.03233081102371216, -0.012920145876705647, 0.005725381895899773, -0.10229440778493881, 0.03137614205479622, 0.10804694145917892, 0.008143718354403973, -0.030230026692152023, 0.05105593800544739, 0.02099669724702835, -0.010045084170997143, 0.004272604826837778, 0.011141719296574593, -0.05873844027519226, -3.679839514843077e-33, 0.06541522592306137, 0.031340327113866806, 0.0231611505150795, 0.02099422551691532, 0.048366207629442215, -0.007681013084948063, 0.018797988072037697, -0.07014277577400208, 0.0025657424703240395, 0.049954574555158615, 0.006477837450802326, 0.03467350825667381, 0.052448343485593796, -0.03076336346566677, 0.079475536942482, -0.011935587972402573, -0.10078680515289307, 0.022881941869854927, -0.014955216087400913, 0.0436038114130497, -0.006274952553212643, -0.06251256167888641, -0.0398123562335968, 0.07289660722017288, 0.0005729738040827215, 0.05337826907634735, 0.07431155443191528, 0.06889285147190094, -0.039419934153556824, 0.03468053415417671, -0.07137040793895721, 0.019770143553614616, -0.08077700436115265, -0.028951600193977356, 0.024456849321722984, -0.019685866311192513, -0.061596889048814774, -0.08159929513931274, -0.07937821000814438, -0.015282301232218742, -0.05784342810511589, -0.0344003327190876, -0.007030603475868702, 0.04452024772763252, 0.0320165678858757, 0.02743653766810894, -0.031432170420885086, -0.0380060151219368, -0.06028106436133385, -0.008008341304957867, -0.050117626786231995, -0.039795346558094025, -0.02928820811212063, -0.06189654394984245, 0.014005823992192745, 0.025895893573760986, -0.03104632906615734, 0.031055700033903122, 0.025180192664265633, 0.033230338245630264, 0.03340187296271324, 0.007302457932382822, 0.003400827292352915, 0.00436083460226655, 0.06770290434360504, 0.01198410615324974, 0.019494714215397835, -0.051204003393650055, 0.12507717311382294, -0.030491478741168976, -0.04347754269838333, 0.049086686223745346, 0.02724580094218254, -0.026637766510248184, -0.0751648023724556, -0.05198436975479126, -0.02852815017104149, 0.069386787712574, 0.05716858431696892, 0.0036402540281414986, -0.04377015680074692, 0.05472999066114426, 0.04868290200829506, 0.08161758631467819, -0.0007204259745776653, -0.05641637369990349, 0.03712776303291321, 0.022084062919020653, -0.10223455727100372, -0.0015185512602329254, -0.014487870037555695, 0.001890908577479422, 0.08499545603990555, 0.09115329384803772, -0.038335490971803665, 1.3594935632015386e-33, 0.007097389083355665, 0.001948534743860364, -0.1151132807135582, -0.001879891031421721, 0.008363676257431507, -0.08378233760595322, 0.027814893051981926, -0.05323636531829834, 0.07503631711006165, 0.011010868474841118, -0.009024299681186676, -0.06323722004890442, -0.030771156772971153, -0.03454255312681198, 0.03917204216122627, -0.04690592363476753, -0.03509236499667168, -0.06434730440378189, -0.07319390773773193, -0.03995902091264725, 0.1001373678445816, 0.09093423932790756, 0.028037743642926216, 0.0398930199444294, -0.014695072546601295, -0.04246101155877113, -0.06561972200870514, 0.03296731412410736, -0.10017332434654236, -0.034252531826496124, 0.07712147384881973, 0.0015700527001172304, 0.015678852796554565, 0.037760697305202484, -0.11927851289510727, -0.016523798927664757, 0.004262302070856094, -0.0372360497713089, 0.03894920274615288, -0.04217054322361946, 0.0361035130918026, 0.04632019251585007, -0.06662774831056595, -0.03935157135128975, 0.026944732293486595, -0.03895390033721924, 0.022330118343234062, -0.048564616590738297, 0.01938546635210514, -0.11205366998910904, -0.027476748451590538, -0.06932450085878372, 0.006550158839672804, -0.013140064664185047, 0.03316889703273773, -0.01768455095589161, 0.09976807236671448, -0.07922852784395218, -0.011568084359169006, 0.09057007730007172, 0.05174052715301514, 0.04628513753414154, 0.0006669166032224894, 0.09174549579620361, 0.058904074132442474, 0.020281830802559853, -0.005450235679745674, -0.039276111871004105, 0.06036581099033356, -0.005630928557366133, 0.021654097363352776, 0.00029182815342210233, 0.014463945291936398, 0.10405653715133667, -0.047471579164266586, -0.04209480434656143, -0.04959973320364952, -0.05919824168086052, -0.10210662335157394, 0.009941061958670616, -0.0735391303896904, -0.09314031898975372, -0.02651478350162506, 0.060113582760095596, -0.01603885181248188, -0.03944408521056175, 0.04312186315655708, -0.02678641863167286, 0.01998167112469673, -0.020281653851270676, -0.10431397706270218, -0.012267633341252804, -0.05885915085673332, 0.0007288974011316895, -0.04779527708888054, -2.0817639168058122e-08, -0.015981756150722504, 0.06339222192764282, -0.04443097487092018, -0.004132778383791447, -0.01428704708814621, -0.0844292864203453, 0.010999666526913643, -0.010326031595468521, -0.03731977567076683, 0.11432935297489166, -0.04593454301357269, -0.025575676932930946, -0.02612059749662876, -0.004158675204962492, 0.07677172124385834, 0.05222168564796448, 0.05450095236301422, 0.1014133170247078, -0.07980864495038986, -0.042174335569143295, 0.10665891319513321, 0.02149301767349243, -0.03631085529923439, -0.038084447383880615, -0.0002547286858316511, -0.0034579636994749308, -0.04018078371882439, 0.06892362982034683, 0.06248779594898224, 0.030104566365480423, -0.010630285367369652, 0.04909416660666466, 0.10510751605033875, 0.06781511008739471, -0.03754643350839615, 0.049563877284526825, 0.061397675424814224, -0.010163623839616776, 0.06553948670625687, 0.03731587901711464, -0.061695441603660583, -0.014261609874665737, 0.028607361018657684, 0.03484164550900459, -0.017381519079208374, 0.008542654104530811, -0.0799781084060669, 0.05630611628293991, 0.018939096480607986, -0.025805693119764328, 0.13468636572360992, -0.01722496561706066, 0.01989034004509449, 0.05609360709786415, 0.02904289774596691, 0.0940670445561409, 0.005198683124035597, -0.06894341111183167, 0.007860192097723484, 0.004916309844702482, -0.0015357439406216145, 0.0035398832987993956, 0.10145160555839539, -0.03254592791199684]'); + `),STICKY_SCROLL_THRESHOLD=120,EXAMPLES=["What is the primary goal of therapeutic communication in nursing?","Name two key techniques of active listening mentioned in the text.","What is the difference between subjective and objective data collected during the Assessment phase?"];function App(){const e=reactExports.useRef(null),r=reactExports.useRef(null),M=reactExports.useRef(null),r0=reactExports.useRef(null),[s0,a0]=reactExports.useState(null),[i0,u0]=reactExports.useState(null),[d0,m0]=reactExports.useState(""),[_0,f0]=reactExports.useState([]),[g0,x0]=reactExports.useState(!1),[k0,F0]=reactExports.useState(null),[C0,R0]=reactExports.useState(""),[y0,w0]=reactExports.useState([]),[A0,q0]=reactExports.useState(null),[U0,X0]=reactExports.useState(null),xr=reactExports.useRef(null);reactExports.useEffect(()=>{const H0=async()=>{try{xr.current=await getDB(),await initDB(xr.current),(await xr.current.query("SELECT * FROM embeddings")).rows.length===0&&await seedDb(xr.current)}catch(lr){console.error("Database setup error:",lr),u0(lr.message)}};xr.current||H0()},[]);function Ir(H0){x0(!0),R0(""),q0(null),vr(H0)}function Ur(){e.current.postMessage({type:"interrupt"})}reactExports.useEffect(()=>{mr()},[C0]);function mr(){if(!M.current)return;const H0=M.current;H0.style.height="auto";const lr=Math.min(Math.max(H0.scrollHeight,24),200);H0.style.height=`${lr}px`}reactExports.useEffect(()=>{r.current||(r.current=new Worker(new URL("/assets/embeddingworker-B0-b0Bg2.js",import.meta.url),{type:"module"}));const H0=async lr=>{switch(lr.data.status){case"initiate":F0(!1);break;case"ready":F0(!0);break;case"complete":const fr=await search(xr.current,lr.data.embedding);console.log("Search results:",fr);const _r=[],wr=lr.data.originalMessage||"";let $0=wr;fr.length>0&&($0=` + +Context: +`+fr.map(Z0=>Z0.content).join(` +`)+` + +`+wr),_r.push({role:"user",content:wr,sources:fr.length>0?fr:void 0,contentForLLM:$0}),w0(Z0=>[...Z0,..._r]);break}};return r.current.addEventListener("message",H0),()=>r.current.removeEventListener("message",H0)});const vr=reactExports.useCallback(H0=>{r.current&&r.current.postMessage({text:H0,originalMessage:H0})},[]);return reactExports.useEffect(()=>{e.current||(e.current=new Worker(new URL("/assets/worker-Mtt72vyt.js",import.meta.url),{type:"module"}),e.current.postMessage({type:"check"}));const H0=fr=>{switch(fr.data.status){case"loading":a0("loading"),m0(fr.data.data);break;case"initiate":f0(_r=>[..._r,fr.data]);break;case"progress":f0(_r=>_r.map(wr=>wr.file===fr.data.file?{...wr,...fr.data}:wr));break;case"done":f0(_r=>_r.filter(wr=>wr.file!==fr.data.file));break;case"ready":a0("ready");break;case"start":w0(_r=>[..._r,{role:"assistant",content:""}]);break;case"update":{const{output:_r,tps:wr,numTokens:$0}=fr.data;q0(wr),X0($0),w0(Z0=>{const j0=[...Z0],S0=j0.at(-1);return j0[j0.length-1]={...S0,content:S0.content+_r},j0})}break;case"complete":x0(!1);break;case"error":u0(fr.data.data);break}},lr=fr=>{console.error("Worker error:",fr)};return e.current.addEventListener("message",H0),e.current.addEventListener("error",lr),()=>{e.current.removeEventListener("message",H0),e.current.removeEventListener("error",lr)}},[]),reactExports.useEffect(()=>{if(y0.filter(lr=>lr.role==="user").length===0||y0.at(-1).role==="assistant")return;q0(null);const H0=y0.map(lr=>({role:lr.role,content:lr.contentForLLM||lr.content}));e.current.postMessage({type:"generate",data:H0})},[y0,g0]),reactExports.useEffect(()=>{if(!r0.current||!g0)return;const H0=r0.current;H0.scrollHeight-H0.scrollTop-H0.clientHeight{e.current.postMessage({type:"load"}),a0("loading")},disabled:s0!==null||i0!==null,children:"Load model"})]})]}),s0==="loading"&&jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:jsxRuntimeExports.jsxs("div",{className:"w-full max-w-[500px] text-left mx-auto p-4 bottom-0 mt-auto",children:[jsxRuntimeExports.jsx("p",{className:"text-center mb-1",children:d0}),_0.map(({file:H0,progress:lr,total:fr},_r)=>jsxRuntimeExports.jsx(Progress,{text:H0,percentage:lr,total:fr},_r))]})}),s0==="ready"&&jsxRuntimeExports.jsxs("div",{ref:r0,className:"overflow-y-auto scrollbar-thin w-full flex flex-col items-center h-full",children:[jsxRuntimeExports.jsx(Chat,{messages:y0}),y0.length===0&&jsxRuntimeExports.jsx("div",{children:EXAMPLES.map((H0,lr)=>jsxRuntimeExports.jsx("div",{className:"m-1 border dark:border-gray-600 rounded-md p-2 bg-gray-100 dark:bg-gray-700 cursor-pointer",onClick:()=>{Ir(H0)},children:H0},lr))}),jsxRuntimeExports.jsx("p",{className:"text-center text-sm min-h-6 text-gray-500 dark:text-gray-300",children:A0&&y0.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[!g0&&jsxRuntimeExports.jsxs("span",{children:["Generated ",U0," tokens in"," ",(U0/A0).toFixed(2)," seconds ("]}),jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{className:"font-medium text-center mr-1 text-black dark:text-white",children:A0.toFixed(2)}),jsxRuntimeExports.jsx("span",{className:"text-gray-500 dark:text-gray-300",children:"tokens/second"})]}),!g0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{className:"mr-1",children:")."}),jsxRuntimeExports.jsx("span",{className:"underline cursor-pointer",onClick:()=>{e.current.postMessage({type:"reset"}),w0([])},children:"Reset"})]})]})})]}),jsxRuntimeExports.jsxs("div",{className:"mt-2 border dark:bg-gray-700 rounded-lg w-[600px] max-w-[80%] max-h-[200px] mx-auto relative mb-3 flex",children:[jsxRuntimeExports.jsx("textarea",{ref:M,className:"scrollbar-thin w-[550px] dark:bg-gray-700 px-3 py-4 rounded-lg bg-transparent border-none outline-none text-gray-800 disabled:text-gray-400 dark:text-gray-200 placeholder-gray-500 dark:placeholder-gray-400 disabled:placeholder-gray-200 resize-none disabled:cursor-not-allowed",placeholder:"Type your message...",type:"text",rows:1,value:C0,disabled:s0!=="ready",title:s0==="ready"?"Model is ready":"Model not loaded yet",onKeyDown:H0=>{C0.length>0&&!g0&&H0.key==="Enter"&&!H0.shiftKey&&(H0.preventDefault(),Ir(C0))},onInput:H0=>R0(H0.target.value)}),g0?jsxRuntimeExports.jsx("div",{className:"cursor-pointer",onClick:Ur,children:jsxRuntimeExports.jsx(StopIcon,{className:"h-8 w-8 p-1 rounded-md text-gray-800 dark:text-gray-100 absolute right-3 bottom-3"})}):C0.length>0?jsxRuntimeExports.jsx("div",{className:"cursor-pointer",onClick:()=>Ir(C0),children:jsxRuntimeExports.jsx(ArrowRightIcon,{className:"h-8 w-8 p-1 bg-gray-800 dark:bg-gray-100 text-white dark:text-black rounded-md absolute right-3 bottom-3"})}):jsxRuntimeExports.jsx("div",{children:jsxRuntimeExports.jsx(ArrowRightIcon,{className:"h-8 w-8 p-1 bg-gray-200 dark:bg-gray-600 text-gray-50 dark:text-gray-800 rounded-md absolute right-3 bottom-3"})})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-gray-400 text-center mb-3",children:"Disclaimer: Generated content may be inaccurate or false."})]})}ReactDOM.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(React.StrictMode,{children:jsxRuntimeExports.jsx(App,{})}));export{C$2 as C,R$1 as R,T$2 as T,U$1 as U,u as a,cr as c,h$1 as h,pr as p,ur as u,x$3 as x}; diff --git a/assets/index-DvLky7EN.css b/assets/index-DvLky7EN.css new file mode 100644 index 0000000000000000000000000000000000000000..770629558a920479841ef4748b45f0c2b82b817e --- /dev/null +++ b/assets/index-DvLky7EN.css @@ -0,0 +1 @@ +@scope (.markdown){pre{margin:.5rem 0;white-space:break-spaces}code{padding:.2em .4em;border-radius:4px;font-family:Consolas,Monaco,Andale Mono,Ubuntu Mono,monospace;font-size:.9em}pre,code{background-color:#f2f2f2}@media (prefers-color-scheme: dark){pre,code{background-color:#333}}pre:has(code){padding:1rem .5rem}pre>code{padding:0}h1,h2,h3,h4,h5,h6{font-weight:600;line-height:1.2}h1{font-size:2em;margin:1rem 0}h2{font-size:1.5em;margin:.83rem 0}h3{font-size:1.25em;margin:.67rem 0}h4{font-size:1em;margin:.5rem 0}h5{font-size:.875em;margin:.33rem 0}h6{font-size:.75em;margin:.25rem 0}h1,h2,h3,h4,h5,h6:first-child{margin-top:0}ul{list-style-type:disc;margin-left:1.5rem}ol{list-style-type:decimal;margin-left:1.5rem}li{margin:.25rem 0}p:not(:first-child){margin-top:.75rem}p:not(:last-child){margin-bottom:.75rem}ul>li{margin-left:1rem}table,th,td{border:1px solid lightgray;padding:.25rem}@media (prefers-color-scheme: dark){table,th,td{border:1px solid #f2f2f2}}}*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.bottom-0{bottom:0}.bottom-3{bottom:.75rem}.right-3{right:.75rem}.z-10{z-index:10}.m-1{margin:.25rem}.mx-auto{margin-left:auto;margin-right:auto}.my-3{margin-top:.75rem;margin-bottom:.75rem}.mb-0\.5{margin-bottom:.125rem}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mr-1{margin-right:.25rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-auto{margin-top:auto}.block{display:block}.flex{display:flex}.hidden{display:none}.h-2\.5{height:.625rem}.h-4{height:1rem}.h-6{height:1.5rem}.h-8{height:2rem}.h-full{height:100%}.h-screen{height:100vh}.max-h-\[200px\]{max-height:200px}.min-h-6{min-height:1.5rem}.w-2\.5{width:.625rem}.w-4{width:1rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-\[550px\]{width:550px}.w-\[600px\]{width:600px}.w-full{width:100%}.w-screen{width:100vw}.min-w-6{min-width:1.5rem}.max-w-\[320px\]{max-width:320px}.max-w-\[480px\]{max-width:480px}.max-w-\[500px\]{max-width:500px}.max-w-\[80\%\]{max-width:80%}.max-w-\[960px\]{max-width:960px}.flex-1{flex:1 1 0%}.rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.flex-col{flex-direction:column}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.gap-1{gap:.25rem}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.whitespace-nowrap{white-space:nowrap}.rounded{border-radius:.25rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.border{border-width:1px}.border-t{border-top-width:1px}.border-none{border-style:none}.border-blue-400{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity))}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity))}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity))}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity))}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.bg-gray-200{--tw-bg-opacity: 1;background-color:rgb(229 231 235 / var(--tw-bg-opacity))}.bg-gray-600{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity))}.bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity))}.bg-transparent{background-color:transparent}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity))}.bg-opacity-\[92\%\]{--tw-bg-opacity: 92%}.p-1{padding:.25rem}.p-2{padding:.5rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-4{padding-top:1rem;padding-bottom:1rem}.pt-3{padding-top:.75rem}.text-left{text-align:left}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity))}.text-blue-100{--tw-text-opacity: 1;color:rgb(219 234 254 / var(--tw-text-opacity))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity))}.text-gray-50{--tw-text-opacity: 1;color:rgb(249 250 251 / var(--tw-text-opacity))}.text-gray-500{--tw-text-opacity: 1;color:rgb(107 114 128 / var(--tw-text-opacity))}.text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity))}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}.underline{text-decoration-line:underline}.placeholder-gray-500::-moz-placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity: 1;color:rgb(107 114 128 / var(--tw-placeholder-opacity))}.outline-none{outline:2px solid transparent;outline-offset:2px}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.scrollbar-thin::-webkit-scrollbar{width:.5rem}.scrollbar-thin::-webkit-scrollbar-track{border-radius:9999px;--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}@media (prefers-color-scheme: dark){.scrollbar-thin::-webkit-scrollbar-track{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity))}}.scrollbar-thin::-webkit-scrollbar-thumb{border-radius:9999px;--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity))}@media (prefers-color-scheme: dark){.scrollbar-thin::-webkit-scrollbar-thumb{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity))}}.scrollbar-thin::-webkit-scrollbar-thumb:hover{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity))}.animation-delay-200{animation-delay:.2s}.animation-delay-400{animation-delay:.4s}.overflow-wrap-anywhere{overflow-wrap:anywhere}.hover\:bg-blue-500:hover{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:bg-blue-100:disabled{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity))}.disabled\:text-gray-400:disabled{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity))}.disabled\:placeholder-gray-200:disabled::-moz-placeholder{--tw-placeholder-opacity: 1;color:rgb(229 231 235 / var(--tw-placeholder-opacity))}.disabled\:placeholder-gray-200:disabled::placeholder{--tw-placeholder-opacity: 1;color:rgb(229 231 235 / var(--tw-placeholder-opacity))}@media (prefers-color-scheme: dark){.dark\:border-gray-600{--tw-border-opacity: 1;border-color:rgb(75 85 99 / var(--tw-border-opacity))}.dark\:bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity))}.dark\:bg-gray-300{--tw-bg-opacity: 1;background-color:rgb(209 213 219 / var(--tw-bg-opacity))}.dark\:bg-gray-600{--tw-bg-opacity: 1;background-color:rgb(75 85 99 / var(--tw-bg-opacity))}.dark\:bg-gray-700{--tw-bg-opacity: 1;background-color:rgb(55 65 81 / var(--tw-bg-opacity))}.dark\:bg-gray-900{--tw-bg-opacity: 1;background-color:rgb(17 24 39 / var(--tw-bg-opacity))}.dark\:text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity))}.dark\:text-gray-100{--tw-text-opacity: 1;color:rgb(243 244 246 / var(--tw-text-opacity))}.dark\:text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity))}.dark\:text-gray-300{--tw-text-opacity: 1;color:rgb(209 213 219 / var(--tw-text-opacity))}.dark\:text-gray-800{--tw-text-opacity: 1;color:rgb(31 41 55 / var(--tw-text-opacity))}.dark\:text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}.dark\:placeholder-gray-400::-moz-placeholder{--tw-placeholder-opacity: 1;color:rgb(156 163 175 / var(--tw-placeholder-opacity))}.dark\:placeholder-gray-400::placeholder{--tw-placeholder-opacity: 1;color:rgb(156 163 175 / var(--tw-placeholder-opacity))}} diff --git a/assets/nodefs-Dvj6UlUO.js b/assets/nodefs-Dvj6UlUO.js new file mode 100644 index 0000000000000000000000000000000000000000..f47f531f36c8dbb1b2e851e21dbaeb73f6b88d69 --- /dev/null +++ b/assets/nodefs-Dvj6UlUO.js @@ -0,0 +1 @@ +import{u as o,C as i,a as n}from"./index-Dv-VkWvZ.js";n();var d=class extends o{constructor(s){super(s),this.rootDir=(void 0)(s),(void 0)((void 0)(this.rootDir))||(void 0)(this.rootDir)}async init(s,e){return this.pg=s,{emscriptenOpts:{...e,preRun:[...e.preRun||[],t=>{let r=t.FS.filesystems.NODEFS;t.FS.mkdir(i),t.FS.mount(r,{root:this.rootDir},i)}]}}}async closeFs(){this.pg.Module.FS.quit()}};export{d as NodeFS}; diff --git a/assets/opfs-ahp-3r0djkxf.js b/assets/opfs-ahp-3r0djkxf.js new file mode 100644 index 0000000000000000000000000000000000000000..91af267c38cd5cc6d0167464d7f5e2a769a4fbdd --- /dev/null +++ b/assets/opfs-ahp-3r0djkxf.js @@ -0,0 +1,3 @@ +import{c as H,R as m,T as o,h as s,p as A,a as C,x as P,U as v}from"./index-Dv-VkWvZ.js";C();var B="state.txt",L="data",W={DIR:16384,FILE:32768},T,I,N,_,w,k,y,j,F,O,S,l,R,E,M,g,f,D,$,x,U=class extends H{constructor(t,{initialPoolSize:e=1e3,maintainedPoolSize:a=100,debug:i=!1}={}){super(t,{debug:i}),m(this,l),m(this,T),m(this,I),m(this,N),m(this,_),m(this,w),m(this,k,new Map),m(this,y,new Map),m(this,j,0),m(this,F,new Map),m(this,O,new Map),this.lastCheckpoint=0,this.checkpointInterval=1e3*60,this.poolCounter=0,m(this,S,new Set),this.initialPoolSize=e,this.maintainedPoolSize=a}async init(t,e){return await o(this,l,R).call(this),super.init(t,e)}async syncToFs(t=!1){await this.maybeCheckpointState(),await this.maintainPool(),t||this.flush()}async closeFs(){for(let t of s(this,y).values())t.close();s(this,w).flush(),s(this,w).close(),this.pg.Module.FS.quit()}async maintainPool(t){t=t||this.maintainedPoolSize;let e=t-this.state.pool.length,a=[];for(let i=0;i{++this.poolCounter;let r=`${(Date.now()-1704063600).toString(16).padStart(8,"0")}-${this.poolCounter.toString(16).padStart(8,"0")}`,c=await s(this,N).getFileHandle(r,{create:!0}),d=await c.createSyncAccessHandle();s(this,k).set(r,c),s(this,y).set(r,d),o(this,l,M).call(this,{opp:"createPoolFile",args:[r]}),this.state.pool.push(r),h()}));for(let i=0;i>e;i--)a.push(new Promise(async h=>{var d;let r=this.state.pool.pop();o(this,l,M).call(this,{opp:"deletePoolFile",args:[r]});let c=s(this,k).get(r);(d=s(this,y).get(r))==null||d.close(),await s(this,N).removeEntry(c.name),s(this,k).delete(r),s(this,y).delete(r),h()}));await Promise.all(a)}_createPoolFileState(t){this.state.pool.push(t)}_deletePoolFileState(t){let e=this.state.pool.indexOf(t);e>-1&&this.state.pool.splice(e,1)}async maybeCheckpointState(){Date.now()-this.lastCheckpoint>this.checkpointInterval&&await this.checkpointState()}async checkpointState(){let t=new TextEncoder().encode(JSON.stringify(this.state));s(this,w).truncate(0),s(this,w).write(t,{at:0}),s(this,w).flush(),this.lastCheckpoint=Date.now()}flush(){for(let t of s(this,S))try{t.flush()}catch{}s(this,S).clear()}chmod(t,e){o(this,l,E).call(this,{opp:"chmod",args:[t,e]},()=>{this._chmodState(t,e)})}_chmodState(t,e){let a=o(this,l,f).call(this,t);a.mode=e}close(t){let e=o(this,l,D).call(this,t);s(this,F).delete(t),s(this,O).delete(e)}fstat(t){let e=o(this,l,D).call(this,t);return this.lstat(e)}lstat(t){let e=o(this,l,f).call(this,t),a=e.type==="file"?s(this,y).get(e.backingFilename).getSize():0,i=4096;return{dev:0,ino:0,mode:e.mode,nlink:1,uid:0,gid:0,rdev:0,size:a,blksize:i,blocks:Math.ceil(a/i),atime:e.lastModified,mtime:e.lastModified,ctime:e.lastModified}}mkdir(t,e){o(this,l,E).call(this,{opp:"mkdir",args:[t,e]},()=>{this._mkdirState(t,e)})}_mkdirState(t,e){let a=o(this,l,g).call(this,t),i=a.pop(),h=[],r=this.state.root;for(let d of a){if(h.push(t),!Object.prototype.hasOwnProperty.call(r.children,d))if(e!=null&&e.recursive)this.mkdir(h.join("/"));else throw new p("ENOENT","No such file or directory");if(r.children[d].type!=="directory")throw new p("ENOTDIR","Not a directory");r=r.children[d]}if(Object.prototype.hasOwnProperty.call(r.children,i))throw new p("EEXIST","File exists");let c={type:"directory",lastModified:Date.now(),mode:(e==null?void 0:e.mode)||W.DIR,children:{}};r.children[i]=c}open(t,e,a){if(o(this,l,f).call(this,t).type!=="file")throw new p("EISDIR","Is a directory");let i=o(this,l,$).call(this);return s(this,F).set(i,t),s(this,O).set(t,i),i}readdir(t){let e=o(this,l,f).call(this,t);if(e.type!=="directory")throw new p("ENOTDIR","Not a directory");return Object.keys(e.children)}read(t,e,a,i,h){let r=o(this,l,D).call(this,t),c=o(this,l,f).call(this,r);if(c.type!=="file")throw new p("EISDIR","Is a directory");return s(this,y).get(c.backingFilename).read(new Uint8Array(e.buffer,a,i),{at:h})}rename(t,e){o(this,l,E).call(this,{opp:"rename",args:[t,e]},()=>{this._renameState(t,e,!0)})}_renameState(t,e,a=!1){let i=o(this,l,g).call(this,t),h=i.pop(),r=o(this,l,f).call(this,i.join("/"));if(!Object.prototype.hasOwnProperty.call(r.children,h))throw new p("ENOENT","No such file or directory");let c=o(this,l,g).call(this,e),d=c.pop(),n=o(this,l,f).call(this,c.join("/"));if(a&&Object.prototype.hasOwnProperty.call(n.children,d)){let u=n.children[d];s(this,y).get(u.backingFilename).truncate(0),this.state.pool.push(u.backingFilename)}n.children[d]=r.children[h],delete r.children[h]}rmdir(t){o(this,l,E).call(this,{opp:"rmdir",args:[t]},()=>{this._rmdirState(t)})}_rmdirState(t){let e=o(this,l,g).call(this,t),a=e.pop(),i=o(this,l,f).call(this,e.join("/"));if(!Object.prototype.hasOwnProperty.call(i.children,a))throw new p("ENOENT","No such file or directory");let h=i.children[a];if(h.type!=="directory")throw new p("ENOTDIR","Not a directory");if(Object.keys(h.children).length>0)throw new p("ENOTEMPTY","Directory not empty");delete i.children[a]}truncate(t,e=0){let a=o(this,l,f).call(this,t);if(a.type!=="file")throw new p("EISDIR","Is a directory");let i=s(this,y).get(a.backingFilename);if(!i)throw new p("ENOENT","No such file or directory");i.truncate(e),s(this,S).add(i)}unlink(t){o(this,l,E).call(this,{opp:"unlink",args:[t]},()=>{this._unlinkState(t,!0)})}_unlinkState(t,e=!1){let a=o(this,l,g).call(this,t),i=a.pop(),h=o(this,l,f).call(this,a.join("/"));if(!Object.prototype.hasOwnProperty.call(h.children,i))throw new p("ENOENT","No such file or directory");let r=h.children[i];if(r.type!=="file")throw new p("EISDIR","Is a directory");if(delete h.children[i],e){let c=s(this,y).get(r.backingFilename);c==null||c.truncate(0),s(this,S).add(c),s(this,O).has(t)&&(s(this,F).delete(s(this,O).get(t)),s(this,O).delete(t))}this.state.pool.push(r.backingFilename)}utimes(t,e,a){o(this,l,E).call(this,{opp:"utimes",args:[t,e,a]},()=>{this._utimesState(t,e,a)})}_utimesState(t,e,a){let i=o(this,l,f).call(this,t);i.lastModified=a}writeFile(t,e,a){let i=o(this,l,g).call(this,t),h=i.pop(),r=o(this,l,f).call(this,i.join("/"));if(Object.prototype.hasOwnProperty.call(r.children,h)){let n=r.children[h];n.lastModified=Date.now(),o(this,l,M).call(this,{opp:"setLastModified",args:[t,n.lastModified]})}else{if(this.state.pool.length===0)throw new Error("No more file handles available in the pool");let n={type:"file",lastModified:Date.now(),mode:(a==null?void 0:a.mode)||W.FILE,backingFilename:this.state.pool.pop()};r.children[h]=n,o(this,l,M).call(this,{opp:"createFileNode",args:[t,n]})}let c=r.children[h],d=s(this,y).get(c.backingFilename);e.length>0&&(d.write(typeof e=="string"?new TextEncoder().encode(e):new Uint8Array(e),{at:0}),t.startsWith("/pg_wal")&&s(this,S).add(d))}_createFileNodeState(t,e){let a=o(this,l,g).call(this,t),i=a.pop(),h=o(this,l,f).call(this,a.join("/"));h.children[i]=e;let r=this.state.pool.indexOf(e.backingFilename);return r>-1&&this.state.pool.splice(r,1),e}_setLastModifiedState(t,e){let a=o(this,l,f).call(this,t);a.lastModified=e}write(t,e,a,i,h){let r=o(this,l,D).call(this,t),c=o(this,l,f).call(this,r);if(c.type!=="file")throw new p("EISDIR","Is a directory");let d=s(this,y).get(c.backingFilename);if(!d)throw new p("EBADF","Bad file descriptor");let n=d.write(new Uint8Array(e,a,i),{at:h});return r.startsWith("/pg_wal")&&s(this,S).add(d),n}};T=new WeakMap,I=new WeakMap,N=new WeakMap,_=new WeakMap,w=new WeakMap,k=new WeakMap,y=new WeakMap,j=new WeakMap,F=new WeakMap,O=new WeakMap,S=new WeakMap,l=new WeakSet,R=async function(){P(this,T,await navigator.storage.getDirectory()),P(this,I,await o(this,l,x).call(this,this.dataDir,{create:!0})),P(this,N,await o(this,l,x).call(this,L,{from:s(this,I),create:!0})),P(this,_,await s(this,I).getFileHandle(B,{create:!0})),P(this,w,await s(this,_).createSyncAccessHandle());let t=new ArrayBuffer(s(this,w).getSize());s(this,w).read(t,{at:0});let e,a=new TextDecoder().decode(t).split(` +`),i=!1;try{e=JSON.parse(a[0])}catch{e={root:{type:"directory",lastModified:Date.now(),mode:W.DIR,children:{}},pool:[]},s(this,w).truncate(0),s(this,w).write(new TextEncoder().encode(JSON.stringify(e)),{at:0}),i=!0}this.state=e;let h=a.slice(1).filter(Boolean).map(n=>JSON.parse(n));for(let n of h){let u=`_${n.opp}State`;if(typeof this[u]=="function")try{this[u].bind(this)(...n.args)}catch(b){console.warn("Error applying OPFS AHP WAL entry",n,b)}}let r=[],c=async n=>{if(n.type==="file")try{let u=await s(this,N).getFileHandle(n.backingFilename),b=await u.createSyncAccessHandle();s(this,k).set(n.backingFilename,u),s(this,y).set(n.backingFilename,b)}catch(u){console.error("Error opening file handle for node",n,u)}else for(let u of Object.values(n.children))r.push(c(u))};await c(this.state.root);let d=[];for(let n of this.state.pool)d.push(new Promise(async u=>{s(this,k).has(n)&&console.warn("File handle already exists for pool file",n);let b=await s(this,N).getFileHandle(n),z=await b.createSyncAccessHandle();s(this,k).set(n,b),s(this,y).set(n,z),u()}));await Promise.all([...r,...d]),await this.maintainPool(i?this.initialPoolSize:this.maintainedPoolSize)},E=function(t,e){let a=o(this,l,M).call(this,t);try{e()}catch(i){throw s(this,w).truncate(a),i}},M=function(t){let e=JSON.stringify(t),a=new TextEncoder().encode(` +${e}`),i=s(this,w).getSize();return s(this,w).write(a,{at:i}),s(this,S).add(s(this,w)),i},g=function(t){return t.split("/").filter(Boolean)},f=function(t,e){let a=o(this,l,g).call(this,t),i=e||this.state.root;for(let h of a){if(i.type!=="directory")throw new p("ENOTDIR","Not a directory");if(!Object.prototype.hasOwnProperty.call(i.children,h))throw new p("ENOENT","No such file or directory");i=i.children[h]}return i},D=function(t){let e=s(this,F).get(t);if(!e)throw new p("EBADF","Bad file descriptor");return e},$=function(){let t=++v(this,j)._;for(;s(this,F).has(t);)v(this,j)._++;return t},x=async function(t,e){let a=o(this,l,g).call(this,t),i=(e==null?void 0:e.from)||s(this,T);for(let h of a)i=await i.getDirectoryHandle(h,{create:e==null?void 0:e.create});return i};var p=class extends Error{constructor(t,e){super(e),typeof t=="number"?this.code=t:typeof t=="string"&&(this.code=A[t])}};export{U as OpfsAhpFS}; diff --git a/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm b/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm new file mode 100644 index 0000000000000000000000000000000000000000..eb8767bc243aba4af1f049b3727c9ba9199efe9f --- /dev/null +++ b/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c46655e8a94afc45338d4cb2b840475f88e5012d524509916e505079c00bfa39 +size 21596019 diff --git a/assets/pglite-BHNxCJwl.wasm b/assets/pglite-BHNxCJwl.wasm new file mode 100644 index 0000000000000000000000000000000000000000..126bcc40c9e4643ea64ffe9ab641ea876994286f --- /dev/null +++ b/assets/pglite-BHNxCJwl.wasm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12def1cbfae6903aa89a551626ed8b01bd2689eb38b29dd47572cf92428379de +size 8859588 diff --git a/assets/pglite-CKoE7lOK.data b/assets/pglite-CKoE7lOK.data new file mode 100644 index 0000000000000000000000000000000000000000..04b1217298d2d2770e38eeb16b3f72a569cd3b8f --- /dev/null +++ b/assets/pglite-CKoE7lOK.data @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3190ae8c8e9b4bc3f493bec6242a96d4d56b817d51cbd1ba92244dba4df8654a +size 4938110 diff --git a/assets/vector.tar-D1fuLWD0.gz b/assets/vector.tar-D1fuLWD0.gz new file mode 100644 index 0000000000000000000000000000000000000000..4a22f228d059556531f314bed9468f7e1d3103e6 --- /dev/null +++ b/assets/vector.tar-D1fuLWD0.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb532e4be9b2ea5032f1388713cd67e937ef5c4535b4634bac0e2f7615ad392f +size 46169 diff --git a/assets/worker-Mtt72vyt.js b/assets/worker-Mtt72vyt.js new file mode 100644 index 0000000000000000000000000000000000000000..6648e87e62649ef61eb26217119852b947ad4651 --- /dev/null +++ b/assets/worker-Mtt72vyt.js @@ -0,0 +1,2896 @@ +var PT=Object.defineProperty;var CT=(ks,qr,Bn)=>qr in ks?PT(ks,qr,{enumerable:!0,configurable:!0,writable:!0,value:Bn}):ks[qr]=Bn;var J=(ks,qr,Bn)=>CT(ks,typeof qr!="symbol"?qr+"":qr,Bn);(function(){"use strict";const ks=new Map,qr=[],Bn=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=ks.get(e);if(s===void 0)ks.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){const o=qr.indexOf(e);o!==-1&&qr.splice(o,1);for(let n=0;n{const r=ks.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{const t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},wv=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?qr:t;let o;const n=[],i=new Set;for(const l of s){const c=await gv(l);typeof c=="string"?n.push({name:l,err:c}):(o||(o=c),o===c&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:c}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);const a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,c)=>c==="executionProviders"?a:Reflect.get(l,c)})]},Mv="1.21.0";let Du="warning";const ms={wasm:{},webgl:{},webgpu:{},versions:{common:Mv},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}`);Du=e}},get logLevel(){return Du}};Object.defineProperty(ms,"logLevel",{enumerable:!0});const bv=ms,yv=(e,r)=>{const t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];const s=t.getContext("2d");if(s!=null){let o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);const i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm;let l,c;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));const p=n*o;let d=0,u=p,f=p*2,_=-1;i==="RGBA"?(d=0,u=p,f=p*2,_=p*3):i==="RGB"?(d=0,u=p,f=p*2):i==="RBG"&&(d=0,f=p,u=p*2);for(let b=0;b{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm;let c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));const d=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const u=4;let f=0,_=1,b=2,k=3,g=0,M=d,$=d*2,v=-1;a==="RGBA"?(g=0,M=d,$=d*2,v=d*3):a==="RGB"?(g=0,M=d,$=d*2):a==="RBG"&&(g=0,$=d,M=d*2),s=t.createImageData(o,n);for(let y=0;y{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:t,width:s}=r,o=r.norm??{mean:255,bias:0};let n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3);let d=4,u=0,f=1,_=2,b=3,k=0,g=c,M=c*2,$=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,b=-1),l==="RGBA"?$=c*3:l==="RBG"?(k=0,M=c,g=c*2):l==="BGR"&&(M=0,g=c,k=c*2);for(let y=0;y{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string";let i,a=r??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){const p=l();p.width=e.width,p.height=e.height;const d=c(p);if(d!=null){let u=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(u=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=u,a.width=f}else a.tensorFormat="RGBA",a.height=u,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,u).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){const u=l();u.width=d,u.height=p;const f=c(u);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");const p=l();p.width=e.width,p.height=e.height;const d=c(p);if(d!=null){const u=e.height,f=e.width;return d.drawImage(e,0,0,f,u),i=d.getImageData(0,0,f,u).data,a.height=u,a.width=f,wa(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,d)=>{const u=l(),f=c(u);if(!e||!f)return d();const _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{u.width=_.width,u.height=_.height,f.drawImage(_,0,0,u.width,u.height);const b=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(wa(b.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return wa(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Tv=(e,r)=>{const{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new as({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},Ev=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new as({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},Pv=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new as({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},Cv=(e,r,t)=>new as({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),Rn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ei=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Lu=!1;const Sv=()=>{if(!Lu){Lu=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(Rn.set("int64",BigInt64Array),ei.set(BigInt64Array,"int64")),r&&(Rn.set("uint64",BigUint64Array),ei.set(BigUint64Array,"uint64")),s?(Rn.set("float16",t),ei.set(t,"float16")):Rn.set("float16",Uint16Array)}},$v=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new as(e.type,e.data,r);case"cpu-pinned":return new as({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new as({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new as({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new as({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let as=class{constructor(r,t,s){Sv();let o,n;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,o=r.type,n=r.dims,r.location){case"cpu-pinned":{const a=Rn.get(o);if(!a)throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`);if(!(r.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=r.data;break}case"texture":{if(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from MLTensor`);this.mlTensorData=r.mlTensor,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,l;if(typeof r=="string")if(o=r,l=s,r==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{const c=Rn.get(r);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&c===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${c.name} as data.`);r==="uint64"||r==="int64"?a=c.from(t,BigInt):a=c.from(t)}else if(t instanceof c)a=t;else if(t instanceof Uint8ClampedArray)if(r==="uint8")a=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(r==="float16"&&t instanceof Uint16Array&&c!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${o} tensor's data must be type of ${c}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const c=typeof r[0];if(c==="string")o="string",a=r;else if(c==="boolean")o="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(r instanceof Uint8ClampedArray)o="uint8",a=Uint8Array.from(r);else{const c=ei.get(r.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);o=c,a=r}if(l===void 0)l=[a.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");n=l,this.cpuData=a,this.dataLocation="cpu"}const i=$v(n);if(this.cpuData&&i!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=n,this.size=i}static async fromImage(r,t){return xv(r,t)}static fromTexture(r,t){return Tv(r,t)}static fromGpuBuffer(r,t){return Ev(r,t)}static fromMLTensor(r,t){return Pv(r,t)}static fromPinnedBuffer(r,t,s){return Cv(r,t,s)}toDataURL(r){return yv(this,r)}toImageData(r){return vv(this,r)}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}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(r){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,r&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=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(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return kv(this,r)}};const jn=as,zu=(e,r)=>{(typeof ms.trace>"u"?!ms.wasm.trace:!ms.trace)||console.timeStamp(`${e}::ORT::${r}`)},Bu=(e,r)=>{var o;const t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[];let s=!1;for(let n=0;n{(typeof ms.trace>"u"?!ms.wasm.trace:!ms.trace)||Bu("BEGIN",e)},ba=e=>{(typeof ms.trace>"u"?!ms.wasm.trace:!ms.trace)||Bu("END",e)};var Iv=Object.freeze({__proto__:null,InferenceSession:class mv{constructor(r){this.handler=r}async run(r,t,s){Ma();const o={};let n={};if(typeof r!="object"||r===null||r instanceof jn||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof jn)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(const c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);o[c]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1;const p=Object.getOwnPropertyNames(t);for(const d of this.outputNames)if(p.indexOf(d)!==-1){const u=t[d];(u===null||u instanceof jn)&&(c=!0,i=!1,o[d]=u)}if(c){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const c of this.inputNames)if(typeof r[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(i)for(const c of this.outputNames)o[c]=null;const a=await this.handler.run(r,o,n),l={};for(const c in a)if(Object.hasOwnProperty.call(a,c)){const p=a[c];p instanceof jn?l[c]=p:l[c]=new jn(p.type,p.data,p.dims)}return ba(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){Ma();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){const p=r;let d=0,u=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(u=r.byteLength-d,typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||d+u>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof o=="object"&&o!==null)i=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 t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,d,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await wv(i),c=await a.createInferenceSessionHandler(n,l);return ba(),new mv(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}},TRACE:zu,TRACE_FUNC_BEGIN:Ma,TRACE_FUNC_END:ba,Tensor:jn,env:bv,registerBackend:Bn});/*! + * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var ya=Object.defineProperty,Av=Object.getOwnPropertyDescriptor,Fv=Object.getOwnPropertyNames,Ov=Object.prototype.hasOwnProperty,Dv=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ve=(e,r)=>()=>(e&&(r=e(e=0)),r),Nn=(e,r)=>{for(var t in r)ya(e,t,{get:r[t],enumerable:!0})},Lv=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of Fv(r))!Ov.call(e,o)&&o!==t&&ya(e,o,{get:()=>r[o],enumerable:!(s=Av(r,o))||s.enumerable});return e},lo=e=>Lv(ya({},"__esModule",{value:!0}),e),co,Gs,cn,Ru,ju,Nu=Ve(()=>{co=new Map,Gs=[],cn=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=co.get(e);if(s===void 0)co.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){let o=Gs.indexOf(e);o!==-1&&Gs.splice(o,1);for(let n=0;n{let r=co.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{let t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},ju=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Gs:t,o,n=[],i=new Set;for(let l of s){let c=await Ru(l);typeof c=="string"?n.push({name:l,err:c}):(o||(o=c),o===c&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,c)=>c==="executionProviders"?a:Reflect.get(l,c)})]}}),zv=Ve(()=>{Nu()}),Vu,Bv=Ve(()=>{Vu="1.22.0-dev.20250409-89f8206ba4"}),va,ls,Uu=Ve(()=>{Bv(),va="warning",ls={wasm:{},webgl:{},webgpu:{},versions:{common:Vu},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}`);va=e}},get logLevel(){return va}},Object.defineProperty(ls,"logLevel",{enumerable:!0})}),Yt,Rv=Ve(()=>{Uu(),Yt=ls}),Wu,Gu,jv=Ve(()=>{Wu=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];let s=t.getContext("2d");if(s!=null){let o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);let i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm,l,c;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));let p=n*o,d=0,u=p,f=p*2,_=-1;i==="RGBA"?(d=0,u=p,f=p*2,_=p*3):i==="RGB"?(d=0,u=p,f=p*2):i==="RBG"&&(d=0,f=p,u=p*2);for(let b=0;b{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let d=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let u=4,f=0,_=1,b=2,k=3,g=0,M=d,$=d*2,v=-1;a==="RGBA"?(g=0,M=d,$=d*2,v=d*3):a==="RGB"?(g=0,M=d,$=d*2):a==="RBG"&&(g=0,$=d,M=d*2),s=t.createImageData(o,n);for(let y=0;y{Ta(),ti=(e,r)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:s}=r,o=r.norm??{mean:255,bias:0},n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),d=4,u=0,f=1,_=2,b=3,k=0,g=c,M=c*2,$=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,b=-1),l==="RGBA"?$=c*3:l==="RBG"?(k=0,M=c,g=c*2):l==="BGR"&&(M=0,g=c,k=c*2);for(let v=0;v{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string",i,a=r??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){let p=l();p.width=e.width,p.height=e.height;let d=c(p);if(d!=null){let u=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(u=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=u,a.width=f}else a.tensorFormat="RGBA",a.height=u,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,u).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){let u=l();u.width=d,u.height=p;let f=c(u);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=e.width,p.height=e.height;let d=c(p);if(d!=null){let u=e.height,f=e.width;return d.drawImage(e,0,0,f,u),i=d.getImageData(0,0,f,u).data,a.height=u,a.width=f,ti(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,d)=>{let u=l(),f=c(u);if(!e||!f)return d();let _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{u.width=_.width,u.height=_.height,f.drawImage(_,0,0,u.width,u.height);let b=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(ti(b.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return ti(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Hu=(e,r)=>{let{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new ss({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},qu=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new ss({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},Qu=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new ss({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},Xu=(e,r,t)=>new ss({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),un,uo,xa,Ju,Vv=Ve(()=>{un=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),uo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),xa=!1,Ju=()=>{if(!xa){xa=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(un.set("int64",BigInt64Array),uo.set(BigInt64Array,"int64")),r&&(un.set("uint64",BigUint64Array),uo.set(BigUint64Array,"uint64")),s?(un.set("float16",t),uo.set(t,"float16")):un.set("float16",Uint16Array)}}}),Yu,Zu,Uv=Ve(()=>{Ta(),Yu=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new ss(e.type,e.data,r);case"cpu-pinned":return new ss({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new ss({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new ss({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new ss({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),ss,Ta=Ve(()=>{jv(),Nv(),Vv(),Uv(),ss=class{constructor(e,r,t){Ju();let s,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=un.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,a;if(typeof e=="string")if(s=e,a=t,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let l=un.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?i=l.from(r,BigInt):i=l.from(r)}else if(r instanceof l)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&l!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(a=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",i=e;else if(l==="boolean")s="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(e);else{let l=uo.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,i=e}if(a===void 0)a=[i.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");o=a,this.cpuData=i,this.dataLocation="cpu"}let n=Yu(o);if(this.cpuData&&n!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(n/2)===this.cpuData.length))throw new Error(`Tensor's size(${n}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=o,this.size=n}static async fromImage(e,r){return Ku(e,r)}static fromTexture(e,r){return Hu(e,r)}static fromGpuBuffer(e,r){return qu(e,r)}static fromMLTensor(e,r){return Qu(e,r)}static fromPinnedBuffer(e,r,t){return Xu(e,r,t)}toDataURL(e){return Wu(this,e)}toImageData(e){return Gu(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Zu(this,e)}}}),_s,ed=Ve(()=>{Ta(),_s=ss}),po,Ea,fs,cs,td=Ve(()=>{Uu(),po=(e,r)=>{(typeof ls.trace>"u"?!ls.wasm.trace:!ls.trace)||console.timeStamp(`${e}::ORT::${r}`)},Ea=(e,r)=>{var o;let t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[],s=!1;for(let n=0;n{(typeof ls.trace>"u"?!ls.wasm.trace:!ls.trace)||Ea("BEGIN",e)},cs=e=>{(typeof ls.trace>"u"?!ls.wasm.trace:!ls.trace)||Ea("END",e)}}),rd,Wv=Ve(()=>{Nu(),ed(),td(),rd=class _v{constructor(r){this.handler=r}async run(r,t,s){fs();let o={},n={};if(typeof r!="object"||r===null||r instanceof _s||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof _s)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);o[c]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(t);for(let d of this.outputNames)if(p.indexOf(d)!==-1){let u=t[d];(u===null||u instanceof _s)&&(c=!0,i=!1,o[d]=u)}if(c){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof r[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(i)for(let c of this.outputNames)o[c]=null;let a=await this.handler.run(r,o,n),l={};for(let c in a)if(Object.hasOwnProperty.call(a,c)){let p=a[c];p instanceof _s?l[c]=p:l[c]=new _s(p.type,p.data,p.dims)}return cs(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){fs();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){let p=r,d=0,u=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(u=r.byteLength-d,typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||d+u>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof o=="object"&&o!==null)i=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 t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,d,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await ju(i),c=await a.createInferenceSessionHandler(n,l);return cs(),new _v(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Pa,Gv=Ve(()=>{Wv(),Pa=rd}),Kv=Ve(()=>{}),Hv=Ve(()=>{}),qv=Ve(()=>{}),Qv=Ve(()=>{}),sd={};Nn(sd,{InferenceSession:()=>Pa,TRACE:()=>po,TRACE_FUNC_BEGIN:()=>fs,TRACE_FUNC_END:()=>cs,Tensor:()=>_s,env:()=>Yt,registerBackend:()=>cn});var gs=Ve(()=>{zv(),Rv(),Gv(),ed(),Kv(),Hv(),td(),qv(),Qv()}),Ca=Ve(()=>{}),nd={};Nn(nd,{default:()=>od});var Sa,$a,od,Xv=Ve(()=>{var e;Rg(),dn(),za(),Sa="ort-wasm-proxy-worker",$a=((e=globalThis.self)==null?void 0:e.name)===Sa,$a&&(self.onmessage=r=>{let{type:t,in:s}=r.data;try{switch(t){case"init-wasm":ja(s.wasm).then(()=>{Zl(s).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:n}=s;ec(n,o).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:o}=s,n=bi(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=s;rc(o,n).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":sc(s),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:i,outputIndices:a,options:l}=s;oc(o,n,i,a,new Array(a.length).fill(null),l).then(c=>{c.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:c},ac([...i,...c]))},c=>{postMessage({type:t,err:c})});break}case"end-profiling":ic(s),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}}),od=$a?null:r=>new Worker(r??ns,{type:"module",name:Sa})}),id={};Nn(id,{default:()=>ad});var ka,Ia,ad,ld,Jv=Ve(()=>{var e,r;Ia=(ka=self.location.href,async function(t={}){var no;var s,o,n=t,i=new Promise((h,E)=>{s=h,o=E}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",c=l&&((no=self.name)==null?void 0:no.startsWith("em-pthread"));n.mountExternalData=(h,E)=>{h.startsWith("./")&&(h=h.substring(2)),(n.Eb||(n.Eb=new Map)).set(h,E)},n.unmountExternalData=()=>{delete n.Eb};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let d=h=>async(...E)=>{var A;try{if(n.Fb)throw Error("Session already started");let z=n.Fb={dc:E[0],errors:[]},V=await h(...E);if(n.Fb!==z)throw Error("Session mismatch");(A=n.Jb)==null||A.flush();let ce=z.errors;if(0De),0{if(h==="webgpu"){[n.Jb,n.Ub,n.Yb,n.Kb,n.Xb,n.jb,n.Zb,n.ac,n.Vb,n.Wb,n.$b]=E;let A=n.Jb;n.jsepRegisterBuffer=(z,V,ce,Pe)=>A.registerBuffer(z,V,ce,Pe),n.jsepGetBuffer=z=>A.getBuffer(z),n.jsepCreateDownloader=(z,V,ce)=>A.createDownloader(z,V,ce),n.jsepOnCreateSession=z=>{A.onCreateSession(z)},n.jsepOnReleaseSession=z=>{A.onReleaseSession(z)},n.jsepOnRunStart=z=>A.onRunStart(z),n.bc=(z,V)=>{A.upload(z,V)}}else if(h==="webnn"){let A=E[0];[n.nc,n.Nb,n.webnnEnsureTensor,n.Ob,n.webnnDownloadTensor]=E.slice(1),n.webnnReleaseTensorId=n.Nb,n.webnnUploadTensor=n.Ob,n.webnnOnRunStart=z=>A.onRunStart(z),n.webnnOnRunEnd=A.onRunEnd.bind(A),n.webnnRegisterMLContext=(z,V)=>{A.registerMLContext(z,V)},n.webnnOnReleaseSession=z=>{A.onReleaseSession(z)},n.webnnCreateMLTensorDownloader=(z,V)=>A.createMLTensorDownloader(z,V),n.webnnRegisterMLTensor=(z,V,ce,Pe)=>A.registerMLTensor(z,V,ce,Pe),n.webnnCreateMLContext=z=>A.createMLContext(z),n.webnnRegisterMLConstant=(z,V,ce,Pe,De,He)=>A.registerMLConstant(z,V,ce,Pe,De,n.Eb,He),n.webnnRegisterGraphInput=A.registerGraphInput.bind(A),n.webnnIsGraphInput=A.isGraphInput.bind(A),n.webnnCreateTemporaryTensor=A.createTemporaryTensor.bind(A),n.webnnIsInt64Supported=A.isInt64Supported.bind(A)}};let u=()=>{let h=(E,A,z)=>(...V)=>{let ce=fr,Pe=A==null?void 0:A();V=E(...V);let De=A==null?void 0:A();return Pe!==De&&(E=De,z(Pe),A=z=null),fr!=ce?new Promise((He,at)=>{zr={resolve:He,reject:at}}):V};(()=>{for(let E of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])n[E]=h(n[E],()=>n[E],A=>n[E]=A)})(),d!==void 0&&(n._OrtRun=d(n._OrtRun),n._OrtRunWithBinding=d(n._OrtRunWithBinding)),u=void 0};n.asyncInit=()=>{u==null||u()};var f,_,b=Object.assign({},n),k=(h,E)=>{throw E},g="";(a||l)&&(l?g=self.location.href:typeof document<"u"&&document.currentScript&&(g=document.currentScript.src),ka&&(g=ka),g=g.startsWith("blob:")?"":g.slice(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(_=h=>{var E=new XMLHttpRequest;return E.open("GET",h,!1),E.responseType="arraybuffer",E.send(null),new Uint8Array(E.response)}),f=async h=>{if(j(h))return new Promise((A,z)=>{var V=new XMLHttpRequest;V.open("GET",h,!0),V.responseType="arraybuffer",V.onload=()=>{V.status==200||V.status==0&&V.response?A(V.response):z(V.status)},V.onerror=z,V.send(null)});var E=await fetch(h,{credentials:"same-origin"});if(E.ok)return E.arrayBuffer();throw Error(E.status+" : "+E.url)});var M=console.log.bind(console),$=console.error.bind(console),v=M,y=$;Object.assign(n,b),b=null;var T,x,P,O,L,G,K,R,te,H,ee,Z,ne,me=n.wasmBinary,ue=!1,j=h=>h.startsWith("file://");function F(){return T.buffer!=O.buffer&&ae(),O}function U(){return T.buffer!=O.buffer&&ae(),L}function se(){return T.buffer!=O.buffer&&ae(),G}function _e(){return T.buffer!=O.buffer&&ae(),K}function ie(){return T.buffer!=O.buffer&&ae(),R}function ve(){return T.buffer!=O.buffer&&ae(),te}function ze(){return T.buffer!=O.buffer&&ae(),H}function Ge(){return T.buffer!=O.buffer&&ae(),ne}if(c){let h=function(E){try{var A=E.data,z=A.Bb;if(z==="load"){let V=[];self.onmessage=ce=>V.push(ce),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let ce of V)h(ce);self.onmessage=h};for(let ce of A.Rb)n[ce]&&!n[ce].proxy||(n[ce]=(...Pe)=>{postMessage({Bb:"callHandler",Qb:ce,args:Pe})},ce=="print"&&(v=n[ce]),ce=="printErr"&&(y=n[ce]));T=A.kc,ae(),Ie(A.lc)}else if(z==="run"){Xs(A.Ab),Zn(A.Ab,0,0,1,0,0),us(),de(A.Ab),X||(Vo(),X=!0);try{Js(A.fc,A.Hb)}catch(V){if(V!="unwind")throw V}}else A.target!=="setimmediate"&&(z==="checkMailbox"?X&&Te():z&&(y(`worker: received unknown command ${z}`),y(A)))}catch(V){throw eo(),V}};var Ie,X=!1;y=function(...E){E=E.join(" "),console.error(E)},self.alert=function(...E){postMessage({Bb:"alert",text:E.join(" "),ic:Sn()})},self.onunhandledrejection=E=>{throw E.reason||E},self.onmessage=h}function ae(){var h=T.buffer;n.HEAP8=O=new Int8Array(h),n.HEAP16=G=new Int16Array(h),n.HEAPU8=L=new Uint8Array(h),n.HEAPU16=K=new Uint16Array(h),n.HEAP32=R=new Int32Array(h),n.HEAPU32=te=new Uint32Array(h),n.HEAPF32=H=new Float32Array(h),n.HEAPF64=ne=new Float64Array(h),n.HEAP64=ee=new BigInt64Array(h),n.HEAPU64=Z=new BigUint64Array(h)}function W(){c?startWorker(n):dt.Ca()}c||(T=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),ae());var be,ke=0,Ee=null;function Me(){if(--ke==0&&Ee){var h=Ee;Ee=null,h()}}function Se(h){throw y(h="Aborted("+h+")"),ue=!0,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),o(h),h}function we(){return{a:{L:Qe,Aa:Be,b:Zs,$:As,A:S,pa:Q,X:re,Z:ge,qa:Fe,na:rt,ga:ft,ma:ht,J:vt,Y:st,V:zt,oa:Ut,W:Nr,va:Sr,E:Ds,Q:Wr,O:Gr,D:je,u:et,r:Xt,P:Vs,z:I,R:N,ja:Y,T:Ne,aa:We,M:tt,F:Mt,ia:de,sa:Bt,t:Wt,Ba:_r,w:ps,o:ar,l:Hr,c:Ts,n:Hn,j:Ei,v:Pi,p:Ci,f:tn,s:Si,m:$i,e:ki,k:Ii,i:Ai,g:rn,d:Fi,da:Oi,ea:ko,fa:Di,ba:Io,ca:qn,N:Fo,xa:Oo,ua:Li,h:Xn,C:zi,G:Bi,ta:mc,x:Ri,ra:ji,U:Ni,q:Ao,y:Vi,K:Ui,S:Wi,za:Do,ya:Gi,ka:Ki,la:zo,_:It,B:Hi,I:Bo,ha:Jn,H:Ro,a:T,wa:Ye}}}var Ae={829644:(h,E,A,z,V)=>{if(n===void 0||!n.Eb)return 1;if((h=Qt(Number(h>>>0))).startsWith("./")&&(h=h.substring(2)),!(h=n.Eb.get(h)))return 2;if(E=Number(E>>>0),A=Number(A>>>0),z=Number(z>>>0),E+A>h.byteLength)return 3;try{let ce=h.subarray(E,E+A);switch(V){case 0:U().set(ce,z>>>0);break;case 1:n.mc?n.mc(z,ce):n.bc(z,ce);break;default:return 4}return 0}catch{return 4}},830468:(h,E,A)=>{n.Ob(h,U().subarray(E>>>0,E+A>>>0))},830532:()=>n.nc(),830574:h=>{n.Nb(h)},830611:()=>{n.Vb()},830642:()=>{n.Wb()},830671:()=>{n.$b()},830696:h=>n.Ub(h),830729:h=>n.Yb(h),830761:(h,E,A)=>{n.Kb(Number(h),Number(E),Number(A),!0)},830824:(h,E,A)=>{n.Kb(Number(h),Number(E),Number(A))},830881:()=>typeof wasmOffsetConverter<"u",830938:h=>{n.jb("Abs",h,void 0)},830989:h=>{n.jb("Neg",h,void 0)},831040:h=>{n.jb("Floor",h,void 0)},831093:h=>{n.jb("Ceil",h,void 0)},831145:h=>{n.jb("Reciprocal",h,void 0)},831203:h=>{n.jb("Sqrt",h,void 0)},831255:h=>{n.jb("Exp",h,void 0)},831306:h=>{n.jb("Erf",h,void 0)},831357:h=>{n.jb("Sigmoid",h,void 0)},831412:(h,E,A)=>{n.jb("HardSigmoid",h,{alpha:E,beta:A})},831491:h=>{n.jb("Log",h,void 0)},831542:h=>{n.jb("Sin",h,void 0)},831593:h=>{n.jb("Cos",h,void 0)},831644:h=>{n.jb("Tan",h,void 0)},831695:h=>{n.jb("Asin",h,void 0)},831747:h=>{n.jb("Acos",h,void 0)},831799:h=>{n.jb("Atan",h,void 0)},831851:h=>{n.jb("Sinh",h,void 0)},831903:h=>{n.jb("Cosh",h,void 0)},831955:h=>{n.jb("Asinh",h,void 0)},832008:h=>{n.jb("Acosh",h,void 0)},832061:h=>{n.jb("Atanh",h,void 0)},832114:h=>{n.jb("Tanh",h,void 0)},832166:h=>{n.jb("Not",h,void 0)},832217:(h,E,A)=>{n.jb("Clip",h,{min:E,max:A})},832286:h=>{n.jb("Clip",h,void 0)},832338:(h,E)=>{n.jb("Elu",h,{alpha:E})},832396:h=>{n.jb("Gelu",h,void 0)},832448:h=>{n.jb("Relu",h,void 0)},832500:(h,E)=>{n.jb("LeakyRelu",h,{alpha:E})},832564:(h,E)=>{n.jb("ThresholdedRelu",h,{alpha:E})},832634:(h,E)=>{n.jb("Cast",h,{to:E})},832692:h=>{n.jb("Add",h,void 0)},832743:h=>{n.jb("Sub",h,void 0)},832794:h=>{n.jb("Mul",h,void 0)},832845:h=>{n.jb("Div",h,void 0)},832896:h=>{n.jb("Pow",h,void 0)},832947:h=>{n.jb("Equal",h,void 0)},833e3:h=>{n.jb("Greater",h,void 0)},833055:h=>{n.jb("GreaterOrEqual",h,void 0)},833117:h=>{n.jb("Less",h,void 0)},833169:h=>{n.jb("LessOrEqual",h,void 0)},833228:(h,E,A,z,V)=>{n.jb("ReduceMean",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},833403:(h,E,A,z,V)=>{n.jb("ReduceMax",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},833577:(h,E,A,z,V)=>{n.jb("ReduceMin",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},833751:(h,E,A,z,V)=>{n.jb("ReduceProd",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},833926:(h,E,A,z,V)=>{n.jb("ReduceSum",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},834100:(h,E,A,z,V)=>{n.jb("ReduceL1",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},834273:(h,E,A,z,V)=>{n.jb("ReduceL2",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},834446:(h,E,A,z,V)=>{n.jb("ReduceLogSum",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},834623:(h,E,A,z,V)=>{n.jb("ReduceSumSquare",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},834803:(h,E,A,z,V)=>{n.jb("ReduceLogSumExp",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},834983:h=>{n.jb("Where",h,void 0)},835036:(h,E,A)=>{n.jb("Transpose",h,{perm:E?Array.from(ie().subarray(Number(E)>>>0,Number(A)>>>0)):[]})},835160:(h,E,A,z)=>{n.jb("DepthToSpace",h,{blocksize:E,mode:Qt(A),format:z?"NHWC":"NCHW"})},835293:(h,E,A,z)=>{n.jb("DepthToSpace",h,{blocksize:E,mode:Qt(A),format:z?"NHWC":"NCHW"})},835426:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr,Ls)=>{n.jb("ConvTranspose",h,{format:He?"NHWC":"NCHW",autoPad:E,dilations:[A],group:z,kernelShape:[V],pads:[ce,Pe],strides:[De],wIsConst:()=>!!F()[at>>>0],outputPadding:xt?Array.from(ie().subarray(Number(xt)>>>0,Number(Ot)>>>0)):[],outputShape:Gt?Array.from(ie().subarray(Number(Gt)>>>0,Number(yr)>>>0)):[],activation:Qt(Ls)})},835859:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr)=>{n.jb("ConvTranspose",h,{format:De?"NHWC":"NCHW",autoPad:E,dilations:Array.from(ie().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:z,kernelShape:Array.from(ie().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(ie().subarray(Number(ce)>>>0,4+(Number(ce)>>>0)>>>0)),strides:Array.from(ie().subarray(Number(Pe)>>>0,2+(Number(Pe)>>>0)>>>0)),wIsConst:()=>!!F()[He>>>0],outputPadding:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],outputShape:Ot?Array.from(ie().subarray(Number(Ot)>>>0,Number(Gt)>>>0)):[],activation:Qt(yr)})},836520:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr,Ls)=>{n.jb("ConvTranspose",h,{format:He?"NHWC":"NCHW",autoPad:E,dilations:[A],group:z,kernelShape:[V],pads:[ce,Pe],strides:[De],wIsConst:()=>!!F()[at>>>0],outputPadding:xt?Array.from(ie().subarray(Number(xt)>>>0,Number(Ot)>>>0)):[],outputShape:Gt?Array.from(ie().subarray(Number(Gt)>>>0,Number(yr)>>>0)):[],activation:Qt(Ls)})},836953:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr)=>{n.jb("ConvTranspose",h,{format:De?"NHWC":"NCHW",autoPad:E,dilations:Array.from(ie().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:z,kernelShape:Array.from(ie().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(ie().subarray(Number(ce)>>>0,4+(Number(ce)>>>0)>>>0)),strides:Array.from(ie().subarray(Number(Pe)>>>0,2+(Number(Pe)>>>0)>>>0)),wIsConst:()=>!!F()[He>>>0],outputPadding:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],outputShape:Ot?Array.from(ie().subarray(Number(Ot)>>>0,Number(Gt)>>>0)):[],activation:Qt(yr)})},837614:(h,E)=>{n.jb("GlobalAveragePool",h,{format:E?"NHWC":"NCHW"})},837705:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr)=>{n.jb("AveragePool",h,{format:yr?"NHWC":"NCHW",auto_pad:E,ceil_mode:A,count_include_pad:z,storage_order:V,dilations:ce?Array.from(ie().subarray(Number(ce)>>>0,Number(Pe)>>>0)):[],kernel_shape:De?Array.from(ie().subarray(Number(De)>>>0,Number(He)>>>0)):[],pads:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],strides:Ot?Array.from(ie().subarray(Number(Ot)>>>0,Number(Gt)>>>0)):[]})},838184:(h,E)=>{n.jb("GlobalAveragePool",h,{format:E?"NHWC":"NCHW"})},838275:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr)=>{n.jb("AveragePool",h,{format:yr?"NHWC":"NCHW",auto_pad:E,ceil_mode:A,count_include_pad:z,storage_order:V,dilations:ce?Array.from(ie().subarray(Number(ce)>>>0,Number(Pe)>>>0)):[],kernel_shape:De?Array.from(ie().subarray(Number(De)>>>0,Number(He)>>>0)):[],pads:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],strides:Ot?Array.from(ie().subarray(Number(Ot)>>>0,Number(Gt)>>>0)):[]})},838754:(h,E)=>{n.jb("GlobalMaxPool",h,{format:E?"NHWC":"NCHW"})},838841:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr)=>{n.jb("MaxPool",h,{format:yr?"NHWC":"NCHW",auto_pad:E,ceil_mode:A,count_include_pad:z,storage_order:V,dilations:ce?Array.from(ie().subarray(Number(ce)>>>0,Number(Pe)>>>0)):[],kernel_shape:De?Array.from(ie().subarray(Number(De)>>>0,Number(He)>>>0)):[],pads:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],strides:Ot?Array.from(ie().subarray(Number(Ot)>>>0,Number(Gt)>>>0)):[]})},839316:(h,E)=>{n.jb("GlobalMaxPool",h,{format:E?"NHWC":"NCHW"})},839403:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr)=>{n.jb("MaxPool",h,{format:yr?"NHWC":"NCHW",auto_pad:E,ceil_mode:A,count_include_pad:z,storage_order:V,dilations:ce?Array.from(ie().subarray(Number(ce)>>>0,Number(Pe)>>>0)):[],kernel_shape:De?Array.from(ie().subarray(Number(De)>>>0,Number(He)>>>0)):[],pads:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],strides:Ot?Array.from(ie().subarray(Number(Ot)>>>0,Number(Gt)>>>0)):[]})},839878:(h,E,A,z,V)=>{n.jb("Gemm",h,{alpha:E,beta:A,transA:z,transB:V})},839982:h=>{n.jb("MatMul",h,void 0)},840036:(h,E,A,z)=>{n.jb("ArgMax",h,{keepDims:!!E,selectLastIndex:!!A,axis:z})},840144:(h,E,A,z)=>{n.jb("ArgMin",h,{keepDims:!!E,selectLastIndex:!!A,axis:z})},840252:(h,E)=>{n.jb("Softmax",h,{axis:E})},840315:(h,E)=>{n.jb("Concat",h,{axis:E})},840375:(h,E,A,z,V)=>{n.jb("Split",h,{axis:E,numOutputs:A,splitSizes:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},840531:h=>{n.jb("Expand",h,void 0)},840585:(h,E)=>{n.jb("Gather",h,{axis:Number(E)})},840656:(h,E)=>{n.jb("GatherElements",h,{axis:Number(E)})},840735:(h,E)=>{n.jb("GatherND",h,{batch_dims:Number(E)})},840814:(h,E,A,z,V,ce,Pe,De,He,at,xt)=>{n.jb("Resize",h,{antialias:E,axes:A?Array.from(ie().subarray(Number(A)>>>0,Number(z)>>>0)):[],coordinateTransformMode:Qt(V),cubicCoeffA:ce,excludeOutside:Pe,extrapolationValue:De,keepAspectRatioPolicy:Qt(He),mode:Qt(at),nearestMode:Qt(xt)})},841176:(h,E,A,z,V,ce,Pe)=>{n.jb("Slice",h,{starts:E?Array.from(ie().subarray(Number(E)>>>0,Number(A)>>>0)):[],ends:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[],axes:ce?Array.from(ie().subarray(Number(ce)>>>0,Number(Pe)>>>0)):[]})},841440:h=>{n.jb("Tile",h,void 0)},841492:(h,E,A)=>{n.jb("InstanceNormalization",h,{epsilon:E,format:A?"NHWC":"NCHW"})},841606:(h,E,A)=>{n.jb("InstanceNormalization",h,{epsilon:E,format:A?"NHWC":"NCHW"})},841720:h=>{n.jb("Range",h,void 0)},841773:(h,E)=>{n.jb("Einsum",h,{equation:Qt(E)})},841854:(h,E,A,z,V)=>{n.jb("Pad",h,{mode:E,value:A,pads:z?Array.from(ie().subarray(Number(z)>>>0,Number(V)>>>0)):[]})},841997:(h,E,A,z,V,ce)=>{n.jb("BatchNormalization",h,{epsilon:E,momentum:A,spatial:!!V,trainingMode:!!z,format:ce?"NHWC":"NCHW"})},842166:(h,E,A,z,V,ce)=>{n.jb("BatchNormalization",h,{epsilon:E,momentum:A,spatial:!!V,trainingMode:!!z,format:ce?"NHWC":"NCHW"})},842335:(h,E,A)=>{n.jb("CumSum",h,{exclusive:Number(E),reverse:Number(A)})},842432:(h,E,A)=>{n.jb("DequantizeLinear",h,{axis:E,blockSize:A})},842522:(h,E,A,z,V)=>{n.jb("GridSample",h,{align_corners:E,mode:Qt(A),padding_mode:Qt(z),format:V?"NHWC":"NCHW"})},842692:(h,E,A,z,V)=>{n.jb("GridSample",h,{align_corners:E,mode:Qt(A),padding_mode:Qt(z),format:V?"NHWC":"NCHW"})},842862:(h,E)=>{n.jb("ScatterND",h,{reduction:Qt(E)})},842947:(h,E,A,z,V,ce,Pe,De,He)=>{n.jb("Attention",h,{numHeads:E,isUnidirectional:A,maskFilterValue:z,scale:V,doRotary:ce,qkvHiddenSizes:Pe?Array.from(ie().subarray(Number(De)>>>0,Number(De)+Pe>>>0)):[],pastPresentShareBuffer:!!He})},843219:h=>{n.jb("BiasAdd",h,void 0)},843274:h=>{n.jb("BiasSplitGelu",h,void 0)},843335:h=>{n.jb("FastGelu",h,void 0)},843391:(h,E,A,z,V,ce,Pe,De,He,at,xt,Ot,Gt,yr,Ls,Qi)=>{n.jb("Conv",h,{format:Ot?"NHWC":"NCHW",auto_pad:E,dilations:A?Array.from(ie().subarray(Number(A)>>>0,Number(z)>>>0)):[],group:V,kernel_shape:ce?Array.from(ie().subarray(Number(ce)>>>0,Number(Pe)>>>0)):[],pads:De?Array.from(ie().subarray(Number(De)>>>0,Number(He)>>>0)):[],strides:at?Array.from(ie().subarray(Number(at)>>>0,Number(xt)>>>0)):[],w_is_const:()=>!!F()[Number(Gt)>>>0],activation:Qt(yr),activation_params:Ls?Array.from(ze().subarray(Number(Ls)>>>0,Number(Qi)>>>0)):[]})},843975:h=>{n.jb("Gelu",h,void 0)},844027:(h,E,A,z,V,ce,Pe,De,He)=>{n.jb("GroupQueryAttention",h,{numHeads:E,kvNumHeads:A,scale:z,softcap:V,doRotary:ce,rotaryInterleaved:Pe,smoothSoftmax:De,localWindowSize:He})},844244:(h,E,A,z)=>{n.jb("LayerNormalization",h,{axis:E,epsilon:A,simplified:!!z})},844355:(h,E,A,z)=>{n.jb("LayerNormalization",h,{axis:E,epsilon:A,simplified:!!z})},844466:(h,E,A,z,V,ce)=>{n.jb("MatMulNBits",h,{k:E,n:A,accuracyLevel:z,bits:V,blockSize:ce})},844593:(h,E,A,z,V,ce)=>{n.jb("MultiHeadAttention",h,{numHeads:E,isUnidirectional:A,maskFilterValue:z,scale:V,doRotary:ce})},844752:(h,E)=>{n.jb("QuickGelu",h,{alpha:E})},844816:(h,E,A,z,V)=>{n.jb("RotaryEmbedding",h,{interleaved:!!E,numHeads:A,rotaryEmbeddingDim:z,scale:V})},844955:(h,E,A)=>{n.jb("SkipLayerNormalization",h,{epsilon:E,simplified:!!A})},845057:(h,E,A)=>{n.jb("SkipLayerNormalization",h,{epsilon:E,simplified:!!A})},845159:(h,E,A,z)=>{n.jb("GatherBlockQuantized",h,{gatherAxis:E,quantizeAxis:A,blockSize:z})},845280:h=>{n.Zb(h)},845314:(h,E)=>n.ac(Number(h),Number(E),n.Fb.dc,n.Fb.errors)};function Be(h,E,A){return Ir(async()=>{await n.Xb(Number(h),Number(E),Number(A))})}function Qe(){return typeof wasmOffsetConverter<"u"}class xe{constructor(E){J(this,"name","ExitStatus");this.message=`Program terminated with exit(${E})`,this.status=E}}var Ze=h=>{h.terminate(),h.onmessage=()=>{}},Ke=[],nt=h=>{St.length==0&&(Cr(),qt(St[0]));var E=St.pop();if(!E)return 6;wt.push(E),Pr[h.Ab]=E,E.Ab=h.Ab;var A={Bb:"run",fc:h.ec,Hb:h.Hb,Ab:h.Ab};return E.postMessage(A,h.Mb),0},Je=0,Oe=(h,E,...A)=>{for(var z=2*A.length,V=An(),ce=ro(8*z),Pe=ce>>>3,De=0;De>>0]=He)}return h=Uo(h,0,z,ce,E),In(V),h};function Ye(h){if(c)return Oe(0,1,h);if(P=h,!(0{if(P=h,c)throw ot(h),"unwind";Ye(h)},St=[],wt=[],Mr=[],Pr={},jr=h=>{var E=h.Ab;delete Pr[E],St.push(h),wt.splice(wt.indexOf(h),1),h.Ab=0,Wo(E)};function us(){Mr.forEach(h=>h())}var qt=h=>new Promise(E=>{h.onmessage=V=>{var ce=(V=V.data).Bb;if(V.Gb&&V.Gb!=Sn()){var Pe=Pr[V.Gb];Pe?Pe.postMessage(V,V.Mb):y(`Internal error! Worker sent a message "${ce}" to target pthread ${V.Gb}, but that thread no longer exists!`)}else ce==="checkMailbox"?Te():ce==="spawnThread"?nt(V):ce==="cleanupThread"?jr(Pr[V.hc]):ce==="loaded"?(h.loaded=!0,E(h)):ce==="alert"?alert(`Thread ${V.ic}: ${V.text}`):V.target==="setimmediate"?h.postMessage(V):ce==="callHandler"?n[V.Qb](...V.args):ce&&y(`worker sent an unknown command ${ce}`)},h.onerror=V=>{throw y(`worker sent an error! ${V.filename}:${V.lineno}: ${V.message}`),V};var A,z=[];for(A of[])n.propertyIsEnumerable(A)&&z.push(A);h.postMessage({Bb:"load",Rb:z,kc:T,lc:x})});function Cr(){var h=new Worker((()=>{let E=URL;return self.location.href>"file:"&&self.location.href<"file;"?new E("ort.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});St.push(h)}var Xs=h=>{ae();var E=ve()[h+52>>>2>>>0];h=ve()[h+56>>>2>>>0],to(E,E-h),In(E)},Js=(h,E)=>{Je=0,h=Ho(h,E),0>>=0);throw E>>>=0,A>>>=0,ve()[z.Ib+16>>>2>>>0]=0,ve()[z.Ib+4>>>2>>>0]=E,ve()[z.Ib+8>>>2>>>0]=A,h}function pt(h,E,A,z){return c?Oe(2,1,h,E,A,z):As(h,E,A,z)}function As(h,E,A,z){if(h>>>=0,A>>>=0,z>>>=0,p===void 0)return 6;var V=[];return c&&V.length===0?pt(h,E>>>=0,A,z):(h={ec:A,Ab:h,Hb:z,Mb:V},c?(h.Bb="spawnThread",postMessage(h,V),0):nt(h))}var Fs=typeof TextDecoder<"u"?new TextDecoder:void 0,Ct=(h,E=0,A=NaN)=>{var z=(E>>>=0)+A;for(A=E;h[A]&&!(A>=z);)++A;if(16(V=(240&V)==224?(15&V)<<12|ce<<6|Pe:(7&V)<<18|ce<<12|Pe<<6|63&h[E++])?z+=String.fromCharCode(V):(V-=65536,z+=String.fromCharCode(55296|V>>10,56320|1023&V))}}else z+=String.fromCharCode(V)}return z},Qt=(h,E)=>(h>>>=0)?Ct(U(),h,E):"";function S(h,E,A){return c?Oe(3,1,h,E,A):0}function Q(h,E){if(c)return Oe(4,1,h,E)}var B=h=>{for(var E=0,A=0;A=z?E++:2047>=z?E+=2:55296<=z&&57343>=z?(E+=4,++A):E+=3}return E},q=(h,E,A)=>{var z=U();if(E>>>=0,0=Pe&&(Pe=65536+((1023&Pe)<<10)|1023&h.charCodeAt(++ce)),127>=Pe){if(E>=A)break;z[E++>>>0]=Pe}else{if(2047>=Pe){if(E+1>=A)break;z[E++>>>0]=192|Pe>>6}else{if(65535>=Pe){if(E+2>=A)break;z[E++>>>0]=224|Pe>>12}else{if(E+3>=A)break;z[E++>>>0]=240|Pe>>18,z[E++>>>0]=128|Pe>>12&63}z[E++>>>0]=128|Pe>>6&63}z[E++>>>0]=128|63&Pe}}z[E>>>0]=0,h=E-V}else h=0;return h};function re(h,E){if(c)return Oe(5,1,h,E)}function ge(h,E,A){if(c)return Oe(6,1,h,E,A)}function Fe(h,E,A){return c?Oe(7,1,h,E,A):0}function rt(h,E){if(c)return Oe(8,1,h,E)}function ft(h,E,A){if(c)return Oe(9,1,h,E,A)}function ht(h,E,A,z){if(c)return Oe(10,1,h,E,A,z)}function vt(h,E,A,z){if(c)return Oe(11,1,h,E,A,z)}function st(h,E,A,z){if(c)return Oe(12,1,h,E,A,z)}function zt(h){if(c)return Oe(13,1,h)}function Ut(h,E){if(c)return Oe(14,1,h,E)}function Nr(h,E,A){if(c)return Oe(15,1,h,E,A)}var Xr,rr,Sr=()=>Se(""),$r=h=>{for(var E="";U()[h>>>0];)E+=Xr[U()[h++>>>0]];return E},Vr={},ds={};function kr(h,E,A={}){return function(z,V,ce={}){var Pe=V.name;if(!z)throw new rr(`type "${Pe}" must have a positive integer typeid pointer`);if(ds.hasOwnProperty(z)){if(ce.Sb)return;throw new rr(`Cannot register type '${Pe}' twice`)}ds[z]=V,Vr.hasOwnProperty(z)&&(V=Vr[z],delete Vr[z],V.forEach(De=>De()))}(h,E,A)}var Os=(h,E,A)=>{switch(E){case 1:return A?z=>F()[z>>>0]:z=>U()[z>>>0];case 2:return A?z=>se()[z>>>1>>>0]:z=>_e()[z>>>1>>>0];case 4:return A?z=>ie()[z>>>2>>>0]:z=>ve()[z>>>2>>>0];case 8:return A?z=>ee[z>>>3]:z=>Z[z>>>3];default:throw new TypeError(`invalid integer width (${E}): ${h}`)}};function Ds(h,E,A){A>>>=0,kr(h>>>=0,{name:E=$r(E>>>0),fromWireType:z=>z,toWireType:function(z,V){if(typeof V!="bigint"&&typeof V!="number")throw V=V===null?"null":(z=typeof V)=="object"||z==="array"||z==="function"?V.toString():""+V,new TypeError(`Cannot convert "${V}" to ${this.name}`);return typeof V=="number"&&(V=BigInt(V)),V},Cb:Ur,readValueFromPointer:Os(E,A,E.indexOf("u")==-1),Db:null})}var Ur=8;function Wr(h,E,A,z){kr(h>>>=0,{name:E=$r(E>>>0),fromWireType:function(V){return!!V},toWireType:function(V,ce){return ce?A:z},Cb:Ur,readValueFromPointer:function(V){return this.fromWireType(U()[V>>>0])},Db:null})}var ts=[],Dr=[];function Ts(h){9<(h>>>=0)&&--Dr[h+1]==0&&(Dr[h]=void 0,ts.push(h))}var pr=h=>{if(!h)throw new rr("Cannot use deleted val. handle = "+h);return Dr[h]},mr=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let E=ts.pop()||Dr.length;return Dr[E]=h,Dr[E+1]=1,E}};function Jr(h){return this.fromWireType(ve()[h>>>2>>>0])}var Ns={name:"emscripten::val",fromWireType:h=>{var E=pr(h);return Ts(h),E},toWireType:(h,E)=>mr(E),Cb:Ur,readValueFromPointer:Jr,Db:null};function Gr(h){return kr(h>>>0,Ns)}var Re=(h,E)=>{switch(E){case 4:return function(A){return this.fromWireType(ze()[A>>>2>>>0])};case 8:return function(A){return this.fromWireType(Ge()[A>>>3>>>0])};default:throw new TypeError(`invalid float width (${E}): ${h}`)}};function je(h,E,A){A>>>=0,kr(h>>>=0,{name:E=$r(E>>>0),fromWireType:z=>z,toWireType:(z,V)=>V,Cb:Ur,readValueFromPointer:Re(E,A),Db:null})}function et(h,E,A,z,V){if(h>>>=0,A>>>=0,E=$r(E>>>0),V===-1&&(V=4294967295),V=De=>De,z===0){var ce=32-8*A;V=De=>De<>>ce}var Pe=E.includes("unsigned")?function(De,He){return He>>>0}:function(De,He){return He};kr(h,{name:E,fromWireType:V,toWireType:Pe,Cb:Ur,readValueFromPointer:Os(E,A,z!==0),Db:null})}function Xt(h,E,A){function z(ce){var Pe=ve()[ce>>>2>>>0];return ce=ve()[ce+4>>>2>>>0],new V(F().buffer,ce,Pe)}var V=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][E];kr(h>>>=0,{name:A=$r(A>>>0),fromWireType:z,Cb:Ur,readValueFromPointer:z},{Sb:!0})}function Vs(h,E){kr(h>>>=0,{name:E=$r(E>>>0),fromWireType:function(A){for(var z,V=ve()[A>>>2>>>0],ce=A+4,Pe=ce,De=0;De<=V;++De){var He=ce+De;De!=V&&U()[He>>>0]!=0||(Pe=Qt(Pe,He-Pe),z===void 0?z=Pe:(z+="\0",z+=Pe),Pe=He+1)}return rs(A),z},toWireType:function(A,z){z instanceof ArrayBuffer&&(z=new Uint8Array(z));var V=typeof z=="string";if(!(V||z instanceof Uint8Array||z instanceof Uint8ClampedArray||z instanceof Int8Array))throw new rr("Cannot pass non-string to std::string");var ce=V?B(z):z.length,Pe=$n(4+ce+1),De=Pe+4;if(ve()[Pe>>>2>>>0]=ce,V)q(z,De,ce+1);else if(V)for(V=0;V>>0]=He}else for(V=0;V>>0]=z[V];return A!==null&&A.push(rs,Pe),Pe},Cb:Ur,readValueFromPointer:Jr,Db(A){rs(A)}})}var Es=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Us=(h,E)=>{for(var A=h>>1,z=A+E/2;!(A>=z)&&_e()[A>>>0];)++A;if(32<(A<<=1)-h&&Es)return Es.decode(U().slice(h,A));for(A="",z=0;!(z>=E/2);++z){var V=se()[h+2*z>>>1>>>0];if(V==0)break;A+=String.fromCharCode(V)}return A},Ps=(h,E,A)=>{if(A??(A=2147483647),2>A)return 0;var z=E;A=(A-=2)<2*h.length?A/2:h.length;for(var V=0;V>>1>>>0]=ce,E+=2}return se()[E>>>1>>>0]=0,E-z},yn=h=>2*h.length,vn=(h,E)=>{for(var A=0,z="";!(A>=E/4);){var V=ie()[h+4*A>>>2>>>0];if(V==0)break;++A,65536<=V?(V-=65536,z+=String.fromCharCode(55296|V>>10,56320|1023&V)):z+=String.fromCharCode(V)}return z},xn=(h,E,A)=>{if(E>>>=0,A??(A=2147483647),4>A)return 0;var z=E;A=z+A-4;for(var V=0;V=ce&&(ce=65536+((1023&ce)<<10)|1023&h.charCodeAt(++V)),ie()[E>>>2>>>0]=ce,(E+=4)+4>A)break}return ie()[E>>>2>>>0]=0,E-z},pe=h=>{for(var E=0,A=0;A=z&&++A,E+=4}return E};function I(h,E,A){if(h>>>=0,E>>>=0,A=$r(A>>>=0),E===2)var z=Us,V=Ps,ce=yn,Pe=De=>_e()[De>>>1>>>0];else E===4&&(z=vn,V=xn,ce=pe,Pe=De=>ve()[De>>>2>>>0]);kr(h,{name:A,fromWireType:De=>{for(var He,at=ve()[De>>>2>>>0],xt=De+4,Ot=0;Ot<=at;++Ot){var Gt=De+4+Ot*E;Ot!=at&&Pe(Gt)!=0||(xt=z(xt,Gt-xt),He===void 0?He=xt:(He+="\0",He+=xt),xt=Gt+E)}return rs(De),He},toWireType:(De,He)=>{if(typeof He!="string")throw new rr(`Cannot pass non-string to C++ string type ${A}`);var at=ce(He),xt=$n(4+at+E);return ve()[xt>>>2>>>0]=at/E,V(He,xt+4,at+E),De!==null&&De.push(rs,xt),xt},Cb:Ur,readValueFromPointer:Jr,Db(De){rs(De)}})}function N(h,E){kr(h>>>=0,{Tb:!0,name:E=$r(E>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function Y(h){Zn(h>>>0,!l,1,!a,131072,!1),us()}var le=h=>{if(!ue)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(ie(),h>>>2,h).value.then(Te),h+=128,Atomics.store(ie(),h>>>2,1))}var Te=()=>{var h=Sn();h&&(de(h),le(Ko))};function Ne(h,E){(h>>>=0)==E>>>0?setTimeout(Te):c?postMessage({Gb:h,Bb:"checkMailbox"}):(h=Pr[h])&&h.postMessage({Bb:"checkMailbox"})}var qe=[];function We(h,E,A,z,V){for(E>>>=0,z/=2,qe.length=z,A=V>>>0>>>3,V=0;V>>0];return(E?Ae[E]:Yn[h])(...qe)}var tt=()=>{Je=0};function Mt(h){h>>>=0,c?postMessage({Bb:"cleanupThread",hc:h}):jr(Pr[h])}function Bt(h){}var Lt=(h,E)=>{var A=ds[h];if(A===void 0)throw h=No(h),A=$r(h),rs(h),new rr(`${E} has unknown type ${A}`);return A},sr=(h,E,A)=>{var z=[];return h=h.toWireType(z,A),z.length&&(ve()[E>>>2>>>0]=mr(z)),h};function Wt(h,E,A){return E>>>=0,A>>>=0,h=pr(h>>>0),E=Lt(E,"emval::as"),sr(E,A,h)}function _r(h,E){return E>>>=0,h=pr(h>>>0),(E=Lt(E,"emval::as")).toWireType(null,h)}var br=h=>{try{h()}catch(E){Se(E)}},ir=0,fr=null,Lr=0,Yr=[],Zt={},gr={},Kr=0,zr=null,Cs=[];function Ir(h){return function(E){if(!ue){if(ir===0){var A=!1,z=!1;E((V=0)=>{if(!ue&&(Lr=V,A=!0,z)){ir=2,br(()=>Qo(fr)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),V=!1;try{var ce=function(){var He=ie()[fr+8>>>2>>>0];return He=dt[gr[He]],--Je,He()}()}catch(He){ce=He,V=!0}var Pe=!1;if(!fr){var De=zr;De&&(zr=null,(V?De.reject:De.resolve)(ce),Pe=!0)}if(V&&!Pe)throw ce}}),z=!0,A||(ir=1,fr=function(){var V=$n(65548),ce=V+12;ve()[V>>>2>>>0]=ce,ve()[V+4>>>2>>>0]=ce+65536,ce=Yr[0];var Pe=Zt[ce];return Pe===void 0&&(Pe=Kr++,Zt[ce]=Pe,gr[Pe]=ce),ce=Pe,ie()[V+8>>>2>>>0]=ce,V}(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),br(()=>qo(fr)))}else ir===2?(ir=0,br(Xo),rs(fr),fr=null,Cs.forEach(le)):Se(`invalid state: ${ir}`);return Lr}}(E=>{h().then(E)})}function ps(h){return h>>>=0,Ir(async()=>{var E=await pr(h);return mr(E)})}var ur=[];function ar(h,E,A,z){return A>>>=0,z>>>=0,(h=ur[h>>>0])(null,E=pr(E>>>0),A,z)}var hr={},nr=h=>{var E=hr[h];return E===void 0?$r(h):E};function Hr(h,E,A,z,V){return A>>>=0,z>>>=0,V>>>=0,(h=ur[h>>>0])(E=pr(E>>>0),E[A=nr(A)],z,V)}var Ws=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Hn(h){return(h>>>=0)==0?mr(Ws()):(h=nr(h),mr(Ws()[h]))}var en=h=>{var E=ur.length;return ur.push(h),E},Ti=(h,E)=>{for(var A=Array(h),z=0;z>>2>>>0],"parameter "+z);return A},Po=(h,E)=>Object.defineProperty(E,"name",{value:h});function Ei(h,E,A){var z=(E=Ti(h,E>>>0)).shift();h--;var V=`return function (obj, func, destructorsRef, args) { +`,ce=0,Pe=[];A===0&&Pe.push("obj");for(var De=["retType"],He=[z],at=0;atxt.name).join(", ")}) => ${z.name}>`,en(Po(A,h))}function Pi(h){return h=nr(h>>>0),mr(n[h])}function Ci(h,E){return E>>>=0,h=pr(h>>>0),E=pr(E),mr(h[E])}function tn(h){9<(h>>>=0)&&(Dr[h+1]+=1)}function Si(){return mr([])}function $i(h){h=pr(h>>>0);for(var E=Array(h.length),A=0;A>>0))}function Ii(){return mr({})}function Ai(h){for(var E=pr(h>>>=0);E.length;){var A=E.pop();E.pop()(A)}Ts(h)}function rn(h,E,A){E>>>=0,A>>>=0,h=pr(h>>>0),E=pr(E),A=pr(A),h[E]=A}function Fi(h,E){return E>>>=0,h=(h=Lt(h>>>0,"_emval_take_value")).readValueFromPointer(E),mr(h)}function Oi(h,E){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),ie()[E>>>2>>>0]=h.getUTCSeconds(),ie()[E+4>>>2>>>0]=h.getUTCMinutes(),ie()[E+8>>>2>>>0]=h.getUTCHours(),ie()[E+12>>>2>>>0]=h.getUTCDate(),ie()[E+16>>>2>>>0]=h.getUTCMonth(),ie()[E+20>>>2>>>0]=h.getUTCFullYear()-1900,ie()[E+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,ie()[E+28>>>2>>>0]=h}var Co=h=>h%4==0&&(h%100!=0||h%400==0),So=[0,31,60,91,121,152,182,213,244,274,305,335],$o=[0,31,59,90,120,151,181,212,243,273,304,334];function ko(h,E){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),ie()[E>>>2>>>0]=h.getSeconds(),ie()[E+4>>>2>>>0]=h.getMinutes(),ie()[E+8>>>2>>>0]=h.getHours(),ie()[E+12>>>2>>>0]=h.getDate(),ie()[E+16>>>2>>>0]=h.getMonth(),ie()[E+20>>>2>>>0]=h.getFullYear()-1900,ie()[E+24>>>2>>>0]=h.getDay();var A=(Co(h.getFullYear())?So:$o)[h.getMonth()]+h.getDate()-1|0;ie()[E+28>>>2>>>0]=A,ie()[E+36>>>2>>>0]=-60*h.getTimezoneOffset(),A=new Date(h.getFullYear(),6,1).getTimezoneOffset();var z=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(A!=z&&h.getTimezoneOffset()==Math.min(z,A)),ie()[E+32>>>2>>>0]=h}function Di(h){h>>>=0;var E=new Date(ie()[h+20>>>2>>>0]+1900,ie()[h+16>>>2>>>0],ie()[h+12>>>2>>>0],ie()[h+8>>>2>>>0],ie()[h+4>>>2>>>0],ie()[h>>>2>>>0],0),A=ie()[h+32>>>2>>>0],z=E.getTimezoneOffset(),V=new Date(E.getFullYear(),6,1).getTimezoneOffset(),ce=new Date(E.getFullYear(),0,1).getTimezoneOffset(),Pe=Math.min(ce,V);return 0>A?ie()[h+32>>>2>>>0]=+(V!=ce&&Pe==z):0>>2>>>0]=E.getDay(),A=(Co(E.getFullYear())?So:$o)[E.getMonth()]+E.getDate()-1|0,ie()[h+28>>>2>>>0]=A,ie()[h>>>2>>>0]=E.getSeconds(),ie()[h+4>>>2>>>0]=E.getMinutes(),ie()[h+8>>>2>>>0]=E.getHours(),ie()[h+12>>>2>>>0]=E.getDate(),ie()[h+16>>>2>>>0]=E.getMonth(),ie()[h+20>>>2>>>0]=E.getYear(),h=E.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function Io(h,E,A,z,V,ce,Pe){return c?Oe(16,1,h,E,A,z,V,ce,Pe):-52}function qn(h,E,A,z,V,ce){if(c)return Oe(17,1,h,E,A,z,V,ce)}var sn={},Ao=()=>performance.timeOrigin+performance.now();function Fo(h,E){if(c)return Oe(18,1,h,E);if(sn[h]&&(clearTimeout(sn[h].id),delete sn[h]),!E)return 0;var A=setTimeout(()=>{delete sn[h],le(()=>Go(h,performance.timeOrigin+performance.now()))},E);return sn[h]={id:A,qc:E},0}function Oo(h,E,A,z){h>>>=0,E>>>=0,A>>>=0,z>>>=0;var V=new Date().getFullYear(),ce=new Date(V,0,1).getTimezoneOffset();V=new Date(V,6,1).getTimezoneOffset();var Pe=Math.max(ce,V);ve()[h>>>2>>>0]=60*Pe,ie()[E>>>2>>>0]=+(ce!=V),h=(E=De=>{var He=Math.abs(De);return`UTC${0<=De?"-":"+"}${String(Math.floor(He/60)).padStart(2,"0")}${String(He%60).padStart(2,"0")}`})(ce),E=E(V),VDate.now();function Li(h,E,A){return 0<=h&&3>=h?(h===0?h=Date.now():h=performance.timeOrigin+performance.now(),ee[A>>>0>>>3]=BigInt(Math.round(1e6*h)),0):28}var Tn=[],Qn=(h,E)=>{Tn.length=0;for(var A;A=U()[h++>>>0];){var z=A!=105;E+=(z&=A!=112)&&E%8?4:0,Tn.push(A==112?ve()[E>>>2>>>0]:A==106?ee[E>>>3]:A==105?ie()[E>>>2>>>0]:Ge()[E>>>3>>>0]),E+=z?8:4}return Tn};function Xn(h,E,A){return h>>>=0,E=Qn(E>>>0,A>>>0),Ae[h](...E)}function zi(h,E,A){return h>>>=0,E=Qn(E>>>0,A>>>0),Ae[h](...E)}var Bi=()=>{};function Ri(h,E){return y(Qt(h>>>0,E>>>0))}var ji=()=>{throw Je+=1,"unwind"};function Ni(){return 4294901760}var Vi=()=>navigator.hardwareConcurrency;function Ui(){return Se("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Wi(h){h>>>=0;var E=U().length;if(h<=E||4294901760=A;A*=2){var z=E*(1+.2/A);z=Math.min(z,h+100663296);e:{z=(Math.min(4294901760,65536*Math.ceil(Math.max(h,z)/65536))-T.buffer.byteLength+65535)/65536|0;try{T.grow(z),ae();var V=1;break e}catch{}V=void 0}if(V)return!0}return!1}var nn=()=>(Se("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),on={},En=h=>{h.forEach(E=>{nn()})};function Do(){var h=Error().stack.toString().split(` +`);return h[0]=="Error"&&h.shift(),En(h),on.Lb=nn(),on.cc=h,on.Lb}function Gi(h,E,A){if(h>>>=0,E>>>=0,on.Lb==h)var z=on.cc;else(z=Error().stack.toString().split(` +`))[0]=="Error"&&z.shift(),En(z);for(var V=3;z[V]&&nn()!=h;)++V;for(h=0;h>>2>>>0]=nn();return h}var Pn,Ss={},Lo=()=>{if(!Pn){var h,E={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(h in Ss)Ss[h]===void 0?delete E[h]:E[h]=Ss[h];var A=[];for(h in E)A.push(`${h}=${E[h]}`);Pn=A}return Pn};function Ki(h,E){if(c)return Oe(19,1,h,E);h>>>=0,E>>>=0;var A=0;return Lo().forEach((z,V)=>{var ce=E+A;for(V=ve()[h+4*V>>>2>>>0]=ce,ce=0;ce>>0]=z.charCodeAt(ce);F()[V>>>0]=0,A+=z.length+1}),0}function zo(h,E){if(c)return Oe(20,1,h,E);h>>>=0,E>>>=0;var A=Lo();ve()[h>>>2>>>0]=A.length;var z=0;return A.forEach(V=>z+=V.length+1),ve()[E>>>2>>>0]=z,0}function Hi(h){return c?Oe(21,1,h):52}function Bo(h,E,A,z){return c?Oe(22,1,h,E,A,z):52}function Jn(h,E,A,z){return c?Oe(23,1,h,E,A,z):70}var qi=[null,[],[]];function Ro(h,E,A,z){if(c)return Oe(24,1,h,E,A,z);E>>>=0,A>>>=0,z>>>=0;for(var V=0,ce=0;ce>>2>>>0],De=ve()[E+4>>>2>>>0];E+=8;for(var He=0;He>>0],xt=qi[h];at===0||at===10?((h===1?v:y)(Ct(xt)),xt.length=0):xt.push(at)}V+=De}return ve()[z>>>2>>>0]=V,0}c||function(){for(var h=n.numThreads-1;h--;)Cr();Ke.unshift(()=>{ke++,function(E){c?E():Promise.all(St.map(qt)).then(E)}(()=>Me())})}();for(var jo=Array(256),Cn=0;256>Cn;++Cn)jo[Cn]=String.fromCharCode(Cn);Xr=jo,rr=n.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},n.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},Dr.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>Dr.length/2-5-ts.length;var dt,Yn=[Ye,ot,pt,S,Q,re,ge,Fe,rt,ft,ht,vt,st,zt,Ut,Nr,Io,qn,Fo,Ki,zo,Hi,Bo,Jn,Ro];(async function(){function h(z,V){return dt=z.exports,dt=function(){var ce=dt,Pe={};for(let[De,He]of Object.entries(ce))Pe[De]=typeof He=="function"?(...at)=>{Yr.push(De);try{return He(...at)}finally{ue||(Yr.pop(),fr&&ir===1&&Yr.length===0&&(ir=0,Je+=1,br(so),typeof Fibers<"u"&&Fibers.rc()))}}:He;return Pe}(),dt=function(){var ce=dt,Pe=He=>at=>He(at)>>>0,De=He=>()=>He()>>>0;return(ce=Object.assign({},ce)).Da=Pe(ce.Da),ce.fb=De(ce.fb),ce.hb=Pe(ce.hb),ce.tb=Pe(ce.tb),ce.ub=De(ce.ub),ce.__cxa_get_exception_ptr=Pe(ce.__cxa_get_exception_ptr),ce}(),Mr.push(dt.ib),x=V,Me(),dt}ke++;var E=we();if(n.instantiateWasm)return new Promise(z=>{n.instantiateWasm(E,(V,ce)=>{h(V,ce),z(V.exports)})});if(c)return new Promise(z=>{Ie=V=>{var ce=new WebAssembly.Instance(V,we());z(h(ce,V))}});be??(be=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",g):g+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href);try{var A=await async function(z){var V=be;if(!me&&typeof WebAssembly.instantiateStreaming=="function"&&!j(V))try{var ce=fetch(V,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ce,z)}catch(Pe){y(`wasm streaming compile failed: ${Pe}`),y("falling back to ArrayBuffer instantiation")}return async function(Pe,De){try{var He=await async function(at){if(!me)try{var xt=await f(at);return new Uint8Array(xt)}catch{}if(at==be&&me)at=new Uint8Array(me);else{if(!_)throw"both async and sync fetching of the wasm failed";at=_(at)}return at}(Pe);return await WebAssembly.instantiate(He,De)}catch(at){y(`failed to asynchronously prepare wasm: ${at}`),Se(at)}}(V,z)}(E);return h(A.instance,A.module)}catch(z){return o(z),Promise.reject(z)}})();var No=h=>(No=dt.Da)(h),Vo=()=>(Vo=dt.Ea)();n._OrtInit=(h,E)=>(n._OrtInit=dt.Fa)(h,E),n._OrtGetLastError=(h,E)=>(n._OrtGetLastError=dt.Ga)(h,E),n._OrtCreateSessionOptions=(h,E,A,z,V,ce,Pe,De,He,at)=>(n._OrtCreateSessionOptions=dt.Ha)(h,E,A,z,V,ce,Pe,De,He,at),n._OrtAppendExecutionProvider=(h,E,A,z,V)=>(n._OrtAppendExecutionProvider=dt.Ia)(h,E,A,z,V),n._OrtAddFreeDimensionOverride=(h,E,A)=>(n._OrtAddFreeDimensionOverride=dt.Ja)(h,E,A),n._OrtAddSessionConfigEntry=(h,E,A)=>(n._OrtAddSessionConfigEntry=dt.Ka)(h,E,A),n._OrtReleaseSessionOptions=h=>(n._OrtReleaseSessionOptions=dt.La)(h),n._OrtCreateSession=(h,E,A)=>(n._OrtCreateSession=dt.Ma)(h,E,A),n._OrtReleaseSession=h=>(n._OrtReleaseSession=dt.Na)(h),n._OrtGetInputOutputCount=(h,E,A)=>(n._OrtGetInputOutputCount=dt.Oa)(h,E,A),n._OrtGetInputOutputMetadata=(h,E,A,z)=>(n._OrtGetInputOutputMetadata=dt.Pa)(h,E,A,z),n._OrtFree=h=>(n._OrtFree=dt.Qa)(h),n._OrtCreateTensor=(h,E,A,z,V,ce)=>(n._OrtCreateTensor=dt.Ra)(h,E,A,z,V,ce),n._OrtGetTensorData=(h,E,A,z,V)=>(n._OrtGetTensorData=dt.Sa)(h,E,A,z,V),n._OrtReleaseTensor=h=>(n._OrtReleaseTensor=dt.Ta)(h),n._OrtCreateRunOptions=(h,E,A,z)=>(n._OrtCreateRunOptions=dt.Ua)(h,E,A,z),n._OrtAddRunConfigEntry=(h,E,A)=>(n._OrtAddRunConfigEntry=dt.Va)(h,E,A),n._OrtReleaseRunOptions=h=>(n._OrtReleaseRunOptions=dt.Wa)(h),n._OrtCreateBinding=h=>(n._OrtCreateBinding=dt.Xa)(h),n._OrtBindInput=(h,E,A)=>(n._OrtBindInput=dt.Ya)(h,E,A),n._OrtBindOutput=(h,E,A,z)=>(n._OrtBindOutput=dt.Za)(h,E,A,z),n._OrtClearBoundOutputs=h=>(n._OrtClearBoundOutputs=dt._a)(h),n._OrtReleaseBinding=h=>(n._OrtReleaseBinding=dt.$a)(h),n._OrtRunWithBinding=(h,E,A,z,V)=>(n._OrtRunWithBinding=dt.ab)(h,E,A,z,V),n._OrtRun=(h,E,A,z,V,ce,Pe,De)=>(n._OrtRun=dt.bb)(h,E,A,z,V,ce,Pe,De),n._OrtEndProfiling=h=>(n._OrtEndProfiling=dt.cb)(h),n._JsepOutput=(h,E,A)=>(n._JsepOutput=dt.db)(h,E,A),n._JsepGetNodeName=h=>(n._JsepGetNodeName=dt.eb)(h);var Sn=()=>(Sn=dt.fb)(),rs=n._free=h=>(rs=n._free=dt.gb)(h),$n=n._malloc=h=>($n=n._malloc=dt.hb)(h),Zn=(h,E,A,z,V,ce)=>(Zn=dt.kb)(h,E,A,z,V,ce),eo=()=>(eo=dt.lb)(),Uo=(h,E,A,z,V)=>(Uo=dt.mb)(h,E,A,z,V),Wo=h=>(Wo=dt.nb)(h),kn=h=>(kn=dt.ob)(h),Go=(h,E)=>(Go=dt.pb)(h,E),Ko=()=>(Ko=dt.qb)(),to=(h,E)=>(to=dt.rb)(h,E),In=h=>(In=dt.sb)(h),ro=h=>(ro=dt.tb)(h),An=()=>(An=dt.ub)(),Ho=n.dynCall_ii=(h,E)=>(Ho=n.dynCall_ii=dt.vb)(h,E),qo=h=>(qo=dt.wb)(h),so=()=>(so=dt.xb)(),Qo=h=>(Qo=dt.yb)(h),Xo=()=>(Xo=dt.zb)();return n.stackSave=()=>An(),n.stackRestore=h=>In(h),n.stackAlloc=h=>ro(h),n.setValue=function(h,E,A="i8"){switch(A.endsWith("*")&&(A="*"),A){case"i1":case"i8":F()[h>>>0]=E;break;case"i16":se()[h>>>1>>>0]=E;break;case"i32":ie()[h>>>2>>>0]=E;break;case"i64":ee[h>>>3]=BigInt(E);break;case"float":ze()[h>>>2>>>0]=E;break;case"double":Ge()[h>>>3>>>0]=E;break;case"*":ve()[h>>>2>>>0]=E;break;default:Se(`invalid type for setValue: ${A}`)}},n.getValue=function(h,E="i8"){switch(E.endsWith("*")&&(E="*"),E){case"i1":case"i8":return F()[h>>>0];case"i16":return se()[h>>>1>>>0];case"i32":return ie()[h>>>2>>>0];case"i64":return ee[h>>>3];case"float":return ze()[h>>>2>>>0];case"double":return Ge()[h>>>3>>>0];case"*":return ve()[h>>>2>>>0];default:Se(`invalid type for getValue: ${E}`)}},n.UTF8ToString=Qt,n.stringToUTF8=q,n.lengthBytesUTF8=B,function h(){if(0{Ca(),Aa=typeof location>"u"?void 0:location.origin,Fa=self.location.href>"file:"&&self.location.href<"file;",cd=()=>{{if(Fa){let e=URL;return new URL(new e("ort.bundle.min.mjs",self.location.href).href,Aa).href}return self.location.href}},ns=cd(),ud=()=>{if(ns&&!ns.startsWith("blob:"))return ns.substring(0,ns.lastIndexOf("/")+1)},ri=(e,r)=>{try{let t=r??ns;return(t?new URL(e,t):new URL(e)).origin===Aa}catch{return!1}},dd=(e,r)=>{let t=r??ns;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},pd=(e,r)=>`${r??"./"}${e}`,Oa=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},hd=async e=>(await import(e)).default,Da=(Xv(),lo(nd)).default,md=async()=>{if(!ns)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ri(ns))return[void 0,Da()];let e=await Oa(ns);return[e,Da(e)]},La=(Jv(),lo(id)).default,_d=async(e,r,t)=>{if(!e&&!r&&La&&ns&&ri(ns))return[void 0,La];{let s="ort-wasm-simd-threaded.jsep.mjs",o=e??dd(s,r),n=t&&o&&!ri(o,r),i=n?await Oa(o):o??pd(s,r);return[n?i:void 0,await hd(i)]}}}),Ba,si,ho,Ra,fd,gd,wd,ja,Jt,dn=Ve(()=>{za(),si=!1,ho=!1,Ra=!1,fd=()=>{if(typeof SharedArrayBuffer>"u")return!1;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}},gd=()=>{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}},wd=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},ja=async e=>{if(si)return Promise.resolve();if(ho)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ra)throw new Error("previous call to 'initializeWebAssembly()' failed.");ho=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!wd())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!gd())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=fd();t>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=t=1);let o=e.wasmPaths,n=typeof o=="string"?o:void 0,i=o==null?void 0:o.mjs,a=(i==null?void 0:i.href)??i,l=o==null?void 0:o.wasm,c=(l==null?void 0:l.href)??l,p=e.wasmBinary,[d,u]=await _d(a,n,t>1),f=!1,_=[];if(r>0&&_.push(new Promise(b=>{setTimeout(()=>{f=!0,b()},r)})),_.push(new Promise((b,k)=>{let g={numThreads:t};if(p)g.wasmBinary=p;else if(c||n)g.locateFile=M=>c??n+M;else if(a&&a.indexOf("blob:")!==0)g.locateFile=M=>new URL(M,a).href;else if(d){let M=ud();M&&(g.locateFile=$=>M+$)}u(g).then(M=>{ho=!1,si=!0,Ba=M,b(),d&&URL.revokeObjectURL(d)},M=>{ho=!1,Ra=!0,k(M)})})),await Promise.race(_),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},Jt=()=>{if(si&&Ba)return Ba;throw new Error("WebAssembly is not initialized yet.")}}),ws,ni,Kt,Na=Ve(()=>{dn(),ws=(e,r)=>{let t=Jt(),s=t.lengthBytesUTF8(e)+1,o=t._malloc(s);return t.stringToUTF8(e,o,s),r.push(o),o},ni=(e,r,t,s)=>{if(typeof e=="object"&&e!==null){if(t.has(e))throw new Error("Circular reference in options");t.add(e)}Object.entries(e).forEach(([o,n])=>{let i=r?r+o:o;if(typeof n=="object")ni(n,i+".",t,s);else if(typeof n=="string"||typeof n=="number")s(i,n.toString());else if(typeof n=="boolean")s(i,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},Kt=e=>{let r=Jt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetLastError(o,o+s);let n=Number(r.getValue(o,s===4?"i32":"i64")),i=r.getValue(o+s,"*"),a=i?r.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),Md,Yv=Ve(()=>{dn(),Na(),Md=e=>{let r=Jt(),t=0,s=[],o=e||{};try{if((e==null?void 0: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==null?void 0: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==null?void 0:e.terminate)===void 0&&(o.terminate=!1);let n=0;return(e==null?void 0:e.tag)!==void 0&&(n=ws(e.tag,s)),t=r._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,n),t===0&&Kt("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&ni(e.extra,"",new WeakSet,(i,a)=>{let l=ws(i,s),c=ws(a,s);r._OrtAddRunConfigEntry(t,l,c)!==0&&Kt(`Can't set a run config entry: ${i} - ${a}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(i=>r._free(i)),n}}}),bd,yd,vd,mo,xd,Td,Zv=Ve(()=>{dn(),Na(),bd=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}`)}},yd=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},vd=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)},mo=(e,r,t,s)=>{let o=ws(r,s),n=ws(t,s);Jt()._OrtAddSessionConfigEntry(e,o,n)!==0&&Kt(`Can't set a session config entry: ${r} - ${t}.`)},xd=async(e,r,t)=>{for(let s of r){let o=typeof s=="string"?s:s.name,n=[];switch(o){case"webnn":if(o="WEBNN",typeof s!="string"){let p=s==null?void 0:s.deviceType;p&&mo(e,"deviceType",p,t)}break;case"webgpu":if(o="JS",typeof s!="string"){let p=s;if(p!=null&&p.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);mo(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=ws(o,t),a=n.length,l=0,c=0;if(a>0){l=Jt()._malloc(a*Jt().PTR_SIZE),t.push(l),c=Jt()._malloc(a*Jt().PTR_SIZE),t.push(c);for(let p=0;p{let r=Jt(),t=0,s=[],o=e||{};vd(o);try{let n=bd(o.graphOptimizationLevel??"all"),i=yd(o.executionMode??"sequential"),a=typeof o.logId=="string"?ws(o.logId,s):0,l=o.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let c=o.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof o.optimizedModelFilePath=="string"?ws(o.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,a,l,c,p),t===0&&Kt("Can't create session options."),o.executionProviders&&await xd(t,o.executionProviders,s),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);mo(t,"enableGraphCapture",o.enableGraphCapture.toString(),s)}if(o.freeDimensionOverrides)for(let[d,u]of Object.entries(o.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof u!="number"||!Number.isInteger(u)||u<0)throw new Error(`free dimension override value must be a non-negative integer: ${u}`);let f=ws(d,s);r._OrtAddFreeDimensionOverride(t,f,u)!==0&&Kt(`Can't set a free dimension override: ${d} - ${u}.`)}return o.extra!==void 0&&ni(o.extra,"",new WeakSet,(d,u)=>{mo(t,d,u,s)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&Kt("Can't release session options."),s.forEach(i=>r._free(i)),n}}}),Vn,zs,pn,Va,oi,Ua,Wa,Ga,gt=Ve(()=>{Vn=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;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},zs=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";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},pn=(e,r)=>{let t=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof r=="number"?r:r.reduce((o,n)=>o*n,1);return t>0?Math.ceil(s*t):void 0},Va=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}`)}},oi=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}`)}},Ua=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Wa=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ga=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;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),Ka,Ed=Ve(()=>{Ca(),Ka=async e=>{if(typeof e=="string"){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"),s=t?parseInt(t,10):0;if(s<1073741824)return new Uint8Array(await r.arrayBuffer());{if(!r.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=r.body.getReader(),n;try{n=new ArrayBuffer(s)}catch(a){if(a instanceof RangeError){let l=Math.ceil(s/65536);n=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw a}let i=0;for(;;){let{done:a,value:l}=await o.read();if(a)break;let c=l.byteLength;new Uint8Array(n,i,c).set(l),i+=c}return new Uint8Array(n,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Pd,Cd,Sd,$d,Ha,kd,Dt,Bs=Ve(()=>{gt(),Pd=["V","I","W","E","F"],Cd=(e,r)=>{console.log(`[${Pd[e]},${new Date().toISOString()}]${r}`)},Ha=(e,r)=>{Sd=e,$d=r},kd=(e,r)=>{let t=oi(e),s=oi(Sd);t>=s&&Cd(t,typeof r=="function"?r():r)},Dt=(...e)=>{$d&&kd(...e)}}),Id,Un,ye,ii,Ad,Fd,Od,Et=Ve(()=>{Id=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},Un=class{static calcShape(e,r,t=!1){let s=e.length,o=r.length;if(s===0)return r;if(o===0)return e;let n=Math.max(e.length,r.length),i=new Array(n);if(t){if(s<2||o<2)return;let a=Id.calcMatMulShape([e[s-2],e[s-1]],[r[o-2],r[o-1]]);if(a===void 0)return;[i[n-2],i[n-1]]=a}for(let a=t?3:1;a<=n;a++){let l=s-a<0?1:e[s-a],c=o-a<0?1:r[o-a];if(l!==c&&l>1&&c>1)return;let p=Math.max(l,c);if(l&&c)i[n-a]=Math.max(l,c);else{if(p>1)return;i[n-a]=0}}return i}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let o=1;o<=t;o++)if(e[t-o]!==1&&e[t-o]!==r[s-o])return!1;return!0}},ye=class ga{static size(r){return ga.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let o=new Array(s),n=s-1;for(;n>=0;){if(r[n]%t===0){o[n]=r[n]/t;break}if(t%r[n]!==0)throw new Error("cannot convert shape");o[n]=1,t/=r[n],n--}for(n--;n>=0;n--)o[n]=r[n];return o}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 ga.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 ga.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let o=1;for(let n=t;n=0;--o)s[o]=s[o+1]*r[o+1];return s}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(s=>this.normalizeAxis(s,t??r.length))}static sortBasedOnPerm(r,t){return t?t.map(s=>r[s]):r.slice().reverse()}static padShape(r,t){let s=r.length;return r.map((o,n)=>o+t[n]+t[n+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,o)=>s===t[o])}},ii=class Zo{static adjustPoolAttributes(r,t,s,o,n,i){if(!r&&s.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 a=0;a=s.length?s.push(t[a+2]):s[a]=t[a+2];for(let a=0;a=s[a]||i[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,o,n,i,a){if(a){if(n.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(o.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{gt(),qa=(e,r)=>new(Va(r))(e)}),Qa,Xa,Ld,Ja,zd,Ya,Za,el,Bd,Rd,ex=Ve(()=>{Bs(),Qa=(e,r=!0)=>{if(e.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let t=e.byteLength/8,s=new BigInt64Array(e.buffer,e.byteOffset,t),o=new Int32Array(t);for(let n=0;n2147483647n||i<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${n}: ${i}`);o[n]=Number(i)}return r?new Uint8Array(o.buffer):o},Xa=(e,r=!0)=>{if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let t=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,t),o=BigInt64Array.from(s,BigInt);return r?new Uint8Array(o.buffer):o},Ld=1,Ja=()=>Ld++,zd=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Ya=(e,r)=>{let t=zd.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,o)=>s*o)*t/8):0},Za=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:r,context:t,tensor:s,dataType:o,shape:n,shouldConvertInt64toInt32:i=!1}=e;this.sessionId=r,this.mlContext=t,this.mlTensor=s,this.dataType=o,this.tensorShape=n,this.shouldConvertInt64toInt32=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Ya(this.dataType,this.tensorShape)}destroy(){Dt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e,r){if(e){let t=await this.mlContext.readTensor(this.mlTensor),s=Xa(new Uint8Array(t));if(r){(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).set(s);return}else return s.buffer}else return r?this.mlContext.readTensor(this.mlTensor,r):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,r,t){return this.mlContext===e&&this.dataType===r&&this.tensorShape.length===t.length&&this.tensorShape.every((s,o)=>s===t[o])}setIsInt64ToInt32Converted(e){this.isInt64ToInt32Converted=e}},el=class{constructor(e,r){this.tensorManager=e,this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,r,t,s){let o=r,n=this.tensorManager.getMLContext(e),i=o==="int64"&&!n.opSupportLimits().input.dataTypes.includes("int64");if(i&&(o="int32",Dt("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(n,o,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Ya(o,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let a=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,o,t,a,!0,!0,i),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let r=e;if(this.wrapper)if(this.wrapper.shouldConvertInt64toInt32&&(r=Qa(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else Dt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(r):this.activeUpload=new Uint8Array(r)}async download(e){var r,t,s;if(this.activeUpload){let o=(r=this.wrapper)!=null&&r.isInt64ToInt32Converted?Xa(this.activeUpload):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(o):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o);return}else return o.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read((t=this.wrapper)==null?void 0:t.shouldConvertInt64toInt32,e):this.wrapper.read((s=this.wrapper)==null?void 0:s.shouldConvertInt64toInt32)}},Bd=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let r=this.backend.getMLContext(e);if(!r)throw new Error("MLContext not found for session.");return r}reserveTensorId(){let e=Ja();return this.tensorTrackersById.set(e,new el(this)),e}releaseTensorId(e){let r=this.tensorTrackersById.get(e);r&&(this.tensorTrackersById.delete(e),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(e,r,t,s,o){Dt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${o}}`);let n=this.tensorTrackersById.get(r);if(!n)throw new Error("Tensor not found.");return n.ensureTensor(e,t,s,o)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){Dt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${r==null?void 0:r.byteLength}}`);let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");return t.download(r)}releaseTensorsForSession(e){for(let r of this.freeTensors)r.sessionId===e&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==e)}registerTensor(e,r,t,s){let o=this.getMLContext(e),n=Ja(),i=new Za({sessionId:e,context:o,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(n,new el(this,i)),this.externalTensors.add(i),n}async getCachedTensor(e,r,t,s,o,n,i=!1){let a=this.getMLContext(e);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(a,r,t)){Dt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let d=this.freeTensors.splice(c,1)[0];return d.sessionId=e,d}Dt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let l=await a.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:o,readable:n});return new Za({sessionId:e,context:a,tensor:l,dataType:r,shape:t,shouldConvertInt64toInt32:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Rd=(...e)=>new Bd(...e)}),ai,jd,Nd,tx=Ve(()=>{gt(),dn(),Dd(),ex(),Bs(),ai=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),jd=(e,r)=>{if(e===r)return!0;if(e===void 0||r===void 0)return!1;let t=Object.keys(e).sort(),s=Object.keys(r).sort();return t.length===s.length&&t.every((o,n)=>o===s[n]&&e[o]===r[o])},Nd=class{constructor(e){this.tensorManager=Rd(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Ha(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Dt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Dt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)Dt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(s=>s.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===void 0){let t=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let r=this.mlContextCache.findIndex(t=>jd(t.options,e));if(r!==-1)return this.mlContextCache[r].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,r){this.mlContextBySessionId.set(e,r);let t=this.sessionIdsByMLContext.get(r);t||(t=new Set,this.sessionIdsByMLContext.set(r,t)),t.add(e),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e);let r=this.mlContextBySessionId.get(e);if(!r)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let t=this.sessionIdsByMLContext.get(r);if(t.delete(e),t.size===0){this.sessionIdsByMLContext.delete(r);let s=this.mlContextCache.findIndex(o=>o.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Dt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,o){let n=ai.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,n,s,o)}async createTemporaryTensor(e,r,t){Dt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=ai.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,s,t,!1);let n=this.temporarySessionTensorIds.get(e);return n?n.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,r){if(!Jt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Dt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${r.byteLength}}`),this.tensorManager.upload(e,r)}async downloadTensor(e,r){return this.tensorManager.download(e,r)}createMLTensorDownloader(e,r){return async()=>{let t=await this.tensorManager.download(e);return qa(t,r)}}registerMLTensor(e,r,t,s){let o=ai.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(e,r,o,s);return Dt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${o}, dimensions: ${s}} -> {tensorId: ${n}}`),n}registerMLConstant(e,r,t,s,o,n,i=!1){if(!n)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let l=n.get(a);if(!l)throw new Error(`File with name ${a} not found in preloaded files.`);if(r+t>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(r,r+t).buffer,p;switch(o.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":i?(p=Qa(new Uint8Array(c),!1),o.dataType="int32"):p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return Dt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(o,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}isInt64Supported(e){var r;return!!((r=this.mlContextBySessionId.get(e))!=null&&r.opSupportLimits().input.dataTypes.includes("int64"))}flush(){}}}),tl=Ve(()=>{}),rl,li,ci,Vd,Ud,sl,nl,Wd,Gd,rx=Ve(()=>{Bs(),tl(),rl=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]]),li=[],ci=e=>Math.ceil(Number(e)/16)*16,Vd=e=>{for(let r=0;rUd++,nl=async(e,r,t,s)=>{let o=ci(t),n=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(r,0,n,0,o),e.flush(),await n.mapAsync(GPUMapMode.READ);let a=n.getMappedRange();if(s){let l=s();return l.set(new Uint8Array(a,0,t)),l}else return new Uint8Array(a.slice(0,t))}finally{n.destroy()}},Wd=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of rl)li.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,o=r.byteLength,n=ci(o),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${o}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:n,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=a.getMappedRange();new Uint8Array(l).set(new Uint8Array(t,s,o)),a.unmap();let c=this.backend.device.createCommandEncoder();c.copyBufferToBuffer(a,0,i.gpuData.buffer,0,n),this.backend.device.queue.submit([c.finish()]),a.destroy(),Dt("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,r){let t=this.storageCache.get(e);if(!t)throw new Error("source gpu data for memcpy does not exist");let s=this.storageCache.get(r);if(!s)throw new Error("destination gpu data for memcpy does not exist");if(t.originalSize!==s.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=ci(t.originalSize),n=this.backend.getCommandEncoder();this.backend.endComputePass(),n.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,o)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return Dt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => 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. + Please use the previous external buffer!`)}else s=sl();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),Dt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Dt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=Vd(e),s,o=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,n=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||n){let a=(o?this.freeBuffers:this.freeUniformBuffers).get(t);a?a.length>0?s=a.pop():s=this.backend.device.createBuffer({size:t,usage:r}):s=this.backend.device.createBuffer({size:t,usage:r})}else s=this.backend.device.createBuffer({size:t,usage:r});let i={id:sl(),type:0,buffer:s};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),Dt("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){var r;return(r=this.storageCache.get(e))==null?void 0:r.gpuData}release(e){let r=typeof e=="bigint"?Number(e):e,t=this.storageCache.get(r);if(!t){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return Dt("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,r){let t=this.storageCache.get(Number(e));if(!t)throw new Error("data does not exist");await nl(this.backend,t.gpuData.buffer,t.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let r=rl.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let t=this.freeBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let t=this.freeUniformBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let r of this.buffersPending)e.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let r=this.capturedPendingBuffers.get(e);r&&(r.forEach(t=>{t.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(Dt("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Gd=(...e)=>new Wd(...e)}),Kd,Nt,cr=Ve(()=>{Kd=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},Nt=e=>new Kd(e)}),Wn,ui,Er,Rr,ct,or,ol,Gn,Ks,lt,_o,$e,it,Hd,il,qd,Qd,Pt=Ve(()=>{gt(),Et(),Wn=64,ui=(e,r)=>{if(r===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(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"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},Er=(e,r=1)=>{let t=ui(e,r);return typeof t=="string"?t:t[0]},Rr=(e,r=1)=>{let t=ui(e,r);return typeof t=="string"?t:t[1]},ct=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:ye.computeStrides(t)})}),r},or=e=>e%4===0?4:e%2===0?2:1,ol=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,Gn=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,Ks=(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,lt=(e,r,t,s)=>e.startsWith("uniforms.")&&t>4?typeof r=="string"?s==="f16"?`${e}[(${r}) / 8][(${r}) % 8 / 4][(${r}) % 8 % 4]`:`${e}[(${r}) / 4][(${r}) % 4]`:s==="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,_o=(e,r,t,s,o)=>{let n=typeof t=="number",i=n?t:t.length,a=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`array`,c=ui(r,o),p=typeof c=="string"?c:c[1],d=typeof c=="string"?c:c[0],u={indices:l,value:p,storage:d,tensor:r},f=j=>typeof j=="string"?j:`${j}u`,_={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},b=n?"uniforms.":"",k=`${b}${e}_shape`,g=`${b}${e}_strides`,M="";for(let j=0;j ${u.indices} { + var indices: ${u.indices}; + var current = offset; + ${M} + return indices; + }`,v=j=>(_.offsetToIndices=!0,i<2?j:`o2i_${e}(${j})`),y=[];if(i>=2)for(let j=i-1;j>=0;j--)y.push(`${lt(g,j,i)} * (indices[${j}])`);let T=i<2?"":` + fn i2o_${e}(indices: ${u.indices}) -> u32 { + return ${y.join("+")}; + }`,x=j=>(_.indicesToOffset=!0,i<2?j:`i2o_${e}(${j})`),P=(...j)=>i===0?"0u":`${u.indices}(${j.map(f).join(",")})`,O=(j,F)=>i<2?`${j}`:`${lt(j,F,i)}`,L=(j,F,U)=>i<2?`${j}=${U};`:`${lt(j,F,i)}=${U};`,G={},K=(j,F)=>{_.broadcastedIndicesToOffset=!0;let U=`${F.name}broadcastedIndicesTo${e}Offset`;if(U in G)return`${U}(${j})`;let se=[];for(let _e=i-1;_e>=0;_e--){let ie=F.indicesGet("outputIndices",_e+F.rank-i);se.push(`${O(g,_e)} * (${ie} % ${O(k,_e)})`)}return G[U]=`fn ${U}(outputIndices: ${F.type.indices}) -> u32 { + return ${se.length>0?se.join("+"):"0u"}; + }`,`${U}(${j})`},R=(j,F)=>(()=>{if(u.storage===u.value)return`${e}[${j}]=${F};`;if(u.storage==="vec2"&&u.value==="i32")return`${e}[${j}]=vec2(u32(${F}), select(0u, 0xFFFFFFFFu, ${F} < 0));`;if(u.storage==="vec2"&&u.value==="u32")return`${e}[${j}]=vec2(u32(${F}), 0u);`;if(u.storage==="u32"&&u.value==="vec4")return`${e}[${j}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${F}));`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),te=j=>(()=>{if(u.storage===u.value)return`${e}[${j}]`;if(u.storage==="vec2"&&u.value==="i32")return`i32(${e}[${j}].x)`;if(u.storage==="vec2"&&u.value==="u32")return`u32(${e}[${j}].x)`;if(u.storage==="u32"&&u.value==="vec4")return`vec4(bool(${e}[${j}] & 0xFFu), bool(${e}[${j}] & 0xFF00u), bool(${e}[${j}] & 0xFF0000u), bool(${e}[${j}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),H=i<2?"":` + fn get_${e}ByIndices(indices: ${u.indices}) -> ${p} { + return ${te(`i2o_${e}(indices)`)}; + }`,ee=i<2?"":(()=>{let j=a.map(U=>`d${U}: u32`).join(", "),F=a.map(U=>`d${U}`).join(", ");return` + fn get_${e}(${j}) -> ${p} { + return get_${e}ByIndices(${P(F)}); + }`})(),Z=(...j)=>{if(j.length!==i)throw new Error(`indices length must be ${i}`);let F=j.map(f).join(",");return i===0?te("0u"):i===1?te(F[0]):(_.get=!0,_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}(${F})`)},ne=j=>i<2?te(j):(_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}ByIndices(${j})`),me=i<2?"":` + fn set_${e}ByIndices(indices: ${u.indices}, value: ${p}) { + ${R(`i2o_${e}(indices)`,"value")} + }`,ue=i<2?"":(()=>{let j=a.map(U=>`d${U}: u32`).join(", "),F=a.map(U=>`d${U}`).join(", ");return` + fn set_${e}(${j}, value: ${p}) { + set_${e}ByIndices(${P(F)}, value); + }`})();return{impl:()=>{let j=[],F=!1;return _.offsetToIndices&&(j.push($),F=!0),_.indicesToOffset&&(j.push(T),F=!0),_.broadcastedIndicesToOffset&&(Object.values(G).forEach(U=>j.push(U)),F=!0),_.set&&(j.push(ue),F=!0),_.setByIndices&&(j.push(me),F=!0),_.get&&(j.push(ee),F=!0),_.getByIndices&&(j.push(H),F=!0),!n&&F&&j.unshift(`const ${k} = ${u.indices}(${t.join(",")});`,`const ${g} = ${u.indices}(${ye.computeStrides(t).join(",")});`),j.join(` +`)},type:u,offsetToIndices:v,indicesToOffset:x,broadcastedIndicesToOffset:K,indices:P,indicesGet:O,indicesSet:L,set:(...j)=>{if(j.length!==i+1)throw new Error(`indices length must be ${i}`);let F=j[i];if(typeof F!="string")throw new Error("value must be string");let U=j.slice(0,i).map(f).join(",");return i===0?R("0u",F):i===1?R(U[0],F):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}(${U}, ${F})`)},setByOffset:R,setByIndices:(j,F)=>i<2?R(j,F):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}ByIndices(${j}, ${F});`),get:Z,getByOffset:te,getByIndices:ne,usage:s,name:e,strides:g,shape:k,rank:i}},$e=(e,r,t,s=1)=>_o(e,r,t,"input",s),it=(e,r,t,s=1)=>_o(e,r,t,"output",s),Hd=(e,r,t)=>_o(e,r,t,"atomicOutput",1),il=(e,r,t,s=1)=>_o(e,r,t,"internal",s),qd=class{constructor(e,r){this.normalizedDispatchGroup=e,this.limits=r,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=Wn){let r=typeof e=="number"?e:e[0],t=typeof e=="number"?1:e[1],s=typeof e=="number"?1:e[2];if(r>this.limits.maxComputeWorkgroupSizeX||t>this.limits.maxComputeWorkgroupSizeY||s>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*t*s>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,n=o?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,i=o?`let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${r*t*s}u + local_idx;`;return`@compute @workgroup_size(${r}, ${t}, ${s}) + fn main(${n}) { + ${i} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,r){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let t=e.usage==="input"?"read":"read_write",s=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${r}) var ${e.name}: array<${s}>;`}declareVariables(...e){return e.map(r=>this.declareVariable(r,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(e,r,t=1){return this.uniforms.push({name:e,type:r,length:t}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:r,type:t,length:s}of this.uniforms)if(s&&s>4)t==="f16"?e.push(`@align(16) ${r}:array, ${Math.ceil(s/8)}>`):e.push(`${r}:array, ${Math.ceil(s/4)}>`);else{let o=s==null||s===1?t:`vec${s}<${t}>`;e.push(`${r}:${o}`)}return` + struct Uniforms { ${e.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` +`)+this.internalVariables.map(e=>e.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[e(r.type),r.length??1])}},Qd=(e,r)=>new qd(e,r)}),Xd,al,Jd,Yd,Zd,ep,os,tp,rp,Hs=Ve(()=>{gt(),Et(),cr(),Pt(),Xd=(e,r)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(r.length!==0&&r.length!==e[0].dims.length)throw new Error(`perm size ${r.length} does not match input rank ${e[0].dims.length}`)},al=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),Jd=(e,r)=>ye.sortBasedOnPerm(e,al(e.length,r)),Yd=(e,r,t,s)=>{let o=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`;for(let n=0;n{let t=[],s=[];for(let o=0;o{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,o=al(s,r),n=Jd(e.dims,o),i=e.dims,a=n,l=s<2||ep(o,e.dims),c;if(l)return c=_=>{let b=$e("input",t,i,4),k=it("output",t,a,4);return` + ${_.registerUniform("output_size","u32").declareVariables(b,k)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let _=ye.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64/4)},programUniforms:[{type:12,data:Math.ceil(_/4)}]}},getShaderSource:c};let{newShape:p,newPerm:d}=Zd(e.dims,o),u=ye.areEqual(d,[2,3,1]),f=ye.areEqual(d,[3,1,2]);if(p.length===2||u||f){i=u?[p[0],p[1]*p[2]]:f?[p[0]*p[1],p[2]]:p,a=[i[1],i[0]];let _=16;return c=b=>{let k=$e("a",t,i.length),g=it("output",t,a.length);return` + ${b.registerUniform("output_size","u32").declareVariables(k,g)} + var tile : array, ${_}>; + ${b.mainStart([_,_,1])} + let stride = (uniforms.output_shape[1] - 1) / ${_} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${_}u + local_id.x; + let input_row = workgroup_id_x * ${_}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${k.getByIndices(`${k.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${_}u + local_id.x; + let output_row = workgroup_id_y * ${_}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${g.setByIndices(`${g.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let b=ye.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/_),y:Math.ceil(a[0]/_)},programUniforms:[{type:12,data:b},...ct(i,a)]}},getShaderSource:c}}return c=_=>{let b=$e("a",t,i.length),k=it("output",t,a.length);return` + ${_.registerUniform("output_size","u32").declareVariables(b,k)} + + ${Yd(o,s,b,k)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${k.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${k.setByOffset("global_idx",b.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let _=ye.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ct(i,a)]}},getShaderSource:c}},tp=(e,r)=>{Xd(e.inputs,r.perm),e.compute(os(e.inputs[0],r.perm))},rp=e=>Nt({perm:e.perm})}),sp,np,op,ip,ap,lp,cp,up,dp,pp,Ms,hp,mp,_p,fp,gp,wp,Mp,bp,yp,vp,sx=Ve(()=>{gt(),Et(),Pt(),cl(),Hs(),sp={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"},np={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"},op={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},ip={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},ap=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,o]},cp=(e,r)=>{let t=e.length+r.length,s=[],o=0;for(let n=0;n{for(let t=0;t{let t=[];if(!up(e,r)){for(let s=0;st.push(s))}return t},pp=(e,r,t,s,o,n,i)=>{let a=t[0].dims,l=ye.size(n),c=ye.size(i),p=$e("_A",t[0].dataType,a),d=it("output",o,n),u=64;l===1&&(u=256);let f=` + var aBestValues : array; + `,_=b=>` + ${b.registerUniform("reduceSize","u32").declareVariables(p,d)} + ${f} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${b.mainStart(u)} + + let outputIndex = global_idx / ${u}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${op[s]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${u}) { + let candidate = f32(${p.getByOffset("offset + k")}); + bestValue = ${sp[s]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${u}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 = ${np[s]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${d.setByOffset("outputIndex",`${s==="mean"?`${d.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${d.type.storage}(${ip[s]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${r};${u}`,inputDependencies:["type"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:l},programUniforms:[{type:12,data:c}]})}},Ms=(e,r,t,s)=>{let o=e.inputs.length===1?t:ll(e.inputs,t),n=o.axes;n.length===0&&!o.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((f,_)=>_));let i=ye.normalizeAxes(n,e.inputs[0].dims.length),a=i,l=e.inputs[0],c=dp(a,e.inputs[0].dims.length);c.length>0&&(l=e.compute(os(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],a=ap(a.length,l.dims.length));let[p,d]=lp(l.dims,a),u=p;o.keepDims&&(u=cp(p,i)),e.compute(pp(r,o.cacheKey,[l],s,e.inputs[0].dataType,u,d),{inputs:[l]})},hp=(e,r)=>{Ms(e,"ReduceMeanShared",r,"mean")},mp=(e,r)=>{Ms(e,"ReduceL1Shared",r,"l1")},_p=(e,r)=>{Ms(e,"ReduceL2Shared",r,"l2")},fp=(e,r)=>{Ms(e,"ReduceLogSumExpShared",r,"logSumExp")},gp=(e,r)=>{Ms(e,"ReduceMaxShared",r,"max")},wp=(e,r)=>{Ms(e,"ReduceMinShared",r,"min")},Mp=(e,r)=>{Ms(e,"ReduceProdShared",r,"prod")},bp=(e,r)=>{Ms(e,"ReduceSumShared",r,"sum")},yp=(e,r)=>{Ms(e,"ReduceSumSquareShared",r,"sumSquare")},vp=(e,r)=>{Ms(e,"ReduceLogSumShared",r,"logSum")}}),bs,xp,di,ll,ys,Tp,Ep,Pp,Cp,Sp,$p,kp,Ip,Ap,Fp,vs,Op,Dp,Lp,zp,Bp,Rp,jp,Np,Vp,Up,cl=Ve(()=>{gt(),Et(),cr(),Pt(),sx(),bs=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.")},xp=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],di=(e,r,t,s,o,n,i=!1,a=!1)=>{let l=[],c=t[0].dims,p=c.length,d=ye.normalizeAxes(o,p),u=!a&&d.length===0;c.forEach((b,k)=>{u||d.indexOf(k)>=0?i&&l.push(1):l.push(b)});let f=l.length,_=ye.size(l);return{name:e,shaderCache:r,getShaderSource:b=>{let k=[],g=$e("_A",t[0].dataType,p),M=it("output",n,f),$=s(g,M,d),v=$[2];for(let y=0,T=0;y=0?(i&&T++,v=`for(var j${y}: u32 = 0; j${y} < ${c[y]}; j${y}++) { + ${$[2].includes("last_index")?`let last_index = j${y};`:""} + ${g.indicesSet("input_indices",y,`j${y}`)} + ${v} + }`):(k.push(`${g.indicesSet("input_indices",y,M.indicesGet("output_indices",T))};`),T++);return` + + ${b.registerUniform("output_size","u32").declareVariables(g,M)} + + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${g.type.indices}; + let output_indices = ${M.offsetToIndices("global_idx")}; + + ${k.join(` +`)} + ${$[0]} // init ops for reduce max/min + ${$[1]} + ${v} + ${$[3]} + ${$.length===4?M.setByOffset("global_idx","value"):$.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:l,dataType:n}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ct(c,l)]})}},ll=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),Nt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},ys=(e,r,t,s)=>{let o=e.inputs,n=o.length===1?t:ll(o,t);e.compute(di(r,{hint:n.cacheKey,inputDependencies:["rank"]},[o[0]],n.noopWithEmptyAxes&&n.axes.length===0?xp:s,n.axes,o[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},Tp=(e,r)=>{bs(e.inputs),ys(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},Ep=(e,r)=>{bs(e.inputs),ys(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},Pp=(e,r)=>{bs(e.inputs),ys(e,"ReduceL2",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Cp=(e,r)=>{bs(e.inputs),ys(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},Sp=(e,r)=>{bs(e.inputs),ys(e,"ReduceMax",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(t.indicesSet("input_indices",i,0));return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},$p=(e,r)=>{bs(e.inputs),ys(e,"ReduceMean",r,(t,s,o)=>{let n=1;for(let i=0;i=0||o.length===0)&&(n*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${n});`]})},kp=(e,r)=>{bs(e.inputs),ys(e,"ReduceMin",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(`input_indices[${i}] = 0;`);return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},Ip=(e,r)=>{bs(e.inputs),ys(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},Ap=(e,r)=>{bs(e.inputs),ys(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},Fp=(e,r)=>{bs(e.inputs),ys(e,"ReduceSumSquare",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},vs=(e,r,t)=>{if(r.length===0)return t;let s=1,o=1;for(let n=0;n1024},Op=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?$p(e,r):hp(e,r)},Dp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Ep(e,r):mp(e,r)},Lp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Pp(e,r):_p(e,r)},zp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Cp(e,r):fp(e,r)},Bp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Sp(e,r):gp(e,r)},Rp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?kp(e,r):wp(e,r)},jp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Ip(e,r):Mp(e,r)},Np=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Ap(e,r):bp(e,r)},Vp=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Fp(e,r):yp(e,r)},Up=(e,r)=>{vs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Tp(e,r):vp(e,r)}}),ul,Wp,Gp,dl,nx=Ve(()=>{gt(),cr(),cl(),ul=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.")},Wp=(e,r)=>{ul(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` +`)}`,`var value = ${s.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?"<=":"<"} value) { + value = ${s.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(di("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Gp=(e,r)=>{ul(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` +`)}`,`var value = ${s.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?">=":">"} value) { + value = ${s.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(di("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},dl=e=>Nt(e)}),Kp,pi,Hp,qp,Qp,fo,Xp,Jp,pl=Ve(()=>{gt(),Et(),tl(),Pt(),Kp=(e,r)=>{let t=e[0],s=e[1],o=e[2],n=e[3],i=e[4],a=e[5];if(i&&a)throw new Error("Attention cannot have both past and attention_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=t.dims[0],c=t.dims[1],p=t.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]!==p)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 d=o.dims[0]/3,u=d,f=u;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let $ of r.qkvHiddenSizes)if($%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");d=r.qkvHiddenSizes[0],u=r.qkvHiddenSizes[1],f=r.qkvHiddenSizes[2]}let _=c;if(d!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==d+u+f)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let b=0;if(i){if(u!==f)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==u/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(b=i.dims[3])}let k=_+b,g=-1,M=0;if(n)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(a){if(a.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(a.dims[0]!==l||a.dims[1]!==r.numHeads||a.dims[2]!==c||a.dims[3]!==k)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:c,pastSequenceLength:b,kvSequenceLength:_,totalSequenceLength:k,maxSequenceLength:g,inputHiddenSize:p,hiddenSize:d,vHiddenSize:f,headSize:Math.floor(d/r.numHeads),vHeadSize:Math.floor(f/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:M,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},pi=(e,r,t)=>r&&e?` + let total_sequence_length_input = u32(${r.getByOffset("0")}); + let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); + let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + `:` + ${t?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,Hp=(e,r,t,s,o,n,i,a)=>{let l=or(i?1:n),c=64,p=n/l;p{let M=it("x",e.dataType,e.dims,l),$=[M],v=i?$e("seq_lens",i.dataType,i.dims):void 0;v&&$.push(v);let y=a?$e("total_sequence_length_input",a.dataType,a.dims):void 0;y&&$.push(y);let T=Rr(e.dataType),x=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${g.registerUniforms(x).declareVariables(...$)} + ${g.mainStart([c,1,1])} + let batchIdx = workgroup_id.z / uniforms.num_heads; + let headIdx = workgroup_id.z % uniforms.num_heads; + let sequence_length = uniforms.sequence_length; + var total_sequence_length = uniforms.total_sequence_length; + ${pi(v,y,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${c}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + var thread_max_vector = ${_}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${_}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(l){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: ${l}`)}})()}; + 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 < seq_causal_length; i++) { + sum_vector += exp(${_}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(l){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: ${l}`)}})()}; + 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 < seq_causal_length; i++) { + x[offset + i] = ${M.type.value}(${T}(1.0) / ${T}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${_}(x[offset + i]); + x[offset + i] = ${M.type.value}(exp(f32input - max_value) / sum); + } + } + ${i?` + for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { + x[offset + total_seq_id] = ${M.type.value}(${T}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${f};${l}`,inputDependencies:b},getShaderSource:k,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:r*t},programUniforms:u})}},qp=(e,r,t,s,o,n,i,a,l)=>{let c=i+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,c],d=e>1&&s,u=n.kvNumHeads?n.kvNumHeads:n.numHeads,f=d?[n.batchSize,u,c,n.headSize]:void 0,_=n.nReps?n.nReps:1,b=n.scale===0?1/Math.sqrt(n.headSize):n.scale,k=or(n.headSize),g=n.headSize/k,M=12,$={x:Math.ceil(c/M),y:Math.ceil(n.sequenceLength/M),z:n.batchSize*n.numHeads},v=[{type:12,data:n.sequenceLength},{type:12,data:g},{type:12,data:c},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:b},{type:12,data:i},{type:12,data:n.kvSequenceLength},{type:12,data:_}],y=d&&s&&ye.size(s.dims)>0,T=["type","type"];y&&T.push("type"),o&&T.push("type"),a&&T.push("type"),l&&T.push("type");let x=[{dims:p,dataType:r.dataType,gpuDataType:0}];d&&x.push({dims:f,dataType:r.dataType,gpuDataType:0});let P=O=>{let L=$e("q",r.dataType,r.dims,k),G=$e("key",t.dataType,t.dims,k),K=[L,G];if(y){let me=$e("past_key",s.dataType,s.dims,k);K.push(me)}o&&K.push($e("attention_bias",o.dataType,o.dims));let R=a?$e("seq_lens",a.dataType,a.dims):void 0;R&&K.push(R);let te=l?$e("total_sequence_length_input",l.dataType,l.dims):void 0;te&&K.push(te);let H=it("output",r.dataType,p),ee=[H];d&&ee.push(it("present_key",r.dataType,f,k));let Z=Rr(1,k),ne=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${M}u; + + var tileQ: array<${L.type.storage}, ${M*M}>; + var tileK: array<${L.type.storage}, ${M*M}>; + ${O.registerUniforms(ne).declareVariables(...K,...ee)} + ${O.mainStart([M,M,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${_===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${_===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${pi(R,te,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${y&&d?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${d?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${Z}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${y&&d?` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }`:` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${d?`if (n + local_id.y < present_sequence_length) { + present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; + }`:""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${Z}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { + let headOffset = workgroup_id.z * uniforms.M * uniforms.N; + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(k){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: ${k}`)}})()}; + output[outputIdx] = ${H.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${k};${o!==void 0};${s!==void 0};${e}`,inputDependencies:T},getRunData:()=>({outputs:x,dispatchGroup:$,programUniforms:v}),getShaderSource:P}},Qp=(e,r,t,s,o,n,i=void 0,a=void 0)=>{let l=n+o.kvSequenceLength,c=o.nReps?o.nReps:1,p=o.vHiddenSize*c,d=e>1&&s,u=o.kvNumHeads?o.kvNumHeads:o.numHeads,f=d?[o.batchSize,u,l,o.headSize]:void 0,_=[o.batchSize,o.sequenceLength,p],b=12,k={x:Math.ceil(o.vHeadSize/b),y:Math.ceil(o.sequenceLength/b),z:o.batchSize*o.numHeads},g=[{type:12,data:o.sequenceLength},{type:12,data:l},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:p},{type:12,data:n},{type:12,data:o.kvSequenceLength},{type:12,data:c}],M=d&&s&&ye.size(s.dims)>0,$=["type","type"];M&&$.push("type"),i&&$.push("type"),a&&$.push("type");let v=[{dims:_,dataType:r.dataType,gpuDataType:0}];d&&v.push({dims:f,dataType:r.dataType,gpuDataType:0});let y=T=>{let x=$e("probs",r.dataType,r.dims),P=$e("v",t.dataType,t.dims),O=[x,P];M&&O.push($e("past_value",s.dataType,s.dims));let L=i?$e("seq_lens",i.dataType,i.dims):void 0;i&&O.push(L);let G=a?$e("total_sequence_length_input",a.dataType,a.dims):void 0;a&&O.push(G);let K=[it("output",r.dataType,_)];d&&K.push(it("present_value",r.dataType,f));let R=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${b}u; + var tileQ: array<${x.type.value}, ${b*b}>; + var tileV: array<${x.type.value}, ${b*b}>; + ${T.registerUniforms(R).declareVariables(...O,...K)} + ${T.mainStart([b,b,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${c===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${c===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let m = global_id.y; + let n = global_id.x; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.K; + ${pi(L,G,!0)} + let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch + ${M&&d?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${d?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${x.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${M&&d?` + if (w + local_id.y < past_sequence_length) { + tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; + } + `:` + if (w + local_id.y < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; + }`} + ${d?` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }`:""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:$},getRunData:()=>({outputs:v,dispatchGroup:k,programUniforms:g}),getShaderSource:y}},fo=(e,r,t,s,o,n,i,a,l,c,p=void 0,d=void 0)=>{let u=Math.min(e.outputCount,1+(i?1:0)+(a?1:0)),f=u>1?c.pastSequenceLength:0,_=f+c.kvSequenceLength,b=l&&ye.size(l.dims)>0?l:void 0,k=[r,t];u>1&&i&&ye.size(i.dims)>0&&k.push(i),b&&k.push(b),p&&k.push(p),d&&k.push(d);let g=e.compute(qp(u,r,t,i,b,c,f,p,d),{inputs:k,outputs:u>1?[-1,1]:[-1]})[0];e.compute(Hp(g,c.batchSize,c.numHeads,f,c.sequenceLength,_,p,d),{inputs:p&&d?[g,p,d]:[g],outputs:[]});let M=[g,s];u>1&&a&&ye.size(a.dims)>0&&M.push(a),p&&M.push(p),d&&M.push(d),e.compute(Qp(u,g,s,a,c,f,p,d),{inputs:M,outputs:u>1?[0,2]:[0]})},Xp=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,o=r.inputHiddenSize,n=r.headSize,i=12,a={x:Math.ceil(r.headSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:s},{type:12,data:o},{type:12,data:n},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:r.hiddenSize},{type:12,data:r.hiddenSize+r.hiddenSize+r.vHiddenSize}],p=d=>{let u=it("output_q",l[0].dataType,t),f=it("output_k",l[0].dataType,t),_=it("output_v",l[0].dataType,t),b=$e("input",l[0].dataType,l[0].dims),k=$e("weight",l[1].dataType,l[1].dims),g=$e("bias",l[2].dataType,l[2].dims),M=b.type.storage,$=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${i}u; + var tileInput: array<${M}, ${i*i}>; + var tileWeightQ: array<${M}, ${i*i}>; + var tileWeightK: array<${M}, ${i*i}>; + var tileWeightV: array<${M}, ${i*i}>; + ${d.registerUniforms($).declareVariables(b,k,g,u,f,_)} + ${d.mainStart([i,i,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${M}(0); + var valueK = ${M}(0); + var valueV = ${M}(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: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:a,programUniforms:c}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},Jp=(e,r)=>{let t=Kp(e.inputs,r),[s,o,n]=Xp(e,t);return fo(e,s,o,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),Yp,Zp,eh,th,ox=Ve(()=>{gs(),gt(),Et(),cr(),Pt(),Yp=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,o,n)=>{let i=o.length;if(i!==s.length)throw new Error(`${n}: num dimensions != ${i}`);o.forEach((a,l)=>{if(a!==s[l])throw new Error(`${n}: dim[${l}] do not match`)})};if(e[0].dims.length>1){let s=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,s,"Invalid input scale"),t(e[2].dims,s,"Invalid input B"),t(e[3].dims,s,"Invalid input mean"),t(e[4].dims,s,"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")},Zp=(e,r)=>{let{epsilon:t,spatial:s,format:o}=r,n=e[0].dims,i=s?or(n[n.length-1]):1,a=o==="NHWC"&&n.length>1?i:1,l=ye.size(n)/i,c=s,p=c?n.length:n,d=$e("x",e[0].dataType,e[0].dims,i),u=$e("scale",e[1].dataType,e[1].dims,a),f=$e("bias",e[2].dataType,e[2].dims,a),_=$e("inputMean",e[3].dataType,e[3].dims,a),b=$e("inputVar",e[4].dataType,e[4].dims,a),k=it("y",e[0].dataType,p,i),g=()=>{let $="";if(s)$=`let cOffset = ${n.length===1?"0u":o==="NHWC"?`outputIndices[${n.length-1}] / ${i}`:"outputIndices[1]"};`;else if(o==="NCHW")$=` + ${k.indicesSet("outputIndices","0","0")} + let cOffset = ${k.indicesToOffset("outputIndices")};`;else{$=`var cIndices = ${u.type.indices}(0); + cIndices[0] = outputIndices[${n.length-1}];`;for(let v=1;v` + const epsilon = ${t}; + ${$.registerUniform("outputSize","u32").declareVariables(d,u,f,_,b,k)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${k.offsetToIndices(`global_idx * ${i}`)}; + ${g()} + let scale = ${u.getByOffset("cOffset")}; + let bias = ${f.getByOffset("cOffset")}; + let inputMean = ${_.getByOffset("cOffset")}; + let inputVar = ${b.getByOffset("cOffset")}; + let x = ${d.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${k.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${i}`,inputDependencies:c?["rank","type","type","type","type"]:void 0},getShaderSource:M,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c?[{type:12,data:l},...ct(n)]:[{type:12,data:l}]})}},eh=e=>Nt(e),th=(e,r)=>{let{inputs:t,outputCount:s}=e,o=eh({...r,outputCount:s});if(Yt.webgpu.validateInputContent&&Yp(t,o),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Zp(t,o))}}),rh,sh,nh,ix=Ve(()=>{Et(),Pt(),rh=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")},sh=e=>{let r=e[0].dims,t=e[0].dims[2],s=ye.size(r)/4,o=e[0].dataType,n=$e("input",o,r,4),i=$e("bias",o,[t],4),a=$e("residual",o,r,4),l=it("output",o,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:c=>` + const channels = ${t}u / 4; + ${c.declareVariables(n,i,a,l)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes(s)} + let value = ${n.getByOffset("global_idx")} + + ${i.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; + ${l.setByOffset("global_idx","value")} + }`}},nh=e=>{rh(e.inputs),e.compute(sh(e.inputs))}}),oh,Rt,ih,ah,lh,ch,uh,dh,ph,hh,mh,_h,fh,gh,wh,Mh,go,bh,hi,yh,vh,xh,Th,Eh,Ph,Ch,Sh,$h,kh,Ih,Ah,Fh,Oh,Dh,Lh,hl,zh,ml,_l,Bh,Rh,jh,Nh,Vh,Uh,fl=Ve(()=>{gt(),Et(),cr(),Pt(),oh=(e,r,t,s,o,n,i)=>{let a=Math.ceil(r/4),l="";typeof o=="string"?l=`${o}(a)`:l=o("a");let c=$e("inputData",t,[a],4),p=it("outputData",s,[a],4),d=[{name:"vec_size",type:"u32"}];return i&&d.push(...i),` + ${e.registerUniforms(d).declareVariables(c,p)} + + ${n??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${c.getByOffset("global_idx")}; + ${p.setByOffset("global_idx",l)} + }`},Rt=(e,r,t,s,o,n=e.dataType,i,a)=>{let l=[{type:12,data:Math.ceil(ye.size(e.dims)/4)}];return i&&l.push(...i),{name:r,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:c=>oh(c,ye.size(e.dims),e.dataType,n,t,s,a),getRunData:c=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(ye.size(c[0].dims)/64/4)},programUniforms:l})}},ih=e=>{e.compute(Rt(e.inputs[0],"Abs","abs"))},ah=e=>{e.compute(Rt(e.inputs[0],"Acos","acos"))},lh=e=>{e.compute(Rt(e.inputs[0],"Acosh","acosh"))},ch=e=>{e.compute(Rt(e.inputs[0],"Asin","asin"))},uh=e=>{e.compute(Rt(e.inputs[0],"Asinh","asinh"))},dh=e=>{e.compute(Rt(e.inputs[0],"Atan","atan"))},ph=e=>{e.compute(Rt(e.inputs[0],"Atanh","atanh"))},hh=e=>Nt(e),mh=(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(Rt(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},_h=e=>{let r,t,s=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Nt({min:r,max:t})},fh=(e,r)=>{let t=r||_h(e.inputs),s=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${s}>(uniforms.min), vec4<${s}>(uniforms.max))`,void 0,t.cacheKey,void 0,[{type:e.inputs[0].dataType,data:t.min},{type:e.inputs[0].dataType,data:t.max}],[{name:"min",type:s},{name:"max",type:s}]),{inputs:[0]})},gh=e=>{e.compute(Rt(e.inputs[0],"Ceil","ceil"))},wh=e=>{e.compute(Rt(e.inputs[0],"Cos","cos"))},Mh=e=>{e.compute(Rt(e.inputs[0],"Cosh","cosh"))},go=e=>Nt(e),bh=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` + const elu_alpha_ = ${t}(${r.alpha}); + + fn elu_f32(a: ${t}) -> ${t} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${t}>) -> vec4<${t}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,r.cacheKey))},hi=(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)); +}`,yh=e=>{let r=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,hi(r)))},vh=e=>{e.compute(Rt(e.inputs[0],"Exp","exp"))},xh=e=>{e.compute(Rt(e.inputs[0],"Floor","floor"))},Th=e=>{let r=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,hi(r)))},Eh=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"LeakyRelu",s=>`select(leaky_relu_alpha_ * ${s}, ${s}, ${s} >= vec4<${t}>(0.0))`,`const leaky_relu_alpha_ = ${t}(${r.alpha});`,r.cacheKey))},Ph=e=>{e.compute(Rt(e.inputs[0],"Not",r=>`!${r}`))},Ch=e=>{e.compute(Rt(e.inputs[0],"Neg",r=>`-${r}`))},Sh=e=>{e.compute(Rt(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},$h=e=>{let r=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},kh=e=>{e.compute(Rt(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},Ih=e=>Nt(e),Ah=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"HardSigmoid",s=>`max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), ${r.alpha} * ${s} + vec4<${t}>(${r.beta})))`,void 0,r.cacheKey))},Fh=e=>{e.compute(Rt(e.inputs[0],"Sin","sin"))},Oh=e=>{e.compute(Rt(e.inputs[0],"Sinh","sinh"))},Dh=e=>{e.compute(Rt(e.inputs[0],"Sqrt","sqrt"))},Lh=e=>{e.compute(Rt(e.inputs[0],"Tan","tan"))},hl=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,zh=e=>{e.compute(Rt(e.inputs[0],"Tanh",hl))},ml=(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 ${hl("v")}; +} +`,_l=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Bh=e=>{let r=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"FastGelu",_l,ml(r),void 0,e.inputs[0].dataType))},Rh=(e,r)=>{let t=Rr(e.inputs[0].dataType);return e.compute(Rt(e.inputs[0],"ThresholdedRelu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${t}>(${r.alpha});`,r.cacheKey)),0},jh=e=>{e.compute(Rt(e.inputs[0],"Log","log"))},Nh=(e,r)=>` +const alpha = vec4<${e}>(${r}); +const one = ${e}(1.0); +const zero = ${e}(0.0); + +fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { + let v = x *alpha; + var x1 : vec4<${e}>; + for (var i = 0; i < 4; i = i + 1) { + if (v[i] >= zero) { + x1[i] = one / (one + exp(-v[i])); + } else { + x1[i] = one - one / (one + exp(v[i])); + } + } + return x * x1; +} +`,Vh=e=>`quick_gelu_impl(${e})`,Uh=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"QuickGelu",Vh,Nh(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),Wh,Gh,Kh,ax=Ve(()=>{Et(),Pt(),fl(),Wh=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")},Gh=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=$e("input",e[0].dataType,e[0].dims,4),s=$e("bias",e[0].dataType,[e[0].dims[2]],4),o=it("output",e[0].dataType,r,4),n=ye.size(r)/4,i=Er(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:a=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${a.declareVariables(t,s,o)} + + ${hi(i)} + + ${a.mainStart()} + ${a.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${o.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Kh=e=>{Wh(e.inputs),e.compute(Gh(e.inputs))}}),Hh,qh,xs,Qh,Xh,Jh,Yh,Zh,em,tm,rm,sm,nm,lx=Ve(()=>{gt(),Et(),Pt(),Hh=(e,r,t,s,o,n,i,a,l,c,p,d)=>{let u,f;typeof a=="string"?u=f=(M,$)=>`${a}((${M}),(${$}))`:typeof a=="function"?u=f=a:(u=a.scalar,f=a.vector);let _=it("outputData",p,s.length,4),b=$e("aData",l,r.length,4),k=$e("bData",c,t.length,4),g;if(o)if(n){let M=ye.size(r)===1,$=ye.size(t)===1,v=r.length>0&&r[r.length-1]%4===0,y=t.length>0&&t[t.length-1]%4===0;M||$?g=_.setByOffset("global_idx",f(M?`${b.type.value}(${b.getByOffset("0")}.x)`:b.getByOffset("global_idx"),$?`${k.type.value}(${k.getByOffset("0")}.x)`:k.getByOffset("global_idx"))):g=` + let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; + let offsetA = ${b.broadcastedIndicesToOffset("outputIndices",_)}; + let offsetB = ${k.broadcastedIndicesToOffset("outputIndices",_)}; + ${_.setByOffset("global_idx",f(i||v?b.getByOffset("offsetA / 4u"):`${b.type.value}(${b.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||y?k.getByOffset("offsetB / 4u"):`${k.type.value}(${k.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else g=_.setByOffset("global_idx",f(b.getByOffset("global_idx"),k.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let M=($,v,y="")=>{let T=`aData[indexA${v}][componentA${v}]`,x=`bData[indexB${v}][componentB${v}]`;return` + let outputIndices${v} = ${_.offsetToIndices(`global_idx * 4u + ${v}u`)}; + let offsetA${v} = ${b.broadcastedIndicesToOffset(`outputIndices${v}`,_)}; + let offsetB${v} = ${k.broadcastedIndicesToOffset(`outputIndices${v}`,_)}; + let indexA${v} = offsetA${v} / 4u; + let indexB${v} = offsetB${v} / 4u; + let componentA${v} = offsetA${v} % 4u; + let componentB${v} = offsetB${v} % 4u; + ${$}[${v}] = ${y}(${u(T,x)}); + `};p===9?g=` + var data = vec4(0); + ${M("data",0,"u32")} + ${M("data",1,"u32")} + ${M("data",2,"u32")} + ${M("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:g=` + ${M("outputData[global_idx]",0)} + ${M("outputData[global_idx]",1)} + ${M("outputData[global_idx]",2)} + ${M("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(b,k,_)} + + ${d??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${g} + }`},qh=(e,r,t,s,o,n,i=t.dataType)=>{let a=t.dims.map(b=>Number(b)??1),l=s.dims.map(b=>Number(b)??1),c=!ye.areEqual(a,l),p=a,d=ye.size(a),u=!1,f=!1,_=[c];if(c){let b=Un.calcShape(a,l,!1);if(!b)throw new Error("Can't perform binary op on the given tensors");p=b.slice(),d=ye.size(p);let k=ye.size(a)===1,g=ye.size(l)===1,M=a.length>0&&a[a.length-1]%4===0,$=l.length>0&&l[l.length-1]%4===0;_.push(k),_.push(g),_.push(M),_.push($);let v=1;for(let y=1;yb.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:b=>Hh(b,a,l,p,u,c,f,o,t.dataType,s.dataType,i,n),getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(ye.size(p)/4)},...ct(a,l,p)]})}},xs=(e,r,t,s,o,n)=>{e.compute(qh(r,o??"",e.inputs[0],e.inputs[1],t,s,n))},Qh=e=>{xs(e,"Add",(r,t)=>`${r}+${t}`)},Xh=e=>{xs(e,"Div",(r,t)=>`${r}/${t}`)},Jh=e=>{xs(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},Yh=e=>{xs(e,"Mul",(r,t)=>`${r}*${t}`)},Zh=e=>{let r=$e("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;xs(e,"Pow",{scalar:(t,s)=>`pow_custom(${t},${s})`,vector:(t,s)=>`pow_vector_custom(${t},${s})`},` + fn pow_custom(a : ${r}, b : ${r}) -> ${r} { + if (b == ${r}(0.0)) { + return ${r}(1.0); + } else if (a < ${r}(0.0) && f32(b) != floor(f32(b))) { + return ${r}(pow(f32(a), f32(b))); // NaN + } + 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)))); + } + fn pow_vector_custom(a : vec4<${r}>, b : vec4<${r}>) -> vec4<${r}> { + // TODO: implement vectorized pow + 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)); + } + `)},em=e=>{xs(e,"Sub",(r,t)=>`${r}-${t}`)},tm=e=>{xs(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},rm=e=>{xs(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},sm=e=>{xs(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},nm=e=>{xs(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),om,im,am,lm,cm,um,cx=Ve(()=>{gt(),Et(),cr(),Pt(),om=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],o=s.dataType,n=s.dims.length;e.forEach((i,a)=>{if(a!==t){if(i.dataType!==o)throw new Error("input tensors should be one type");if(i.dims.length!==n)throw new Error("input tensors should have the same shape");i.dims.forEach((l,c)=>{if(c!==r&&l!==s.dims[c])throw new Error("non concat dimensions must match")})}})},im=(e,r)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${r}); + for (var i: u32 = 0u; i < ${e}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${e}u; + }`,am=(e,r)=>{let t=e.length,s=[];for(let o=0;o{let o=ye.size(t),n=new Array(e.length),i=new Array(e.length),a=0,l=[],c=[],p=[{type:12,data:o}];for(let b=0;b`uniforms.sizeInConcatAxis${b}`).join(","),_=b=>` + + ${(()=>{b.registerUniform("outputSize","u32");for(let k=0;k(${f}); + ${u} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${am(i,d)} + }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}),getShaderSource:_}},cm=(e,r)=>{let t=e.inputs,s=t[0].dims,o=ye.normalizeAxis(r.axis,s.length);om(t,o);let n=s.slice();n[o]=t.reduce((a,l)=>a+(l.dims.length>o?l.dims[o]:0),0);let i=t.filter(a=>ye.size(a.dims)>0);e.compute(lm(i,o,n,t[0].dataType),{inputs:i})},um=e=>Nt({axis:e.axis})}),hn,mn,_n,gl,fn=Ve(()=>{gt(),Et(),hn=(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"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},mn=(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})},_n=(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"})},gl=e=>{let r=(e==null?void 0:e.activation)||"";if(r==="HardSigmoid"){let[t,s]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:r,alpha:t,beta:s}}else if(r==="Clip"){let[t,s]=(e==null?void 0:e.activation_params)||[Fd,Od];return{activation:r,clipMax:s,clipMin:t}}else if(r==="LeakyRelu"){let[t]=(e==null?void 0:e.activation_params)||[.01];return{activation:r,alpha:t}}return{activation:r}}}),Or,dm,wl=Ve(()=>{Or=(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.`)}},dm=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),pm,ux=Ve(()=>{pm=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)); +} +`}),wo,Ml,bl=Ve(()=>{gt(),Et(),Pt(),fn(),wo=(e,r,t,s,o)=>{let n=s-t;return` + ${Array.from({length:t}).map((i,a)=>` + if (${lt(r.shape,a,r.rank)} != 1) { + ${r.indicesSet(e,a,lt(o,a+n,s))} + } else { + ${r.indicesSet(e,a,0)} + }`).join("")} +`},Ml=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i[i.length-2],c=a[a.length-1],p=i[i.length-1],d=or(c),u=or(p),f=or(l),_=ye.size(t)/d/f,b=e.length>2,k=s?s.slice(0,-2):t.slice(0,-2),g=[ye.size(k),l,c],M=[{type:12,data:_},{type:12,data:l},{type:12,data:c},{type:12,data:p}];mn(r,M),M.push(...ct(k,i,a)),b&&M.push(...ct(e[2].dims)),M.push(...ct(g));let $=v=>{let y=il("batch_dims",e[0].dataType,k.length),T=$e("a",e[0].dataType,i.length,u),x=$e("b",e[1].dataType,a.length,d),P=it("output",e[0].dataType,g.length,d),O=Er(P.type.tensor),L=hn(r,P.type.value,O),G=[T,x],K="";if(b){let H=o?d:1;G.push($e("bias",e[2].dataType,e[2].dims.length,H)),K=`${o?`value += bias[col / ${H}];`:`value += ${P.type.value}(bias[row + i]);`}`}let R=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];_n(r,R);let te=()=>{let H=`var a_data: ${T.type.value};`;for(let ee=0;ee; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) { + ${te()} + } + for (var i = 0u; i < ${f}u; i++) { + var value = values[i]; + ${K} + ${L} + let cur_indices = ${P.type.indices}(batch, row + i, col); + let offset = ${P.indicesToOffset("cur_indices")}; + ${P.setByOffset(`offset / ${d}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${d};${u};${f};${o}`,inputDependencies:b?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:M}),getShaderSource:$}}}),hm,mm,yl,vl,_m,xl,fm,mi,Tl=Ve(()=>{gt(),Et(),Pt(),fn(),bl(),wl(),hm=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${r?", batchIndices":""}); + `,mm=(e,r)=>e?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${r===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]; + ${r===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]; + ${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,yl=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32)=>{let l=r[1]*e[1],c=r[0]*e[0],p=o?l:n,d=o?n:l,u=p/r[0],f=n/r[1];if(!((o&&u===4&&e[1]===4||!o&&(u===3||u===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${u} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${u} must be 3 or 4. + tileAWidth ${p} must be divisible by workgroupSize[0]${r[0]}. tileInner ${n} must be divisible by workgroupSize[1] ${r[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${p/u}>, ${d}>; +var mm_Bsub: array, ${c/e[0]}>, ${n}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${u}; +const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${l}; + + let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${f}; + 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; + ${hm(o,s)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${f}; 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]; + ${u===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${mm(o,u)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},vl=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${r?", batchIndices":""}); + `,_m=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",xl=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32,l=!1)=>{let c=e[1]*r[1],p=e[0]*r[0],d=o?c:n,u=o?n:c;if(!(u%r[1]===0&&d%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${u} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${r[0]}, tileInner ${n} must be divisible by workgroupSize[1]${r[1]}`);let f=u/r[1],_=d/r[0],b=n/r[1],k=l?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${c}; + let globalColStart = i32(workgroupId.x) * ${p}; + + // 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 < ${u}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${r[0]}) { + ${vl(o,s)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${n}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${r[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<${t}, 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 * ${r[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${r[1]}];`:`mm_Asub[localRow + innerRow * ${r[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 * ${r[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${r[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${c}; + +let tileRowA = i32(localId.y) * ${f}; +let tileColA = i32(localId.x) * ${_}; +let tileRowB = i32(localId.y) * ${b}; +// 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 < ${f}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${_}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${vl(o,s)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${b}; 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<${t}, 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) { + ${_m(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, ${u}>; + var mm_Bsub : array, ${n}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc : array, rowPerThread>; + ${k} + } +`},fm=(e,r,t,s,o=!1)=>{let[n,i,a,l]=s,c=Er(s[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${Or(e,c)} { + var value = ${Or(e,c)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${i.type.indices}; + ${wo("aIndices",i,i.rank-2,n.rank,"batchIndices")} + ${i.indicesSet("aIndices",i.rank-2,"u32(row)")} + ${i.indicesSet("aIndices",i.rank-1,"u32(colIn)")} + value = ${i.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${Or(e,c)} { + var value = ${Or(e,c)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${a.type.indices}; + ${wo("bIndices",a,a.rank-2,n.rank,"batchIndices")} + ${a.indicesSet("bIndices",a.rank-2,"u32(row)")} + ${a.indicesSet("bIndices",a.rank-1,"u32(colIn)")} + value = ${a.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Or(e,c)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${r?`value = value + ${o?"bias[colIn]":`${Or(e,c)}(bias[row])`};`:""} + ${t} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},mi=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i.slice(0,-2),c=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),d=ye.size(p),u=i[i.length-2],f=i[i.length-1],_=a[a.length-1],b=f%4===0&&_%4===0,k=u<=8?[4,1,1]:[4,4,1],g=[8,8,1],M=[Math.ceil(_/g[0]/k[0]),Math.ceil(u/g[1]/k[1]),Math.ceil(d/g[2]/k[2])],$=b?4:1,v=[...l,u,f/$],y=v.length,T=[...c,f,_/$],x=T.length,P=[d,u,_/$],O=[{type:6,data:u},{type:6,data:_},{type:6,data:f}];mn(r,O),O.push(...ct(p,v,T));let L=["rank","rank"],G=e.length>2;G&&(O.push(...ct(e[2].dims)),L.push("rank")),O.push(...ct(P));let K=R=>{let te=p.length,H=il("batchDims",e[0].dataType,te,1),ee=Er(e[0].dataType),Z=$e("a",e[0].dataType,y,$),ne=$e("b",e[1].dataType,x,$),me=it("result",e[0].dataType,P.length,$),ue=[Z,ne];if(G){let _e=o?$:1;ue.push($e("bias",e[2].dataType,e[2].dims.length,_e))}let j=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];_n(r,j);let F=Er(me.type.tensor),U=hn(r,me.type.value,F),se=fm($,G,U,[H,Z,ne,me],o);return` + ${R.registerUniforms(j).registerInternalVariables(H).declareVariables(...ue,me)} + ${se} + ${b?yl(k,g,ee,H):xl(k,g,ee,H)} + `};return{name:"MatMul",shaderCache:{hint:`${k};${r.activation};${b};${o}`,inputDependencies:L},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:M[0],y:M[1],z:M[2]},programUniforms:O}),getShaderSource:K}}}),gm,wm,dx=Ve(()=>{gt(),Bs(),Pt(),fn(),wl(),ux(),Tl(),gm=(e,r,t,s,o=!1,n,i=4,a=4,l=4,c="f32")=>{let p=O=>{switch(O){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${O} is not supported.`)}},d=O=>{switch(O){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 ${O} is not supported.`)}},u=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,f=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,_=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",b=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",k=e?"row":"col",g=e?"col":"row",M=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${k} / outWidth; + let outCol = ${k} % outWidth; + + let WRow = ${g} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${g} / 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 = ${g} % inChannels; + var resData = ${Or(i,c)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${_} && xCol >= 0 && xCol < ${b}) { + ${u} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${p(i)} + } + return resData;`,$=e?r&&s?` + let col = colIn * ${i}; + ${M}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${M} + } + return ${Or(i,c)}(0.0);`:s&&t?` + let col = colIn * ${i}; + ${M}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${M} + } + return ${Or(i,c)}(0.0);`,v=e?s&&t?d(a):` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${d(a)} + } + return ${Or(a,c)}(0.0);`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${d(a)} + } + return ${Or(a,c)}(0.0);`,y=Or(l,c),T=Or(e?i:a,c),x=Or(e?a:i,c),P=hn(n,y,c);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${T} { + ${e?$:v} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${x} { + ${e?v:$} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${y}) { + let col = colIn * ${l}; + 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])"}; + ${f} + ${dm(o)} + ${P} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},wm=(e,r,t,s,o,n,i,a,l)=>{let c=r.format==="NHWC",p=c?e[0].dims[3]:e[0].dims[1],d=t[0],u=c?t[2]:t[3],f=c?t[1]:t[2],_=c?t[3]:t[1],b=c&&(p%4===0||p%3===0)&&_%4===0,k=c?_:u*f,g=c?u*f:_,M=[8,8,1],$=s<=8?[4,1,1]:[4,4,1],v=[Math.ceil(k/M[0]/$[0]),Math.ceil(g/M[1]/$[1]),Math.ceil(d/M[2]/$[2])];Dt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${v}`);let y=b?c&&p%4!==0?3:4:1,T=M[1]*$[1],x=M[0]*$[0],P=Math.max(M[0]*y,M[1]),O=s%T===0,L=o%x===0,G=n%P===0,K=b?[y,4,4]:[1,1,1],R=[{type:6,data:s},{type:6,data:o},{type:6,data:n},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];mn(r,R),R.push(...ct(e[0].dims,e[1].dims));let te=["rank","rank"];i&&(R.push(...ct(e[2].dims)),te.push("rank")),R.push(...ct(t));let H=ee=>{let Z=[{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}];_n(r,Z);let ne=b?4:1,me=Er(e[0].dataType),ue=` + fn setOutputAtIndex(flatIndex : i32, value : ${b?`vec4<${me}>`:me}) { + result[flatIndex] = ${b?`vec4<${me}>`:me}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${b?`vec4<${me}>`:me}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${b?"/ 4":""}, value); + }`,j=$e("x",e[0].dataType,e[0].dims.length,y===3?1:y),F=$e("w",e[1].dataType,e[1].dims.length,ne),U=[j,F],se=it("result",e[0].dataType,t.length,ne);if(i){let _e=$e("bias",e[2].dataType,e[2].dims.length,ne);U.push(_e),ue+=` + fn getBiasByOutputCoords(coords : vec4) -> ${b?`vec4<${me}>`:me} { + return bias[coords.${c?"w":"y"}${b?"/ 4":""}]; + }`}return` + ${pm("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 }; + ${ee.registerUniforms(Z).declareVariables(...U,se)} + ${ue} + ${gm(c,O,L,G,i,r,K[0],K[1],K[2],me)} + ${b?yl($,M,me,void 0,!c,P):xl($,M,me,void 0,!c,P,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${y};${b};${O};${L};${G};${T};${x};${P}`,inputDependencies:te},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:R}),getShaderSource:H}}}),Mm,El,Mo,bm,Pl,ym,vm,xm,px=Ve(()=>{gt(),Bs(),Et(),Pt(),fn(),wl(),Mm=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,Mo=(e,r)=>r<=1?e:e+(e-1)*(r-1),bm=(e,r,t,s=1)=>{let o=Mo(r,s);return Math.floor((e[0]*(t-1)-t+o)/2)},Pl=(e,r,t,s,o)=>{o==null&&(o=bm(e,r[0],s[0]));let n=[0,0,0,t];for(let i=0;i<3;i++)e[i]+2*o>=r[i]&&(n[i]=Math.trunc((e[i]-r[i]+2*o)/s[i]+1));return n},ym=(e,r,t,s,o,n,i,a,l,c)=>{let p,d,u,f;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let _=Pl([r,t,s,1],[a,l,c],1,[o,n,i],e);d=_[0],u=_[1],f=_[2]}else if(Array.isArray(e)){if(!e.every((b,k,g)=>b===g[0]))throw Error(`Unsupported padding parameter: ${e}`);p={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let _=Pl([r,t,s,1],[a,l,c],1,[o,n,i],e[0]);d=_[0],u=_[1],f=_[2]}else if(e==="SAME_UPPER"){d=Math.ceil(r/o),u=Math.ceil(t/n),f=Math.ceil(s/i);let _=(d-1)*o+a-r,b=(u-1)*n+l-t,k=(f-1)*i+c-s,g=Math.floor(_/2),M=_-g,$=Math.floor(b/2),v=b-$,y=Math.floor(k/2),T=k-y;p={top:$,bottom:v,left:y,right:T,front:g,back:M}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:u,outWidth:f}},vm=(e,r,t,s,o,n=!1,i="channelsLast")=>{let a,l,c,p,d;if(i==="channelsLast")[a,l,c,p,d]=e;else if(i==="channelsFirst")[a,d,l,c,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[u,,f,_,b]=r,[k,g,M]=El(t),[$,v,y]=El(s),T=Mo(f,$),x=Mo(_,v),P=Mo(b,y),{padInfo:O,outDepth:L,outHeight:G,outWidth:K}=ym(o,l,c,p,k,g,M,T,x,P),R=n?u*d:u,te=[0,0,0,0,0];return i==="channelsFirst"?te=[a,R,L,G,K]:i==="channelsLast"&&(te=[a,L,G,K,R]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:c,inWidth:p,inChannels:d,outDepth:L,outHeight:G,outWidth:K,outChannels:R,padInfo:O,strideDepth:k,strideHeight:g,strideWidth:M,filterDepth:f,filterHeight:_,filterWidth:b,effectiveFilterDepth:T,effectiveFilterHeight:x,effectiveFilterWidth:P,dilationDepth:$,dilationHeight:v,dilationWidth:y,inShape:e,outShape:te,filterShape:r}},xm=(e,r,t,s,o,n)=>{let i=n==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((k,g)=>g)},c=[Math.ceil(Mm(l.x.map(k=>t[k]))/a[0]),1,1];Dt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${c}`);let p=1,d=ye.size(t),u=[{type:12,data:d},{type:12,data:s},{type:12,data:o},{type:12,data:r.strides},{type:12,data:r.dilations}];mn(r,u),u.push(...ct(e[0].dims,e[1].dims));let f=["rank","rank"],_=e.length===3;_&&(u.push(...ct(e[2].dims)),f.push("rank")),u.push(...ct(t));let b=k=>{let g=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];_n(r,g);let M=1,$=Er(e[0].dataType),v=$e("x",e[0].dataType,e[0].dims.length,p),y=$e("W",e[1].dataType,e[1].dims.length,M),T=[v,y],x=it("result",e[0].dataType,t.length,M),P="";if(_){let G=$e("bias",e[2].dataType,e[2].dims.length,M);T.push(G),P+=` + fn getBiasByOutputCoords(coords : array) -> ${$} { + return bias[${i?lt("coords",4,5):lt("coords",1,5)}]; + }`}let O=Or(p,$),L=hn(r,O,$);return` + ${P} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${v.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${y.getByIndices("aIndices")}; + } + ${k.registerUniforms(g).declareVariables(...T,x)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${x.offsetToIndices("global_idx")}; + let batch = ${lt("coords",0,v.rank)}; + let d2 = ${i?lt("coords",v.rank-1,v.rank):lt("coords",1,v.rank)}; + let xFRCCorner = vec3(${i?lt("coords",1,v.rank):lt("coords",2,v.rank)}, + ${i?lt("coords",2,v.rank):lt("coords",3,v.rank)}, + ${i?lt("coords",3,v.rank):lt("coords",4,v.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${i?lt("uniforms.x_shape",1,v.rank):lt("uniforms.x_shape",2,v.rank)}; + let xShapeZ = ${i?lt("uniforms.x_shape",2,v.rank):lt("uniforms.x_shape",3,v.rank)}; + let xShapeW = ${i?lt("uniforms.x_shape",3,v.rank):lt("uniforms.x_shape",4,v.rank)}; + let xShapeU = ${i?lt("uniforms.x_shape",4,v.rank):lt("uniforms.x_shape",1,v.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${i?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${i?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${i?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${_?"value = value + getBiasByOutputCoords(coords)":""}; + ${L} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${i};${p};${_}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:c[0],y:c[1],z:c[2]},programUniforms:u}),getShaderSource:b}}}),Tm,Em,hx=Ve(()=>{gt(),Et(),Pt(),fn(),Tm=(e,r,t,s)=>{let o=e.length>2,n=o?"value += b[output_channel];":"",i=e[0].dims,a=e[1].dims,l=r.format==="NHWC",c=l?t[3]:t[1],p=c/r.group,d=l&&p>=4?or(c):1,u=ye.size(t)/d,f=[{type:12,data:u},{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:p}];mn(r,f),f.push(...ct(i,[a[0],a[1],a[2],a[3]/d]));let _=o?["rank","rank","rank"]:["rank","rank"];f.push(...ct([t[0],t[1],t[2],t[3]/d]));let b=k=>{let g=it("output",e[0].dataType,t.length,d),M=Er(g.type.tensor),$=hn(r,g.type.value,M),v=$e("x",e[0].dataType,i.length),y=$e("w",e[1].dataType,a.length,d),T=[v,y];o&&T.push($e("b",e[2].dataType,e[2].dims,d));let x=[{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"}];_n(r,x);let P=l?` + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { + continue; + } + + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + let xVal = ${v.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${y.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + 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[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[3]) { + continue; + } + + let xVal = ${v.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${y.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${k.registerUniforms(x).declareVariables(...T,g)} + + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${g.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${l?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${d} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}]; + + var value: ${g.type.value} = ${g.type.value}(0); + ${P} + ${n} + ${$} + ${g.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${d}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:b}},Em=(e,r,t,s)=>{let o=e.length>2,n=or(t[3]),i=or(t[2]),a=ye.size(t)/n/i,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/n],p=[t[0],t[1],t[2],t[3]/n],d=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];mn(r,d),d.push(...ct(l,c,p));let u=(i-1)*r.strides[1]+c[1],f=_=>{let b=it("output",e[0].dataType,p.length,n),k=Er(b.type.tensor),g=hn(r,b.type.value,k),M=$e("x",e[0].dataType,l.length,n),$=$e("w",e[1].dataType,c.length,n),v=[M,$];o&&v.push($e("b",e[2].dataType,e[2].dims,n));let y=o?"value += b[output_channel];":"",T=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return _n(r,T),` + ${_.registerUniforms(T).declareVariables(...v,b)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${i}u; + let col = (index1 % width1) * ${i}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<${M.type.value}, ${u}>; + var values: array<${b.type.value}, ${i}>; + 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 < ${c[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 < ${u}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${M.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${M.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) { + let w_val = ${$.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${i}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${i}u; i++) { + var value = values[i]; + ${y} + ${g} + ${b.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${i};${u};${c[0]};${c[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:f}}}),Pm,_i,Cm,fi,Cl,Sl,Sm,$m,$l,mx=Ve(()=>{Et(),dx(),px(),Tl(),hx(),fn(),bl(),Hs(),Pm=(e,r,t,s,o,n)=>{let i=e[0],a=e.slice(n?1:2,n?3:4),l=a.length,c=r[0],p=r.slice(2).map((u,f)=>u+(u-1)*(t[f]-1)),d=a.map((u,f)=>u+s[f]+s[f+l]).map((u,f)=>Math.floor((u-p[f]+o[f])/o[f]));return d.splice(0,0,i),d.splice(n?3:1,0,c),d},_i=[2,3,1,0],Cm=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");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],s=e[1].dims[1]*r.group;if(t!==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(r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},fi=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=gl(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,n=e.group,i=e.kernel_shape,a=e.pads,l=e.strides,c=e.w_is_const();return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,pads:a,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},Sl=(e,r,t,s)=>{let o=t.format==="NHWC",n=Pm(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,o);if(t.group!==1){let T=[r[0]];if(o){let x=e.kernelCustomData.wT??e.compute(os(r[1],_i),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=x),T.push(x)}else T.push(r[1]);r.length===3&&T.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(Em(T,t,n,s),{inputs:T}):e.compute(Tm(T,t,n,s),{inputs:T});return}let i=r.length===3,a=r[0].dims[o?1:2],l=r[0].dims[o?2:3],c=r[0].dims[o?3:1],p=r[1].dims[2],d=r[1].dims[3],u=n[o?1:2],f=n[o?2:3],_=n[o?3:1],b=o&&p===a&&d===l&&t.pads[0]===0&&t.pads[1]===0;if(b||p===1&&d===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 T=n[0],x,P,O,L=[];if(o){let R=e.kernelCustomData.wT??e.compute(os(r[1],_i),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=R),b){let te=a*l*c;x=r[0].reshape([1,T,te]),P=R.reshape([1,te,_]),O=[1,T,_]}else x=r[0].reshape([T,a*l,c]),P=R.reshape([1,c,_]),O=[T,u*f,_];L.push(x),L.push(P)}else x=r[0].reshape([T,c,a*l]),P=r[1].reshape([1,_,c]),O=[T,_,u*f],L.push(P),L.push(x);i&&L.push(r[2]);let G=O[2],K=L[0].dims[L[0].dims.length-1];G<8&&K<8?e.compute(Ml(L,t,n,O,o,s),{inputs:L}):e.compute(mi(L,t,n,O,o,s),{inputs:L});return}let k=!0,g=e.kernelCustomData.wT??e.compute(os(r[1],_i),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=g);let M=[r[0],g];i&&M.push(r[2]);let $=o?u*f:_,v=o?_:u*f,y=p*d*c;e.compute(wm(M,t,n,$,v,y,i,k,s),{inputs:M})},Sm=(e,r)=>{let t=r.format==="NHWC",s=[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&&s.push(e.inputs[2]);let o=[0,r.pads[0],0,r.pads[1]],n=[1].concat(r.strides),i=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=fi({...r,pads:o,strides:n,dilations:i,kernelShape:a},s);Sl(e,s,l,c=>t?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},$m=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",o=fi(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=vm(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(xm(r,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},$l=(e,r)=>{if(Cm(e.inputs,r),e.inputs[0].dims.length===3)Sm(e,r);else if(e.inputs[0].dims.length===5)$m(e,e.inputs,r);else{let t=fi(r,e.inputs);Sl(e,e.inputs,t)}}}),km,_x=Ve(()=>{gt(),Bs(),Et(),Pt(),km=(e,r,t)=>{let s=e.length>2,o=r.outputShape,n=r.format==="NHWC",i=r.group,a=e[1].dims,l=a[2]/i,c=a[3],p=n?or(l):1,d=n&&c===1&&l>=4,u=d?Math.floor(l/4)*4:Math.floor(l/p)*p,f=l-u,_=n?or(c):1,b=n?c===1?p:_:1,k=ye.size(o)/_,g=[Math.ceil(k/64),1,1];Dt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${g}`);let M=["rank","rank"],$=[r.strides[0],r.strides[1]],v=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],y=[r.dilations[0],r.dilations[1]],T=[v[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),v[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],x=[T[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),T[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],P=[{type:12,data:k},{type:12,data:$},{type:12,data:v},{type:12,data:y},{type:12,data:T},{type:6,data:x},{type:12,data:u},{type:12,data:l},{type:12,data:c},...ct(e[0].dims,e[1].dims)];s&&(P.push(...ct(e[2].dims)),M.push("rank")),P.push(...ct(o));let O=L=>{let G=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:$.length},{name:"filter_dims",type:"u32",length:v.length},{name:"dilations",type:"u32",length:v.length},{name:"effective_filter_dims",type:"u32",length:T.length},{name:"pads",type:"i32",length:x.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],K=Er(e[0].dataType),R=n?1:2,te=n?2:3,H=n?3:1,ee=$e("W",e[1].dataType,e[1].dims.length,b),Z=$e("Dy",e[0].dataType,e[0].dims.length,p),ne=[Z,ee];s&&ne.push($e("bias",e[2].dataType,[o[H]].length,_));let me=it("result",e[0].dataType,o.length,_),ue=()=>{let U="";if(d)p===4?U+=` + let xValue = ${Z.getByOffset("x_offset")}; + let wValue = ${ee.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue); + x_offset += 1u; + w_offset += 1u;`:p===2?U+=` + dotProd = dotProd + dot(vec4<${K}>(${Z.getByOffset("x_offset")}, ${Z.getByOffset("x_offset + 1u")}), vec4<${K}>(${ee.getByOffset("w_offset")}, ${ee.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;`:p===1&&(U+=` + dotProd = dotProd + dot(vec4<${K}>(${Z.getByOffset("x_offset")}, ${Z.getByOffset("x_offset + 1u")}, ${Z.getByOffset("x_offset + 2u")}, ${Z.getByOffset("x_offset + 3u")}), vec4<${K}>(${ee.getByOffset("w_offset")}, ${ee.getByOffset("w_offset + 1u")}, ${ee.getByOffset("w_offset + 2u")}, ${ee.getByOffset("w_offset + 3u")})); + x_offset += 4u; + w_offset += 4u;`);else if(U+=` + let xValue = ${n?Z.getByOffset(`${Z.indicesToOffset(`${Z.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):Z.get("batch","inputChannel","idyR","idyC")}; + `,p===1)U+=` + let w_offset = ${ee.indicesToOffset(`${ee.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${ee.getByOffset(`w_offset / ${b}`)}; + dotProd = dotProd + xValue * wValue;`;else for(let se=0;se{if(f===0)return"";if(!d)throw new Error(`packInputAs4 ${d} is not true.`);let U="";if(p===1){U+="dotProd = dotProd";for(let se=0;se(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 = ${me.type.value}(0.0); + var wR: u32 = 0; + if (uniforms.dilations.x == 1) { + // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 + wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); + } + for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${K}(dyRCorner) + ${K}(wR)) / ${K}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${K}(uniforms.Dy_shape[${R}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + var wC: u32 = 0; + if (uniforms.dilations.y == 1) { + // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 + wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); + } + for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${K}(dyCCorner) + ${K}(wC)) / ${K}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${K}(uniforms.Dy_shape[${te}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + ${d?` + var x_offset = ${Z.indicesToOffset(`${Z.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; + var w_offset = ${ee.indicesToOffset(`${ee.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${b}; + `:""} + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${d?4:p}) { + ${ue()} + inputChannel = inputChannel + ${d?4:p}; + } + ${j()} + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${s?` + bias[d1 / ${_}]`:""}; + ${me.setByOffset("global_idx","value")}; + `;return` + ${L.registerUniforms(G).declareVariables(...ne,me)} + ${L.mainStart()} + ${L.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${F}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${b}${_}${d}${f}`,inputDependencies:M},getRunData:()=>({dispatchGroup:{x:g[0],y:g[1],z:g[2]},outputs:[{dims:t?t(o):o,dataType:e[0].dataType}],programUniforms:P}),getShaderSource:O}}}),Im,Am,Fm,kl,Om,Dm,Il,Lm,zm,fx=Ve(()=>{_x(),fn(),Hs(),Im=(e,r,t,s,o,n)=>(e-1)*r+t+(s-1)*o+1-n,Am=(e,r,t,s,o)=>{let n=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=n,t[o]=e-n):r==="SAME_LOWER"&&(t[s]=e-n,t[o]=n)},Fm=(e,r,t,s,o,n,i,a,l,c)=>{let p=e.length-2,d=c.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((d,u)=>d*u,1)===0){t.length=0;for(let d=2;dd+u,0)===0){let d=r[0].dims.length-2;l=new Array(d).fill(1)}let c=e.strides.slice();if(c.reduce((d,u)=>d+u,0)===0){let d=r[0].dims.length-2;c=new Array(d).fill(1)}Fm(a,t,l,e.autoPad,e.group,o,c,s,i,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:o,outputPadding:i,outputShape:n,dilations:l,strides:c}),p},Om=e=>{let r=gl(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,n=e.group,i=e.kernelShape,a=e.pads,l=e.strides,c=e.wIsConst(),p=e.outputPadding,d=e.outputShape;return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,outputPadding:p,outputShape:d,pads:a,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},Dm=(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],s=e[1].dims[0];if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.reduce((i,a)=>i+a,0)>0&&r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.reduce((i,a)=>i+a,0)>0&&r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.reduce((i,a)=>i+a,0)>0&&r.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(r.outputPadding.length!==n&&r.outputPadding.length!==0)throw new Error(`output_padding should be ${n}D`);if(r.kernelShape.reduce((i,a)=>i+a,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")},Il=(e,r,t,s)=>{let o=e.kernelCustomData.wT??e.compute(os(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let n=[r[0],o];r.length===3&&n.push(r[2]),e.compute(km(n,t,s),{inputs:n})},Lm=(e,r)=>{let t=r.format==="NHWC",s=[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&&s.push(e.inputs[2]);let o=r.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let n=r.dilations;(n.length===0||n[0]===0)&&(n=[1]);let i=r.strides;(i.length===0||i[0]===0)&&(i=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],i=[1].concat(i),n=[1].concat(n),o=[1].concat(o);let l=r.outputPadding;l=[0].concat(l);let c=kl({...r,pads:a,strides:i,dilations:n,kernelShape:o,outputPadding:l},s);Il(e,s,c,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},zm=(e,r)=>{if(Dm(e.inputs,r),e.inputs[0].dims.length===3)Lm(e,r);else{let t=kl(r,e.inputs);Il(e,e.inputs,t)}}}),Bm,Rm,jm,gx=Ve(()=>{gt(),Et(),cr(),Pt(),Bm=(e,r,t,s)=>{let o=ye.size(r),n=r.length,i=$e("input",e,n),a=it("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),c=ye.normalizeAxis(l,n),p=d=>{let u=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,f=lt("uniforms.input_shape","uniforms.axis",n),_=s.reverse?u+(s.exclusive?" + 1":""):"0",b=s.reverse?f:u+(s.exclusive?"":" + 1");return` + ${d.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,a)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${a.offsetToIndices("global_idx")}; + var sum = ${a.type.value}(0); + let first : i32 = ${_}; + let last : i32 = ${b}; + for (var i : i32 = first; i < last; i++) { + ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${i.getByIndices("inputIndices")}; + } + ${a.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:c},...ct(r,r)]}),getShaderSource:p}},Rm=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,o=e.inputs[1];e.compute(Bm(s,t,o,r),{inputs:[0]})},jm=e=>{let r=e.exclusive===1,t=e.reverse===1;return Nt({exclusive:r,reverse:t})}}),Nm,Vm,Um,Wm,Gm,wx=Ve(()=>{gt(),Et(),cr(),Pt(),Nm=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.")},Vm=(e,r,t,s)=>{let o=[];o.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`);for(let n=0;n{let t,s,o,n,i,a,l=r.format==="NHWC",c=r.blocksize,p=r.mode==="DCR";l?([t,s,o,n]=e.dims,i=p?[t,s,o,c,c,n/c**2]:[t,s,o,n/c**2,c,c],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,o,n]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=p?[t,c,c,n/c**2,s,o]:[t,n/c**2,c,c,s,o],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(i),u=d.dims.length,f=e.dataType,_=$e("a",f,u),b=it("output",f,u),k=g=>` + ${g.registerUniform("output_size","u32").declareVariables(_,b)} + + ${Vm(a,u,_,b)} + + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${b.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${b.setByOffset("global_idx",_.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:g=>{let M=l?[t,s*c,o*c,n/c**2]:[t,n/c**2,s*c,o*c],$=ye.size(M),v=d.dims,y=ye.sortBasedOnPerm(v,a);return{outputs:[{dims:M,dataType:g[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:[{type:12,data:$},...ct(v,y)]}},getShaderSource:k}},Wm=(e,r)=>{Nm(e.inputs),e.compute(Um(e.inputs[0],r))},Gm=e=>Nt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),gi,bo,Al,Km,Hm,qm,Qm,Fl,Xm,Jm,Ym,Mx=Ve(()=>{gt(),Et(),cr(),Pt(),gi="[a-zA-Z]|\\.\\.\\.",bo="("+gi+")+",Al="^"+bo+"$",Km="("+bo+",)*"+bo,Hm="^"+Km+"$",qm=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,r){let t=this.symbolToIndices.get(e);t===void 0?t=[r]:t.push(r),this.symbolToIndices.set(e,t)}},Qm=class{constructor(e,r){var o;this.equation=r,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,s]=r.includes("->")?r.split("->",2):[r,""];if(!t.match(RegExp(Hm)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,i)=>{let a=e[i].dims.slice();if(!n.match(RegExp(Al)))throw new Error("Invalid LHS term");let l=this.processTerm(n,!0,a,i);this.lhs.push(l)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,i])=>i.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(bo)))throw new Error("Invalid RHS");(o=s.match(RegExp(gi,"g")))==null||o.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(n);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(e,r,t){let s=this.symbolToInfo.get(e);if(s!==void 0){if(s.dimValue!==r&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(t)}else s={count:1,dimValue:r,inputIndices:[t]};this.symbolToInfo.set(e,s)}processTerm(e,r,t,s=-1){let o=t.length,n=!1,i=[],a=0;if(!e.match(RegExp(Al))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(gi,"g")),c=new qm(s);return l==null||l.forEach((p,d)=>{if(p==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let u=o-l.length+1;if(u<0)throw new Error("Ellipsis out of bounds");if(i=t.slice(a,a+u),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let f=0;fe+"_max",Xm=(e,r,t,s)=>{let o=e.map(c=>c.length).map((c,p)=>$e(`input${p}`,r,c)),n=ye.size(s),i=it("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(c=>!t.rhs.symbolToIndices.has(c)),l=c=>{let p=[],d="var prod = 1.0;",u="var sum = 0.0;",f="sum += prod;",_=[],b=[],k=[],g=[],M=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((v,y)=>{var T;if(t.rhs.symbolToIndices.has(y)){let x=(T=t.rhs.symbolToIndices.get(y))==null?void 0:T[0];x!==void 0&&t.lhs.forEach((P,O)=>{if(v.inputIndices.includes(O)){let L=P.symbolToIndices.get(y);if(L===void 0)throw new Error("Invalid symbol error");L.forEach(G=>{p.push(`${o[O].indicesSet(`input${O}Indices`,G,i.indicesGet("outputIndices",x))}`)})}})}else t.lhs.forEach((x,P)=>{if(v.inputIndices.includes(P)){let O=x.symbolToIndices.get(y);if(O===void 0)throw new Error("Invalid symbol error");O.forEach(L=>{_.push(`${o[P].indicesSet(`input${P}Indices`,L,`${y}`)}`)}),g.push(`prod *= ${o[P].getByIndices(`input${P}Indices`)};`)}}),b.push(`for(var ${y}: u32 = 0; ${y} < uniforms.${Fl(y)}; ${y}++) {`),k.push("}")});let $=M?[...p,`let sum = ${o.map((v,y)=>v.getByIndices(`input${y}Indices`)).join(" * ")};`]:[...p,u,...b,..._,d,...g,f,...k];return` + ${c.registerUniforms(a.map(v=>({name:`${Fl(v)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${o.map((v,y)=>`var input${y}Indices: ${o[y].type.indices};`).join(` +`)} + ${$.join(` +`)}; + ${i.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let c=a.filter(d=>t.symbolToInfo.has(d)).map(d=>{var u;return{type:12,data:((u=t.symbolToInfo.get(d))==null?void 0:u.dimValue)||0}});c.push({type:12,data:n});let p=e.map((d,u)=>[...ct(d)]).reduce((d,u)=>d.concat(u),c);return p.push(...ct(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},Jm=(e,r)=>{let t=new Qm(e.inputs,r.equation),s=t.outputDims,o=e.inputs.map((n,i)=>n.dims);e.compute(Xm(o,e.inputs[0].dataType,t,s))},Ym=e=>{let r=e.equation.replace(/\s+/g,"");return Nt({equation:r})}}),Zm,Ol,e_,t_,r_,bx=Ve(()=>{gt(),Et(),Pt(),Zm=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),s=t.length{let t=e.length-r.length,s=[];for(let o=0;oe.length>r.length?Ol(e,r):Ol(r,e),t_=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=e_(r,t),o=e[0].dataType,n=o===9||ye.size(r)===1,i=o===9||r.length>0&&r[r.length-1]%4===0?4:1,a=n||s.length>0&&s[s.length-1]%4===0?4:1,l=Math.ceil(ye.size(s)/a),c=d=>{let u=$e("input",o,r.length,i),f=it("output",o,s.length,a),_;if(o===9){let b=(k,g,M="")=>` + let outputIndices${g} = ${f.offsetToIndices(`outputOffset + ${g}u`)}; + let offset${g} = ${u.broadcastedIndicesToOffset(`outputIndices${g}`,f)}; + let index${g} = offset${g} / 4u; + let component${g} = offset${g} % 4u; + ${k}[${g}] = ${M}(${u.getByOffset(`index${g}`)}[component${g}]); + `;_=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${b("data",0,"u32")} + ${b("data",1,"u32")} + ${b("data",2,"u32")} + ${b("data",3,"u32")} + ${f.setByOffset("global_idx","data")} + }`}else _=` + let outputIndices = ${f.offsetToIndices(`global_idx * ${a}`)}; + let inputOffset = ${u.broadcastedIndicesToOffset("outputIndices",f)}; + let data = ${f.type.value}(${u.getByOffset(`inputOffset / ${i}`)}); + ${f.setByOffset("global_idx","data")} + }`;return` + ${d.registerUniform("vec_size","u32").declareVariables(u,f)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${_}`},p=[{type:12,data:l},...ct(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${i}${a}`,inputDependencies:["rank"]},getShaderSource:c,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},r_=e=>{Zm(e.inputs),e.compute(t_(e.inputs),{inputs:[0]})}}),s_,n_,yx=Ve(()=>{gt(),Et(),Pt(),fl(),s_=e=>{let r=e[0].dataType,t=ye.size(e[0].dims),s=ye.size(e[1].dims),o=s%4===0,n=i=>{let a=$e("x",r,[1],4),l=$e("bias",r,[1],4),c=it("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],d=f=>` + let bias${f}_offset: u32 = (global_idx * 4 + ${f}) % uniforms.bias_size; + let bias${f} = ${l.getByOffset(`bias${f}_offset / 4`)}[bias${f}_offset % 4];`,u=o?` + let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${d(0)}${d(1)}${d(2)}${d(3)} + let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(p).declareVariables(a,l,c)} + + ${ml(Rr(r))} + + ${i.mainStart(Wn)} + ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${a.getByOffset("global_idx")}; + ${u} + let x_in = x + bias; + ${c.setByOffset("global_idx",_l("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:n,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/Wn/4)}})}},n_=e=>{e.inputs.length<2||ye.size(e.inputs[1].dims)===0?Bh(e):e.compute(s_(e.inputs))}}),o_,i_,a_,l_,vx=Ve(()=>{gt(),Et(),cr(),Pt(),o_=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},i_=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=ye.normalizeAxis(r.axis,o),i=t.slice(0);i.splice(n,1,...s);let a=t[n],l=e[0].dataType===9?4:1,c=Math.ceil(ye.size(i)/l),p=[{type:12,data:c},{type:6,data:a},{type:12,data:n},...ct(e[0].dims,e[1].dims,i)],d=u=>{let f=$e("data",e[0].dataType,e[0].dims.length,l),_=$e("inputIndices",e[1].dataType,e[1].dims.length),b=it("output",e[0].dataType,i.length,l),k=M=>{let $=s.length,v=`var indicesIndices${M} = ${_.type.indices}(0);`;for(let y=0;y<$;y++)v+=`${$>1?`indicesIndices${M}[${y}]`:`indicesIndices${M}`} = ${i.length>1?`outputIndices${M}[uniforms.axis + ${y}]`:`outputIndices${M}`};`;v+=` + var idx${M} = ${_.getByIndices(`indicesIndices${M}`)}; + if (idx${M} < 0) { + idx${M} = idx${M} + uniforms.axisDimLimit; + } + var dataIndices${M} : ${f.type.indices}; + `;for(let y=0,T=0;y1?`dataIndices${M}[${y}]`:`dataIndices${M}`} = u32(idx${M});`,T+=$):(v+=`${o>1?`dataIndices${M}[${y}]`:`dataIndices${M}`} = ${i.length>1?`outputIndices${M}[${T}]`:`outputIndices${M}`};`,T++);return v},g;if(e[0].dataType===9){let M=($,v,y="")=>` + let outputIndices${v} = ${b.offsetToIndices(`outputOffset + ${v}u`)}; + ${k(v)}; + let offset${v} = ${f.indicesToOffset(`dataIndices${v}`)}; + let index${v} = offset${v} / 4u; + let component${v} = offset${v} % 4u; + ${$}[${v}] = ${y}(${f.getByOffset(`index${v}`)}[component${v}]); + `;g=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${M("value",0,"u32")} + ${M("value",1,"u32")} + ${M("value",2,"u32")} + ${M("value",3,"u32")} + ${b.setByOffset("global_idx","value")} + `}else g=` + let outputIndices = ${b.offsetToIndices("global_idx")}; + ${k("")}; + let value = ${f.getByIndices("dataIndices")}; + ${b.setByOffset("global_idx","value")}; + `;return` + ${u.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(f,_,b)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${g} + }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:d}},a_=e=>Nt({axis:e.axis}),l_=(e,r)=>{let t=e.inputs;o_(t),e.compute(i_(e.inputs,r))}}),c_,u_,d_,xx=Ve(()=>{gt(),Et(),Pt(),c_=(e,r,t,s,o,n,i,a,l)=>{let c=[{type:12,data:n},{type:12,data:s},{type:12,data:o},{type:12,data:t},{type:12,data:i},{type:12,data:a},{type:12,data:l}],p=[n];c.push(...ct(r.dims,p));let d=u=>{let f=$e("indices_data",r.dataType,r.dims.length),_=it("input_slice_offsets_data",12,1,1),b=[f,_],k=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:t.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${u.registerUniforms(k).declareVariables(...b)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let batch_idx = global_idx / uniforms.num_slices_per_batch; + let base_offset = batch_idx * uniforms.input_batch_stride; + + let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; + var relative_slice_offset = 0; + for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { + var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); + let input_dim_idx = uniforms.batch_dims + dim_idx; + if (index < 0) { + ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${t.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:c}),getShaderSource:d},{inputs:[r],outputs:[-1]})[0]},u_=(e,r)=>{let t=e.inputs,s=t[0].dims,o=t[0].dataType,n=t[1].dims,i=n[n.length-1],a=ye.sizeToDimension(n,n.length-1),l=ye.sizeFromDimension(s,r.batchDims+i),c=ye.sizeToDimension(s,r.batchDims),p=ye.sizeFromDimension(s,r.batchDims),d=a/c,u=new Array(i),f=l;for(let v=0;vs.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let k=n.slice(0,-1).concat(s.slice(b)),g=ye.size(k),M=[{type:12,data:g},{type:12,data:l},...ct(t[0].dims,_.dims,k)],$=v=>{let y=$e("data",t[0].dataType,t[0].dims.length),T=$e("slice_offsets",12,_.dims.length),x=it("output",t[0].dataType,k.length);return` + ${v.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(y,T,x)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; + output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; + }`};e.compute({name:"GatherND",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:k,dataType:o}],dispatchGroup:{x:Math.ceil(g/64)},programUniforms:M}),getShaderSource:$},{inputs:[t[0],_]})},d_=e=>({batchDims:e.batch_dims,cacheKey:""})}),p_,h_,m_,__,Tx=Ve(()=>{gt(),Et(),cr(),Pt(),p_=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=ye.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,o=e[0],n=e[2],i=e.length===4?e[3]:void 0;if(n.dims.length!==o.dims.length||!o.dims.map((a,l)=>l===t?Math.ceil(a/s)===n.dims[l]:a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==n.dims.length||!i.dims.map((a,l)=>a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},h_=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=ye.normalizeAxis(r.gatherAxis,o),i=ye.normalizeAxis(r.quantizeAxis,o),a=t.slice(0);a.splice(n,1,...s);let l=ye.size(a),c=e[2].dataType,p=e[0].dataType===22,d=[{type:12,data:l},{type:12,data:i},{type:12,data:n},{type:12,data:r.blockSize},...ct(...e.map((f,_)=>f.dims),a)],u=f=>{let _=$e("data",e[0].dataType,e[0].dims.length),b=$e("inputIndices",e[1].dataType,e[1].dims.length),k=$e("scales",e[2].dataType,e[2].dims.length),g=e.length>3?$e("zeroPoint",e[3].dataType,e[3].dims.length):void 0,M=it("output",c,a.length),$=[_,b,k];g&&$.push(g);let v=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${f.registerUniforms(v).declareVariables(...$,M)} + ${f.mainStart()} + let output_indices = ${M.offsetToIndices("global_idx")}; + var indices_indices = ${b.type.indices}(0); + ${s.length>1?` + for (var i: u32 = 0; i < ${s.length}; i++) { + let index = ${M.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${b.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${M.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${_.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${M.indicesGet("output_indices","i")}; + ${_.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${b.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${t[n]}; + } + ${_.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${a.length}; i++) { + let index = ${M.indicesGet("output_indices",`i + ${s.length} - 1`)}; + ${_.indicesSet("data_indices","i","index")}; + } + let data_offset = ${_.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${_.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); + let quantized_data = quantized_data_vec[data_index / 2]; + var scale_indices = data_indices; + let quantize_axis_index = ${k.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${k.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${k.getByIndices("scale_indices")}; + ${g?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${g.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${g.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${Rr(c)}(quantized_data - zero_point) * scale; + ${M.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((f,_)=>_!==1).map(f=>f.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(f,_)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:c}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:u}},m_=(e,r)=>{let t=e.inputs;p_(t,r),e.compute(h_(e.inputs,r))},__=e=>Nt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),f_,g_,w_,M_,Ex=Ve(()=>{gt(),Et(),cr(),Pt(),f_=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.`)},g_=(e,r)=>{let t=e[0].dims,s=e[0].dataType,o=t.length,n=e[1].dims,i=e[1].dataType,a=ye.normalizeAxis(r.axis,o),l=t[a],c=n.slice(0),p=ye.size(c),d=$e("input",s,o),u=$e("indicesInput",i,n.length),f=it("output",s,c.length),_=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return _.push(...ct(t,n,c)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:_}),getShaderSource:b=>` + ${b.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,u,f)} + ${b.mainStart()} + ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${f.offsetToIndices("global_idx")}; + + var idx = ${u.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${d.type.indices}(outputIndices); + ${d.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${d.getByIndices("inputIndices")}; + + ${f.setByOffset("global_idx","value")}; + }`}},w_=e=>Nt({axis:e.axis}),M_=(e,r)=>{let t=e.inputs;f_(t),e.compute(g_(e.inputs,r))}}),b_,y_,v_,x_,Px=Ve(()=>{gt(),Et(),Pt(),b_=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")},y_=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[o,n,i]=Ad.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[o,n];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,c=Math.ceil(n/l),p=Math.ceil(o/l),d=!0,u=ye.size(a),f=[{type:12,data:d?c:u},{type:12,data:o},{type:12,data:n},{type:12,data:i},{type:1,data:r.alpha},{type:1,data:r.beta}],_=["type","type"];e.length===3&&(f.push(...ct(e[2].dims)),_.push("rank")),f.push(...ct(a));let b=g=>{let M="";r.transA&&r.transB?M="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?M="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?M="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(M="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let $=r.alpha===1?"":"value *= uniforms.alpha;",v=$e("a",e[0].dataType,e[0].dims),y=$e("b",e[1].dataType,e[1].dims),T=v.type.value,x=null,P=[v,y];e.length===3&&(x=$e("c",e[2].dataType,e[2].dims.length),P.push(x));let O=it("output",e[0].dataType,a.length);P.push(O);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` + ${g.registerUniforms(L).declareVariables(...P)} + + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${T}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${M} + } + + ${$} + ${x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",O)}; value += ${T}(uniforms.beta) * ${x.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},k=g=>{let M=$e("a",e[0].dataType,e[0].dims),$=$e("b",e[1].dataType,e[1].dims),v=null,y=[M,$];e.length===3&&(v=$e("c",e[2].dataType,e[2].dims.length),y.push(v));let T=it("output",e[0].dataType,a.length);y.push(T);let x=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],P="",O="";r.transA&&r.transB?(O=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${M.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${$.type.value}(0); + } + `,P="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(O=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${M.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${$.type.value}(0); + } + `,P="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(O=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${M.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${$.type.value}(0); + } + `,P="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(O=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${M.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${$.type.value}(0); + } + `,P="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let L=r.alpha===1?"":"value *= uniforms.alpha;";return` + ${g.registerUniforms(x).declareVariables(...y)} + var tile_a: array, ${l}>; + var tile_b: array, ${l}>; + ${g.mainStart([l,l,1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${l}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${l}; + let num_tiles = (uniforms.K - 1) / ${l} + 1; + var k_start = 0u; + var value = ${T.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${O} + k_start = k_start + ${l}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${l}; k++) { + ${P} + } + workgroupBarrier(); + } + + ${L} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${v!=null?`let cOffset = ${v.broadcastedIndicesToOffset("vec2(m, n)",T)}; value += ${T.type.value}(uniforms.beta) * ${v.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return d?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:c*p},programUniforms:f}),getShaderSource:k}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:b}},v_=e=>{let r=e.transA,t=e.transB,s=e.alpha,o=e.beta;return{transA:r,transB:t,alpha:s,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},x_=(e,r)=>{b_(e.inputs),e.compute(y_(e.inputs,r))}}),Is,Rs,gn,wn,T_,E_,P_,C_,S_,$_,k_,I_,A_,F_,Cx=Ve(()=>{gt(),Et(),cr(),Pt(),[Is,Rs,gn,wn]=[0,1,2,3],T_=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},E_=` + fn gs_get_cubic_coeffs(x: f32) -> vec4 { + let cubic_alpha = -0.75f; + let x_abs = abs(x); + var coeffs: vec4; + coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha); + coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1); + coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1); + coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); + return coeffs; + } +`,P_=e=>` + fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { + var v: vec4; + var coeffs = gs_get_cubic_coeffs(x); + for (var i = 0; i < 4; i++) { + v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3]; + } + coeffs = gs_get_cubic_coeffs(y); + let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); + return pixel; + } +`,C_=e=>` + fn gs_denormalize(n: f32, length: i32) -> f32 { + ${e.alignCorners===0?` + // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] + return ((n + 1.0) * f32(length) - 1.0) / 2.0; + `:` + // alignCorners: true => [-1, 1] to [0, length - 1] + return (n + 1.0) / 2.0 * (f32(length - 1)); + `} + } +`,S_=e=>` + ${e.paddingMode==="reflection"?` + fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { + var dx = 0.0; + var fx = f32(x); + let range = x_max - x_min; + if (fx < x_min) { + dx = x_min - fx; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_min + r; + } else { + fx = x_max - r; + } + } else if (fx > x_max) { + dx = fx - x_max; + let n = u32(dx / range); + let r = dx - f32(n) * range; + if (n % 2 == 0) { + fx = x_max - r; + } else { + fx = x_min + r; + } + } + return u32(fx); + }`:""} +`,$_=(e,r,t)=>` + fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${r} { + var pixel = ${r}(0); + var indices = vec4(0); + indices[${Is}] = batch; + indices[${Rs}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${gn}] = u32(r); + indices[${wn}] = u32(c); + } else { + return ${r}(0); + } + `;case"border":return` + indices[${gn}] = u32(clamp(r, 0, H - 1)); + indices[${wn}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${gn}] = gs_reflect(r, border[1], border[3]); + indices[${wn}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,k_=(e,r,t)=>(()=>{switch(t.mode){case"nearest":return` + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Is}], indices[${Rs}], border); + `;case"bilinear":return` + let x1 = i32(floor(x)); + let y1 = i32(floor(y)); + let x2 = x1 + 1; + let y2 = y1 + 1; + + let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${Is}], indices[${Rs}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Is}], indices[${Rs}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Is}], indices[${Rs}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Is}], indices[${Rs}], border); + + let dx2 = ${r}(f32(x2) - x); + let dx1 = ${r}(x - f32(x1)); + let dy2 = ${r}(f32(y2) - y); + let dy1 = ${r}(y - f32(y1)); + let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); + `;case"bicubic":return` + let x0 = i32(floor(x)) - 1; + let y0 = i32(floor(y)) - 1; + var p: mat4x4<${r}>; + for (var h = 0; h < 4; h++) { + for (var w = 0; w < 4; w++) { + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Is}], indices[${Rs}], border); + } + } + + let dx = x - f32(x0 + 1); + let dy = y - f32(y0 + 1); + let result = gs_bicubic_interpolate(p, dx, dy); + `;default:throw new Error(`mode ${t.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,I_=(e,r)=>{let t=$e("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=$e("grid",e[1].dataType,s.length,2),n=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];r.format==="NHWC"&&(n=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[Is,Rs,gn,wn]=[0,3,1,2]);let i=it("output",e[0].dataType,n.length),a=t.type.value,l=ye.size(n),c=[{type:12,data:l},...ct(e[0].dims,s,n)],p=d=>` + ${d.registerUniform("output_size","u32").declareVariables(t,o,i)} + ${E_} + ${P_(a)} + ${C_(r)} + ${S_(r)} + ${$_(t,a,r)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${gn}]); + let W_in = i32(uniforms.x_shape[${wn}]); + + ${r.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${i.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${Is}], indices[${gn}], indices[${wn}]); + let nxy = ${o.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${k_(i,a,r)} + }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:d=>{let u=ye.size(n);return{outputs:[{dims:n,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}},getShaderSource:p}},A_=(e,r)=>{T_(e.inputs),e.compute(I_(e.inputs,r))},F_=e=>Nt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Qr,O_,D_,Dl,L_,yo,z_,B_=Ve(()=>{gt(),Et(),cr(),tl(),pl(),Pt(),Hs(),Qr=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,O_=(e,r)=>{let t=e[0],s=Qr(e,1),o=Qr(e,2),n=Qr(e,3),i=Qr(e,4),a=Qr(e,5),l=Qr(e,6),c=Qr(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 p=t.dims[0],d=t.dims[1],u=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],f=d,_=0,b=0,k=Math.floor(u/r.numHeads);if(l&&c&&ye.size(l.dims)&&ye.size(c.dims)){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==p||l.dims[1]!==r.numHeads||l.dims[3]!==k)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==p||c.dims[1]!==r.numHeads||c.dims[3]!==k)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');_=l.dims[2],b=l.dims[2]}else if(l&&ye.size(l.dims)||c&&ye.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let g;if(s&&ye.size(s.dims)>0){if(t.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(t.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]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');g=2,f=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==k)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.');g=5,f=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==k)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');g=0,f=s.dims[2]}}else{if(t.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(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');g=3}if(n&&ye.size(n.dims)>0){if(n.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let M=_+f,$=0;if(i&&ye.size(i.dims)>0){$=8;let x=i.dims;throw x.length===1?x[0]===p?$=1:x[0]===3*p+2&&($=3):x.length===2&&x[0]===p&&x[1]===M&&($=5),$===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let v=!1,y=u;if(o&&ye.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.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(f!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');y=o.dims[2]}else{if(f!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');y=o.dims[1]*o.dims[3],v=!0}}let T=!1;if(i&&ye.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(a&&ye.size(a.dims)>0){if(a.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(a.dims[0]!==p||a.dims[1]!==r.numHeads||a.dims[2]!==d||a.dims[3]!==M)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:d,pastSequenceLength:_,kvSequenceLength:f,totalSequenceLength:M,maxSequenceLength:b,inputHiddenSize:0,hiddenSize:u,vHiddenSize:y,headSize:k,vHeadSize:Math.floor(y/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:$,scale:r.scale,broadcastResPosBias:T,passPastInKv:v,qkvFormat:g}},D_=e=>Nt({...e}),Dl=Nt({perm:[0,2,1,3]}),L_=(e,r,t,s,o,n,i)=>{let a=[s,o,n],l=ye.size(a),c=[{type:12,data:l},{type:12,data:i},{type:12,data:n}],p=d=>{let u=it("qkv_with_bias",r.dataType,a),f=$e("qkv",r.dataType,a),_=$e("bias",t.dataType,a),b=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${d.registerUniforms(b).declareVariables(f,_,u)} + ${d.mainStart()} + ${d.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:a,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},yo=(e,r,t,s,o,n,i,a)=>{let l=n;if(i&&ye.size(i.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=L_(e,n,i,r,s,t*o,a),l=l.reshape([r,s,t,o]),t===1||s===1?l:e.compute(os(l,Dl.perm),{inputs:[l],outputs:[-1]})[0]}else return n.dims.length===3&&(l=n.reshape([r,s,t,o])),t===1||s===1?l:e.compute(os(l,Dl.perm),{inputs:[l],outputs:[-1]})[0]},z_=(e,r)=>{let t=O_(e.inputs,r),s=e.inputs[0],o=Qr(e.inputs,1),n=Qr(e.inputs,2),i=Qr(e.inputs,3),a=Qr(e.inputs,4),l=Qr(e.inputs,5),c=Qr(e.inputs,6),p=Qr(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((o==null?void 0:o.dims.length)===5)throw new Error("Packed KV is not implemented");let d=o&&n&&o.dims.length===4&&n.dims.length===4,u=yo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(d)return fo(e,u,o,n,a,void 0,c,p,l,t);if(!o||!n)throw new Error("key and value must be provided");let f=yo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,o,i,t.hiddenSize),_=yo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,i,2*t.hiddenSize);fo(e,u,f,_,a,void 0,c,p,l,t)}}),R_,j_,N_,V_,Ll,U_,W_,G_=Ve(()=>{gt(),Et(),cr(),Pt(),R_=e=>{if(!e||e.length<1)throw new Error("too few inputs")},j_=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>t.push(Number(o))),s=t.length),Nt({numOutputs:s,axis:r.axis,splitSizes:t})},N_=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${lt("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,V_=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=ye.size(t),o=e[0].dataType,n=ye.normalizeAxis(r.axis,t.length),i=new Array(r.numOutputs),a=$e("input",o,t.length),l=new Array(r.numOutputs),c=[],p=[],d=0,u=[{type:12,data:s}];for(let _=0;_` + ${_.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...i)} + ${N_(l.length)} + ${V_(i)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${a.offsetToIndices("global_idx")}; + var index = ${a.indicesGet("indices",n)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${lt("uniforms.size_in_split_axis","output_number - 1u",l.length)}; + ${a.indicesSet("indices",n,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:f,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:u})}},U_=(e,r)=>{R_(e.inputs);let t=e.inputs.length===1?r:j_(e.inputs,r);e.compute(Ll(e.inputs,t),{inputs:[0]})},W_=e=>{let r=e.axis,t=e.splitSizes,s=e.numOutputs<0?t.length:e.numOutputs;if(s!==t.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Nt({axis:r,numOutputs:s,splitSizes:t})}}),K_,wi,H_,q_=Ve(()=>{gt(),Et(),cr(),Pt(),K_=(e,r)=>{let[t,s,o,n]=e,{numHeads:i,rotaryEmbeddingDim:a}=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(!ye.areEqual(s.dims,[])&&!ye.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(n.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(!ye.areEqual(o.dims,n.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],c=t.dims[t.dims.length-2],p=o.dims[0],d=ye.sizeFromDimension(t.dims,1)/c,u=a===0?o.dims[1]*2:d/i;if(a>u)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(l!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(c!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(u/2!==o.dims[1]&&a/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(c>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},wi=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:o,scale:n}=r,i=e[0].dims[0],a=ye.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],c=a/l,p=e[2].dims[1],d=o===0?p*2:c/s,u=new Array(i,l,c/d,d-p),f=ye.computeStrides(u),_=[{type:1,data:n},{type:12,data:u},{type:12,data:f},...e[0].dims.length===3?new Array({type:12,data:[a,c,d,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,d,l*d,1]}):[],...ct(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],b=k=>{let g=$e("input",e[0].dataType,e[0].dims.length),M=$e("position_ids",e[1].dataType,e[1].dims.length),$=$e("cos_cache",e[2].dataType,e[2].dims.length),v=$e("sin_cache",e[3].dataType,e[3].dims.length),y=it("output",e[0].dataType,e[0].dims.length);return k.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:f.length},{name:"input_output_strides",type:"u32",length:f.length}]),` + ${k.declareVariables(g,M,$,v,y)} + + ${k.mainStart(Wn)} + let half_rotary_emb_dim = uniforms.${$.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${k.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${M.broadcastedIndicesToOffset("bsnh.xy",it("",M.type.tensor,2))}; + let position_id = + u32(${M.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${t}); + let j = i + select(half_rotary_emb_dim, 1, ${t}); + let re = ${g.getByOffset("i")} * ${$.get("position_id","bsnh[3]")} - + ${g.getByOffset("j")} * ${v.get("position_id","bsnh[3]")}; + ${y.setByOffset("i","re")} + let im = ${g.getByOffset("i")} * ${v.get("position_id","bsnh[3]")} + + ${g.getByOffset("j")} * ${$.get("position_id","bsnh[3]")}; + ${y.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${y.setByOffset("k",g.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Nt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:b,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ye.size(u)/Wn)},programUniforms:_})}},H_=(e,r)=>{K_(e.inputs,r),e.compute(wi(e.inputs,r))}}),Q_,X_,zl,J_,Y_,Sx=Ve(()=>{cr(),gt(),pl(),B_(),G_(),Hs(),q_(),Pt(),Q_=(e,r)=>{if(r.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let t=e[0],s=e[1],o=e[2],n=e[3],i=e[4];if(r.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(r.localWindowSize!==-1)throw new Error("Local attention is not supported");if(r.softcap!==0)throw new Error("Softcap is not supported");if(r.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(r.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let a=!1,l=t.dims[0],c=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],d=c,u=0,f=!s||s.dims.length===0,_=Math.floor(f?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);f&&(p=_*r.numHeads);let b=n&&n.dims.length!==0,k=i&&i.dims.length!==0;if(b&&n.dims.length===4&&n.dims[0]===l&&n.dims[1]!==r.kvNumHeads&&n.dims[2]===r.kvNumHeads&&n.dims[3]===_)throw new Error("BSNH pastKey/pastValue is not supported");if(b&&k){if(n.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');u=n.dims[2]}else if(b||k)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let g=1;if(s&&s.dims.length>0){if(t.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(t.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(t.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');d=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==_)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.');d=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=s.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');g=3}let M=0,$=!1,v=r.kvNumHeads?_*r.kvNumHeads:p;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.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(d!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');v=o.dims[2]}else{if(d!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');v=o.dims[1]*o.dims[3],$=!0}}let y=e.length>4?e[5]:void 0;if(y&&y.dims.length!==1&&y.dims[0]!==l)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:l,sequenceLength:c,pastSequenceLength:u,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:v,headSize:_,vHeadSize:Math.floor(v/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:M,scale:r.scale,broadcastResPosBias:!1,passPastInKv:$,qkvFormat:g}},X_=Nt({perm:[0,2,1,3]}),zl=(e,r,t)=>{let s=r,o=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,o,t.headSize]),s=e.compute(os(s,X_.perm),{inputs:[s],outputs:[-1]})[0]),s},J_=(e,r,t,s)=>{let o=7,n=["type","type"],i=[e*r],a=e*r,l=[{type:12,data:a},{type:12,data:r},{type:12,data:e}],c=p=>{let d=$e("seq_lens",t.dataType,t.dims),u=$e("total_seq_lens",s.dataType,s.dims),f=it("pos_ids",o,i),_=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` + ${p.registerUniforms(_).declareVariables(d,u,f)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let total_sequence_length = u32(${u.getByOffset("0")}); + let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length; + let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length; + let batch_idx = global_idx / uniforms.sequence_length; + let sequence_idx = i32(global_idx % uniforms.sequence_length); + var pos_id: i32 = 0; + let seqlen = ${d.getByOffset("batch_idx")}; + let total_seqlen = seqlen + 1; + if (is_first_prompt) { + if (sequence_idx < total_seqlen) { + pos_id = sequence_idx; + } else { + pos_id = 1; + } + ${f.setByOffset("global_idx","pos_id")} + } else if (is_subsequent_prompt) { + let past_seqlen = total_seqlen - i32(uniforms.sequence_length); + if (past_seqlen + sequence_idx < total_seqlen) { + pos_id = past_seqlen + sequence_idx; + } else { + pos_id = 1; + } + ${f.setByOffset("global_idx","pos_id")} + } else if (global_idx < uniforms.batch_size) { + ${f.setByOffset("global_idx","seqlen")} + }; + } + `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${r}`,inputDependencies:n},getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:c}},Y_=(e,r)=>{var v;let t=Q_(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((v=e.inputs[1])==null?void 0:v.dims.length)===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,n=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,i=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,c=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,d=Nt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[u,f,_]=!o&&!n?e.compute(Ll([s],d),{inputs:[s],outputs:[-1,-1,-1]}):[s,o,n],b,k;if(r.doRotary){let y=e.compute(J_(t.batchSize,t.sequenceLength,l,c),{inputs:[l,c],outputs:[-1]})[0],T=e.inputs[7],x=e.inputs[8],P=Nt({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),O=[u,y,T,x],L=[-1];b=e.compute(wi(O,P),{inputs:O,outputs:L})[0],O.splice(0,1,f);let G=Nt({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});k=e.compute(wi(O,G),{inputs:O,outputs:L})[0]}let g=yo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?b:u,void 0,0),M=zl(e,r.doRotary?k:f,t),$=zl(e,_,t);fo(e,g,M,$,void 0,void 0,i,a,void 0,t,l,c)}}),Bl,Z_,ef,tf,$x=Ve(()=>{gt(),Et(),Hs(),Pt(),Bl=(e,r,t,s,o,n,i,a)=>{let l=or(n),c=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,d=o*i,u=64;d===1&&(u=256);let f=[o,i,n/l],_=[o,i,2],b=["rank","type","type"],k=[];k.push(...ct(f,_));let g=M=>{let $=$e("x",r.dataType,3,l),v=$e("scale",t.dataType,t.dims),y=$e("bias",s.dataType,s.dims),T=it("output",1,3,2),x=[$,v,y,T];return` + var workgroup_shared : array<${p}, ${u}>; + const workgroup_size = ${u}u; + ${M.declareVariables(...x)} + ${M.mainStart(u)} + let batch = workgroup_index / uniforms.x_shape[1]; + let channel = workgroup_index % uniforms.x_shape[1]; + let hight = uniforms.x_shape[2]; + // initialize workgroup memory + var sum = ${c}(0); + var squared_sum = ${c}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${c}(${$.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${p}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${Ks("workgroup_shared[0][0]",l)} / f32(hight * ${l}); + let squared_sum_final = ${Ks("workgroup_shared[0][1]",l)} / f32(hight * ${l}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${a})); + let channel_scale = inv_std_dev * f32(scale[channel]); + let channel_shift = f32(bias[channel]) - sum_final * channel_scale; + output[workgroup_index] = vec2f(channel_scale, channel_shift); + } + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${a};${u}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:_,dataType:1}],dispatchGroup:{x:d},programUniforms:k}),getShaderSource:g},{inputs:[r,t,s],outputs:[-1]})[0]},Z_=(e,r,t)=>{let s=r[0].dims,o=s,n=2,i=s[0],a=s[1],l=ye.sizeFromDimension(s,n),c=or(l),p=ye.size(o)/c,d=Bl(e,r[0],r[1],r[2],i,l,a,t.epsilon),u=[i,a,l/c],f=[i,a],_=["type","none"],b=k=>{let g=$e("x",r[0].dataType,u.length,c),M=$e("scale_shift",1,f.length,2),$=it("output",r[0].dataType,u.length,c),v=[g,M,$];return` + ${k.registerUniform("output_size","u32").declareVariables(...v)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${$.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${M.getByIndices("vec2(batch, channel)")}; + let value = ${g.getByOffset("global_idx")} * ${$.type.value}(scale_shift.x) + ${$.type.value}(scale_shift.y); + ${$.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${c}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...ct(u,f,u)]}),getShaderSource:b},{inputs:[r[0],d]})},ef=(e,r,t)=>{let s=r[0].dims,o=s,n=s[0],i=s[s.length-1],a=ye.sizeFromDimension(s,1)/i,l=or(i),c=ye.size(o)/l,p=[{type:12,data:a},{type:12,data:Math.floor(i/l)}],d=["type","type"],u=!1,f=[0,s.length-1];for(let g=0;gs[f[M]])),b=Bl(e,_,r[1],r[2],n,a,i,t.epsilon),k=g=>{let M=Er(r[0].dataType),$=l===1?"vec2f":`mat${l}x2f`,v=x=>{let P=x===0?"x":"y",O=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${M}(${O}(scale.${P}))`;case 2:return`vec2<${M}>(${O}(scale[0].${P}, scale[1].${P}))`;case 4:return`vec4<${M}>(${O}(scale[0].${P}, scale[1].${P}, scale[2].${P}, scale[3].${P}))`;default:throw new Error(`Not supported compoents ${l}`)}},y=$e("input",r[0].dataType,r[0].dims,l),T=it("output",r[0].dataType,o,l);return` + @group(0) @binding(0) var input : array<${y.type.storage}>; + @group(0) @binding(1) var scale_input : array<${$}>; + @group(0) @binding(2) var output : array<${T.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${g.mainStart()} + let current_image_number = global_idx / (uniforms.C * uniforms.H); + let current_channel_number = global_idx % uniforms.C; + + let scale_offset = current_image_number * uniforms.C + current_channel_number; + let scale = scale_input[scale_offset]; + output[global_idx] = fma(input[global_idx], ${v(0)}, ${v(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:k},{inputs:[r[0],b]})},tf=(e,r)=>{r.format==="NHWC"?ef(e,e.inputs,r):Z_(e,e.inputs,r)}}),rf,sf,nf,kx=Ve(()=>{gt(),Et(),Pt(),rf=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},sf=(e,r,t)=>{let s=r.simplified,o=e[0].dims,n=e[1],i=!s&&e[2],a=o,l=ye.normalizeAxis(r.axis,o.length),c=ye.sizeToDimension(o,l),p=ye.sizeFromDimension(o,l),d=ye.size(n.dims),u=i?ye.size(i.dims):0;if(d!==p||i&&u!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. + Size of scale and bias (if provided) must match this. + Got scale size of ${d} and bias size of ${u}`);let f=[];for(let y=0;y1,M=t>2,$=y=>{let T=Er(e[0].dataType),x=[$e("x",e[0].dataType,e[0].dims,_),$e("scale",n.dataType,n.dims,_)];i&&x.push($e("bias",i.dataType,i.dims,_)),x.push(it("output",e[0].dataType,a,_)),g&&x.push(it("mean_data_output",1,f)),M&&x.push(it("inv_std_output",1,f));let P=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${y.registerUniforms(P).declareVariables(...x)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${ol("f32",_)}; + var mean_square_vector = ${ol("f32",_)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Gn(T,_,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Ks("mean_vector",_)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Ks("mean_square_vector",_)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Gn(T,_,"x[j + offset]")}; + let f32scale = ${Gn(T,_,"scale[j]")}; + output[j + offset] = ${x[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${Gn(T,_,"bias[j]")}`:""} + ); + } + + ${g?"mean_data_output[global_idx] = mean":""}; + ${M?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},v=[{dims:a,dataType:e[0].dataType}];return g&&v.push({dims:f,dataType:1}),M&&v.push({dims:f,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${t};${s}`,inputDependencies:b},getRunData:()=>({outputs:v,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:k}),getShaderSource:$}},nf=(e,r)=>{rf(e.inputs),e.compute(sf(e.inputs,r,e.outputCount))}}),of,af,Ix=Ve(()=>{Et(),bl(),Tl(),of=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.")},af=e=>{of(e.inputs);let r=Un.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],s=e.inputs[0].dims[e.inputs[0].dims.length-1];if(t<8&&s<8)e.compute(Ml(e.inputs,{activation:""},r));else{let o=r[r.length-2],n=ye.size(e.inputs[0].dims.slice(0,-2)),i=ye.size(e.inputs[1].dims.slice(0,-2));if(n!==1&&o===1&&i===1){let a=e.inputs[0].reshape([1,n,s]),l=e.inputs[1].reshape([1,s,t]),c=[1,n,t],p=[a,l];e.compute(mi(p,{activation:""},r,c),{inputs:p})}else e.compute(mi(e.inputs,{activation:""},r))}}}),lf,cf,uf,df,pf,Ax=Ve(()=>{gt(),Et(),cr(),Pt(),lf=(e,r)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=e[0],s=t.dims.length;if(t.dims[s-1]!==r.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((r.k+r.blockSize-1)/r.blockSize),n=r.blockSize/8*r.bits,i=e[1];if(!ye.areEqual(i.dims,[r.n,o,n]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(ye.size(a)!==r.n*o)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,c=r.bits>4?r.n*o:r.n*Math.floor((o+1)/2);if(ye.size(l)!==c)throw new Error("zeroPoints input size error.")}},cf=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=ye.size(a),c=e[1].dims[2]/4,p=e[0].dataType,d=or(r.k),u=or(c),f=or(i),_=a.concat([o,i]),b=o>1&&i/f%2===0?2:1,k=ye.size(_)/f/b,g=64,M=[],$=[l,o,n/d],v=ye.convertShape(e[1].dims).slice();v.splice(-1,1,c/u),M.push(...ct($)),M.push(...ct(v)),M.push(...ct(e[2].dims)),e.length===4&&M.push(...ct(ye.convertShape(e[3].dims)));let y=[l,o,i/f];M.push(...ct(y));let T=x=>{let P=$.length,O=$e("a",e[0].dataType,P,d),L=$e("b",12,v.length,u),G=$e("scales",e[2].dataType,e[2].dims.length),K=[O,L,G],R=e.length===4?$e("zero_points",12,e[3].dims.length):void 0;R&&K.push(R);let te=y.length,H=it("output",e[0].dataType,te,f),ee=Er(e[0].dataType),Z=(()=>{switch(d){case 1:return`array<${ee}, 8>`;case 2:return`mat4x2<${ee}>`;case 4:return`mat2x4<${ee}>`;default:throw new Error(`${d}-component is not supported.`)}})(),ne=()=>{let j=` + // reuse a data + var input_offset = ${O.indicesToOffset(`${O.type.indices}(batch, row, word_offset)`)}; + var a_data: ${Z}; + for (var j: u32 = 0; j < ${8/d}; j++) { + a_data[j] = ${O.getByOffset("input_offset")}; + input_offset++; + } + `;for(let F=0;F> 4) & b_mask); + b_quantized_values = ${Z}(${Array.from({length:4},(U,se)=>`${ee}(b_value_lower[${se}]), ${ee}(b_value_upper[${se}])`).join(", ")}); + b_dequantized_values = ${d===1?`${Z}(${Array.from({length:8},(U,se)=>`(b_quantized_values[${se}] - ${R?`zero_point${F}`:"zero_point"}) * scale${F}`).join(", ")});`:`(b_quantized_values - ${Z}(${Array(8).fill(`${R?`zero_point${F}`:"zero_point"}`).join(",")})) * scale${F};`}; + workgroup_shared[local_id.x * ${b} + ${Math.floor(F/f)}]${f>1?`[${F%f}]`:""} += ${Array.from({length:8/d},(U,se)=>`${d===1?`a_data[${se}] * b_dequantized_values[${se}]`:`dot(a_data[${se}], b_dequantized_values[${se}])`}`).join(" + ")}; + `;return j},me=()=>{let j=` + var col_index = col * ${f}; + ${R?` + let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; + var zero_point_byte_count: u32; + var zero_point_word_index: u32; + var zero_point_byte_offset: u32; + let zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32; + var zero_point_word: u32;`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${ee}(8);`} + `;for(let F=0;F> 0x1u); + zero_point_word_index = zero_point_byte_count >> 0x2u; + zero_point_byte_offset = zero_point_byte_count & 0x3u; + zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + zero_point_word = ${R.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${F} = ${ee}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return j},ue=()=>{let j=`col_index = col * ${f};`;for(let F=0;F; + var b_value_upper: vec4; + var b_quantized_values: ${Z}; + var b_dequantized_values: ${Z};`,j};return` + var workgroup_shared: array<${H.type.value}, ${b*g}>; + ${x.declareVariables(...K,H)} + ${x.mainStart([g,1,1])} + let output_indices = ${H.offsetToIndices(`(global_idx / ${g}) * ${b}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let nBlocksPerCol = uniforms.b_shape[1]; + + for (var block = local_id.x; block < nBlocksPerCol; block += ${g}) { + //process one block + var word_offset: u32 = block * ${r.blockSize/d}; + ${me()} + for (var word: u32 = 0; word < ${c}; word += ${u}) { + ${ue()} + for (var i: u32 = 0; i < ${u}; i++) { + ${ne()} + word_offset += ${8/d}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${b}) { + var output_value: ${H.type.value} = ${H.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${g}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${b}; + } + ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${d};${u};${f};${b};${g}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:k},programUniforms:M}),getShaderSource:T}},uf=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=ye.size(a),c=e[1].dims[2]/4,p=e[0].dataType,d=or(r.k),u=or(c),f=a.concat([o,i]),_=128,b=i%8===0?8:i%4===0?4:1,k=_/b,g=k*u*8,M=g/d,$=g/r.blockSize,v=ye.size(f)/b,y=[],T=[l,o,n/d],x=ye.convertShape(e[1].dims).slice();x.splice(-1,1,c/u),y.push(...ct(T)),y.push(...ct(x)),y.push(...ct(e[2].dims)),e.length===4&&y.push(...ct(ye.convertShape(e[3].dims)));let P=[l,o,i];y.push(...ct(P));let O=L=>{let G=T.length,K=$e("a",e[0].dataType,G,d),R=$e("b",12,x.length,u),te=$e("scales",e[2].dataType,e[2].dims.length),H=[K,R,te],ee=e.length===4?$e("zero_points",12,e[3].dims.length):void 0;ee&&H.push(ee);let Z=P.length,ne=it("output",e[0].dataType,Z),me=Er(e[0].dataType),ue=()=>{switch(d){case 1:return` + let a_data0 = vec4<${me}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${me}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` + let a_data0 = vec4<${me}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${me}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` + let a_data0 = sub_a[word_offset]; + let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${d}-component is not supported.`)}};return` + var sub_a: array<${K.type.value}, ${M}>; + var inter_results: array, ${b}>; + ${L.declareVariables(...H,ne)} + ${L.mainStart([k,b,1])} + let output_indices = ${ne.offsetToIndices(`workgroup_index * ${b}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let n_blocks_per_col = uniforms.b_shape[1]; + let num_tiles = (n_blocks_per_col - 1) / ${$} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${M}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${M}; a_offset += ${_}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${K.getByIndices(`${K.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${K.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${$} + local_id.x; + ${ee?` + let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; + let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); + let zero_point_word_index = zero_point_byte_count >> 0x2u; + let zero_point_byte_offset = zero_point_byte_count & 0x3u; + let zero_point_nibble_offset: u32 = block & 0x1u; + let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + let zero_point_word = ${ee.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${me}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${me}(8);`} + let scale = ${te.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${R.getByIndices(`${R.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${r.blockSize/d}; + for (var i: u32 = 0; i < ${u}; i++) { + ${ue()} + let b_value = ${u===1?"b_data":"b_data[i]"}; + let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); + let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); + let b_quantized_values = mat2x4<${me}>(${Array.from({length:4},(j,F)=>`${me}(b_value_lower[${F}]), ${me}(b_value_upper[${F}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${me}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(j,F)=>`${`dot(a_data${F}, b_dequantized_values[${F}])`}`).join(" + ")}; + word_offset += ${8/d}; + } + workgroupBarrier(); + } + + if (local_idx < ${b}) { + var output_value: ${ne.type.value} = ${ne.type.value}(0); + for (var b = 0u; b < ${k}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${ne.setByIndices(`${ne.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${d};${u};${k};${b}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:v},programUniforms:y}),getShaderSource:O}},df=(e,r)=>{lf(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(uf(e.inputs,r)):e.compute(cf(e.inputs,r))},pf=e=>Nt(e)}),hf,mf,_f,ff,gf,wf,Mf,bf,yf,Fx=Ve(()=>{gt(),Et(),Pt(),hf=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].")}},mf=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${lt("uniforms.pads",o,t)}; + if (k < 0) { + break; + } + if (k >= i32(${lt("uniforms.x_shape",o,r)})) { + break; + } + offset += k * i32(${lt("uniforms.x_strides",o,r)}); + `;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]; + } + `},_f=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${lt("uniforms.pads",o,t)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${lt("uniforms.x_shape",o,r)}) - 1); + k = k % _2n_1; + if(k >= i32(${lt("uniforms.x_shape",o,r)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${lt("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},ff=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${lt("uniforms.pads",o,t)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${lt("uniforms.x_shape",o,r)})) { + k = i32(${lt("uniforms.x_shape",o,r)}) - 1; + } + offset += k * i32(${lt("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},gf=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${lt("uniforms.pads",o,t)}; + if (k < 0) { + k += i32(${lt("uniforms.x_shape",o,r)}]); + } + if (k >= i32(${lt("uniforms.x_shape",o,r)})) { + k -= i32(${lt("uniforms.x_shape",o,r)}); + } + offset += k * i32(${lt("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},wf=(e,r,t)=>{switch(t.mode){case 0:return mf(e,r,t.pads.length);case 1:return _f(e,r,t.pads.length);case 2:return ff(e,r,t.pads.length);case 3:return gf(e,r,t.pads.length);default:throw new Error("Invalid mode")}},Mf=(e,r)=>{let t=ye.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,o=ye.size(t),n=[{type:12,data:o},{type:6,data:r.pads}],i=e.length>=3&&e[2].data;r.mode===0&&n.push({type:i?e[2].dataType:1,data:r.value}),n.push(...ct(e[0].dims,t));let a=["rank"],l=c=>{let p=it("output",e[0].dataType,t.length),d=$e("x",e[0].dataType,s.length),u=d.type.value,f=wf(p,s.length,r),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&_.push({name:"constant_value",type:i?u:"f32"}),` + ${c.registerUniforms(_).declareVariables(d,p)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${p.offsetToIndices("global_idx")}; + + var value = ${u}(0); + ${f} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${i}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(ye.size(t)/64)},programUniforms:n}),getShaderSource:l}},bf=(e,r)=>{if(e.length>1){let t=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,n=new Int32Array(2*o).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;ln[Number(l)]=Number(a));let i=[];return n.forEach(a=>i.push(a)),{mode:r.mode,value:s,pads:i}}else return r},yf=(e,r)=>{hf(e.inputs);let t=bf(e.inputs,r);e.compute(Mf(e.inputs,t),{inputs:[0]})}}),vo,Rl,jl,Nl,Vl,vf,xf,Ul,Wl,Tf,Ef,Gl,Pf,Cf,Kl,Sf,$f,kf,If,Ox=Ve(()=>{gs(),gt(),Et(),Pt(),vo=e=>{if(Yt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Rl=(e,r,t)=>{let s=r.format==="NHWC",o=e.dims.slice();s&&o.splice(1,0,o.pop());let n=Object.hasOwnProperty.call(r,"dilations"),i=r.kernelShape.slice(),a=r.strides.slice(),l=n?r.dilations.slice():[],c=r.pads.slice();ii.adjustPoolAttributes(t,o,i,a,l,c);let p=ii.computePoolOutputShape(t,o,a,l,i,c,r.autoPad),d=Object.assign({},r);n?Object.assign(d,{kernelShape:i,strides:a,pads:c,dilations:l,cacheKey:r.cacheKey}):Object.assign(d,{kernelShape:i,strides:a,pads:c,cacheKey:r.cacheKey});let u=p.slice();return u.push(u.splice(1,1)[0]),[d,s?u:p]},jl=(e,r)=>{let t=r.format==="NHWC",s=ye.size(e),o=ye.size(r.kernelShape),n=[{type:12,data:s},{type:12,data:o}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let a=r.kernelShape[r.kernelShape.length-1],l=r.strides[r.strides.length-1],c=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],d=!!(c+p);n.push({type:12,data:a},{type:12,data:l},{type:12,data:c},{type:12,data:p}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(r.kernelShape.length===2){let f=r.kernelShape[r.kernelShape.length-2],_=r.strides[r.strides.length-2],b=r.pads[r.pads.length/2-2],k=r.pads[r.pads.length-2];u=!!(b+k),n.push({type:12,data:f},{type:12,data:_},{type:12,data:b},{type:12,data:k}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,i,!0,d,u]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=ye.computeStrides(r.kernelShape);n.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),i.push({name:"kernelStrides",type:"u32",length:a.length},{name:"pads",type:"u32",length:r.pads.length},{name:"strides",type:"u32",length:r.strides.length});let l=r.pads.reduce((c,p)=>c+p);return[n,i,!!l,!1,!1]}},Nl=(e,r,t,s,o,n,i,a,l,c,p,d)=>{let u=o.format==="NHWC",f=r.type.value,_=it("output",r.type.tensor,s);if(o.kernelShape.length<=2){let b="",k="",g="",M=t-(u?2:1);if(p?b=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${M}] = indices[${M}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${M}] < 0 || xIndices[${M}] + >= uniforms.x_shape[${M}]) { + pad++; + continue; + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:b=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${M}] = indices[${M}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`,o.kernelShape.length===2){let $=t-(u?3:2);d?k=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${$}] = indices[${$}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${$}] < 0 || xIndices[${$}] >= uniforms.x_shape[${$}]) { + pad += i32(uniforms.kw); + continue; + } + `:k=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${$}] = indices[${$}] * uniforms.sh - uniforms.phStart + j; + `,g=` + } + `}return` + ${e.registerUniforms(l).declareVariables(r,_)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${_.offsetToIndices("global_idx")}; + var xIndices = ${_.offsetToIndices("global_idx")}; + + var value = ${f}(${a}); + var pad = 0; + ${k} + ${b} + ${g} + ${i} + + output[global_idx] = value; + }`}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let b=o.kernelShape.length,k=o.pads.length,g="";return c?g=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:g=` + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + `,` + ${e.registerUniforms(l).declareVariables(r,_)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${_.offsetToIndices("global_idx")}; + var xIndices = ${_.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${f}(${a}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${b-1}u; j++) { + offsets[j] = offset / ${lt("uniforms.kernelStrides","j",b)}; + offset -= offsets[j] * ${lt("uniforms.kernelStrides","j",b)}; + } + offsets[${b-1}] = offset; + + isPad = false; + for (var j = ${t-b}u; j < ${t}u; j++) { + xIndices[j] = indices[j] * ${lt("uniforms.strides",`j - ${t-b}u`,b)} + + offsets[j - ${t-b}u] - ${lt("uniforms.pads","j - 2u",k)}; + ${g} + } + ${i} + + output[global_idx] = value; + }`}},Vl=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,vf=e=>`${Vl(e)};${e.countIncludePad}`,xf=e=>`${Vl(e)};${e.storageOrder};${e.dilations}`,Ul=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}),Wl=(e,r,t,s)=>{let[o,n]=Rl(r,s,t),i=$e("x",r.dataType,r.dims.length),a=i.type.value,l="value += x_val;",c="";o.countIncludePad?c+=`value /= ${a}(uniforms.kernelSize);`:c+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,d,u,f,_]=jl(n,o);p.push(...ct(r.dims,n));let b=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${u};${f};${_}`,inputDependencies:b},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(ye.size(n)/64)},programUniforms:p}),getShaderSource:k=>Nl(k,i,r.dims.length,n.length,o,l,c,0,d,u,f,_)}},Tf=e=>{let r=e.count_include_pad!==0,t=Ul(e);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:r,...t,cacheKey:""};return{...s,cacheKey:vf(s)}},Ef=(e,r)=>{vo(e.inputs),e.compute(Wl("AveragePool",e.inputs[0],!1,r))},Gl={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Pf=e=>{let r=e.format;return{format:r,...Gl,cacheKey:r}},Cf=(e,r)=>{vo(e.inputs),e.compute(Wl("GlobalAveragePool",e.inputs[0],!0,r))},Kl=(e,r,t,s)=>{let[o,n]=Rl(r,s,t),i=` + value = max(x_val, value); + `,a="",l=$e("x",r.dataType,r.dims.length),c=["rank"],[p,d,u,f,_]=jl(n,o);return p.push(...ct(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${u};${f};${_}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(ye.size(n)/64)},programUniforms:p}),getShaderSource:b=>Nl(b,l,r.dims.length,n.length,o,i,a,r.dataType===10?-65504:-1e5,d,u,f,_)}},Sf=(e,r)=>{vo(e.inputs),e.compute(Kl("MaxPool",e.inputs[0],!1,r))},$f=e=>{let r=e.storage_order,t=e.dilations,s=Ul(e);if(r!==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:r,dilations:t,...s,cacheKey:""};return{...o,cacheKey:xf(o)}},kf=e=>{let r=e.format;return{format:r,...Gl,cacheKey:r}},If=(e,r)=>{vo(e.inputs),e.compute(Kl("GlobalMaxPool",e.inputs[0],!0,r))}}),Af,Ff,Of,Df,Dx=Ve(()=>{gt(),Et(),cr(),Pt(),Af=(e,r)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((t,s)=>t===e[2].dims[s]).reduce((t,s)=>t&&s,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(r.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,n)=>n===r.axis||o===e[0].dims[n]).reduce((o,n)=>o&&n,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let t=e[0].dims[r.axis],s=e[1].dims[r.axis];if(r.blockSizeMath.ceil(t/(s-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Ff=(e,r)=>{let t=ye.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,o=s===3,n=e[0].dims,i=e[1].dataType,a=ye.size(n),l=s===3||s===2,c=l?[Math.ceil(ye.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,d=e.length>2?e[2]:void 0,u=d?l?[Math.ceil(ye.size(d.dims)/4)]:d.dims:void 0,f=p.length===0||p.length===1&&p[0]===1,_=f===!1&&p.length===1,b=or(a),k=f&&(!l||b===4),g=k?b:1,M=k&&!l?b:1,$=$e("input",l?12:s,c.length,M),v=$e("scale",i,p.length),y=d?$e("zero_point",l?12:s,u.length):void 0,T=it("output",i,n.length,g),x=[$,v];y&&x.push(y);let P=[c,p];d&&P.push(u);let O=[{type:12,data:a/g},{type:12,data:t},{type:12,data:r.blockSize},...ct(...P,n)],L=G=>{let K=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${G.registerUniforms(K).declareVariables(...x,T)} + ${G.mainStart()} + ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${T.offsetToIndices("global_idx")}; + + // Set input x + ${l?` + let input = ${$.getByOffset("global_idx / 4")}; + let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${g===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${$.getByOffset("global_idx")};`}; + + // Set scale input + ${f?`let scale_value= ${v.getByOffset("0")}`:_?` + let scale_index = ${T.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${v.getByOffset("scale_index")};`:` + var scale_indices: ${v.type.indices} = output_indices; + let index = ${v.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${v.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${v.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${y?f?l?` + let zero_point_input = ${y.getByOffset("0")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${y.getByOffset("0")}`:_?l?` + let zero_point_index = ${T.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${y.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${T.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${y.getByOffset("zero_point_index")};`:l?` + let zero_point_offset = ${v.indicesToOffset("scale_indices")}; + let zero_point_input = ${y.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${y.getByIndices("scale_indices")};`:`let zero_point_value = ${l?o?"i32":"u32":$.type.value}(0);`}; + // Compute and write output + ${T.setByOffset("global_idx",`${T.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getShaderSource:L,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(a/g/64),y:1,z:1},programUniforms:O})}},Of=(e,r)=>{Af(e.inputs,r),e.compute(Ff(e.inputs,r))},Df=e=>Nt({axis:e.axis,blockSize:e.blockSize})}),Lf,zf,Bf,Lx=Ve(()=>{gs(),gt(),Pt(),Lf=(e,r,t)=>{let s=e===r,o=er&&t>0;if(s||o||n)throw new Error("Range these inputs' contents are invalid.")},zf=(e,r,t,s)=>{let o=Math.abs(Math.ceil((r-e)/t)),n=[o],i=o,a=[{type:12,data:i},{type:s,data:e},{type:s,data:t},...ct(n)],l=c=>{let p=it("output",s,n.length),d=p.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:d},{name:"delta",type:d}];return` + ${c.registerUniforms(u).declareVariables(p)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${d}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:a})}},Bf=e=>{let r=0,t=0,s=0;e.inputs[0].dataType===6?(r=e.inputs[0].getInt32Array()[0],t=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(r=e.inputs[0].getFloat32Array()[0],t=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),Yt.webgpu.validateInputContent&&Lf(r,t,s),e.compute(zf(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),Rf,Hl,ql,jf,Nf,Vf,zx=Ve(()=>{gt(),Et(),cr(),Pt(),Rf=(e,r,t,s)=>{if(e!=="none"&&s!=="i32"&&s!=="u32"&&s!=="f32")throw new Error(`Input ${s} is not supported with reduction ${e}.`);let o=`{ + var oldValue = 0; + loop { + let newValueF32 =`,n=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${r}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${r}=${t};`;case"add":return s==="i32"||s==="u32"?`atomicAdd(&${r}, bitcast<${s}>(${t}));`:` + ${o}bitcast<${s}>(oldValue) + (${t})${n}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` + ${o}max(bitcast(oldValue), (${t}))${n}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${o}min(bitcast<${s}>(oldValue), (${t}))${n}`;case"mul":return`${o}(bitcast<${s}>(oldValue) * (${t}))${n}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Hl=(e,r)=>`${e===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[${r?"i - indices_start":"i"}]; + let dim_value = uniforms.output_shape[${r?"i - indices_start":"i"} + uniforms.last_index_dimension];`} + + if (index >= 0) { + if (index >= i32(dim_value)) { + index = i32(dim_value - 1); + } + } else { + if (index < -i32(dim_value)) { + index = 0; + } else { + index += i32(dim_value); + } + } + data_offset += u32((u32(index) * element_count_dim));`,ql=(e,r,t)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * ${t?"global_idx":"idx"} + i]; + ${Rf(e.reduction,"output[data_offset + i]","value",r)} + }`,jf=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t,n=1,i=Math.ceil(ye.size(s)/n),a=s[s.length-1],l=ye.sizeFromDimension(t,a),c=ye.sizeFromDimension(s,0)/a,p=[{type:12,data:i},{type:12,data:a},{type:12,data:l},...ct(e[1].dims,e[2].dims,o)],d=u=>{let f=$e("indices",e[1].dataType,e[1].dims.length),_=$e("updates",e[2].dataType,e[2].dims.length,n),b=r.reduction!=="none"&&r.reduction!==""?Hd("output",e[0].dataType,o.length):it("output",e[0].dataType,o.length,n);return` + ${u.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(f,_,b)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var hasDuplicates = false; + if (${r.reduction==="none"}) { + for (var i = 0; i < ${c}; i = i + 1) { + for (var j = i + 1; j < ${c}; j = j + 1) { + var index_i = i32(indices[i].x); + var index_j = i32(indices[j].x); + if (index_i == index_j) { + hasDuplicates = true; + break; + } + } + if (hasDuplicates) { + break; + } + } + } + + if (${r.reduction==="none"} && hasDuplicates) { + if (global_idx != 0u) { + return; + } + // Process each index-update pair individually when duplicates exist + for (var idx = 0u; idx < ${c}u; idx++) { + var data_offset = 0u; + for (var i = 0u; i < uniforms.last_index_dimension; i++) { + var index = i32(indices[idx * uniforms.last_index_dimension + i].x); + ${Hl(t.length,!1)} + } + ${ql(r,b.type.value,!1)} + } + return; + } + + var data_offset = 0u; + var indices_start = uniforms.last_index_dimension * global_idx; + var indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${Hl(t.length,!0)} + } + ${ql(r,b.type.value,!0)} + }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:d}},Nf=e=>Nt({reduction:e.reduction}),Vf=(e,r)=>{e.compute(jf(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Uf,Wf,Gf,Ql,Kf,Hf,qf,Qf,Xf,Jf,Yf,Zf,Xl,eg,tg,rg,sg,ng,og,ig,Bx=Ve(()=>{gt(),Et(),cr(),Pt(),Uf=(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 + 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")}},Wf=(e,r,t)=>{r.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(t).fill(1);return r.forEach((o,n)=>s[o]=e[n]),s},Gf=(e,r,t,s,o,n)=>{let[i,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(p=>n.push(p));else if(r.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(a>0&&e.length>a&&e[a].dims.length===1&&e[a].dims[0]>0){if(e[a].getFloat32Array().forEach(p=>s.push(p)),s.length!==0&&s.length!==c&&t>=18&&s.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");Uf(s,r),r.axes.length>0&&Wf(s,r.axes,c).forEach((p,d)=>s[d]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>o.push(Number(p))),o.length!==0&&o.length!==c&&t>=18&&o.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(s.length!==0&&s.length!==r.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.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 s<"u"&&typeof o<"u"&&s.length>0&&o.length>c)throw new Error("Resize requires only of scales or sizes to be specified")},Ql=(e,r,t,s)=>` + // 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 big = (${e}) * (${r}); + let whole = ${s}(big / (${t})); + let fract = ${s}(big % (${t})) / ${s}(${t}); + return whole + fract; +`,Kf=(e,r)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${r} { `+(()=>{switch(e){case"asymmetric":return` + if (xScale < 1.0 || floor(xScale) != xScale) { + return ${r}(xResized) / ${r}(xScale); + } else { + ${Ql("xResized","lengthOriginal","lengthResized",r)} + } + `;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${r}(xResized) + 0.5) / ${r}(xScale);`;case"align_corners":return`if (lengthResized == 1) { + return 0.0; + } else { + ${Ql("xResized","lengthOriginal - 1","lengthResized - 1",r)} + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${r}(roiStart) * ${r}(lengthOriginal - 1) + + (${r}(xResized) * ${r}(roiEnd - roiStart) * ${r}(lengthOriginal - 1)) / + ${r}(lengthResized - 1); + } else { + return 0.5 * ${r}(roiStart + roiEnd) * ${r}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${r}xScale * ${r}(lengthResized); + const adjustment = ${r}(lengthResized) / outputWidth; + const center = ${r}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + 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`)}})()+"}",Hf=(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`)}})()+"}",qf=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),o=e.length===0?s:e.slice();return r.length>0?(r.forEach((n,i)=>{s[n]=o[i],s[i+t]=o[r.length+i]}),s):o},Qf=(e,r,t,s)=>{let o=[];if(t.length>0)if(s.length>0){if(e.forEach(n=>o.push(n)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((n,i)=>o[n]=t[i])}else t.forEach(n=>o.push(n));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((n,i)=>Math.round(n*r[i]))}return o},Xf=(e,r,t)=>{let s=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(n=>r[n]),Number.MAX_VALUE):Math.min(...r,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(n=>r[n]),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 o=e.slice();return t.axes.length>0?(t.axes.forEach(n=>r[n]=s),t.axes.forEach(n=>o[n]=Math.round(e[n]*r[n]))):(r.fill(s,0,r.length),o.forEach((n,i)=>o[i]=Math.round(n*r[i]))),o},Jf=(e,r,t,s,o)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${t.length}> { + var original_indices: array<${e.type.value}, ${t.length}>; + for (var i:u32 = 0; i < ${t.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${lt("uniforms.scales","i",s)}; + var roi_low = ${lt("uniforms.roi","i",o)}; + var roi_hi = ${lt("uniforms.roi",`i + ${r.length}`,o)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${lt("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${lt("uniforms.output_shape","i",t.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,Yf=(e,r,t,s,o,n,i)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${r.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${lt("uniforms.scales","i",o)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${lt("uniforms.roi","i",n)}; + var roi_hi = ${lt("uniforms.roi",`i + ${t.length}`,n)}; + var input_shape_i = ${lt("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${lt("uniforms.output_shape","i",s.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${i} || (original_idx >= 0 && original_idx < ${r.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${r.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; + }`,Zf=(e,r)=>` + fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { + for (var i:u32 = 0; i < ${r.length}; i++) { + var input_index = ${e.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${lt("uniforms.input_shape","i",r.length)}) { + return false; + } + } + return true; + }`,Xl=(e,r,t,s)=>e.rank>s?` + ${e.indicesSet("input_indices",r,"channel")}; + ${e.indicesSet("input_indices",t,"batch")}; +`:"",eg=(e,r,t,s,o)=>{let[n,i,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],c=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${c} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(row, ${t[i]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; + ${Xl(e,l,n,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${c} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${c} = originalIndices[${i}]; + var col:${c} = originalIndices[${a}]; + ${s?`if (row < 0 || row > (${t[i]} - 1) || col < 0 || col > (${t[a]} - 1)) { + return ${o}; + }`:""}; + row = max(0, min(row, ${t[i]} - 1)); + col = max(0, min(col, ${t[a]} - 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 = ${t.length>2?`u32(originalIndices[${l}])`:"0"}; + var batch: u32 = ${t.length>2?`u32(originalIndices[${n}])`:"0"}; + var x11: ${c} = getInputValue(batch, channel, row1, col1); + var x12: ${c} = getInputValue(batch, channel, row1, col2); + var x21: ${c} = getInputValue(batch, channel, row2, col1); + var x22: ${c} = getInputValue(batch, channel, row2, col2); + var dx1: ${c} = abs(row - ${c}(row1)); + var dx2: ${c} = abs(${c}(row2) - row); + var dy1: ${c} = abs(col - ${c}(col1)); + var dy2: ${c} = abs(${c}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},tg=(e,r,t,s,o,n,i,a,l,c)=>{let p=t.length===2,[d,u]=p?[0,1]:[2,3],f=e.type.value,_=b=>{let k=b===d?"row":"col";return` + fn ${k}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${f} { + var output_index = ${r.indicesGet("output_indices",b)}; + var originalIdx: ${f} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[b]}, + ${s[b]}, ${t[b]}, ${n[b]}, ${n[b]} + ${t.length}); + var fractOriginalIdx: ${f} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${a} && (originalIdx < 0 || originalIdx > (${t[b]} - 1))) { + return ${l}; + } + var data: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${k}: ${f} = originalIdx + ${f}(i); + if (${k} < 0 || ${k} >= ${t[b]}) { + ${c?`coefs[i + 1] = 0.0; + continue;`:a?`return ${l};`:`${k} = max(0, min(${k}, ${t[b]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",b,`u32(${k})`)}; + data[i + 1] = ${b===d?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${_(d)}; + ${_(u)}; + fn getCubicInterpolationCoefs(s: ${f}) -> array<${f}, 4> { + var absS = abs(s); + var coeffs: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${f} = 1.0 - absS; + var twoMinusAbsS: ${f} = 2.0 - absS; + var onePlusAbsS: ${f} = 1.0 + absS; + coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; + coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; + coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${f}, 4>, coefs: array<${f}, 4>) -> ${f} { + var coefsSum: ${f} = 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: ${r.type.indices}) -> ${f} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},rg=(e,r,t,s,o)=>{let[n,i,a,l,c]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${p} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(depth, ${t[i]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(height, ${t[a]} - 1))`)}; + ${e.indicesSet("input_indices",l,`max(0, min(width, ${t[l]} - 1))`)}; + ${Xl(e,c,n,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${r.type.indices}) -> ${p} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${p} = originalIndices[${i}]; + var height:${p} = originalIndices[${a}]; + var width:${p} = originalIndices[${l}]; + ${s?`if (depth < 0 || depth > (${t[i]} - 1) || height < 0 || height > (${t[a]} - 1) || width < 0 || (width > ${t[l]} - 1)) { + return ${o}; + }`:""}; + + depth = max(0, min(depth, ${t[i]} - 1)); + height = max(0, min(height, ${t[a]} - 1)); + width = max(0, min(width, ${t[l]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${t.length>3?`u32(originalIndices[${c}])`:"0"}; + var batch: u32 = ${t.length>3?`u32(originalIndices[${n}])`:"0"}; + + var x111: ${p} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${p} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${p} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${p} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${p} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${p} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${p} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${p} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${p} = abs(depth - ${p}(depth1)); + var dx2: ${p} = abs(${p}(depth2) - depth); + var dy1: ${p} = abs(height - ${p}(height1)); + var dy2: ${p} = abs(${p}(height2) - height); + var dz1: ${p} = abs(width - ${p}(width1)); + var dz2: ${p} = abs(${p}(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); + }`},sg=(e,r,t,s,o,n)=>{let i=e.dims,a=qf(n,r.axes,i.length),l=Qf(i,s,o,r.axes),c=s.slice();s.length===0&&(c=i.map((M,$)=>M===0?1:l[$]/M),r.keepAspectRatioPolicy!=="stretch"&&(l=Xf(i,c,r)));let p=it("output",e.dataType,l.length),d=$e("input",e.dataType,i.length),u=ye.size(l),f=i.length===l.length&&i.every((M,$)=>M===l[$]),_=r.coordinateTransformMode==="tf_crop_and_resize",b=r.extrapolationValue,k=d.type.value,g=M=>` + ${f?"":` + ${Kf(r.coordinateTransformMode,k)}; + ${(()=>{switch(r.mode){case"nearest":return` + ${Zf(d,i)}; + ${Hf(r.nearestMode,t,k)}; + ${Yf(d,p,i,l,c.length,a.length,_)}; + `;case"linear":return` + ${Jf(p,i,l,c.length,a.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${eg(d,p,i,_,b)}`;if(i.length===3||i.length===5)return`${rg(d,p,i,_,b)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(i.length===2||i.length===4)return`${tg(d,p,i,l,c,a,r.cubicCoeffA,_,r.extrapolationValue,r.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${M.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",a.length).declareVariables(d,p)} + ${M.mainStart()} + ${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${f?"output[global_idx] = input[global_idx];":` + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${d.type.indices}; + ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${d.getByIndices("input_indices")}; + } else { + output[global_idx] = ${r.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${r.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${r.cacheKey}|${t}|${c.length>0?r.mode==="cubic"?c:c.length:""}|${o.length>0?o:""}|${a.length>0?a:""}|${f}|${r.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:1,data:c},{type:1,data:a},...ct(i,l)]})}},ng=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},og=(e,r)=>{let t=[],s=[],o=[],n=ng(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Gf(e.inputs,r,n,t,s,o),e.compute(sg(e.inputs[0],r,n,t,s,o),{inputs:[0]})},ig=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,o=e.cubicCoeffA,n=e.excludeOutside!==0,i=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return Nt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:o,excludeOutside:n,extrapolationValue:i,keepAspectRatioPolicy:a,mode:l,nearestMode:c})}}),ag,lg,cg,Rx=Ve(()=>{gt(),Et(),Pt(),ag=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let r=e[0],t=e[1],s=e[2];if(r.dataType!==t.dataType||r.dataType!==s.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 o=r.dims[r.dims.length-1],n=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==n)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 i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},lg=(e,r,t,s)=>{let o=r.simplified,n=e[0].dims,i=ye.size(n),a=n,l=i,c=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],d=!o&&e.length>3,u=e.length>4,f=s&&t>1,_=s&&t>2,b=t>3,k=64,g=or(c),M=[{type:12,data:l},{type:12,data:g},{type:12,data:c},{type:1,data:r.epsilon}],$=y=>{let T=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],x=[$e("x",e[0].dataType,e[0].dims,g),$e("skip",e[1].dataType,e[1].dims,g),$e("gamma",e[2].dataType,e[2].dims,g)];d&&x.push($e("beta",e[3].dataType,e[3].dims,g)),u&&x.push($e("bias",e[4].dataType,e[4].dims,g)),x.push(it("output",e[0].dataType,a,g)),f&&x.push(it("mean_output",1,p)),_&&x.push(it("inv_std_output",1,p)),b&&x.push(it("input_skip_bias_sum",e[0].dataType,a,g));let P=Er(e[0].dataType),O=Er(1,g);return` + + ${y.registerUniforms(T).declareVariables(...x)} + var sum_shared : array<${O}, ${k}>; + var sum_squared_shared : array<${O}, ${k}>; + + ${y.mainStart([k,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${k}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${k}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${k-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${u?"bias[offset1d + i]":P+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${b?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Gn(P,g,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${k}; + for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { + reduce_size = curr_size + (reduce_size & 1); + if (ix < curr_size) { + sum_shared[ix] += sum_shared[ix + reduce_size]; + sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; + } + workgroupBarrier(); + } + + let sum = sum_shared[0]; + let square_sum = sum_squared_shared[0]; + let mean = ${Ks("sum",g)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Ks("square_sum",g)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); + ${f?"mean_output[global_idx] = mean;":""} + ${_?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${o?"":`- ${P}(mean)`}) * + ${P}(inv_std_dev) * gamma[offset1d + i] + ${d?"+ beta[offset1d + i]":""}; + } + }`},v=[{dims:a,dataType:e[0].dataType}];return t>1&&v.push({dims:p,dataType:1}),t>2&&v.push({dims:p,dataType:1}),t>3&&v.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${g};${f};${_};${b}`,inputDependencies:e.map((y,T)=>"type")},getShaderSource:$,getRunData:()=>({outputs:v,dispatchGroup:{x:Math.ceil(l/c)},programUniforms:M})}},cg=(e,r)=>{ag(e.inputs);let t=[0];e.outputCount>1&&t.push(-3),e.outputCount>2&&t.push(-3),e.outputCount>3&&t.push(3),e.compute(lg(e.inputs,r,e.outputCount,!1),{outputs:t})}}),ug,xo,dg,Jl,pg,hg,mg,_g,jx=Ve(()=>{gt(),Et(),cr(),Pt(),ug=(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,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`)})},xo=(e,r)=>{let t=[];if(e.length>r)if(e[r].dataType===7)e[r].getBigInt64Array().forEach(s=>t.push(Number(s)));else if(e[r].dataType===6)e[r].getInt32Array().forEach(s=>t.push(Number(s)));else throw new Error(`Input ${r} must be an array of int32 or int64`);return t},dg=(e,r)=>{if(e.length>1){let t=xo(e,1),s=xo(e,2),o=xo(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),Nt({starts:t,ends:s,axes:o})}else return r},Jl=(e,r,t,s,o)=>{let n=e;return e<0&&(n+=t[s[r]]),o[r]<0?Math.max(0,Math.min(n,t[s[r]]-1)):Math.max(0,Math.min(n,t[s[r]]))},pg=(e,r,t)=>`fn calculateInputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${t.length}; i >= 0; i--) { + let input_shape_i = ${lt("uniforms.input_shape","i",t.length)}; + let steps_i = ${lt("uniforms.steps","i",t.length)}; + let signs_i = ${lt("uniforms.signs","i",t.length)}; + let starts_i = ${lt("uniforms.starts","i",t.length)}; + var output_index = ${r.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; + }`,hg=(e,r)=>{let t=e[0].dims,s=ye.size(t),o=r.axes.length>0?ye.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=xo(e,4);n.forEach(g=>g!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(o.length).fill(1));let i=r.starts.map((g,M)=>Jl(g,M,t,o,n)),a=r.ends.map((g,M)=>Jl(g,M,t,o,n));if(o.length!==i.length||o.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==t.length)for(let g=0;gMath.sign(g));n.forEach((g,M,$)=>{if(g<0){let v=(a[M]-i[M])/g,y=i[M],T=y+v*n[M];i[M]=T,a[M]=y,$[M]=-g}});let c=t.slice(0);o.forEach((g,M)=>{c[g]=Math.ceil((a[g]-i[g])/n[g])});let p={dims:c,dataType:e[0].dataType},d=it("output",e[0].dataType,c.length),u=$e("input",e[0].dataType,e[0].dims.length),f=ye.size(c),_=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:n.length}],b=[{type:12,data:f},{type:12,data:i},{type:6,data:l},{type:12,data:n},...ct(e[0].dims,c)],k=g=>` + ${g.registerUniforms(_).declareVariables(u,d)} + ${pg(u,d,t)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${d.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${d.setByOffset("global_idx",u.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:b})}},mg=(e,r)=>{ug(e.inputs,r);let t=dg(e.inputs,r);e.compute(hg(e.inputs,t),{inputs:[0]})},_g=e=>{let r=e.starts,t=e.ends,s=e.axes;return Nt({starts:r,ends:t,axes:s})}}),fg,gg,wg,Mg,Nx=Ve(()=>{gt(),Et(),cr(),Hs(),Pt(),fg=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},gg=(e,r)=>{let t=e.inputs[0],s=t.dims,o=ye.size(s),n=s.length,i=ye.normalizeAxis(r.axis,n),a=iP),c[i]=n-1,c[n-1]=i,l=e.compute(os(t,c),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,d=p[n-1],u=o/d,f=or(d),_=d/f,b=64;u===1&&(b=256);let k=(x,P)=>P===4?`max(max(${x}.x, ${x}.y), max(${x}.z, ${x}.w))`:P===2?`max(${x}.x, ${x}.y)`:P===3?`max(max(${x}.x, ${x}.y), ${x}.z)`:x,g=$e("x",l.dataType,l.dims,f),M=it("result",l.dataType,l.dims,f),$=g.type.value,v=Er(l.dataType)==="f32"?`var threadMax = ${$}(-3.402823e+38f);`:`var threadMax = ${$}(-65504.0h);`,y=x=>` + var rowMaxShared : ${$}; + var rowSumShared : ${$}; + var threadShared : array<${$}, ${b}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${$} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${$}) { + let index = row * row_stride + col; + result[index] = value; + } + ${x.registerUniform("packedCols","i32").declareVariables(g,M)} + ${x.mainStart(b)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${b}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${v} + 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 = ${$}(${k("threadShared[0]",f)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${$}(0.0); + for (var col = lindex; col < cols; col += wg) { + let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); + threadSum += subExp; + } + threadShared[lindex] = threadSum; + workgroupBarrier(); + + for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { + if (lindex < currSize) { + threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; + } + workgroupBarrier(); + } + if (lindex == 0) { + rowSumShared = ${$}(${Ks("threadShared[0]",f)}); + } + 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); + } + }`,T=e.compute({name:"Softmax",shaderCache:{hint:`${f};${b}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:_}]}),getShaderSource:y},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(os(T,c),{inputs:[T]})},wg=(e,r)=>{fg(e.inputs),gg(e,r)},Mg=e=>Nt({axis:e.axis})}),Yl,bg,yg,vg,xg,Vx=Ve(()=>{gt(),Et(),Pt(),Yl=e=>Array.from(e.getBigInt64Array(),Number),bg=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, 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(Yl(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")},yg=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Yl(e[1]),o=yg(t,s),n=ye.size(o),i=e[0].dataType,a=$e("input",i,t.length),l=it("output",i,o.length),c=p=>` + const inputShape = ${a.indices(...t)}; + ${p.registerUniform("output_size","u32").declareVariables(a,l)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${l.offsetToIndices("global_idx")}; + var input_indices: ${a.type.indices}; + for (var i = 0; i < ${t.length}; i++) { + let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i; + + ${a.indicesSet("input_indices","i","input_dim_value")} + } + ${l.setByOffset("global_idx",a.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...ct(e[0].dims,o)]}),getShaderSource:c}},xg=e=>{bg(e.inputs),e.compute(vg(e.inputs),{inputs:[0]})}}),Tg,Eg,Pg,Ux=Ve(()=>{gt(),Et(),Pt(),Tg=(e,r,t,s,o)=>{let n=it("output_data",o,t.length,4),i=$e("a_data",r[1].dataType,r[1].dims.length,4),a=$e("b_data",r[2].dataType,r[2].dims.length,4),l=$e("c_data",r[0].dataType,r[0].dims.length,4),c,p=(d,u,f)=>`select(${u}, ${d}, ${f})`;if(!s)c=n.setByOffset("global_idx",p(i.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let d=(u,f,_="")=>{let b=`a_data[index_a${f}][component_a${f}]`,k=`b_data[index_b${f}][component_b${f}]`,g=`bool(c_data[index_c${f}] & (0xffu << (component_c${f} * 8)))`;return` + let output_indices${f} = ${n.offsetToIndices(`global_idx * 4u + ${f}u`)}; + let offset_a${f} = ${i.broadcastedIndicesToOffset(`output_indices${f}`,n)}; + let offset_b${f} = ${a.broadcastedIndicesToOffset(`output_indices${f}`,n)}; + let offset_c${f} = ${l.broadcastedIndicesToOffset(`output_indices${f}`,n)}; + let index_a${f} = offset_a${f} / 4u; + let index_b${f} = offset_b${f} / 4u; + let index_c${f} = offset_c${f} / 4u; + let component_a${f} = offset_a${f} % 4u; + let component_b${f} = offset_b${f} % 4u; + let component_c${f} = offset_c${f} % 4u; + ${u}[${f}] = ${_}(${p(b,k,g)}); + `};o===9?c=` + var data = vec4(0); + ${d("data",0,"u32")} + ${d("data",1,"u32")} + ${d("data",2,"u32")} + ${d("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=` + ${d("output_data[global_idx]",0)} + ${d("output_data[global_idx]",1)} + ${d("output_data[global_idx]",2)} + ${d("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(l,i,a,n)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${c} + }`},Eg=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,o=e[1].dataType,n=!(ye.areEqual(r,t)&&ye.areEqual(t,s)),i=r,a=ye.size(r);if(n){let c=Un.calcShape(Un.calcShape(r,t,!1),s,!1);if(!c)throw new Error("Can't perform where op on the given tensors");i=c,a=ye.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>Tg(c,e,i,n,o),getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...ct(s,r,t,i)]})}},Pg=e=>{e.compute(Eg(e.inputs))}}),Cg,Wx=Ve(()=>{nx(),pl(),ox(),ix(),ax(),lx(),cx(),mx(),fx(),gx(),wx(),Mx(),bx(),yx(),vx(),xx(),Tx(),Ex(),Px(),Cx(),Sx(),$x(),kx(),Ix(),Ax(),B_(),Fx(),Ox(),Dx(),Lx(),zx(),cl(),Bx(),q_(),Rx(),jx(),Nx(),G_(),Vx(),Hs(),fl(),Ux(),Cg=new Map([["Abs",[ih]],["Acos",[ah]],["Acosh",[lh]],["Add",[Qh]],["ArgMax",[Gp,dl]],["ArgMin",[Wp,dl]],["Asin",[ch]],["Asinh",[uh]],["Atan",[dh]],["Atanh",[ph]],["Attention",[Jp]],["AveragePool",[Ef,Tf]],["BatchNormalization",[th]],["BiasAdd",[nh]],["BiasSplitGelu",[Kh]],["Cast",[mh,hh]],["Ceil",[gh]],["Clip",[fh]],["Concat",[cm,um]],["Conv",[$l,Cl]],["ConvTranspose",[zm,Om]],["Cos",[wh]],["Cosh",[Mh]],["CumSum",[Rm,jm]],["DepthToSpace",[Wm,Gm]],["DequantizeLinear",[Of,Df]],["Div",[Xh]],["Einsum",[Jm,Ym]],["Elu",[bh,go]],["Equal",[Jh]],["Erf",[yh]],["Exp",[vh]],["Expand",[r_]],["FastGelu",[n_]],["Floor",[xh]],["FusedConv",[$l,Cl]],["Gather",[l_,a_]],["GatherElements",[M_,w_]],["GatherBlockQuantized",[m_,__]],["GatherND",[u_,d_]],["Gelu",[Th]],["Gemm",[x_,v_]],["GlobalAveragePool",[Cf,Pf]],["GlobalMaxPool",[If,kf]],["Greater",[tm]],["GreaterOrEqual",[sm]],["GridSample",[A_,F_]],["GroupQueryAttention",[Y_]],["HardSigmoid",[Ah,Ih]],["InstanceNormalization",[tf]],["LayerNormalization",[nf]],["LeakyRelu",[Eh,go]],["Less",[rm]],["LessOrEqual",[nm]],["Log",[jh]],["MatMul",[af]],["MatMulNBits",[df,pf]],["MaxPool",[Sf,$f]],["Mul",[Yh]],["MultiHeadAttention",[z_,D_]],["Neg",[Ch]],["Not",[Ph]],["Pad",[yf]],["Pow",[Zh]],["QuickGelu",[Uh,go]],["Range",[Bf]],["Reciprocal",[Sh]],["ReduceMin",[Rp]],["ReduceMean",[Op]],["ReduceMax",[Bp]],["ReduceSum",[Np]],["ReduceProd",[jp]],["ReduceL1",[Dp]],["ReduceL2",[Lp]],["ReduceLogSum",[Up]],["ReduceLogSumExp",[zp]],["ReduceSumSquare",[Vp]],["Relu",[$h]],["Resize",[og,ig]],["RotaryEmbedding",[H_]],["ScatterND",[Vf,Nf]],["Sigmoid",[kh]],["Sin",[Fh]],["Sinh",[Oh]],["Slice",[mg,_g]],["SkipLayerNormalization",[cg]],["Split",[U_,W_]],["Sqrt",[Dh]],["Softmax",[wg,Mg]],["Sub",[em]],["Tan",[Lh]],["Tanh",[zh]],["ThresholdedRelu",[Rh,go]],["Tile",[xg]],["Transpose",[tp,rp]],["Where",[Pg]]])}),Sg,Gx=Ve(()=>{gs(),Bs(),Pt(),Sg=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t,s,o){fs(e.programInfo.name);let n=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let c of r)a.push({binding:a.length,resource:{buffer:c.buffer}});for(let c of t)a.push({binding:a.length,resource:{buffer:c.buffer}});o&&a.push({binding:a.length,resource:o});let l=n.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}i.setPipeline(e.computePipeline),i.setBindGroup(0,l),i.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(),cs(e.programInfo.name)}dispose(){}build(e,r){fs(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(c=>{t.features.has(c.feature)&&s.push(`enable ${c.extension};`)});let o=Qd(r,this.backend.device.limits),n=e.getShaderSource(o),i=`${s.join(` +`)} +${o.additionalImplementations} +${n}`,a=t.createShaderModule({code:i,label:e.name});Dt("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return cs(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let r=typeof e=="number"?e:e.x,t=typeof e=="number"?1:e.y||1,s=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=o&&t<=o&&s<=o)return[r,t,s];let n=r*t*s,i=Math.ceil(Math.sqrt(n));if(i>o){if(i=Math.ceil(Math.cbrt(n)),i>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),$g={};Nn($g,{WebGpuBackend:()=>Fg});var kg,Ig,Ag,Fg,Kx=Ve(()=>{gs(),gt(),Bs(),Dd(),rx(),Wx(),Gx(),kg=(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 s=0;s{var o,n;let s=e.name;return(o=e.shaderCache)!=null&&o.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${kg(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},Ag=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Fg=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,r){this.env=e;let t=[],s={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},o=n=>r.features.has(n)&&t.push(n)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new Ag(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Gd(this),this.programManager=new Sg(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ha(e.logLevel,!!e.debug),this.device.onuncapturederror=n=>{n.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${n.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;fs(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var s;let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let o=0;o"u"&&(this.queryTimeBase=f);let b=Number(f-this.queryTimeBase),k=Number(_-this.queryTimeBase);if(!Number.isSafeInteger(b)||!Number.isSafeInteger(k))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:d.map(g=>({dims:g.dims,dataType:zs(g.dataType)})),outputsMetadata:u.map(g=>({dims:g.dims,dataType:zs(g.dataType)})),kernelId:i,kernelType:l,kernelName:c,programName:p,startTime:b,endTime:k});else{let g="";d.forEach(($,v)=>{g+=`input[${v}]: [${$.dims}] | ${zs($.dataType)}, `});let M="";u.forEach(($,v)=>{M+=`output[${v}]: [${$.dims}] | ${zs($.dataType)}, `}),console.log(`[profiling] kernel "${i}|${l}|${c}|${p}" ${g}${M}execution time: ${k-b} ns`)}po("GPU",`${p}::${f}::${_}`)}e.unmap(),this.pendingQueries.delete(e)}),cs()}run(e,r,t,s,o,n){fs(e.name);let i=[];for(let M=0;M$):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let d=[],u=[];for(let M=0;M=n)throw new Error(`Invalid output index: ${p[M]}`);if(p[M]===-3)continue;let $=p[M]===-1,v=p[M]===-2,y=$||v?o(a[M].dataType,a[M].dims):s(p[M],a[M].dataType,a[M].dims);if(d.push(y),y.data===0)continue;let T=this.gpuDataManager.get(y.data);if(!T)throw new Error(`no GPU data for output: ${y.data}`);if($&&this.temporaryData.push(T),v){let x=this.kernelPersistentData.get(this.currentKernelId);x||(x=[],this.kernelPersistentData.set(this.currentKernelId,x)),x.push(T)}u.push(T)}if(i.length!==r.length||u.length!==d.length){if(u.length===0)return cs(e.name),d;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let f;if(c){let M=0,$=[];c.forEach(x=>{let P=typeof x.data=="number"?[x.data]:x.data;if(P.length===0)return;let O=x.type===10?2:4,L,G;x.type===10?(G=P.length>4?16:P.length>2?8:P.length*O,L=P.length>4?16:O*P.length):(G=P.length<=2?P.length*O:16,L=16),M=Math.ceil(M/G)*G,$.push(M);let K=x.type===10?8:4;M+=P.length>4?Math.ceil(P.length/K)*L:P.length*O});let v=16;M=Math.ceil(M/v)*v;let y=new ArrayBuffer(M);c.forEach((x,P)=>{let O=$[P],L=typeof x.data=="number"?[x.data]:x.data;if(x.type===6)new Int32Array(y,O,L.length).set(L);else if(x.type===12)new Uint32Array(y,O,L.length).set(L);else if(x.type===10)new Uint16Array(y,O,L.length).set(L);else if(x.type===1)new Float32Array(y,O,L.length).set(L);else throw new Error(`Unsupported uniform type: ${zs(x.type)}`)});let T=this.gpuDataManager.create(M,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(T.buffer,0,y,0,M),this.gpuDataManager.release(T.id),f={offset:0,size:M,buffer:T.buffer}}let _=this.programManager.normalizeDispatchGroupSize(l),b=_[1]===1&&_[2]===1,k=Ig(e,r,b),g=this.programManager.getArtifact(k);if(g||(g=this.programManager.build(e,_),this.programManager.setArtifact(k,g),Dt("info",()=>`[artifact] key: ${k}, programName: ${e.name}`)),c&&g.uniformVariablesInfo){if(c.length!==g.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${g.uniformVariablesInfo.length}, got ${c.length} in program "${g.programInfo.name}".`);for(let M=0;M`[ProgramManager] run "${e.name}" (key=${k}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let M={kernelId:this.currentKernelId,programName:g.programInfo.name,inputTensorViews:r,outputTensorViews:d};this.pendingKernels.push(M),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(M)}return this.programManager.run(g,i,u,_,f),cs(e.name),d}upload(e,r){this.gpuDataManager.upload(e,r)}memcpy(e,r){this.gpuDataManager.memcpy(e,r)}async download(e,r){await this.gpuDataManager.download(e,r)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,r,t,s){let o=Cg.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:s,kernelEntry:o[0],attributes:[o[1],t]};this.kernels.set(r,n)}releaseKernel(e){let r=this.kernelPersistentData.get(e);if(r){for(let t of r)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,r,t){let s=this.kernels.get(e);if(!s)throw new Error(`kernel not created: ${e}`);let o=s.kernelType,n=s.kernelName,i=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),Dt("info",()=>`[WebGPU] Start to run kernel "[${o}] ${n}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(r,a[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${n}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${o}] ${n}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let n=o.get(r),i=this.gpuDataManager.registerExternalBuffer(t,s,n);return o.set(r,[i,t]),i}unregisterBuffers(e){let r=this.sessionExternalDataMapping.get(e);r&&(r.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let r=this.gpuDataManager.get(e);if(!r)throw new Error(`no GPU data for buffer: ${e}`);return r.buffer}createDownloader(e,r,t){return async()=>{let s=await nl(this,e,r);return qa(s.buffer,t)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.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(){Dt("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(){Dt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Dt("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),t=e.length;this.pendingKernels=[];for(let s=0;s=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Og={};Nn(Og,{init:()=>Lg});var Mi,Dg,Lg,Hx=Ve(()=>{gt(),Bs(),Et(),tx(),Mi=class fv{constructor(r,t,s,o){this.module=r,this.dataType=t,this.data=s,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=ye.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=ye.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=ye.size(this.dims);return r===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,r)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let r=ye.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(ye.size(r)!==ye.size(this.dims))throw new Error("Invalid new shape");return new fv(this.module,this.dataType,this.data,r)}},Dg=class{constructor(e,r,t){this.module=e,this.backend=r,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=r.adapterInfo;let s=e.PTR_SIZE,o=t/e.PTR_SIZE,n=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*o++,n));let i=Number(e.getValue(s*o++,n));this.outputCount=Number(e.getValue(s*o++,n)),this.customDataOffset=Number(e.getValue(s*o++,"*")),this.customDataSize=Number(e.getValue(s*o++,n));let a=[];for(let l=0;ltypeof a=="number"?this.inputs[a]:a))??this.inputs,s=(r==null?void 0:r.outputs)??[],o=(a,l,c)=>new Mi(this.module,l,this.output(a,c),c),n=(a,l)=>{let c=pn(a,l);if(!c)throw new Error(`Unsupported data type: ${a}`);let p=c>0?this.backend.gpuDataManager.create(c).id:0;return new Mi(this.module,a,p,l)};return this.backend.run(e,t,s,o,n,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,o=s===4?"i32":"i64",n=this.module.stackAlloc((1+r.length)*s);this.module.setValue(n,r.length,o);for(let i=0;i{let o=r.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let n=(Kx(),lo($g)).WebGpuBackend,i=new n;await i.initialize(t,s),o("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,c,p=!1)=>{if(p)Dt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(c)}`),i.memcpy(Number(a),Number(l));else{Dt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(c)}`);let d=r.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(c));i.upload(Number(l),d)}},async(a,l,c)=>{Dt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${c}`),await i.download(Number(a),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+c)>>>0))},(a,l,c)=>i.createKernel(a,Number(l),c,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,c,p)=>{Dt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${a}, contextDataOffset=${l}`);let d=new Dg(r,i,Number(l));return i.computeKernel(Number(a),d,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let n=new Nd(t);o("webnn",[n,()=>n.reserveTensorId(),i=>n.releaseTensorId(i),async(i,a,l,c,p)=>n.ensureTensor(i,a,l,c,p),(i,a)=>{n.uploadTensor(i,a)},async(i,a)=>n.downloadTensor(i,a)])}}}),zg,Zl,ec,qs,Bg,tc,bi,rc,sc,nc,oc,ic,ac,Rg=Ve(()=>{Yv(),Zv(),gt(),dn(),Na(),Ed(),zg=(e,r)=>{Jt()._OrtInit(e,r)!==0&&Kt("Can't initialize onnxruntime.")},Zl=async e=>{zg(e.wasm.numThreads,oi(e.logLevel))},ec=async(e,r)=>{var t,s;(s=(t=Jt()).asyncInit)==null||s.call(t);{let o=(Hx(),lo(Og)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await o("webgpu",Jt(),e,n)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await o("webnn",Jt(),e)}}},qs=new Map,Bg=e=>{let r=Jt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,o,o+s)!==0&&Kt("Can't get session input/output count.");let n=s===4?"i32":"i64";return[Number(r.getValue(o,n)),Number(r.getValue(o+s,n))]}finally{r.stackRestore(t)}},tc=(e,r)=>{let t=Jt(),s=t.stackSave(),o=0;try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputMetadata(e,r,i,i+n)!==0&&Kt("Can't get session input/output metadata.");let a=Number(t.getValue(i,"*"));o=Number(t.getValue(i+n,"*"));let l=t.HEAP32[o/4];if(l===0)return[a,0];let c=t.HEAPU32[o/4+1],p=[];for(let d=0;d{let r=Jt(),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]},rc=async(e,r)=>{var d,u,f,_;let t,s,o=Jt();Array.isArray(e)?[t,s]=e:e.buffer===o.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=bi(e);let n=0,i=0,a=0,l=[],c=[],p=[];try{if([i,l]=await Td(r),(r==null?void 0:r.externalData)&&o.mountExternalData){let P=[];for(let O of r.externalData){let L=typeof O=="string"?O:O.path;P.push(Ka(typeof O=="string"?O:O.data).then(G=>{o.mountExternalData(L,G)}))}await Promise.all(P)}for(let P of(r==null?void 0:r.executionProviders)??[])if((typeof P=="string"?P:P.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof P!="string"){let O=P,L=O==null?void 0:O.context,G=O==null?void 0:O.gpuDevice,K=O==null?void 0:O.deviceType,R=O==null?void 0:O.powerPreference;L?o.currentContext=L:G?o.currentContext=await o.webnnCreateMLContext(G):o.currentContext=await o.webnnCreateMLContext({deviceType:K,powerPreference:R})}else o.currentContext=await o.webnnCreateMLContext();break}n=await o._OrtCreateSession(t,s,i),(d=o.webgpuOnCreateSession)==null||d.call(o,n),n===0&&Kt("Can't create a session."),(u=o.jsepOnCreateSession)==null||u.call(o),o.currentContext&&(o.webnnRegisterMLContext(n,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[b,k]=Bg(n),g=!!(r!=null&&r.enableGraphCapture),M=[],$=[],v=[],y=[],T=[];for(let P=0;PP==="gpu-buffer"||P==="ml-tensor")&&(a=o._OrtCreateBinding(n),a===0&&Kt("Can't create IO binding."),x={handle:a,outputPreferredLocations:T,outputPreferredLocationsEncoded:T.map(P=>Ga(P))}),qs.set(n,[n,c,p,x,g,!1]),[n,M,$,v,y]}catch(b){throw c.forEach(k=>o._OrtFree(k)),p.forEach(k=>o._OrtFree(k)),a!==0&&o._OrtReleaseBinding(a)!==0&&Kt("Can't release IO binding."),n!==0&&o._OrtReleaseSession(n)!==0&&Kt("Can't release session."),b}finally{o._free(t),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&Kt("Can't release session options."),l.forEach(b=>o._free(b)),(_=o.unmountExternalData)==null||_.call(o)}},sc=e=>{var l,c,p;let r=Jt(),t=qs.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,o,n,i,a]=t;i&&(a&&r._OrtClearBoundOutputs(i.handle)!==0&&Kt("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&Kt("Can't release IO binding.")),(l=r.jsepOnReleaseSession)==null||l.call(r,e),(c=r.webnnOnReleaseSession)==null||c.call(r,e),(p=r.webgpuOnReleaseSession)==null||p.call(r,e),o.forEach(d=>r._OrtFree(d)),n.forEach(d=>r._OrtFree(d)),r._OrtReleaseSession(s)!==0&&Kt("Can't release session."),qs.delete(e)},nc=async(e,r,t,s,o,n,i=!1)=>{if(!e){r.push(0);return}let a=Jt(),l=a.PTR_SIZE,c=e[0],p=e[1],d=e[3],u=d,f,_;if(c==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${n} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let g=e[2].gpuBuffer;_=pn(Vn(c),p);{let M=a.jsepRegisterBuffer;if(!M)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');f=M(s,n,g,_)}}else if(d==="ml-tensor"){let g=e[2].mlTensor;_=pn(Vn(c),p);let M=a.webnnRegisterMLTensor;if(!M)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');f=M(s,g,Vn(c),p)}else{let g=e[2];if(Array.isArray(g)){_=l*g.length,f=a._malloc(_),t.push(f);for(let M=0;Ma.setValue(k+$*l,M,l===4?"i32":"i64"));let g=a._OrtCreateTensor(Vn(c),f,_,k,p.length,Ga(u));g===0&&Kt(`Can't create tensor for input/output. session=${s}, index=${n}.`),r.push(g)}finally{a.stackRestore(b)}},oc=async(e,r,t,s,o,n)=>{var G,K,R,te;let i=Jt(),a=i.PTR_SIZE,l=qs.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],p=l[1],d=l[2],u=l[3],f=l[4],_=l[5],b=r.length,k=s.length,g=0,M=[],$=[],v=[],y=[],T=i.stackSave(),x=i.stackAlloc(b*a),P=i.stackAlloc(b*a),O=i.stackAlloc(k*a),L=i.stackAlloc(k*a);try{[g,M]=Md(n);for(let Z=0;ZX*ae,1);F=zs(_e);let Ie=u==null?void 0:u.outputPreferredLocations[s[Z]];if(F==="string"){if(Ie==="gpu-buffer"||Ie==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let X=[];for(let ae=0;ae0){let X=i.jsepGetBuffer;if(!X)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ae=X(U),W=pn(_e,Ge);if(W===void 0||!Ua(F))throw new Error(`Unsupported data type: ${F}`);j=!0,ee.push([F,ze,{gpuBuffer:ae,download:i.jsepCreateDownloader(ae,W,F),dispose:()=>{i._OrtReleaseTensor(ne)!==0&&Kt("Can't release tensor.")}},"gpu-buffer"])}else if(Ie==="ml-tensor"&&Ge>0){let X=i.webnnEnsureTensor,ae=i.webnnIsInt64Supported;if(!X||!ae)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(pn(_e,Ge)===void 0||!Wa(F))throw new Error(`Unsupported data type: ${F}`);if(F==="int64"&&!ae(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let W=await X(e,U,_e,ze,!1);j=!0,ee.push([F,ze,{mlTensor:W,download:i.webnnCreateMLTensorDownloader(U,F),dispose:()=>{i.webnnReleaseTensorId(U),i._OrtReleaseTensor(ne)}},"ml-tensor"])}else{let X=Va(F),ae=new X(Ge);new Uint8Array(ae.buffer,ae.byteOffset,ae.byteLength).set(i.HEAPU8.subarray(U,U+ae.byteLength)),ee.push([F,ze,ae,"cpu"])}}finally{i.stackRestore(me),F==="string"&&U&&i._free(U),j||i._OrtReleaseTensor(ne),(te=i.webnnOnRunEnd)==null||te.call(i,c)}}return u&&!f&&(i._OrtClearBoundOutputs(u.handle)!==0&&Kt("Can't clear bound outputs."),qs.set(e,[c,p,d,u,f,!1])),ee}finally{i.stackRestore(T),$.forEach(H=>i._OrtReleaseTensor(H)),v.forEach(H=>i._OrtReleaseTensor(H)),y.forEach(H=>i._free(H)),g!==0&&i._OrtReleaseRunOptions(g),M.forEach(H=>i._free(H))}},ic=e=>{let r=Jt(),t=qs.get(e);if(!t)throw new Error("invalid session id");let s=t[0],o=r._OrtEndProfiling(s);o===0&&Kt("Can't get an profile file name."),r._OrtFree(o)},ac=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),Qs,es,Kn,To,Eo,yi,lc,vi,Mn,bn,jg,Ng,Vg,Ug,Wg,Gg,Kg,Hg,qg=Ve(()=>{gs(),Rg(),dn(),za(),Qs=()=>!!Yt.wasm.proxy&&typeof document<"u",Kn=!1,To=!1,Eo=!1,vi=new Map,Mn=(e,r)=>{let t=vi.get(e);t?t.push(r):vi.set(e,[r])},bn=()=>{if(Kn||!To||Eo||!es)throw new Error("worker not ready")},jg=e=>{switch(e.data.type){case"init-wasm":Kn=!1,e.data.err?(Eo=!0,lc[1](e.data.err)):(To=!0,lc[0]()),yi&&(URL.revokeObjectURL(yi),yi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=vi.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},Ng=async()=>{if(!To){if(Kn)throw new Error("multiple calls to 'initWasm()' detected.");if(Eo)throw new Error("previous call to 'initWasm()' failed.");if(Kn=!0,Qs())return new Promise((e,r)=>{es==null||es.terminate(),md().then(([t,s])=>{try{es=s,es.onerror=n=>r(n),es.onmessage=jg,lc=[e,r];let o={type:"init-wasm",in:Yt};!o.in.wasm.wasmPaths&&(t||Fa)&&(o.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href}),es.postMessage(o),yi=t}catch(o){r(o)}},r)});try{await ja(Yt.wasm),await Zl(Yt),To=!0}catch(e){throw Eo=!0,e}finally{Kn=!1}}},Vg=async e=>{if(Qs())return bn(),new Promise((r,t)=>{Mn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Yt}};es.postMessage(s)});await ec(Yt,e)},Ug=async e=>Qs()?(bn(),new Promise((r,t)=>{Mn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};es.postMessage(s,[e.buffer])})):bi(e),Wg=async(e,r)=>{if(Qs()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return bn(),new Promise((t,s)=>{Mn("create",[t,s]);let o={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),es.postMessage(o,n)})}else return rc(e,r)},Gg=async e=>{if(Qs())return bn(),new Promise((r,t)=>{Mn("release",[r,t]);let s={type:"release",in:e};es.postMessage(s)});sc(e)},Kg=async(e,r,t,s,o,n)=>{if(Qs()){if(t.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return bn(),new Promise((i,a)=>{Mn("run",[i,a]);let l=t,c={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};es.postMessage(c,ac(l))})}else return oc(e,r,t,s,o,n)},Hg=async e=>{if(Qs())return bn(),new Promise((r,t)=>{Mn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};es.postMessage(s)});ic(e)}}),cc,Qg,Xg,qx=Ve(()=>{gs(),qg(),gt(),Ca(),Ed(),cc=(e,r)=>{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"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${r()}`)}},Qg=e=>{switch(e[3]){case"cpu":return new _s(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!Ua(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:o}=e[2];return _s.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:o})}case"ml-tensor":{let r=e[0];if(!Wa(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:o}=e[2];return _s.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},Xg=class{async fetchModelAndCopyToWasmMemory(e){return Ug(await Ka(e))}async loadModel(e,r){fs();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Wg(t,r),cs()}async dispose(){return Gg(this.sessionId)}async run(e,r,t){fs();let s=[],o=[];Object.entries(e).forEach(d=>{let u=d[0],f=d[1],_=this.inputNames.indexOf(u);if(_===-1)throw new Error(`invalid input '${u}'`);s.push(f),o.push(_)});let n=[],i=[];Object.entries(r).forEach(d=>{let u=d[0],f=d[1],_=this.outputNames.indexOf(u);if(_===-1)throw new Error(`invalid output '${u}'`);n.push(f),i.push(_)});let a=s.map((d,u)=>cc(d,()=>`input "${this.inputNames[o[u]]}"`)),l=n.map((d,u)=>d?cc(d,()=>`output "${this.outputNames[i[u]]}"`):null),c=await Kg(this.sessionId,o,a,i,l,t),p={};for(let d=0;ddc,initializeFlags:()=>uc,wasmBackend:()=>Yg});var uc,dc,Yg,Qx=Ve(()=>{gs(),qg(),qx(),uc=()=>{(typeof Yt.wasm.initTimeout!="number"||Yt.wasm.initTimeout<0)&&(Yt.wasm.initTimeout=0);let e=Yt.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Yt.wasm.simd=!1),typeof Yt.wasm.proxy!="boolean"&&(Yt.wasm.proxy=!1),typeof Yt.wasm.trace!="boolean"&&(Yt.wasm.trace=!1),typeof Yt.wasm.numThreads!="number"||!Number.isInteger(Yt.wasm.numThreads)||Yt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Yt.wasm.numThreads=1;else{let r=typeof navigator>"u"?Dv("node:os").cpus().length:navigator.hardwareConcurrency;Yt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},dc=class{async init(e){uc(),await Ng(),await Vg(e)}async createInferenceSessionHandler(e,r){let t=new Xg;return await t.loadModel(e,r),t}},Yg=new dc});gs(),gs(),gs();var Xx="1.22.0-dev.20250409-89f8206ba4",Jx=sd;{let e=(Qx(),lo(Jg)).wasmBackend;cn("webgpu",e,5),cn("webnn",e,5),cn("cpu",e,10),cn("wasm",e,10)}Object.defineProperty(Yt.versions,"web",{value:Xx,enumerable:!0});/** +* @license +* Copyright 2021 Google LLC. All Rights Reserved. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============================================================================= +*//** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Yx=Object.freeze({__proto__:null,get InferenceSession(){return Pa},get TRACE(){return po},get TRACE_FUNC_BEGIN(){return fs},get TRACE_FUNC_END(){return cs},get Tensor(){return _s},default:Jx,get env(){return Yt},get registerBackend(){return cn}}),js={},Zx={"onnxruntime-common":e=>{e.exports=Iv},"onnxruntime-web":e=>{e.exports=Yx},"?2ce3":()=>{},"?7992":()=>{},"?5af5":()=>{},"?2b25":()=>{},"?db59":()=>{},"?383f":()=>{},"?fa4b":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,r,t)=>{t.r(r),t.d(r,{Environment:()=>Oe,Interpreter:()=>ot,Template:()=>Qt,parse:()=>ie,tokenize:()=>p});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),o=class{constructor(S,Q){this.value=S,this.type=Q}};function n(S){return/\w/.test(S)}function i(S){return/[0-9]/.test(S)}var a=[["{%",s.OpenStatement],["%}",s.CloseStatement],["{{",s.OpenExpression],["}}",s.CloseExpression],["(",s.OpenParen],[")",s.CloseParen],["{",s.OpenCurlyBracket],["}",s.CloseCurlyBracket],["[",s.OpenSquareBracket],["]",s.CloseSquareBracket],[",",s.Comma],[".",s.Dot],[":",s.Colon],["|",s.Pipe],["<=",s.ComparisonBinaryOperator],[">=",s.ComparisonBinaryOperator],["==",s.ComparisonBinaryOperator],["!=",s.ComparisonBinaryOperator],["<",s.ComparisonBinaryOperator],[">",s.ComparisonBinaryOperator],["+",s.AdditiveBinaryOperator],["-",s.AdditiveBinaryOperator],["~",s.AdditiveBinaryOperator],["*",s.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],l=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function c(S,Q={}){return S.endsWith(` +`)&&(S=S.slice(0,-1)),Q.lstrip_blocks&&(S=S.replace(/^[ \t]*({[#%-])/gm,"$1")),Q.trim_blocks&&(S=S.replace(/([#%-]})\n/g,"$1")),S.replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{").replace(/-#}\s*/g,"#}").replace(/\s*{#-/g,"{#").replace(/{%\s*(end)?generation\s*%}/gs,"")}function p(S,Q={}){var rt,ft;const B=[],q=c(S,Q);let re=0,ge=0;const Fe=ht=>{let vt="";for(;ht(q[re]);){if(q[re]==="\\"){if(++re,re>=q.length)throw new SyntaxError("Unexpected end of input");const st=q[re++],zt=l.get(st);if(zt===void 0)throw new SyntaxError(`Unexpected escaped character: ${st}`);vt+=zt;continue}if(vt+=q[re++],re>=q.length)throw new SyntaxError("Unexpected end of input")}return vt};e:for(;re0){B.push(new o(st,s.Text));continue}}if(q[re]==="{"&&q[re+1]==="#"){re+=2;let st="";for(;q[re]!=="#"||q[re+1]!=="}";){if(re+2>=q.length)throw new SyntaxError("Missing end of comment tag");st+=q[re++]}B.push(new o(st,s.Comment)),re+=2;continue}Fe(st=>/\s/.test(st));const vt=q[re];if(vt==="-"||vt==="+"){const st=(ft=B.at(-1))==null?void 0:ft.type;if(st===s.Text||st===void 0)throw new SyntaxError(`Unexpected character: ${vt}`);switch(st){case s.Identifier:case s.NumericLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++re;const zt=Fe(i);B.push(new o(`${vt}${zt}`,zt.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[st,zt]of a){if(st==="}}"&&ge>0)continue;if(q.slice(re,re+st.length)===st){B.push(new o(st,zt)),zt===s.OpenExpression?ge=0:zt===s.OpenCurlyBracket?++ge:zt===s.CloseCurlyBracket&&--ge,re+=st.length;continue e}}if(vt==="'"||vt==='"'){++re;const st=Fe(zt=>zt!==vt);B.push(new o(st,s.StringLiteral)),++re;continue}if(i(vt)){let st=Fe(i);if(q[re]==="."&&i(q[re+1])){++re;const zt=Fe(i);st=`${st}.${zt}`}B.push(new o(st,s.NumericLiteral));continue}if(n(vt)){const st=Fe(n);B.push(new o(st,s.Identifier));continue}throw new SyntaxError(`Unexpected character: ${vt}`)}return B}var d=class{constructor(){J(this,"type","Statement")}},u=class extends d{constructor(Q){super();J(this,"type","Program");this.body=Q}},f=class extends d{constructor(Q,B,q){super();J(this,"type","If");this.test=Q,this.body=B,this.alternate=q}},_=class extends d{constructor(Q,B,q,re){super();J(this,"type","For");this.loopvar=Q,this.iterable=B,this.body=q,this.defaultBlock=re}},b=class extends d{constructor(){super(...arguments);J(this,"type","Break")}},k=class extends d{constructor(){super(...arguments);J(this,"type","Continue")}},g=class extends d{constructor(Q,B,q){super();J(this,"type","Set");this.assignee=Q,this.value=B,this.body=q}},M=class extends d{constructor(Q,B,q){super();J(this,"type","Macro");this.name=Q,this.args=B,this.body=q}},$=class extends d{constructor(Q){super();J(this,"type","Comment");this.value=Q}},v=class extends d{constructor(){super(...arguments);J(this,"type","Expression")}},y=class extends v{constructor(Q,B,q){super();J(this,"type","MemberExpression");this.object=Q,this.property=B,this.computed=q}},T=class extends v{constructor(Q,B){super();J(this,"type","CallExpression");this.callee=Q,this.args=B}},x=class extends v{constructor(Q){super();J(this,"type","Identifier");this.value=Q}},P=class extends v{constructor(Q){super();J(this,"type","Literal");this.value=Q}},O=class extends P{constructor(){super(...arguments);J(this,"type","IntegerLiteral")}},L=class extends P{constructor(){super(...arguments);J(this,"type","FloatLiteral")}},G=class extends P{constructor(){super(...arguments);J(this,"type","StringLiteral")}},K=class extends P{constructor(){super(...arguments);J(this,"type","ArrayLiteral")}},R=class extends P{constructor(){super(...arguments);J(this,"type","TupleLiteral")}},te=class extends P{constructor(){super(...arguments);J(this,"type","ObjectLiteral")}},H=class extends v{constructor(Q,B,q){super();J(this,"type","BinaryExpression");this.operator=Q,this.left=B,this.right=q}},ee=class extends v{constructor(Q,B){super();J(this,"type","FilterExpression");this.operand=Q,this.filter=B}},Z=class extends d{constructor(Q,B){super();J(this,"type","FilterStatement");this.filter=Q,this.body=B}},ne=class extends v{constructor(Q,B){super();J(this,"type","SelectExpression");this.lhs=Q,this.test=B}},me=class extends v{constructor(Q,B,q){super();J(this,"type","TestExpression");this.operand=Q,this.negate=B,this.test=q}},ue=class extends v{constructor(Q,B){super();J(this,"type","UnaryExpression");this.operator=Q,this.argument=B}},j=class extends v{constructor(Q=void 0,B=void 0,q=void 0){super();J(this,"type","SliceExpression");this.start=Q,this.stop=B,this.step=q}},F=class extends v{constructor(Q,B){super();J(this,"type","KeywordArgumentExpression");this.key=Q,this.value=B}},U=class extends v{constructor(Q){super();J(this,"type","SpreadExpression");this.argument=Q}},se=class extends d{constructor(Q,B,q){super();J(this,"type","CallStatement");this.call=Q,this.callerArgs=B,this.body=q}},_e=class extends v{constructor(Q,B,q){super();J(this,"type","Ternary");this.condition=Q,this.trueExpr=B,this.falseExpr=q}};function ie(S){const Q=new u([]);let B=0;function q(Re,je){const et=S[B++];if(!et||et.type!==Re)throw new Error(`Parser Error: ${je}. ${et.type} !== ${Re}.`);return et}function re(Re){if(!ft(Re))throw new SyntaxError(`Expected ${Re}`);++B}function ge(){switch(S[B].type){case s.Comment:return new $(S[B++].value);case s.Text:return ht();case s.OpenStatement:return vt();case s.OpenExpression:return st();default:throw new SyntaxError(`Unexpected token type: ${S[B].type}`)}}function Fe(...Re){return B+Re.length<=S.length&&Re.every((je,et)=>je===S[B+et].type)}function rt(...Re){var je,et,Xt;return((je=S[B])==null?void 0:je.type)===s.OpenStatement&&((et=S[B+1])==null?void 0:et.type)===s.Identifier&&Re.includes((Xt=S[B+1])==null?void 0:Xt.value)}function ft(...Re){return B+Re.length<=S.length&&Re.every((je,et)=>S[B+et].type==="Identifier"&&je===S[B+et].value)}function ht(){return new G(q(s.Text,"Expected text token").value)}function vt(){if(q(s.OpenStatement,"Expected opening statement token"),S[B].type!==s.Identifier)throw new SyntaxError(`Unknown statement, got ${S[B].type}`);const Re=S[B].value;let je;switch(Re){case"set":++B,je=zt();break;case"if":++B,je=Ut(),q(s.OpenStatement,"Expected {% token"),re("endif"),q(s.CloseStatement,"Expected %} token");break;case"macro":++B,je=Nr(),q(s.OpenStatement,"Expected {% token"),re("endmacro"),q(s.CloseStatement,"Expected %} token");break;case"for":++B,je=rr(),q(s.OpenStatement,"Expected {% token"),re("endfor"),q(s.CloseStatement,"Expected %} token");break;case"call":{++B;let et=null;Fe(s.OpenParen)&&(et=ts());const Xt=Gr();if(Xt.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const Vs=ts();q(s.CloseStatement,"Expected closing statement token");const Es=[];for(;!rt("endcall");)Es.push(ge());q(s.OpenStatement,"Expected '{%'"),re("endcall"),q(s.CloseStatement,"Expected closing statement token");const Us=new T(Xt,Vs);je=new se(Us,et,Es);break}case"break":++B,q(s.CloseStatement,"Expected closing statement token"),je=new b;break;case"continue":++B,q(s.CloseStatement,"Expected closing statement token"),je=new k;break;case"filter":{++B;let et=Gr();et instanceof x&&Fe(s.OpenParen)&&(et=Wr(et)),q(s.CloseStatement,"Expected closing statement token");const Xt=[];for(;!rt("endfilter");)Xt.push(ge());q(s.OpenStatement,"Expected '{%'"),re("endfilter"),q(s.CloseStatement,"Expected '%}'"),je=new Z(et,Xt);break}default:throw new SyntaxError(`Unknown statement type: ${Re}`)}return je}function st(){q(s.OpenExpression,"Expected opening expression token");const Re=Sr();return q(s.CloseExpression,"Expected closing expression token"),Re}function zt(){const Re=Xr();let je=null;const et=[];if(Fe(s.Equals))++B,je=Xr();else{for(q(s.CloseStatement,"Expected %} token");!rt("endset");)et.push(ge());q(s.OpenStatement,"Expected {% token"),re("endset")}return q(s.CloseStatement,"Expected closing statement token"),new g(Re,je,et)}function Ut(){const Re=Sr();q(s.CloseStatement,"Expected closing statement token");const je=[],et=[];for(;!rt("elif","else","endif");)je.push(ge());if(rt("elif")){++B,++B;const Xt=Ut();et.push(Xt)}else if(rt("else"))for(++B,++B,q(s.CloseStatement,"Expected closing statement token");!rt("endif");)et.push(ge());return new f(Re,je,et)}function Nr(){const Re=Gr();if(Re.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const je=ts();q(s.CloseStatement,"Expected closing statement token");const et=[];for(;!rt("endmacro");)et.push(ge());return new M(Re,je,et)}function Xr(Re=!1){const je=Re?Gr:Sr,et=[je()],Xt=Fe(s.Comma);for(;Xt&&(++B,et.push(je()),!!Fe(s.Comma)););return Xt?new R(et):et[0]}function rr(){const Re=Xr(!0);if(!(Re instanceof x||Re instanceof R))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Re.type} instead`);if(!ft("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++B;const je=Sr();q(s.CloseStatement,"Expected closing statement token");const et=[];for(;!rt("endfor","else");)et.push(ge());const Xt=[];if(rt("else"))for(++B,++B,q(s.CloseStatement,"Expected closing statement token");!rt("endfor");)Xt.push(ge());return new _(Re,je,et,Xt)}function Sr(){return $r()}function $r(){const Re=Vr();if(ft("if")){++B;const je=Vr();if(ft("else")){++B;const et=$r();return new _e(je,Re,et)}else return new ne(Re,je)}return Re}function Vr(){let Re=ds();for(;ft("or");){const je=S[B];++B;const et=ds();Re=new H(je,Re,et)}return Re}function ds(){let Re=kr();for(;ft("and");){const je=S[B];++B;const et=kr();Re=new H(je,Re,et)}return Re}function kr(){let Re;for(;ft("not");){const je=S[B];++B;const et=kr();Re=new ue(je,et)}return Re??Os()}function Os(){let Re=Ds();for(;;){let je;if(ft("not","in"))je=new o("not in",s.Identifier),B+=2;else if(ft("in"))je=S[B++];else if(Fe(s.ComparisonBinaryOperator))je=S[B++];else break;const et=Ds();Re=new H(je,Re,et)}return Re}function Ds(){let Re=mr();for(;Fe(s.AdditiveBinaryOperator);){const je=S[B];++B;const et=mr();Re=new H(je,Re,et)}return Re}function Ur(){const Re=pr(Gr());return Fe(s.OpenParen)?Wr(Re):Re}function Wr(Re){let je=new T(Re,ts());return je=pr(je),Fe(s.OpenParen)&&(je=Wr(je)),je}function ts(){q(s.OpenParen,"Expected opening parenthesis for arguments list");const Re=Dr();return q(s.CloseParen,"Expected closing parenthesis for arguments list"),Re}function Dr(){const Re=[];for(;!Fe(s.CloseParen);){let je;if(S[B].type===s.MultiplicativeBinaryOperator&&S[B].value==="*"){++B;const et=Sr();je=new U(et)}else if(je=Sr(),Fe(s.Equals)){if(++B,!(je instanceof x))throw new SyntaxError("Expected identifier for keyword argument");const et=Sr();je=new F(je,et)}Re.push(je),Fe(s.Comma)&&++B}return Re}function Ts(){const Re=[];let je=!1;for(;!Fe(s.CloseSquareBracket);)Fe(s.Colon)?(Re.push(void 0),++B,je=!0):(Re.push(Sr()),Fe(s.Colon)&&(++B,je=!0));if(Re.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(je){if(Re.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new j(...Re)}return Re[0]}function pr(Re){for(;Fe(s.Dot)||Fe(s.OpenSquareBracket);){const je=S[B];++B;let et;const Xt=je.type===s.OpenSquareBracket;if(Xt)et=Ts(),q(s.CloseSquareBracket,"Expected closing square bracket");else if(et=Gr(),et.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Re=new y(Re,et,Xt)}return Re}function mr(){let Re=Jr();for(;Fe(s.MultiplicativeBinaryOperator);){const je=S[B++],et=Jr();Re=new H(je,Re,et)}return Re}function Jr(){let Re=Ns();for(;ft("is");){++B;const je=ft("not");je&&++B;const et=Gr();if(!(et instanceof x))throw new SyntaxError("Expected identifier for the test");Re=new me(Re,je,et)}return Re}function Ns(){let Re=Ur();for(;Fe(s.Pipe);){++B;let je=Gr();if(!(je instanceof x))throw new SyntaxError("Expected identifier for the filter");Fe(s.OpenParen)&&(je=Wr(je)),Re=new ee(Re,je)}return Re}function Gr(){const Re=S[B++];switch(Re.type){case s.NumericLiteral:{const je=Re.value;return je.includes(".")?new L(Number(je)):new O(Number(je))}case s.StringLiteral:{let je=Re.value;for(;Fe(s.StringLiteral);)je+=S[B++].value;return new G(je)}case s.Identifier:return new x(Re.value);case s.OpenParen:{const je=Xr();return q(s.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),je}case s.OpenSquareBracket:{const je=[];for(;!Fe(s.CloseSquareBracket);)je.push(Sr()),Fe(s.Comma)&&++B;return++B,new K(je)}case s.OpenCurlyBracket:{const je=new Map;for(;!Fe(s.CloseCurlyBracket);){const et=Sr();q(s.Colon,"Expected colon between key and value in object literal");const Xt=Sr();je.set(et,Xt),Fe(s.Comma)&&++B}return++B,new te(je)}default:throw new SyntaxError(`Unexpected token: ${Re.type}`)}}for(;B=0?(Q=(Q??(Q=0))<0?Math.max(S.length+Q,0):Math.min(Q,S.length),B=(B??(B=S.length))<0?Math.max(S.length+B,0):Math.min(B,S.length)):(Q=(Q??(Q=S.length-1))<0?Math.max(S.length+Q,-1):Math.min(Q,S.length-1),B=(B??(B=-1))<-1?Math.max(S.length+B,-1):Math.min(B,S.length-1));const ge=[];for(let Fe=Q;re*FeQ.toUpperCase())}function Ie(S){return X(new Date,S)}function X(S,Q){const B=new Intl.DateTimeFormat(void 0,{month:"long"}),q=new Intl.DateTimeFormat(void 0,{month:"short"}),re=ge=>ge<10?"0"+ge:ge.toString();return Q.replace(/%[YmdbBHM%]/g,ge=>{switch(ge){case"%Y":return S.getFullYear().toString();case"%m":return re(S.getMonth()+1);case"%d":return re(S.getDate());case"%b":return q.format(S);case"%B":return B.format(S);case"%H":return re(S.getHours());case"%M":return re(S.getMinutes());case"%%":return"%";default:return ge}})}function ae(S){return S.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function W(S,Q,B,q){if(q===0)return S;let re=q==null||q<0?1/0:q;const ge=Q.length===0?new RegExp("(?=)","gu"):new RegExp(ae(Q),"gu");return S.replaceAll(ge,Fe=>re>0?(--re,B):Fe)}var be=class extends Error{},ke=class extends Error{},Ee=class{constructor(S=void 0){J(this,"type","RuntimeValue");J(this,"value");J(this,"builtins",new Map);this.value=S}__bool__(){return new Ae(!!this.value)}toString(){return String(this.value)}},Me=class extends Ee{constructor(){super(...arguments);J(this,"type","IntegerValue")}},Se=class extends Ee{constructor(){super(...arguments);J(this,"type","FloatValue")}toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},we=class extends Ee{constructor(){super(...arguments);J(this,"type","StringValue");J(this,"builtins",new Map([["upper",new Ke(()=>new we(this.value.toUpperCase()))],["lower",new Ke(()=>new we(this.value.toLowerCase()))],["strip",new Ke(()=>new we(this.value.trim()))],["title",new Ke(()=>new we(Ge(this.value)))],["capitalize",new Ke(()=>new we(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new Me(this.value.length)],["rstrip",new Ke(()=>new we(this.value.trimEnd()))],["lstrip",new Ke(()=>new we(this.value.trimStart()))],["startswith",new Ke(Q=>{if(Q.length===0)throw new Error("startswith() requires at least one argument");const B=Q[0];if(B instanceof we)return new Ae(this.value.startsWith(B.value));if(B instanceof xe){for(const q of B.value){if(!(q instanceof we))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(q.value))return new Ae(!0)}return new Ae(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Ke(Q=>{if(Q.length===0)throw new Error("endswith() requires at least one argument");const B=Q[0];if(B instanceof we)return new Ae(this.value.endsWith(B.value));if(B instanceof xe){for(const q of B.value){if(!(q instanceof we))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(q.value))return new Ae(!0)}return new Ae(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Ke(Q=>{const B=Q[0]??new nt;if(!(B instanceof we||B instanceof nt))throw new Error("sep argument must be a string or null");const q=Q[1]??new Me(-1);if(!(q instanceof Me))throw new Error("maxsplit argument must be a number");let re=[];if(B instanceof nt){const ge=this.value.trimStart();for(const{0:Fe,index:rt}of ge.matchAll(/\S+/g)){if(q.value!==-1&&re.length>=q.value&&rt!==void 0){re.push(Fe+ge.slice(rt+Fe.length));break}re.push(Fe)}}else{if(B.value==="")throw new Error("empty separator");re=this.value.split(B.value),q.value!==-1&&re.length>q.value&&re.push(re.splice(q.value).join(B.value))}return new xe(re.map(ge=>new we(ge)))})],["replace",new Ke(Q=>{if(Q.length<2)throw new Error("replace() requires at least two arguments");const B=Q[0],q=Q[1];if(!(B instanceof we&&q instanceof we))throw new Error("replace() arguments must be strings");let re;if(Q.length>2?Q[2].type==="KeywordArgumentsValue"?re=Q[2].value.get("count")??new nt:re=Q[2]:re=new nt,!(re instanceof Me||re instanceof nt))throw new Error("replace() count argument must be a number or null");return new we(W(this.value,B.value,q.value,re.value))})]]))}},Ae=class extends Ee{constructor(){super(...arguments);J(this,"type","BooleanValue")}},Be=class extends Ee{constructor(){super(...arguments);J(this,"type","ObjectValue");J(this,"builtins",new Map([["get",new Ke(([Q,B])=>{if(!(Q instanceof we))throw new Error(`Object key must be a string: got ${Q.type}`);return this.value.get(Q.value)??B??new nt})],["items",new Ke(()=>this.items())],["keys",new Ke(()=>this.keys())],["values",new Ke(()=>this.values())]]))}__bool__(){return new Ae(this.value.size>0)}items(){return new xe(Array.from(this.value.entries()).map(([Q,B])=>new xe([new we(Q),B])))}keys(){return new xe(Array.from(this.value.keys()).map(Q=>new we(Q)))}values(){return new xe(Array.from(this.value.values()))}},Qe=class extends Be{constructor(){super(...arguments);J(this,"type","KeywordArgumentsValue")}},xe=class extends Ee{constructor(){super(...arguments);J(this,"type","ArrayValue");J(this,"builtins",new Map([["length",new Me(this.value.length)]]))}__bool__(){return new Ae(this.value.length>0)}},Ze=class extends xe{constructor(){super(...arguments);J(this,"type","TupleValue")}},Ke=class extends Ee{constructor(){super(...arguments);J(this,"type","FunctionValue")}},nt=class extends Ee{constructor(){super(...arguments);J(this,"type","NullValue")}},Je=class extends Ee{constructor(){super(...arguments);J(this,"type","UndefinedValue")}},Oe=class{constructor(S){J(this,"variables",new Map([["namespace",new Ke(S=>{if(S.length===0)return new Be(new Map);if(S.length!==1||!(S[0]instanceof Be))throw new Error("`namespace` expects either zero arguments or a single object argument");return S[0]})]]));J(this,"tests",new Map([["boolean",S=>S.type==="BooleanValue"],["callable",S=>S instanceof Ke],["odd",S=>{if(!(S instanceof Me))throw new Error(`cannot odd on ${S.type}`);return S.value%2!==0}],["even",S=>{if(!(S instanceof Me))throw new Error(`cannot even on ${S.type}`);return S.value%2===0}],["false",S=>S.type==="BooleanValue"&&!S.value],["true",S=>S.type==="BooleanValue"&&S.value],["none",S=>S.type==="NullValue"],["string",S=>S.type==="StringValue"],["number",S=>S instanceof Me||S instanceof Se],["integer",S=>S instanceof Me],["iterable",S=>S.type==="ArrayValue"||S.type==="StringValue"],["mapping",S=>S.type==="ObjectValue"],["lower",S=>{const Q=S.value;return S.type==="StringValue"&&Q===Q.toLowerCase()}],["upper",S=>{const Q=S.value;return S.type==="StringValue"&&Q===Q.toUpperCase()}],["none",S=>S.type==="NullValue"],["defined",S=>S.type!=="UndefinedValue"],["undefined",S=>S.type==="UndefinedValue"],["equalto",(S,Q)=>S.value===Q.value],["eq",(S,Q)=>S.value===Q.value]]));this.parent=S}set(S,Q){return this.declareVariable(S,It(Q))}declareVariable(S,Q){if(this.variables.has(S))throw new SyntaxError(`Variable already declared: ${S}`);return this.variables.set(S,Q),Q}setVariable(S,Q){return this.variables.set(S,Q),Q}resolve(S){if(this.variables.has(S))return this;if(this.parent)return this.parent.resolve(S);throw new Error(`Unknown variable: ${S}`)}lookupVariable(S){try{return this.resolve(S).variables.get(S)??new Je}catch{return new Je}}};function Ye(S){S.set("false",!1),S.set("true",!0),S.set("none",null),S.set("raise_exception",Q=>{throw new Error(Q)}),S.set("range",ve),S.set("strftime_now",Ie),S.set("True",!0),S.set("False",!1),S.set("None",null)}var ot=class{constructor(S){J(this,"global");this.global=S??new Oe}run(S){return this.evaluate(S,this.global)}evaluateBinaryExpression(S,Q){const B=this.evaluate(S.left,Q);switch(S.operator.value){case"and":return B.__bool__().value?this.evaluate(S.right,Q):B;case"or":return B.__bool__().value?B:this.evaluate(S.right,Q)}const q=this.evaluate(S.right,Q);switch(S.operator.value){case"==":return new Ae(B.value==q.value);case"!=":return new Ae(B.value!=q.value)}if(B instanceof Je||q instanceof Je){if(q instanceof Je&&["in","not in"].includes(S.operator.value))return new Ae(S.operator.value==="not in");throw new Error(`Cannot perform operation ${S.operator.value} on undefined values`)}else{if(B instanceof nt||q instanceof nt)throw new Error("Cannot perform operation on null values");if(S.operator.value==="~")return new we(B.value.toString()+q.value.toString());if((B instanceof Me||B instanceof Se)&&(q instanceof Me||q instanceof Se)){const re=B.value,ge=q.value;switch(S.operator.value){case"+":case"-":case"*":{const Fe=S.operator.value==="+"?re+ge:S.operator.value==="-"?re-ge:re*ge;return B instanceof Se||q instanceof Se?new Se(Fe):new Me(Fe)}case"/":return new Se(re/ge);case"%":{const Fe=re%ge;return B instanceof Se||q instanceof Se?new Se(Fe):new Me(Fe)}case"<":return new Ae(re":return new Ae(re>ge);case">=":return new Ae(re>=ge);case"<=":return new Ae(re<=ge)}}else if(B instanceof xe&&q instanceof xe)switch(S.operator.value){case"+":return new xe(B.value.concat(q.value))}else if(q instanceof xe){const re=q.value.find(ge=>ge.value===B.value)!==void 0;switch(S.operator.value){case"in":return new Ae(re);case"not in":return new Ae(!re)}}}if(B instanceof we||q instanceof we)switch(S.operator.value){case"+":return new we(B.value.toString()+q.value.toString())}if(B instanceof we&&q instanceof we)switch(S.operator.value){case"in":return new Ae(q.value.includes(B.value));case"not in":return new Ae(!q.value.includes(B.value))}if(B instanceof we&&q instanceof Be)switch(S.operator.value){case"in":return new Ae(q.value.has(B.value));case"not in":return new Ae(!q.value.has(B.value))}throw new SyntaxError(`Unknown operator "${S.operator.value}" between ${B.type} and ${q.type}`)}evaluateArguments(S,Q){const B=[],q=new Map;for(const re of S)if(re.type==="SpreadExpression"){const ge=re,Fe=this.evaluate(ge.argument,Q);if(!(Fe instanceof xe))throw new Error(`Cannot unpack non-iterable type: ${Fe.type}`);for(const rt of Fe.value)B.push(rt)}else if(re.type==="KeywordArgumentExpression"){const ge=re;q.set(ge.key.value,this.evaluate(ge.value,Q))}else{if(q.size>0)throw new Error("Positional arguments must come before keyword arguments");B.push(this.evaluate(re,Q))}return[B,q]}applyFilter(S,Q,B){if(Q.type==="Identifier"){const q=Q;if(q.value==="tojson")return new we(St(S));if(S instanceof xe)switch(q.value){case"list":return S;case"first":return S.value[0];case"last":return S.value[S.value.length-1];case"length":return new Me(S.value.length);case"reverse":return new xe(S.value.reverse());case"sort":return new xe(S.value.sort((re,ge)=>{if(re.type!==ge.type)throw new Error(`Cannot compare different types: ${re.type} and ${ge.type}`);switch(re.type){case"IntegerValue":case"FloatValue":return re.value-ge.value;case"StringValue":return re.value.localeCompare(ge.value);default:throw new Error(`Cannot compare type: ${re.type}`)}}));case"join":return new we(S.value.map(re=>re.value).join(""));case"string":return new we(St(S));case"unique":{const re=new Set,ge=[];for(const Fe of S.value)re.has(Fe.value)||(re.add(Fe.value),ge.push(Fe));return new xe(ge)}default:throw new Error(`Unknown ArrayValue filter: ${q.value}`)}else if(S instanceof we)switch(q.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const re=S.builtins.get(q.value);if(re instanceof Ke)return re.value([],B);if(re instanceof Me)return re;throw new Error(`Unknown StringValue filter: ${q.value}`)}case"trim":return new we(S.value.trim());case"indent":return new we(S.value.split(` +`).map((re,ge)=>ge===0||re.length===0?re:" "+re).join(` +`));case"join":case"string":return S;case"int":{const re=parseInt(S.value,10);return new Me(isNaN(re)?0:re)}case"float":{const re=parseFloat(S.value);return new Se(isNaN(re)?0:re)}default:throw new Error(`Unknown StringValue filter: ${q.value}`)}else if(S instanceof Me||S instanceof Se)switch(q.value){case"abs":return S instanceof Me?new Me(Math.abs(S.value)):new Se(Math.abs(S.value));case"int":return new Me(Math.floor(S.value));case"float":return new Se(S.value);default:throw new Error(`Unknown NumericValue filter: ${q.value}`)}else if(S instanceof Be)switch(q.value){case"items":return new xe(Array.from(S.value.entries()).map(([re,ge])=>new xe([new we(re),ge])));case"length":return new Me(S.value.size);default:throw new Error(`Unknown ObjectValue filter: ${q.value}`)}else if(S instanceof Ae)switch(q.value){case"bool":return new Ae(S.value);case"int":return new Me(S.value?1:0);case"float":return new Se(S.value?1:0);case"string":return new we(S.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${q.value}`)}throw new Error(`Cannot apply filter "${q.value}" to type: ${S.type}`)}else if(Q.type==="CallExpression"){const q=Q;if(q.callee.type!=="Identifier")throw new Error(`Unknown filter: ${q.callee.type}`);const re=q.callee.value;if(re==="tojson"){const[,ge]=this.evaluateArguments(q.args,B),Fe=ge.get("indent")??new nt;if(!(Fe instanceof Me||Fe instanceof nt))throw new Error("If set, indent must be a number");return new we(St(S,Fe.value))}else if(re==="join"){let ge;if(S instanceof we)ge=Array.from(S.value);else if(S instanceof xe)ge=S.value.map(ht=>ht.value);else throw new Error(`Cannot apply filter "${re}" to type: ${S.type}`);const[Fe,rt]=this.evaluateArguments(q.args,B),ft=Fe.at(0)??rt.get("separator")??new we("");if(!(ft instanceof we))throw new Error("separator must be a string");return new we(ge.join(ft.value))}else if(re==="int"||re==="float"){const[ge,Fe]=this.evaluateArguments(q.args,B),rt=ge.at(0)??Fe.get("default")??(re==="int"?new Me(0):new Se(0));if(S instanceof we){const ft=re==="int"?parseInt(S.value,10):parseFloat(S.value);return isNaN(ft)?rt:re==="int"?new Me(ft):new Se(ft)}else{if(S instanceof Me||S instanceof Se)return S;if(S instanceof Ae)return re==="int"?new Me(S.value?1:0):new Se(S.value?1:0);throw new Error(`Cannot apply filter "${re}" to type: ${S.type}`)}}else if(re==="default"){const[ge,Fe]=this.evaluateArguments(q.args,B),rt=ge[0]??new we(""),ft=ge[1]??Fe.get("boolean")??new Ae(!1);if(!(ft instanceof Ae))throw new Error("`default` filter flag must be a boolean");return S instanceof Je||ft.value&&!S.__bool__().value?rt:S}if(S instanceof xe){switch(re){case"selectattr":case"rejectattr":{const ge=re==="selectattr";if(S.value.some(st=>!(st instanceof Be)))throw new Error(`\`${re}\` can only be applied to array of objects`);if(q.args.some(st=>st.type!=="StringLiteral"))throw new Error(`arguments of \`${re}\` must be strings`);const[Fe,rt,ft]=q.args.map(st=>this.evaluate(st,B));let ht;if(rt){const st=B.tests.get(rt.value);if(!st)throw new Error(`Unknown test: ${rt.value}`);ht=st}else ht=(...st)=>st[0].__bool__().value;const vt=S.value.filter(st=>{const zt=st.value.get(Fe.value),Ut=zt?ht(zt,ft):!1;return ge?Ut:!Ut});return new xe(vt)}case"map":{const[,ge]=this.evaluateArguments(q.args,B);if(ge.has("attribute")){const Fe=ge.get("attribute");if(!(Fe instanceof we))throw new Error("attribute must be a string");const rt=ge.get("default"),ft=S.value.map(ht=>{if(!(ht instanceof Be))throw new Error("items in map must be an object");return ht.value.get(Fe.value)??rt??new Je});return new xe(ft)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${re}`)}else if(S instanceof we){switch(re){case"indent":{const[ge,Fe]=this.evaluateArguments(q.args,B),rt=ge.at(0)??Fe.get("width")??new Me(4);if(!(rt instanceof Me))throw new Error("width must be a number");const ft=ge.at(1)??Fe.get("first")??new Ae(!1),ht=ge.at(2)??Fe.get("blank")??new Ae(!1),vt=S.value.split(` +`),st=" ".repeat(rt.value),zt=vt.map((Ut,Nr)=>!ft.value&&Nr===0||!ht.value&&Ut.length===0?Ut:st+Ut);return new we(zt.join(` +`))}case"replace":{const ge=S.builtins.get("replace");if(!(ge instanceof Ke))throw new Error("replace filter not available");const[Fe,rt]=this.evaluateArguments(q.args,B);return ge.value([...Fe,new Qe(rt)],B)}}throw new Error(`Unknown StringValue filter: ${re}`)}else throw new Error(`Cannot apply filter "${re}" to type: ${S.type}`)}throw new Error(`Unknown filter: ${Q.type}`)}evaluateFilterExpression(S,Q){const B=this.evaluate(S.operand,Q);return this.applyFilter(B,S.filter,Q)}evaluateTestExpression(S,Q){const B=this.evaluate(S.operand,Q),q=Q.tests.get(S.test.value);if(!q)throw new Error(`Unknown test: ${S.test.value}`);const re=q(B);return new Ae(S.negate?!re:re)}evaluateSelectExpression(S,Q){return this.evaluate(S.test,Q).__bool__().value?this.evaluate(S.lhs,Q):new Je}evaluateUnaryExpression(S,Q){const B=this.evaluate(S.argument,Q);switch(S.operator.value){case"not":return new Ae(!B.value);default:throw new SyntaxError(`Unknown operator: ${S.operator.value}`)}}evaluateTernaryExpression(S,Q){return this.evaluate(S.condition,Q).__bool__().value?this.evaluate(S.trueExpr,Q):this.evaluate(S.falseExpr,Q)}evalProgram(S,Q){return this.evaluateBlock(S.body,Q)}evaluateBlock(S,Q){let B="";for(const q of S){const re=this.evaluate(q,Q);re.type!=="NullValue"&&re.type!=="UndefinedValue"&&(B+=re.toString())}return new we(B)}evaluateIdentifier(S,Q){return Q.lookupVariable(S.value)}evaluateCallExpression(S,Q){const[B,q]=this.evaluateArguments(S.args,Q);q.size>0&&B.push(new Qe(q));const re=this.evaluate(S.callee,Q);if(re.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${re.type}`);return re.value(B,Q)}evaluateSliceExpression(S,Q,B){if(!(S instanceof xe||S instanceof we))throw new Error("Slice object must be an array or string");const q=this.evaluate(Q.start,B),re=this.evaluate(Q.stop,B),ge=this.evaluate(Q.step,B);if(!(q instanceof Me||q instanceof Je))throw new Error("Slice start must be numeric or undefined");if(!(re instanceof Me||re instanceof Je))throw new Error("Slice stop must be numeric or undefined");if(!(ge instanceof Me||ge instanceof Je))throw new Error("Slice step must be numeric or undefined");return S instanceof xe?new xe(ze(S.value,q.value,re.value,ge.value)):new we(ze(Array.from(S.value),q.value,re.value,ge.value).join(""))}evaluateMemberExpression(S,Q){const B=this.evaluate(S.object,Q);let q;if(S.computed){if(S.property.type==="SliceExpression")return this.evaluateSliceExpression(B,S.property,Q);q=this.evaluate(S.property,Q)}else q=new we(S.property.value);let re;if(B instanceof Be){if(!(q instanceof we))throw new Error(`Cannot access property with non-string: got ${q.type}`);re=B.value.get(q.value)??B.builtins.get(q.value)}else if(B instanceof xe||B instanceof we)if(q instanceof Me)re=B.value.at(q.value),B instanceof we&&(re=new we(B.value.at(q.value)));else if(q instanceof we)re=B.builtins.get(q.value);else throw new Error(`Cannot access property with non-string/non-number: got ${q.type}`);else{if(!(q instanceof we))throw new Error(`Cannot access property with non-string: got ${q.type}`);re=B.builtins.get(q.value)}return re instanceof Ee?re:new Je}evaluateSet(S,Q){const B=S.value?this.evaluate(S.value,Q):this.evaluateBlock(S.body,Q);if(S.assignee.type==="Identifier"){const q=S.assignee.value;Q.setVariable(q,B)}else if(S.assignee.type==="TupleLiteral"){const q=S.assignee;if(!(B instanceof xe))throw new Error(`Cannot unpack non-iterable type in set: ${B.type}`);const re=B.value;if(re.length!==q.value.length)throw new Error(`Too ${q.value.length>re.length?"few":"many"} items to unpack in set`);for(let ge=0;geUt.setVariable(S.loopvar.value,st);else if(S.loopvar.type==="TupleLiteral"){const Ut=S.loopvar;if(st.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${st.type}`);const Nr=st;if(Ut.value.length!==Nr.value.length)throw new Error(`Too ${Ut.value.length>Nr.value.length?"few":"many"} items to unpack`);zt=Xr=>{for(let rr=0;rr0?ge[ht-1]:new Je],["nextitem",ht{var Fe;const re=new Oe(q);B=B.slice();let ge;((Fe=B.at(-1))==null?void 0:Fe.type)==="KeywordArgumentsValue"&&(ge=B.pop());for(let rt=0;rt{const ht=new Oe(ft);if(S.callerArgs)for(let vt=0;vtthis.evaluate(B,Q)));case"TupleLiteral":return new Ze(S.value.map(B=>this.evaluate(B,Q)));case"ObjectLiteral":{const B=new Map;for(const[q,re]of S.value){const ge=this.evaluate(q,Q);if(!(ge instanceof we))throw new Error(`Object keys must be strings: got ${ge.type}`);B.set(ge.value,this.evaluate(re,Q))}return new Be(B)}case"Identifier":return this.evaluateIdentifier(S,Q);case"CallExpression":return this.evaluateCallExpression(S,Q);case"MemberExpression":return this.evaluateMemberExpression(S,Q);case"UnaryExpression":return this.evaluateUnaryExpression(S,Q);case"BinaryExpression":return this.evaluateBinaryExpression(S,Q);case"FilterExpression":return this.evaluateFilterExpression(S,Q);case"FilterStatement":return this.evaluateFilterStatement(S,Q);case"TestExpression":return this.evaluateTestExpression(S,Q);case"SelectExpression":return this.evaluateSelectExpression(S,Q);case"Ternary":return this.evaluateTernaryExpression(S,Q);case"Comment":return new nt;default:throw new SyntaxError(`Unknown node type: ${S.type}`)}}};function It(S){switch(typeof S){case"number":return Number.isInteger(S)?new Me(S):new Se(S);case"string":return new we(S);case"boolean":return new Ae(S);case"undefined":return new Je;case"object":return S===null?new nt:Array.isArray(S)?new xe(S.map(It)):new Be(new Map(Object.entries(S).map(([Q,B])=>[Q,It(B)])));case"function":return new Ke((Q,B)=>{const q=S(...Q.map(re=>re.value))??null;return It(q)});default:throw new Error(`Cannot convert to runtime value: ${S}`)}}function St(S,Q,B){const q=B??0;switch(S.type){case"NullValue":case"UndefinedValue":return"null";case"IntegerValue":case"FloatValue":case"StringValue":case"BooleanValue":return JSON.stringify(S.value);case"ArrayValue":case"ObjectValue":{const re=Q?" ".repeat(Q):"",ge=` +`+re.repeat(q),Fe=ge+re;if(S.type==="ArrayValue"){const rt=S.value.map(ft=>St(ft,Q,q+1));return Q?`[${Fe}${rt.join(`,${Fe}`)}${ge}]`:`[${rt.join(", ")}]`}else{const rt=Array.from(S.value.entries()).map(([ft,ht])=>{const vt=`"${ft}": ${St(ht,Q,q+1)}`;return Q?`${Fe}${vt}`:vt});return Q?`{${rt.join(",")}${ge}}`:`{${rt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${S.type}`)}}var wt=` +`,Mr="{%- ",Pr=" -%}";function jr(S){switch(S.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return S.operator.value==="and"?1:S.operator.value==="in"||S.operator.value==="not in"?2:0}return 0}function us(S,Q=" "){const B=typeof Q=="number"?" ".repeat(Q):Q;return Cr(S.body,0,B).replace(/\n$/,"")}function qt(...S){return Mr+S.join(" ")+Pr}function Cr(S,Q,B){return S.map(q=>Xs(q,Q,B)).join(wt)}function Xs(S,Q,B){const q=B.repeat(Q);switch(S.type){case"Program":return Cr(S.body,Q,B);case"If":return Js(S,Q,B);case"For":return Ys(S,Q,B);case"Set":return Zs(S,Q,B);case"Macro":return pt(S,Q,B);case"Break":return q+qt("break");case"Continue":return q+qt("continue");case"CallStatement":return As(S,Q,B);case"FilterStatement":return Fs(S,Q,B);case"Comment":return q+"{# "+S.value+" #}";default:return q+"{{- "+Ct(S)+" -}}"}}function Js(S,Q,B){const q=B.repeat(Q),re=[];let ge=S;for(;ge&&(re.push({test:ge.test,body:ge.body}),ge.alternate.length===1&&ge.alternate[0].type==="If");)ge=ge.alternate[0];let Fe=q+qt("if",Ct(re[0].test))+wt+Cr(re[0].body,Q+1,B);for(let rt=1;rt0&&(Fe+=wt+q+qt("else")+wt+Cr(ge.alternate,Q+1,B)),Fe+=wt+q+qt("endif"),Fe}function Ys(S,Q,B){const q=B.repeat(Q);let re="";if(S.iterable.type==="SelectExpression"){const Fe=S.iterable;re=`${Ct(Fe.lhs)} if ${Ct(Fe.test)}`}else re=Ct(S.iterable);let ge=q+qt("for",Ct(S.loopvar),"in",re)+wt+Cr(S.body,Q+1,B);return S.defaultBlock.length>0&&(ge+=wt+q+qt("else")+wt+Cr(S.defaultBlock,Q+1,B)),ge+=wt+q+qt("endfor"),ge}function Zs(S,Q,B){const q=B.repeat(Q),re=Ct(S.assignee),ge=S.value?Ct(S.value):"",Fe=q+qt("set",`${re}${S.value?" = "+ge:""}`);return S.body.length===0?Fe:Fe+wt+Cr(S.body,Q+1,B)+wt+q+qt("endset")}function pt(S,Q,B){const q=B.repeat(Q),re=S.args.map(Ct).join(", ");return q+qt("macro",`${S.name.value}(${re})`)+wt+Cr(S.body,Q+1,B)+wt+q+qt("endmacro")}function As(S,Q,B){const q=B.repeat(Q),re=S.callerArgs&&S.callerArgs.length>0?`(${S.callerArgs.map(Ct).join(", ")})`:"",ge=Ct(S.call);let Fe=q+qt(`call${re}`,ge)+wt;return Fe+=Cr(S.body,Q+1,B)+wt,Fe+=q+qt("endcall"),Fe}function Fs(S,Q,B){const q=B.repeat(Q),re=S.filter.type==="Identifier"?S.filter.value:Ct(S.filter);let ge=q+qt("filter",re)+wt;return ge+=Cr(S.body,Q+1,B)+wt,ge+=q+qt("endfilter"),ge}function Ct(S,Q=-1){switch(S.type){case"SpreadExpression":return`*${Ct(S.argument)}`;case"Identifier":return S.value;case"IntegerLiteral":return`${S.value}`;case"FloatLiteral":return`${S.value}`;case"StringLiteral":return JSON.stringify(S.value);case"BinaryExpression":{const B=S,q=jr(B),re=Ct(B.left,q),ge=Ct(B.right,q+1),Fe=`${re} ${B.operator.value} ${ge}`;return q`${Ct(q)}: ${Ct(re)}`).join(", ")}}`;case"SliceExpression":{const B=S,q=B.start?Ct(B.start):"",re=B.stop?Ct(B.stop):"",ge=B.step?`:${Ct(B.step)}`:"";return`${q}:${re}${ge}`}case"KeywordArgumentExpression":{const B=S;return`${B.key.value}=${Ct(B.value)}`}case"Ternary":{const B=S,q=`${Ct(B.trueExpr)} if ${Ct(B.condition,0)} else ${Ct(B.falseExpr)}`;return Q>-1?`(${q})`:q}default:throw new Error(`Unknown expression type: ${S.type}`)}}var Qt=class{constructor(S){J(this,"parsed");const Q=p(S,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=ie(Q)}render(S){const Q=new Oe;if(Ye(Q),S)for(const[re,ge]of Object.entries(S))Q.set(re,ge);return new ot(Q).run(this.parsed).value}format(S){return us(this.parsed,(S==null?void 0:S.indent)||" ")}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>k,deviceToExecutionProviders:()=>_,isONNXProxy:()=>$,isONNXTensor:()=>g});var o=t("./src/env.js"),n=t("?2ce3"),i=t("onnxruntime-web"),a=t("onnxruntime-common");const l=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),c=[];let p,d;const u=Symbol.for("onnxruntime");if(u in globalThis)d=globalThis[u];else if(o.apis.IS_NODE_ENV){switch(d=n??(s||(s=t.t(n,2))),process.platform){case"win32":c.push("dml");break;case"linux":process.arch==="x64"&&c.push("cuda");break}c.push("cpu"),p=["cpu"]}else d=i,o.apis.IS_WEBNN_AVAILABLE&&c.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&c.push("webgpu"),c.push("wasm"),p=["wasm"];const f=d.InferenceSession;function _(v=null){if(!v)return p;switch(v){case"auto":return c;case"gpu":return c.filter(y=>["webgpu","cuda","dml","webnn-gpu"].includes(y))}if(c.includes(v))return[l[v]??v];throw new Error(`Unsupported device: "${v}". Should be one of: ${c.join(", ")}.`)}let b=null;async function k(v,y,T){b&&await b;const x=f.create(v,y);b??(b=x);const P=await x;return P.config=T,P}function g(v){return v instanceof d.Tensor}const M=d==null?void 0:d.env;M!=null&&M.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!M.wasm.wasmPaths&&(M.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`),M.wasm.proxy=!1),M!=null&&M.webgpu&&(M.webgpu.powerPreference="high-performance");function $(){var v;return(v=M==null?void 0:M.wasm)==null?void 0:v.proxy}o.env.backends.onnx=M},"./src/base/feature_extraction_utils.js":(e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>i,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(c){super(),this.config=c}static async from_pretrained(c,p={}){const d=await(0,n.getModelJSON)(c,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(d)}}function a(l,c){var p;if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${c} expects input to be a Float32Array or a Float64Array, but got ${((p=l==null?void 0:l.constructor)==null?void 0:p.name)??typeof l} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(e,r,t)=>{t.r(r),t.d(r,{ImageProcessor:()=>v,center_to_corners_format:()=>d,post_process_instance_segmentation:()=>$,post_process_object_detection:()=>u,post_process_panoptic_segmentation:()=>M,post_process_semantic_segmentation:()=>f});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/utils/image.js");var i=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function c(y,T,x=0,P=null){const O=y/T;let L=(0,n.bankers_round)(O)*T;return P!==null&&L>P&&(L=Math.floor(O)*T),LT&&F.push(se)}else{let se=(0,n.max)(j.data)[1];if(se===R-1||(U=(0,n.softmax)(j.data),U[se]ie*ee[(ve+1)%2])),Z.boxes.push(_e),Z.classes.push(se),Z.scores.push(U[se])}}te.push(Z)}return te}function f(y,T=null){const x=y.logits,P=x.dims[0];if(T!==null&&T.length!==P)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const O=[];for(let L=0;Lee[F]&&(ee[F]=j[F],Z[F]=ue)}const ne=new Array(K.dims[0]);for(let ue=0;ueue!==void 0);O.push({segmentation:H,labels:me})}return O}function _(y,T,x,P){const O=[],L=[],G=[];for(let K=0;Kx&&(O.push(te),L.push(Z),G.push(H))}return[O,L,G]}function b(y,T,x,P=.5,O=.8){const L=[];let G=0,K=0;const R=T[x].data;for(let H=0;H=P&&++K;let te=G>0&&K>0;return te&&(te=G/K>O),[te,L]}function k(y,T,x,P,O,L=null,G=null){const[K,R]=G??y[0].dims,te=new o.Tensor("int32",new Int32Array(K*R),[K,R]),H=[];if(G!==null)for(let ue=0;ueZ[U]&&(ee[U]=ue,Z[U]=F[U])}let ne=0;const me=te.data;for(let ue=0;ue200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(y,T)/Math.min(y,T)}`);let L=Math.round(y/x)*x,G=Math.round(T/x)*x;if(L*G>O){const K=Math.sqrt(y*T/O);L=Math.floor(y/K/x)*x,G=Math.floor(T/K/x)*x}else if(L*GL?te=Math.floor(L*R/O):L>O&&(R=Math.floor(O*te/L)),await T.resize(te,R,{resample:P}))}async crop_margin(T,x=200){const P=T.clone().grayscale(),O=(0,n.min)(P.data)[0],G=(0,n.max)(P.data)[0]-O;if(G===0)return T;const K=x/255;let R=P.width,te=P.height,H=0,ee=0;const Z=P.data;for(let ne=0;nethis.preprocess(L)));return{pixel_values:(0,o.stack)(P.map(L=>L.pixel_values),0),original_sizes:P.map(L=>L.original_size),reshaped_input_sizes:P.map(L=>L.reshaped_input_size)}}static async from_pretrained(T,x={}){const P=await(0,a.getModelJSON)(T,l.IMAGE_PROCESSOR_NAME,!0,x);return new this(P)}}},"./src/base/processing_utils.js":(e,r,t)=>{t.r(r),t.d(r,{Processor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(l,c,p){super(),this.config=l,this.components=c,this.chat_template=p}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(l,c={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,chat_template:this.chat_template??void 0,...c})}batch_decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...l)}decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...l)}async _call(l,...c){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...c);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,c={}){const[p,d,u]=await Promise.all([this.uses_processor_config?(0,n.getModelJSON)(l,s.PROCESSOR_NAME,!0,c):{},Promise.all(this.classes.filter(f=>f in this).map(async f=>{const _=await this[f].from_pretrained(l,c);return[f.replace(/_class$/,""),_]})).then(Object.fromEntries),this.uses_chat_template_file?(0,n.getModelText)(l,s.CHAT_TEMPLATE_NAME,!0,c):null]);return new this(p,d,u)}}J(i,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),J(i,"uses_processor_config",!1),J(i,"uses_chat_template_file",!1)},"./src/configs.js":(e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>p,PretrainedConfig:()=>c,getCacheShapes:()=>a});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js");async function n(d,u){return await(0,o.getModelJSON)(d,"config.json",!0,u)}function i(d){const u={};let f={};switch(d.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"voxtral":case"smolvlm":case"gemma3n":f=i(d.text_config);break;case"moondream1":f=i(d.phi_config);break;case"musicgen":f=i(d.decoder);break;case"multi_modality":f=i(d.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":u.num_heads="num_attention_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size";break;case"llama":case"arcee":case"lfm2":case"smollm3":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size",u.num_attention_heads="num_attention_heads",u.dim_kv="head_dim";break;case"qwen3":case"gemma":case"gemma2":case"gemma3_text":case"gemma3n_text":case"glm":case"helium":case"ernie4_5":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.dim_kv="head_dim";break;case"openelm":u.num_heads="num_kv_heads",u.num_layers="num_transformer_layers",u.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":u.num_heads="num_heads",u.num_layers="num_layers",u.hidden_size="hidden_size";break;case"bloom":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="hidden_size";break;case"mpt":u.num_heads="n_heads",u.num_layers="n_layers",u.hidden_size="d_model";break;case"exaone":u.num_heads="num_key_value_heads",u.num_layers="num_layers",u.dim_kv="head_dim",u.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":u.num_decoder_layers="num_decoder_layers",u.num_decoder_heads="num_heads",u.decoder_dim_kv="d_kv",u.num_encoder_layers="num_layers",u.num_encoder_heads="num_heads",u.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="d_model",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="d_model";break;case"speecht5":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="hidden_size",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="hidden_size";break;case"trocr":u.num_encoder_layers=u.num_decoder_layers="decoder_layers",u.num_encoder_heads=u.num_decoder_heads="decoder_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="d_model";break;case"musicgen_decoder":u.num_encoder_layers=u.num_decoder_layers="num_hidden_layers",u.num_encoder_heads=u.num_decoder_heads="num_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"moonshine":u.num_decoder_layers="decoder_num_hidden_layers",u.num_decoder_heads="decoder_num_key_value_heads",u.num_encoder_layers="encoder_num_hidden_layers",u.num_encoder_heads="encoder_num_key_value_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const b=i(d.decoder),k="num_decoder_layers"in b,g=(0,s.pick)(d,["model_type","is_encoder_decoder"]);return k?(g.num_decoder_layers=b.num_decoder_layers,g.num_decoder_heads=b.num_decoder_heads,g.decoder_hidden_size=b.decoder_hidden_size,g.num_encoder_layers=b.num_encoder_layers,g.num_encoder_heads=b.num_encoder_heads,g.encoder_hidden_size=b.encoder_hidden_size):(g.num_layers=b.num_layers,g.num_heads=b.num_heads,g.hidden_size=b.hidden_size),g}const _={...f,...(0,s.pick)(d,["model_type","multi_query","is_encoder_decoder"])};for(const b in u)_[b]=d[u[b]];return _}function a(d,u){if(d.model_type==="lfm2"){const f=(u==null?void 0:u.prefix)??"past_key_values",_=f==="present"?"present":"past",b={},{layer_types:k,num_attention_heads:g,num_key_value_heads:M,hidden_size:$,conv_L_cache:v}=d,y=$/g,T=(u==null?void 0:u.batch_size)??1;for(let x=0;x{var O,L;t.r(r),t.d(r,{apis:()=>g,env:()=>x});var s=t("?db59"),o=t("?383f"),n=t("?fa4b");const i="3.7.1",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes((O=self.constructor)==null?void 0:O.name),c=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,d=typeof navigator<"u"&&"ml"in navigator,u=typeof process<"u",f=u&&((L=process==null?void 0:process.release)==null?void 0:L.name)==="node",_=!P(s),b=!P(o),k=typeof globalThis.Deno<"u",g=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:c,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:d,IS_PROCESS_AVAILABLE:u,IS_NODE_ENV:f,IS_FS_AVAILABLE:_,IS_PATH_AVAILABLE:b}),M=_&&b;let $="./";if(M){const G=Object({url:self.location.href}).url;G?$=o.dirname(o.dirname(n.fileURLToPath(G))):typeof __dirname<"u"&&($=o.dirname(__dirname))}const v=M?o.join($,"/.cache/"):null,y="/models/",T=M?o.join($,y):y,x={version:i,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:T,useFS:_,useBrowserCache:c&&!k,useFSCache:_,cacheDir:v,useCustomCache:!1,customCache:null};function P(G){return Object.keys(G).length===0}},"./src/generation/configuration_utils.js":(e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>o});var s=t("./src/utils/core.js");class o{constructor(i){J(this,"max_length",20);J(this,"max_new_tokens",null);J(this,"min_length",0);J(this,"min_new_tokens",null);J(this,"early_stopping",!1);J(this,"max_time",null);J(this,"do_sample",!1);J(this,"num_beams",1);J(this,"num_beam_groups",1);J(this,"penalty_alpha",null);J(this,"use_cache",!0);J(this,"temperature",1);J(this,"top_k",50);J(this,"top_p",1);J(this,"typical_p",1);J(this,"epsilon_cutoff",0);J(this,"eta_cutoff",0);J(this,"diversity_penalty",0);J(this,"repetition_penalty",1);J(this,"encoder_repetition_penalty",1);J(this,"length_penalty",1);J(this,"no_repeat_ngram_size",0);J(this,"bad_words_ids",null);J(this,"force_words_ids",null);J(this,"renormalize_logits",!1);J(this,"constraints",null);J(this,"forced_bos_token_id",null);J(this,"forced_eos_token_id",null);J(this,"remove_invalid_values",!1);J(this,"exponential_decay_length_penalty",null);J(this,"suppress_tokens",null);J(this,"streamer",null);J(this,"begin_suppress_tokens",null);J(this,"forced_decoder_ids",null);J(this,"guidance_scale",null);J(this,"num_return_sequences",1);J(this,"output_attentions",!1);J(this,"output_hidden_states",!1);J(this,"output_scores",!1);J(this,"return_dict_in_generate",!1);J(this,"pad_token_id",null);J(this,"bos_token_id",null);J(this,"eos_token_id",null);J(this,"encoder_no_repeat_ngram_size",0);J(this,"decoder_start_token_id",null);J(this,"generation_kwargs",{});Object.assign(this,(0,s.pick)(i,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>g,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>c,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>_,MinNewTokensLengthLogitsProcessor:()=>b,NoBadWordsLogitsProcessor:()=>k,NoRepeatNGramLogitsProcessor:()=>u,RepetitionPenaltyLogitsProcessor:()=>f,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>M,TopKLogitsWarper:()=>v,TopPLogitsWarper:()=>$,WhisperTimeStampLogitsProcessor:()=>d});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var o=t("./src/utils/maths.js");class n extends s.Callable{_call(T,x){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(T,x){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(T){this.processors.push(T)}extend(T){this.processors.push(...T)}_call(T,x){let P=x;for(const O of this.processors)P=O(T,P);return P}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(T){super(),this.bos_token_id=T}_call(T,x){for(let P=0;P=1&&L[L.length-1]>=this.timestamp_begin,K=L.length<2||L[L.length-2]>=this.timestamp_begin;if(G&&(K?O.subarray(this.timestamp_begin).fill(-1/0):O.subarray(0,this.eos_token_id).fill(-1/0)),T[P].length===this.begin_index&&this.max_initial_timestamp_index!==null){const ee=this.timestamp_begin+this.max_initial_timestamp_index;O.subarray(ee+1).fill(-1/0)}const R=(0,o.log_softmax)(O),te=Math.log(R.subarray(this.timestamp_begin).map(Math.exp).reduce((ee,Z)=>ee+Z)),H=(0,o.max)(R.subarray(0,this.timestamp_begin))[0];te>H&&O.subarray(0,this.timestamp_begin).fill(-1/0)}return x}}class u extends n{constructor(T){super(),this.no_repeat_ngram_size=T}getNgrams(T){const x=T.length,P=[];for(let L=0;L1 to use the classifier free guidance processor, got guidance scale ${T}.`);this.guidance_scale=T}_call(T,x){if(x.dims[0]!==2*T.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${x.dims[0]} for the logits and ${T.length} for the input ids.`);const P=T.length,O=x.slice([0,P],null),L=x.slice([P,x.dims[0]],null);for(let G=0;G1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${T}`);if(!Number.isInteger(P)||P<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${P}`);this.top_p=T,this.filter_value=x,this.min_tokens_to_keep=P}}class v extends i{constructor(T,{filter_value:x=-1/0,min_tokens_to_keep:P=1}={}){if(super(),!Number.isInteger(T)||T<0)throw new Error(`\`top_k\` must be a positive integer, but is ${T}`);this.top_k=Math.max(T,P),this.filter_value=x}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>i});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class i extends s.Callable{constructor(d){super(),this.generation_config=d}async _call(d){return this.sample(d)}async sample(d){throw Error("sample should be implemented in subclasses.")}getLogits(d,u){let f=d.dims.at(-1),_=d.data;if(u===-1)_=_.slice(-f);else{let b=u*f;_=_.slice(b,b+f)}return _}randomSelect(d){let u=0;for(let _=0;_1)return new c(d);if(d.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${d.num_return_sequences}.`);return new a(d)}}class a extends i{async sample(d){const u=(0,n.max)(d.data)[1];return[[BigInt(u),0]]}}class l extends i{async sample(d){let u=d.dims.at(-1);this.generation_config.top_k>0&&(u=Math.min(this.generation_config.top_k,u));const[f,_]=await(0,o.topk)(d,u),b=(0,n.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},()=>{const k=this.randomSelect(b);return[_.data[k],Math.log(b[k])]})}}class c extends i{async sample(d){let u=d.dims.at(-1);this.generation_config.top_k>0&&(u=Math.min(this.generation_config.top_k,u));const[f,_]=await(0,o.topk)(d,u),b=(0,n.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},(k,g)=>[_.data[g],Math.log(b[g])])}}},"./src/generation/stopping_criteria.js":(e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>i,StoppingCriteria:()=>o,StoppingCriteriaList:()=>n});var s=t("./src/utils/generic.js");class o extends s.Callable{_call(p,d){throw Error("StoppingCriteria needs to be subclassed")}}class n extends s.Callable{constructor(){super(),this.criteria=[]}push(p){this.criteria.push(p)}extend(p){p instanceof n?p=p.criteria:p instanceof o&&(p=[p]),this.criteria.push(...p)}_call(p,d){const u=new Array(p.length).fill(!1);for(const f of this.criteria){const _=f(p,d);for(let b=0;bd.length>=this.max_length)}}class a extends o{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,d){return p.map(u=>{const f=u.at(-1);return this.eos_token_id.some(_=>f==_)})}}class l extends o{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,d){return new Array(p.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>i,TextStreamer:()=>l,WhisperTextStreamer:()=>c});var s=t("./src/utils/core.js"),o=t("./src/tokenizers.js"),n=t("./src/env.js");class i{put(d){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const a=n.apis.IS_PROCESS_AVAILABLE?p=>process.stdout.write(p):p=>console.log(p);class l extends i{constructor(d,{skip_prompt:u=!1,callback_function:f=null,token_callback_function:_=null,skip_special_tokens:b=!0,decode_kwargs:k={},...g}={}){super(),this.tokenizer=d,this.skip_prompt=u,this.callback_function=f??a,this.token_callback_function=_,this.decode_kwargs={skip_special_tokens:b,...k,...g},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(d){var k;if(d.length>1)throw Error("TextStreamer only supports batch size of 1");const u=this.next_tokens_are_prompt;if(u&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const f=d[0];(k=this.token_callback_function)==null||k.call(this,f),this.token_cache=(0,s.mergeArrays)(this.token_cache,f);const _=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let b;u||_.endsWith(` +`)?(b=_.slice(this.print_len),this.token_cache=[],this.print_len=0):_.length>0&&(0,o.is_chinese_char)(_.charCodeAt(_.length-1))?(b=_.slice(this.print_len),this.print_len+=b.length):(b=_.slice(this.print_len,_.lastIndexOf(" ")+1),this.print_len+=b.length),this.on_finalized_text(b,!1)}end(){let d;this.token_cache.length>0?(d=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):d="",this.next_tokens_are_prompt=!0,this.on_finalized_text(d,!0)}on_finalized_text(d,u){var f,_;d.length>0&&((f=this.callback_function)==null||f.call(this,d)),u&&this.callback_function===a&&n.apis.IS_PROCESS_AVAILABLE&&((_=this.callback_function)==null||_.call(this,` +`))}}class c extends l{constructor(d,{skip_prompt:u=!1,callback_function:f=null,token_callback_function:_=null,on_chunk_start:b=null,on_chunk_end:k=null,on_finalize:g=null,time_precision:M=.02,skip_special_tokens:$=!0,decode_kwargs:v={}}={}){super(d,{skip_prompt:u,skip_special_tokens:$,callback_function:f,token_callback_function:_,decode_kwargs:v}),this.timestamp_begin=d.timestamp_begin,this.on_chunk_start=b,this.on_chunk_end=k,this.on_finalize=g,this.time_precision=M,this.waiting_for_timestamp=!1}put(d){var f,_,b;if(d.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const u=d[0];if(u.length===1){const k=Number(u[0])-this.timestamp_begin;if(k>=0){const g=k*this.time_precision;this.waiting_for_timestamp?(f=this.on_chunk_end)==null||f.call(this,g):(_=this.on_chunk_start)==null||_.call(this,g),this.waiting_for_timestamp=!this.waiting_for_timestamp,(b=this.token_callback_function)==null||b.call(this,u);return}}return super.put(d)}end(){var d;super.end(),(d=this.on_finalize)==null||d.call(this)}}},"./src/models.js":(e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>Io,ASTModel:()=>Di,ASTPreTrainedModel:()=>ko,AlbertForMaskedLM:()=>Mt,AlbertForQuestionAnswering:()=>tt,AlbertForSequenceClassification:()=>We,AlbertModel:()=>qe,AlbertPreTrainedModel:()=>Ne,ArceeForCausalLM:()=>xt,ArceeModel:()=>at,ArceePreTrainedModel:()=>He,AutoModel:()=>Su,AutoModelForAudioClassification:()=>Y0,AutoModelForAudioFrameClassification:()=>ev,AutoModelForAudioTextToText:()=>cv,AutoModelForCTC:()=>J0,AutoModelForCausalLM:()=>j0,AutoModelForDepthEstimation:()=>nv,AutoModelForDocumentQuestionAnswering:()=>tv,AutoModelForImageClassification:()=>W0,AutoModelForImageFeatureExtraction:()=>av,AutoModelForImageMatting:()=>rv,AutoModelForImageSegmentation:()=>G0,AutoModelForImageTextToText:()=>lv,AutoModelForImageToImage:()=>sv,AutoModelForMaskGeneration:()=>X0,AutoModelForMaskedLM:()=>N0,AutoModelForNormalEstimation:()=>ov,AutoModelForObjectDetection:()=>q0,AutoModelForPoseEstimation:()=>iv,AutoModelForQuestionAnswering:()=>V0,AutoModelForSemanticSegmentation:()=>K0,AutoModelForSeq2SeqLM:()=>L0,AutoModelForSequenceClassification:()=>O0,AutoModelForSpeechSeq2Seq:()=>z0,AutoModelForTextToSpectrogram:()=>B0,AutoModelForTextToWaveform:()=>R0,AutoModelForTokenClassification:()=>D0,AutoModelForUniversalSegmentation:()=>H0,AutoModelForVision2Seq:()=>U0,AutoModelForXVector:()=>Z0,AutoModelForZeroShotObjectDetection:()=>Q0,BartForConditionalGeneration:()=>gr,BartForSequenceClassification:()=>Kr,BartModel:()=>Zt,BartPretrainedModel:()=>Yr,BaseModelOutput:()=>ke,BeitForImageClassification:()=>mM,BeitModel:()=>hM,BeitPreTrainedModel:()=>Uc,BertForMaskedLM:()=>Se,BertForQuestionAnswering:()=>Be,BertForSequenceClassification:()=>we,BertForTokenClassification:()=>Ae,BertModel:()=>Me,BertPreTrainedModel:()=>Ee,BlenderbotForConditionalGeneration:()=>nr,BlenderbotModel:()=>hr,BlenderbotPreTrainedModel:()=>ar,BlenderbotSmallForConditionalGeneration:()=>Hn,BlenderbotSmallModel:()=>Ws,BlenderbotSmallPreTrainedModel:()=>Hr,BloomForCausalLM:()=>Lw,BloomModel:()=>Dw,BloomPreTrainedModel:()=>Ic,CLIPModel:()=>Lo,CLIPPreTrainedModel:()=>Ss,CLIPSegForImageSegmentation:()=>Zn,CLIPSegModel:()=>$n,CLIPSegPreTrainedModel:()=>rs,CLIPTextModel:()=>Ki,CLIPTextModelWithProjection:()=>zo,CLIPVisionModel:()=>Hi,CLIPVisionModelWithProjection:()=>Bo,CamembertForMaskedLM:()=>ht,CamembertForQuestionAnswering:()=>zt,CamembertForSequenceClassification:()=>vt,CamembertForTokenClassification:()=>st,CamembertModel:()=>ft,CamembertPreTrainedModel:()=>rt,CausalLMOutput:()=>Fn,CausalLMOutputWithPast:()=>yT,ChineseCLIPModel:()=>dt,ChineseCLIPPreTrainedModel:()=>Cn,ClapAudioModelWithProjection:()=>fy,ClapModel:()=>my,ClapPreTrainedModel:()=>ra,ClapTextModelWithProjection:()=>_y,CodeGenForCausalLM:()=>V,CodeGenModel:()=>z,CodeGenPreTrainedModel:()=>A,CohereForCausalLM:()=>fw,CohereModel:()=>_w,CoherePreTrainedModel:()=>vc,ConvBertForMaskedLM:()=>Fs,ConvBertForQuestionAnswering:()=>S,ConvBertForSequenceClassification:()=>Ct,ConvBertForTokenClassification:()=>Qt,ConvBertModel:()=>As,ConvBertPreTrainedModel:()=>pt,ConvNextForImageClassification:()=>lb,ConvNextModel:()=>ab,ConvNextPreTrainedModel:()=>nu,ConvNextV2ForImageClassification:()=>ub,ConvNextV2Model:()=>cb,ConvNextV2PreTrainedModel:()=>ou,DFineForObjectDetection:()=>CM,DFineModel:()=>PM,DFinePreTrainedModel:()=>Qc,DPTForDepthEstimation:()=>UM,DPTModel:()=>VM,DPTPreTrainedModel:()=>tu,DacDecoderModel:()=>n0,DacDecoderOutput:()=>t0,DacEncoderModel:()=>s0,DacEncoderOutput:()=>e0,DacModel:()=>r0,DacPreTrainedModel:()=>ca,DebertaForMaskedLM:()=>Xr,DebertaForQuestionAnswering:()=>$r,DebertaForSequenceClassification:()=>rr,DebertaForTokenClassification:()=>Sr,DebertaModel:()=>Nr,DebertaPreTrainedModel:()=>Ut,DebertaV2ForMaskedLM:()=>kr,DebertaV2ForQuestionAnswering:()=>Ur,DebertaV2ForSequenceClassification:()=>Os,DebertaV2ForTokenClassification:()=>Ds,DebertaV2Model:()=>ds,DebertaV2PreTrainedModel:()=>Vr,DecisionTransformerModel:()=>zy,DecisionTransformerPreTrainedModel:()=>Ly,DeiTForImageClassification:()=>AM,DeiTModel:()=>IM,DeiTPreTrainedModel:()=>Jc,DepthAnythingForDepthEstimation:()=>GM,DepthAnythingPreTrainedModel:()=>WM,DepthProForDepthEstimation:()=>XM,DepthProPreTrainedModel:()=>QM,DetrForObjectDetection:()=>fM,DetrForSegmentation:()=>Wc,DetrModel:()=>_M,DetrObjectDetectionOutput:()=>Gc,DetrPreTrainedModel:()=>Xi,DetrSegmentationOutput:()=>gM,Dinov2ForImageClassification:()=>pb,Dinov2Model:()=>db,Dinov2PreTrainedModel:()=>iu,Dinov2WithRegistersForImageClassification:()=>mb,Dinov2WithRegistersModel:()=>hb,Dinov2WithRegistersPreTrainedModel:()=>au,DistilBertForMaskedLM:()=>mr,DistilBertForQuestionAnswering:()=>pr,DistilBertForSequenceClassification:()=>Dr,DistilBertForTokenClassification:()=>Ts,DistilBertModel:()=>ts,DistilBertPreTrainedModel:()=>Wr,DonutSwinModel:()=>ib,DonutSwinPreTrainedModel:()=>ob,EfficientNetForImageClassification:()=>xy,EfficientNetModel:()=>vy,EfficientNetPreTrainedModel:()=>wu,ElectraForMaskedLM:()=>q,ElectraForQuestionAnswering:()=>Fe,ElectraForSequenceClassification:()=>re,ElectraForTokenClassification:()=>ge,ElectraModel:()=>B,ElectraPreTrainedModel:()=>Q,Ernie4_5_ForCausalLM:()=>cy,Ernie4_5_Model:()=>ly,Ernie4_5_PretrainedModel:()=>hu,EsmForMaskedLM:()=>Gr,EsmForSequenceClassification:()=>Re,EsmForTokenClassification:()=>je,EsmModel:()=>Ns,EsmPreTrainedModel:()=>Jr,ExaoneForCausalLM:()=>iw,ExaoneModel:()=>ow,ExaonePreTrainedModel:()=>gc,FalconForCausalLM:()=>hy,FalconModel:()=>py,FalconPreTrainedModel:()=>_u,FastViTForImageClassification:()=>rM,FastViTModel:()=>tM,FastViTPreTrainedModel:()=>Bc,Florence2ForConditionalGeneration:()=>ji,Florence2PreTrainedModel:()=>Ri,GLPNForDepthEstimation:()=>nb,GLPNModel:()=>sb,GLPNPreTrainedModel:()=>su,GPT2LMHeadModel:()=>Wo,GPT2Model:()=>Uo,GPT2PreTrainedModel:()=>eo,GPTBigCodeForCausalLM:()=>E,GPTBigCodeModel:()=>h,GPTBigCodePreTrainedModel:()=>no,GPTJForCausalLM:()=>Xo,GPTJModel:()=>Qo,GPTJPreTrainedModel:()=>so,GPTNeoForCausalLM:()=>ro,GPTNeoModel:()=>In,GPTNeoPreTrainedModel:()=>to,GPTNeoXForCausalLM:()=>qo,GPTNeoXModel:()=>Ho,GPTNeoXPreTrainedModel:()=>An,Gemma2ForCausalLM:()=>bw,Gemma2Model:()=>Mw,Gemma2PreTrainedModel:()=>Tc,Gemma3ForCausalLM:()=>vw,Gemma3Model:()=>yw,Gemma3PreTrainedModel:()=>Ec,Gemma3nForConditionalGeneration:()=>nn,Gemma3nPreTrainedModel:()=>Wi,GemmaForCausalLM:()=>ww,GemmaModel:()=>gw,GemmaPreTrainedModel:()=>xc,GlmForCausalLM:()=>nw,GlmModel:()=>sw,GlmPreTrainedModel:()=>fc,GraniteForCausalLM:()=>mw,GraniteModel:()=>hw,GranitePreTrainedModel:()=>yc,GroundingDinoForObjectDetection:()=>fb,GroundingDinoPreTrainedModel:()=>_b,GroupViTModel:()=>eM,GroupViTPreTrainedModel:()=>Zw,HeliumForCausalLM:()=>rw,HeliumModel:()=>tw,HeliumPreTrainedModel:()=>_c,HieraForImageClassification:()=>OM,HieraModel:()=>FM,HieraPreTrainedModel:()=>Yc,HubertForCTC:()=>Kb,HubertForSequenceClassification:()=>Hb,HubertModel:()=>Gb,HubertPreTrainedModel:()=>aT,IJepaForImageClassification:()=>Ww,IJepaModel:()=>Uw,IJepaPreTrainedModel:()=>Dc,Idefics3ForConditionalGeneration:()=>En,Idefics3PreTrainedModel:()=>on,ImageMattingOutput:()=>dv,JAISLMHeadModel:()=>Ko,JAISModel:()=>Go,JAISPreTrainedModel:()=>kn,JinaCLIPModel:()=>No,JinaCLIPPreTrainedModel:()=>Yn,JinaCLIPTextModel:()=>Vo,JinaCLIPVisionModel:()=>Sn,Lfm2ForCausalLM:()=>yr,Lfm2Model:()=>Gt,Lfm2PreTrainedModel:()=>Ot,LiteWhisperForConditionalGeneration:()=>Fo,LlamaForCausalLM:()=>De,LlamaModel:()=>Pe,LlamaPreTrainedModel:()=>ce,LlavaForConditionalGeneration:()=>Xn,LlavaOnevisionForConditionalGeneration:()=>zi,LlavaPreTrainedModel:()=>Qn,LlavaQwen2ForCausalLM:()=>Ui,LongT5ForConditionalGeneration:()=>br,LongT5Model:()=>_r,LongT5PreTrainedModel:()=>Wt,M2M100ForConditionalGeneration:()=>Pb,M2M100Model:()=>Eb,M2M100PreTrainedModel:()=>uu,MBartForCausalLM:()=>ur,MBartForConditionalGeneration:()=>Ir,MBartForSequenceClassification:()=>ps,MBartModel:()=>Cs,MBartPreTrainedModel:()=>zr,MPNetForMaskedLM:()=>vn,MPNetForQuestionAnswering:()=>I,MPNetForSequenceClassification:()=>xn,MPNetForTokenClassification:()=>pe,MPNetModel:()=>yn,MPNetPreTrainedModel:()=>Ps,MT5ForConditionalGeneration:()=>Lr,MT5Model:()=>fr,MT5PreTrainedModel:()=>ir,MarianMTModel:()=>Tb,MarianModel:()=>xb,MarianPreTrainedModel:()=>cu,MaskFormerForInstanceSegmentation:()=>rb,MaskFormerModel:()=>tb,MaskFormerPreTrainedModel:()=>ru,MaskedLMOutput:()=>Ar,Metric3DForDepthEstimation:()=>YM,Metric3DPreTrainedModel:()=>JM,Metric3Dv2ForDepthEstimation:()=>eb,Metric3Dv2PreTrainedModel:()=>ZM,MgpstrForSceneTextRecognition:()=>Vy,MgpstrModelOutput:()=>jy,MgpstrPreTrainedModel:()=>Ny,MimiDecoderModel:()=>Zy,MimiDecoderOutput:()=>Xy,MimiEncoderModel:()=>Yy,MimiEncoderOutput:()=>Qy,MimiModel:()=>Jy,MimiPreTrainedModel:()=>la,MistralForCausalLM:()=>ay,MistralModel:()=>iy,MistralPreTrainedModel:()=>pu,MobileBertForMaskedLM:()=>Vs,MobileBertForQuestionAnswering:()=>Us,MobileBertForSequenceClassification:()=>Es,MobileBertModel:()=>Xt,MobileBertPreTrainedModel:()=>et,MobileLLMForCausalLM:()=>lw,MobileLLMModel:()=>aw,MobileLLMPreTrainedModel:()=>wc,MobileNetV1ForImageClassification:()=>Ey,MobileNetV1ForSemanticSegmentation:()=>Py,MobileNetV1Model:()=>Ty,MobileNetV1PreTrainedModel:()=>na,MobileNetV2ForImageClassification:()=>Sy,MobileNetV2ForSemanticSegmentation:()=>$y,MobileNetV2Model:()=>Cy,MobileNetV2PreTrainedModel:()=>oa,MobileNetV3ForImageClassification:()=>Iy,MobileNetV3ForSemanticSegmentation:()=>Ay,MobileNetV3Model:()=>ky,MobileNetV3PreTrainedModel:()=>ia,MobileNetV4ForImageClassification:()=>Oy,MobileNetV4ForSemanticSegmentation:()=>Dy,MobileNetV4Model:()=>Fy,MobileNetV4PreTrainedModel:()=>aa,MobileViTForImageClassification:()=>iM,MobileViTModel:()=>oM,MobileViTPreTrainedModel:()=>Rc,MobileViTV2ForImageClassification:()=>lM,MobileViTV2Model:()=>aM,MobileViTV2PreTrainedModel:()=>jc,ModelOutput:()=>be,ModernBertDecoderForCausalLM:()=>Pr,ModernBertDecoderModel:()=>Mr,ModernBertDecoderPreTrainedModel:()=>wt,ModernBertForMaskedLM:()=>ot,ModernBertForSequenceClassification:()=>It,ModernBertForTokenClassification:()=>St,ModernBertModel:()=>Ye,ModernBertPreTrainedModel:()=>Oe,Moondream1ForConditionalGeneration:()=>Bi,MoonshineForConditionalGeneration:()=>Li,MoonshineModel:()=>mc,MoonshinePreTrainedModel:()=>Oo,MptForCausalLM:()=>Bw,MptModel:()=>zw,MptPreTrainedModel:()=>Ac,MultiModalityCausalLM:()=>Ry,MultiModalityPreTrainedModel:()=>By,MusicgenForCausalLM:()=>dT,MusicgenForConditionalGeneration:()=>bu,MusicgenModel:()=>uT,MusicgenPreTrainedModel:()=>Mu,NeoBertForMaskedLM:()=>Ze,NeoBertForQuestionAnswering:()=>Je,NeoBertForSequenceClassification:()=>Ke,NeoBertForTokenClassification:()=>nt,NeoBertModel:()=>xe,NeoBertPreTrainedModel:()=>Qe,NomicBertModel:()=>us,NomicBertPreTrainedModel:()=>jr,OPTForCausalLM:()=>jw,OPTModel:()=>Rw,OPTPreTrainedModel:()=>Fc,Olmo2ForCausalLM:()=>pw,Olmo2Model:()=>dw,Olmo2PreTrainedModel:()=>bc,OlmoForCausalLM:()=>uw,OlmoModel:()=>cw,OlmoPreTrainedModel:()=>Mc,OpenELMForCausalLM:()=>Tw,OpenELMModel:()=>xw,OpenELMPreTrainedModel:()=>Pc,OwlViTForObjectDetection:()=>uM,OwlViTModel:()=>cM,OwlViTPreTrainedModel:()=>Nc,Owlv2ForObjectDetection:()=>pM,Owlv2Model:()=>dM,Owlv2PreTrainedModel:()=>Vc,PaliGemmaForConditionalGeneration:()=>Vi,PaliGemmaPreTrainedModel:()=>Ni,PatchTSMixerForPrediction:()=>Ky,PatchTSMixerModel:()=>Gy,PatchTSMixerPreTrainedModel:()=>vu,PatchTSTForPrediction:()=>Wy,PatchTSTModel:()=>Uy,PatchTSTPreTrainedModel:()=>yu,Phi3ForCausalLM:()=>Ow,Phi3Model:()=>Fw,Phi3PreTrainedModel:()=>kc,Phi3VForCausalLM:()=>Pn,Phi3VPreTrainedModel:()=>Gi,PhiForCausalLM:()=>Aw,PhiModel:()=>Iw,PhiPreTrainedModel:()=>$c,PreTrainedModel:()=>W,PretrainedMixin:()=>jt,PvtForImageClassification:()=>qw,PvtModel:()=>Hw,PvtPreTrainedModel:()=>Lc,PyAnnoteForAudioFrameClassification:()=>Ab,PyAnnoteModel:()=>Ib,PyAnnotePreTrainedModel:()=>du,QuestionAnsweringModelOutput:()=>Br,Qwen2ForCausalLM:()=>Pw,Qwen2Model:()=>Ew,Qwen2PreTrainedModel:()=>Cc,Qwen2VLForConditionalGeneration:()=>kw,Qwen2VLPreTrainedModel:()=>$w,Qwen3ForCausalLM:()=>Sw,Qwen3Model:()=>Cw,Qwen3PreTrainedModel:()=>Sc,RFDetrForObjectDetection:()=>TM,RFDetrModel:()=>xM,RFDetrObjectDetectionOutput:()=>EM,RFDetrPreTrainedModel:()=>qc,RTDetrForObjectDetection:()=>MM,RTDetrModel:()=>wM,RTDetrObjectDetectionOutput:()=>Jo,RTDetrPreTrainedModel:()=>Kc,RTDetrV2ForObjectDetection:()=>yM,RTDetrV2Model:()=>bM,RTDetrV2ObjectDetectionOutput:()=>vM,RTDetrV2PreTrainedModel:()=>Hc,ResNetForImageClassification:()=>LM,ResNetModel:()=>DM,ResNetPreTrainedModel:()=>Zc,RoFormerForMaskedLM:()=>Xs,RoFormerForQuestionAnswering:()=>Zs,RoFormerForSequenceClassification:()=>Js,RoFormerForTokenClassification:()=>Ys,RoFormerModel:()=>Cr,RoFormerPreTrainedModel:()=>qt,RobertaForMaskedLM:()=>Po,RobertaForQuestionAnswering:()=>Ci,RobertaForSequenceClassification:()=>Ei,RobertaForTokenClassification:()=>Pi,RobertaModel:()=>Ti,RobertaPreTrainedModel:()=>en,SamImageSegmentationOutput:()=>vb,SamModel:()=>yb,SamPreTrainedModel:()=>bb,SapiensForDepthEstimation:()=>HM,SapiensForNormalEstimation:()=>qM,SapiensForSemanticSegmentation:()=>KM,SapiensPreTrainedModel:()=>Yi,SegformerForImageClassification:()=>wy,SegformerForSemanticSegmentation:()=>My,SegformerModel:()=>cT,SegformerPreTrainedModel:()=>sa,Seq2SeqLMOutput:()=>bT,SequenceClassifierOutput:()=>Tt,SiglipModel:()=>qi,SiglipPreTrainedModel:()=>Jn,SiglipTextModel:()=>Ro,SiglipVisionModel:()=>jo,SmolLM3ForCausalLM:()=>ew,SmolLM3Model:()=>Qi,SmolLM3PreTrainedModel:()=>Ls,SmolVLMForConditionalGeneration:()=>Do,SnacDecoderModel:()=>a0,SnacEncoderModel:()=>i0,SnacModel:()=>o0,SnacPreTrainedModel:()=>ua,SpeechT5ForSpeechToText:()=>ty,SpeechT5ForTextToSpeech:()=>ry,SpeechT5HifiGan:()=>sy,SpeechT5Model:()=>lT,SpeechT5PreTrainedModel:()=>ta,SqueezeBertForMaskedLM:()=>le,SqueezeBertForQuestionAnswering:()=>Te,SqueezeBertForSequenceClassification:()=>de,SqueezeBertModel:()=>Y,SqueezeBertPreTrainedModel:()=>N,StableLmForCausalLM:()=>yy,StableLmModel:()=>by,StableLmPreTrainedModel:()=>gu,Starcoder2ForCausalLM:()=>dy,Starcoder2Model:()=>uy,Starcoder2PreTrainedModel:()=>mu,StyleTextToSpeech2Model:()=>ey,StyleTextToSpeech2PreTrainedModel:()=>Zb,Swin2SRForImageSuperResolution:()=>NM,Swin2SRModel:()=>jM,Swin2SRPreTrainedModel:()=>eu,SwinForImageClassification:()=>BM,SwinForSemanticSegmentation:()=>RM,SwinModel:()=>zM,SwinPreTrainedModel:()=>Ji,T5ForConditionalGeneration:()=>sr,T5Model:()=>Lt,T5PreTrainedModel:()=>Bt,TableTransformerForObjectDetection:()=>$M,TableTransformerModel:()=>SM,TableTransformerObjectDetectionOutput:()=>kM,TableTransformerPreTrainedModel:()=>Xc,TokenClassifierOutput:()=>vr,TrOCRForCausalLM:()=>oy,TrOCRPreTrainedModel:()=>ny,UltravoxModel:()=>xu,UltravoxPreTrainedModel:()=>Hy,UniSpeechForCTC:()=>Lb,UniSpeechForSequenceClassification:()=>zb,UniSpeechModel:()=>Db,UniSpeechPreTrainedModel:()=>Zi,UniSpeechSatForAudioFrameClassification:()=>Nb,UniSpeechSatForCTC:()=>Rb,UniSpeechSatForSequenceClassification:()=>jb,UniSpeechSatModel:()=>Bb,UniSpeechSatPreTrainedModel:()=>Yo,ViTForImageClassification:()=>Vw,ViTMAEModel:()=>Xw,ViTMAEPreTrainedModel:()=>Qw,ViTMSNForImageClassification:()=>Yw,ViTMSNModel:()=>Jw,ViTMSNPreTrainedModel:()=>zc,ViTModel:()=>Nw,ViTPreTrainedModel:()=>Oc,VisionEncoderDecoderModel:()=>Tn,VitMatteForImageMatting:()=>nM,VitMattePreTrainedModel:()=>sM,VitPoseForPoseEstimation:()=>Kw,VitPosePreTrainedModel:()=>Gw,VitsModel:()=>fu,VitsModelOutput:()=>pv,VitsPreTrainedModel:()=>gy,VoxtralForConditionalGeneration:()=>qy,Wav2Vec2BertForCTC:()=>Ub,Wav2Vec2BertForSequenceClassification:()=>Wb,Wav2Vec2BertModel:()=>Vb,Wav2Vec2BertPreTrainedModel:()=>ea,Wav2Vec2ForAudioFrameClassification:()=>kb,Wav2Vec2ForCTC:()=>Sb,Wav2Vec2ForSequenceClassification:()=>$b,Wav2Vec2Model:()=>Cb,Wav2Vec2PreTrainedModel:()=>an,WavLMForAudioFrameClassification:()=>Yb,WavLMForCTC:()=>Qb,WavLMForSequenceClassification:()=>Xb,WavLMForXVector:()=>Jb,WavLMModel:()=>qb,WavLMPreTrainedModel:()=>oo,WeSpeakerResNetModel:()=>Ob,WeSpeakerResNetPreTrainedModel:()=>Fb,WhisperForConditionalGeneration:()=>Ao,WhisperModel:()=>sn,WhisperPreTrainedModel:()=>qn,XLMForQuestionAnswering:()=>Ai,XLMForSequenceClassification:()=>ki,XLMForTokenClassification:()=>Ii,XLMModel:()=>Si,XLMPreTrainedModel:()=>tn,XLMRobertaForMaskedLM:()=>Oi,XLMRobertaForQuestionAnswering:()=>$o,XLMRobertaForSequenceClassification:()=>Co,XLMRobertaForTokenClassification:()=>So,XLMRobertaModel:()=>Fi,XLMRobertaPreTrainedModel:()=>rn,XLMWithLMHeadModel:()=>$i,XVectorOutput:()=>uv,YolosForObjectDetection:()=>wb,YolosModel:()=>gb,YolosObjectDetectionOutput:()=>Mb,YolosPreTrainedModel:()=>lu});var s=t("./src/configs.js"),o=t("./src/backends/onnx.js"),n=t("./src/utils/dtypes.js"),i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),c=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),d=t("./src/generation/configuration_utils.js"),u=t("./src/utils/tensor.js"),f=t("./src/utils/image.js"),_=t("./src/utils/maths.js"),b=t("./src/generation/stopping_criteria.js"),k=t("./src/generation/logits_sampler.js"),g=t("./src/env.js"),M=t("./src/models/whisper/generation_whisper.js"),$=t("./src/models/whisper/common_whisper.js");const v={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11,ImageAudioTextToText:12},y=new Map,T=new Map,x=new Map;async function P(w,C,D){var Fr;let oe=((Fr=D.config)==null?void 0:Fr["transformers.js_config"])??{},fe=D.device??oe.device;fe&&typeof fe!="string"&&(fe.hasOwnProperty(C)?fe=fe[C]:(console.warn(`device not specified for "${C}". Using the default device.`),fe=null));const he=fe??(g.apis.IS_NODE_ENV?"cpu":"wasm"),Ce=(0,o.deviceToExecutionProviders)(he),Le=oe.device_config??{};Le.hasOwnProperty(he)&&(oe={...oe,...Le[he]});let Ue=D.dtype??oe.dtype;if(typeof Ue!="string"&&(Ue&&Ue.hasOwnProperty(C)?Ue=Ue[C]:(Ue=n.DEFAULT_DEVICE_DTYPE_MAPPING[he]??n.DATA_TYPES.fp32,console.warn(`dtype not specified for "${C}". Using the default dtype (${Ue}) for this device (${he}).`))),Ue===n.DATA_TYPES.auto){let kt=oe.dtype;typeof kt!="string"&&(kt=kt==null?void 0:kt[C]),kt&&kt!==n.DATA_TYPES.auto&&n.DATA_TYPES.hasOwnProperty(kt)?Ue=kt:Ue=n.DEFAULT_DEVICE_DTYPE_MAPPING[he]??n.DATA_TYPES.fp32}const Xe=Ue;if(n.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Xe)){if(Xe===n.DATA_TYPES.fp16&&he==="webgpu"&&!await(0,n.isWebGpuFp16Supported)())throw new Error(`The device (${he}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Xe}. Should be one of: ${Object.keys(n.DATA_TYPES).join(", ")}`);const mt=oe.kv_cache_dtype,bt=mt?typeof mt=="string"?mt:mt[Xe]??"float32":void 0;if(bt&&!["float32","float16"].includes(bt))throw new Error(`Invalid kv_cache_dtype: ${bt}. Should be one of: float32, float16`);const yt={dtype:Xe,kv_cache_dtype:bt,device:he},Ft=n.DEFAULT_DTYPE_SUFFIX_MAPPING[Xe],_t=`${C}${Ft}.onnx`,$t=`${D.subfolder??""}/${_t}`,ut={...D.session_options};ut.executionProviders??(ut.executionProviders=Ce);const At=oe.free_dimension_overrides;At?ut.freeDimensionOverrides??(ut.freeDimensionOverrides=At):he.startsWith("webnn")&&!ut.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${he}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const Ht=g.apis.IS_NODE_ENV&&g.env.useFSCache,er=(0,l.getModelFile)(w,$t,!0,D,Ht),dr=D.use_external_data_format??oe.use_external_data_format;let lr=[];if(dr){let kt;typeof dr=="object"?dr.hasOwnProperty(_t)?kt=dr[_t]:dr.hasOwnProperty(C)?kt=dr[C]:kt=!1:kt=dr;const xr=+kt;if(xr>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${xr}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let is=0;is{const Dn=await(0,l.getModelFile)(w,Zr,!0,D,Ht);hs(Dn instanceof Uint8Array?{path:On,data:Dn}:On)}))}}else ut.externalData!==void 0&&(lr=ut.externalData.map(async kt=>{if(typeof kt.data=="string"){const xr=await(0,l.getModelFile)(w,kt.data,!0,D);return{...kt,data:xr}}return kt}));if(lr.length>0){const kt=await Promise.all(lr);g.apis.IS_NODE_ENV||(ut.externalData=kt)}if(he==="webgpu"){const kt=(0,s.getCacheShapes)(D.config,{prefix:"present"});if(Object.keys(kt).length>0&&!(0,o.isONNXProxy)()){const xr={};for(const is in kt)xr[is]="gpu-buffer";ut.preferredOutputLocation=xr}}return{buffer_or_path:await er,session_options:ut,session_config:yt}}async function O(w,C,D){return Object.fromEntries(await Promise.all(Object.keys(C).map(async oe=>{const{buffer_or_path:fe,session_options:he,session_config:Ce}=await P(w,C[oe],D),Le=await(0,o.createInferenceSession)(fe,he,Ce);return[oe,Le]})))}async function L(w,C,D){return Object.fromEntries(await Promise.all(Object.keys(C).map(async oe=>{const fe=await(0,l.getModelJSON)(w,C[oe],!1,D);return[oe,fe]})))}function G(w,C){const D=Object.create(null),oe=[];for(const Ce of w.inputNames){const Le=C[Ce];if(!(Le instanceof u.Tensor)){oe.push(Ce);continue}D[Ce]=(0,o.isONNXProxy)()?Le.clone():Le}if(oe.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${oe.join(", ")}.`);const fe=Object.keys(C).length,he=w.inputNames.length;if(fe>he){let Ce=Object.keys(C).filter(Le=>!w.inputNames.includes(Le));console.warn(`WARNING: Too many inputs were provided (${fe} > ${he}). The following inputs will be ignored: "${Ce.join(", ")}".`)}return D}let K=Promise.resolve();async function R(w,C){const D=G(w,C);try{const oe=Object.fromEntries(Object.entries(D).map(([Ce,Le])=>[Ce,Le.ort_tensor])),fe=()=>w.run(oe),he=await(g.apis.IS_BROWSER_ENV||g.apis.IS_WEBWORKER_ENV?K=K.then(fe):fe());return te(he)}catch(oe){const fe=Object.fromEntries(Object.entries(D).map(([he,Ce])=>{const Le={type:Ce.type,dims:Ce.dims,location:Ce.location};return Le.location!=="gpu-buffer"&&(Le.data=Ce.data),[he,Le]}));throw console.error(`An error occurred during model execution: "${oe}".`),console.error("Inputs given to model:",fe),oe}}function te(w){for(let C in w)(0,o.isONNXTensor)(w[C])?w[C]=new u.Tensor(w[C]):typeof w[C]=="object"&&te(w[C]);return w}function H(w){if(w instanceof u.Tensor)return w;if(w.length===0)throw Error("items must be non-empty");if(Array.isArray(w[0])){if(w.some(C=>C.length!==w[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new u.Tensor("int64",BigInt64Array.from(w.flat().map(C=>BigInt(C))),[w.length,w[0].length])}else return new u.Tensor("int64",BigInt64Array.from(w.map(C=>BigInt(C))),[1,w.length])}function ee(w){return new u.Tensor("bool",[w],[1])}async function Z(w,C){let{encoder_outputs:D,input_ids:oe,decoder_input_ids:fe,...he}=C;if(!D){const Le=(0,a.pick)(C,w.sessions.model.inputNames);D=(await ne(w,Le)).last_hidden_state}return he.input_ids=fe,he.encoder_hidden_states=D,w.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(he.encoder_attention_mask=C.attention_mask),await ue(w,he,!0)}async function ne(w,C){const D=w.sessions.model,oe=(0,a.pick)(C,D.inputNames);if(D.inputNames.includes("inputs_embeds")&&!oe.inputs_embeds){if(!C.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");oe.inputs_embeds=await w.encode_text({input_ids:C.input_ids})}if(D.inputNames.includes("token_type_ids")&&!oe.token_type_ids){if(!oe.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");oe.token_type_ids=(0,u.zeros_like)(oe.input_ids)}if(D.inputNames.includes("pixel_mask")&&!oe.pixel_mask){if(!oe.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const fe=oe.pixel_values.dims;oe.pixel_mask=(0,u.ones)([fe[0],fe[2],fe[3]])}return await R(D,oe)}async function me(w,C){const D=await w.encode(C);return await w.decode(D)}async function ue(w,C,D=!1){const oe=w.sessions[D?"decoder_model_merged":"model"],{past_key_values:fe,...he}=C;if(oe.inputNames.includes("use_cache_branch")&&(he.use_cache_branch=ee(!!fe)),oe.inputNames.includes("position_ids")&&he.attention_mask&&!he.position_ids){const Le=["paligemma","gemma3_text","gemma3"].includes(w.config.model_type)?1:0;he.position_ids=ze(he,fe,Le)}w.addPastKeyValues(he,fe);const Ce=(0,a.pick)(he,oe.inputNames);return await R(oe,Ce)}function j({modality_token_id:w,inputs_embeds:C,modality_features:D,input_ids:oe,attention_mask:fe}){const he=oe.tolist().map(Xe=>Xe.reduce((mt,bt,yt)=>(bt==w&&mt.push(yt),mt),[])),Ce=he.reduce((Xe,mt)=>Xe+mt.length,0),Le=D.dims[0];if(Ce!==Le)throw new Error(`Number of tokens and features do not match: tokens: ${Ce}, features ${Le}`);let Ue=0;for(let Xe=0;Xehe.dims[1]||fe[fe.at(-1)])),{...D,decoder_input_ids:H(C)}}function X(w,...C){return w.config.is_encoder_decoder?Ie(w,...C):Ge(w,...C)}function ae(w,C,D,oe){const fe=!!D.past_key_values;return oe.guidance_scale!==null&&oe.guidance_scale>1&&(fe?D.input_ids=(0,u.cat)([D.input_ids,D.input_ids],0):(D.input_ids=(0,u.cat)([D.input_ids,(0,u.full_like)(D.input_ids,BigInt(oe.pad_token_id))],0),D.attention_mask=(0,u.cat)([D.attention_mask,(0,u.full_like)(D.attention_mask,0n)],0))),(fe||!D.pixel_values)&&(D.pixel_values=(0,u.full)([0,0,3,384,384],1)),fe&&(D.images_seq_mask=new u.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),D.images_emb_mask=new u.Tensor("bool",new Array(0).fill(!1),[1,1,0])),D}class W extends i.Callable{constructor(D,oe,fe){super();J(this,"main_input_name","input_ids");J(this,"forward_params",["input_ids","attention_mask"]);this.config=D,this.sessions=oe,this.configs=fe;const he=x.get(this.constructor),Ce=y.get(he);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ce){case v.DecoderOnly:this.can_generate=!0,this._forward=ue,this._prepare_inputs_for_generation=Ge;break;case v.Seq2Seq:case v.Vision2Seq:case v.Musicgen:this.can_generate=!0,this._forward=Z,this._prepare_inputs_for_generation=Ie;break;case v.EncoderDecoder:this._forward=Z;break;case v.ImageTextToText:this.can_generate=!0,this._forward=ie,this._prepare_inputs_for_generation=X;break;case v.AudioTextToText:this.can_generate=!0,this._forward=_e,this._prepare_inputs_for_generation=X;break;case v.Phi3V:case v.ImageAudioTextToText:this.can_generate=!0,this._prepare_inputs_for_generation=X;break;case v.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=ae;break;case v.AutoEncoder:this._forward=me;break;default:this._forward=ne;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var oe;const D=[];for(const fe of Object.values(this.sessions))(oe=fe==null?void 0:fe.handler)!=null&&oe.dispose&&D.push(fe.handler.dispose());return await Promise.all(D)}static async from_pretrained(D,{progress_callback:oe=null,config:fe=null,cache_dir:he=null,local_files_only:Ce=!1,revision:Le="main",model_file_name:Ue=null,subfolder:Xe="onnx",device:mt=null,dtype:bt=null,use_external_data_format:yt=null,session_options:Ft={}}={}){let _t={progress_callback:oe,config:fe,cache_dir:he,local_files_only:Ce,revision:Le,model_file_name:Ue,subfolder:Xe,device:mt,dtype:bt,use_external_data_format:yt,session_options:Ft};const $t=x.get(this),ut=y.get($t);fe=_t.config=await s.AutoConfig.from_pretrained(D,_t);let At;if(ut===v.DecoderOnly)At=await Promise.all([O(D,{model:_t.model_file_name??"model"},_t),L(D,{generation_config:"generation_config.json"},_t)]);else if(ut===v.Seq2Seq||ut===v.Vision2Seq)At=await Promise.all([O(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},_t),L(D,{generation_config:"generation_config.json"},_t)]);else if(ut===v.MaskGeneration)At=await Promise.all([O(D,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},_t)]);else if(ut===v.EncoderDecoder)At=await Promise.all([O(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},_t)]);else if(ut===v.ImageTextToText){const Ht={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};fe.is_encoder_decoder&&(Ht.model="encoder_model"),At=await Promise.all([O(D,Ht,_t),L(D,{generation_config:"generation_config.json"},_t)])}else if(ut===v.AudioTextToText){const Ht={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};At=await Promise.all([O(D,Ht,_t),L(D,{generation_config:"generation_config.json"},_t)])}else if(ut===v.ImageAudioTextToText){const Ht={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};At=await Promise.all([O(D,Ht,_t),L(D,{generation_config:"generation_config.json"},_t)])}else if(ut===v.Musicgen)At=await Promise.all([O(D,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},_t),L(D,{generation_config:"generation_config.json"},_t)]);else if(ut===v.MultiModality)At=await Promise.all([O(D,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},_t),L(D,{generation_config:"generation_config.json"},_t)]);else if(ut===v.Phi3V)At=await Promise.all([O(D,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},_t),L(D,{generation_config:"generation_config.json"},_t)]);else if(ut===v.AutoEncoder)At=await Promise.all([O(D,{encoder_model:"encoder_model",decoder_model:"decoder_model"},_t)]);else{if(ut!==v.EncoderOnly){const Ht=$t??(fe==null?void 0:fe.model_type);Ht!=="custom"&&console.warn(`Model type for '${Ht}' not found, assuming encoder-only architecture. Please report this at ${c.GITHUB_ISSUE_URL}.`)}At=await Promise.all([O(D,{model:_t.model_file_name??"model"},_t)])}return new this(fe,...At)}async _call(D){return await this.forward(D)}async forward(D){return await this._forward(this,D)}get generation_config(){var D;return((D=this.configs)==null?void 0:D.generation_config)??null}_get_logits_warper(D){const oe=new p.LogitsProcessorList;return D.temperature!==null&&D.temperature!==1&&oe.push(new p.TemperatureLogitsWarper(D.temperature)),D.top_k!==null&&D.top_k!==0&&oe.push(new p.TopKLogitsWarper(D.top_k)),D.top_p!==null&&D.top_p<1&&oe.push(new p.TopPLogitsWarper(D.top_p)),oe}_get_logits_processor(D,oe,fe=null){const he=new p.LogitsProcessorList;if(D.repetition_penalty!==null&&D.repetition_penalty!==1&&he.push(new p.RepetitionPenaltyLogitsProcessor(D.repetition_penalty)),D.no_repeat_ngram_size!==null&&D.no_repeat_ngram_size>0&&he.push(new p.NoRepeatNGramLogitsProcessor(D.no_repeat_ngram_size)),D.bad_words_ids!==null&&he.push(new p.NoBadWordsLogitsProcessor(D.bad_words_ids,D.eos_token_id)),D.min_length!==null&&D.eos_token_id!==null&&D.min_length>0&&he.push(new p.MinLengthLogitsProcessor(D.min_length,D.eos_token_id)),D.min_new_tokens!==null&&D.eos_token_id!==null&&D.min_new_tokens>0&&he.push(new p.MinNewTokensLengthLogitsProcessor(oe,D.min_new_tokens,D.eos_token_id)),D.forced_bos_token_id!==null&&he.push(new p.ForcedBOSTokenLogitsProcessor(D.forced_bos_token_id)),D.forced_eos_token_id!==null&&he.push(new p.ForcedEOSTokenLogitsProcessor(D.max_length,D.forced_eos_token_id)),D.begin_suppress_tokens!==null){const Ce=oe>1||D.forced_bos_token_id===null?oe:oe+1;he.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ce))}return D.guidance_scale!==null&&D.guidance_scale>1&&he.push(new p.ClassifierFreeGuidanceLogitsProcessor(D.guidance_scale)),fe!==null&&he.extend(fe),he}_prepare_generation_config(D,oe,fe=d.GenerationConfig){const he={...this.config};for(const Le of["decoder","generator","text_config"])Le in he&&Object.assign(he,he[Le]);const Ce=new fe(he);return Object.assign(Ce,this.generation_config??{}),D&&Object.assign(Ce,D),oe&&Object.assign(Ce,(0,a.pick)(oe,Object.getOwnPropertyNames(Ce))),Ce}_get_stopping_criteria(D,oe=null){const fe=new b.StoppingCriteriaList;return D.max_length!==null&&fe.push(new b.MaxLengthCriteria(D.max_length,this.config.max_position_embeddings??null)),D.eos_token_id!==null&&fe.push(new b.EosTokenCriteria(D.eos_token_id)),oe&&fe.extend(oe),fe}_validate_model_class(){if(!this.can_generate){const D=[Pu,Cu,Eu,Tu],oe=x.get(this.constructor),fe=new Set,he=this.config.model_type;for(const Le of D){const Ue=Le.get(he);Ue&&fe.add(Ue[0])}let Ce=`The current model class (${oe}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw fe.size>0&&(Ce+=` Please use the following class instead: ${[...fe].join(", ")}`),Error(Ce)}}prepare_inputs_for_generation(...D){return this._prepare_inputs_for_generation(this,...D)}_update_model_kwargs_for_generation({generated_input_ids:D,outputs:oe,model_inputs:fe,is_encoder_decoder:he}){return fe.past_key_values=this.getPastKeyValues(oe,fe.past_key_values),fe.input_ids=new u.Tensor("int64",D.flat(),[D.length,1]),he||(fe.attention_mask=(0,u.cat)([fe.attention_mask,(0,u.ones)([fe.attention_mask.dims[0],1])],1)),fe.position_ids=null,fe}_prepare_model_inputs({inputs:D,bos_token_id:oe,model_kwargs:fe}){const he=(0,a.pick)(fe,this.forward_params),Ce=this.main_input_name;if(Ce in he){if(D)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else he[Ce]=D;return{inputs_tensor:he[Ce],model_inputs:he,model_input_name:Ce}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:D,model_inputs:oe,model_input_name:fe,generation_config:he}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!oe.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Le,pixel_values:Ue,attention_mask:Xe,...mt}=oe,bt=await this._prepare_inputs_embeds(oe);oe={...mt,...(0,a.pick)(bt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ce}=await ne(this,oe);if(he.guidance_scale!==null&&he.guidance_scale>1)Ce=(0,u.cat)([Ce,(0,u.full_like)(Ce,0)],0),"attention_mask"in oe&&(oe.attention_mask=(0,u.cat)([oe.attention_mask,(0,u.zeros_like)(oe.attention_mask)],0));else if(oe.decoder_input_ids){const Le=H(oe.decoder_input_ids).dims[0];if(Le!==Ce.dims[0]){if(Ce.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ce.dims[0]}) than the decoder inputs (${Le}).`);Ce=(0,u.cat)(Array.from({length:Le},()=>Ce),0)}}return oe.encoder_outputs=Ce,oe}_prepare_decoder_input_ids_for_generation({batch_size:D,model_input_name:oe,model_kwargs:fe,decoder_start_token_id:he,bos_token_id:Ce,generation_config:Le}){let{decoder_input_ids:Ue,...Xe}=fe;if(!(Ue instanceof u.Tensor)){if(Ue)Array.isArray(Ue[0])||(Ue=Array.from({length:D},()=>Ue));else if(he??(he=Ce),this.config.model_type==="musicgen")Ue=Array.from({length:D*this.config.decoder.num_codebooks},()=>[he]);else if(Array.isArray(he)){if(he.length!==D)throw new Error(`\`decoder_start_token_id\` expcted to have length ${D} but got ${he.length}`);Ue=he}else Ue=Array.from({length:D},()=>[he]);Ue=H(Ue)}return fe.decoder_attention_mask=(0,u.ones_like)(Ue),{input_ids:Ue,model_inputs:Xe}}async generate({inputs:D=null,generation_config:oe=null,logits_processor:fe=null,stopping_criteria:he=null,streamer:Ce=null,...Le}){this._validate_model_class(),oe=this._prepare_generation_config(oe,Le);let{inputs_tensor:Ue,model_inputs:Xe,model_input_name:mt}=this._prepare_model_inputs({inputs:D,model_kwargs:Le});const bt=this.config.is_encoder_decoder;bt&&("encoder_outputs"in Xe||(Xe=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Ue,model_inputs:Xe,model_input_name:mt,generation_config:oe})));let yt;bt?{input_ids:yt,model_inputs:Xe}=this._prepare_decoder_input_ids_for_generation({batch_size:Xe[mt].dims.at(0),model_input_name:mt,model_kwargs:Xe,decoder_start_token_id:oe.decoder_start_token_id,bos_token_id:oe.bos_token_id,generation_config:oe}):yt=Xe[mt];let Ft=yt.dims.at(-1);oe.max_new_tokens!==null&&(oe.max_length=Ft+oe.max_new_tokens);const _t=this._get_logits_processor(oe,Ft,fe),$t=this._get_stopping_criteria(oe,he),ut=Xe[mt].dims.at(0),At=k.LogitsSampler.getSampler(oe),Ht=new Array(ut).fill(0),er=yt.tolist();Ce&&Ce.put(er);let dr,lr={};for(;;){if(Xe=this.prepare_inputs_for_generation(er,Xe,oe),dr=await this.forward(Xe),oe.output_attentions&&oe.return_dict_in_generate){const Zr=this.getAttentions(dr);for(const hs in Zr)hs in lr||(lr[hs]=[]),lr[hs].push(Zr[hs])}const kt=dr.logits.slice(null,-1,null),xr=_t(er,kt),is=[];for(let Zr=0;ZrZr))break;Xe=this._update_model_kwargs_for_generation({generated_input_ids:is,outputs:dr,model_inputs:Xe,is_encoder_decoder:bt})}Ce&&Ce.end();const wr=this.getPastKeyValues(dr,Xe.past_key_values,!0),Fr=new u.Tensor("int64",er.flat(),[er.length,er[0].length]);if(oe.return_dict_in_generate)return{sequences:Fr,past_key_values:wr,...lr};for(const kt of Object.values(dr))kt.location==="gpu-buffer"&&kt.dispose();return Fr}getPastKeyValues(D,oe,fe=!1){const he=Object.create(null);for(const Ce in D)if(Ce.startsWith("present")){const Le=Ce.replace("present_conv","past_conv").replace("present","past_key_values"),Ue=Ce.includes("encoder");if(Ue&&oe?he[Le]=oe[Le]:he[Le]=D[Ce],oe&&(!Ue||fe)){const Xe=oe[Le];Xe.location==="gpu-buffer"&&Xe.dispose()}}return he}getAttentions(D){const oe={};for(const fe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const he in D)he.startsWith(fe)&&(fe in oe||(oe[fe]=[]),oe[fe].push(D[he]));return oe}addPastKeyValues(D,oe){var fe,he,Ce;if(oe)Object.assign(D,oe);else{const Le=this.sessions.decoder_model_merged??this.sessions.model,Ue=((he=(fe=D[this.main_input_name]??D.attention_mask)==null?void 0:fe.dims)==null?void 0:he[0])??1,Xe=((Ce=Le==null?void 0:Le.config)==null?void 0:Ce.kv_cache_dtype)??"float32",mt=Xe==="float16"?u.DataTypeMap.float16:u.DataTypeMap.float32,bt=(0,s.getCacheShapes)(this.config,{batch_size:Ue});for(const yt in bt){const Ft=bt[yt].reduce((_t,$t)=>_t*$t,1);D[yt]=new u.Tensor(Xe,new mt(Ft),bt[yt])}}}async encode_image({pixel_values:D}){return(await R(this.sessions.vision_encoder,{pixel_values:D})).image_features}async encode_text({input_ids:D}){return(await R(this.sessions.embed_tokens,{input_ids:D})).inputs_embeds}async encode_audio({audio_values:D}){return(await R(this.sessions.audio_encoder,{audio_values:D})).audio_features}}class be{}class ke extends be{constructor({last_hidden_state:C,hidden_states:D=null,attentions:oe=null}){super(),this.last_hidden_state=C,this.hidden_states=D,this.attentions=oe}}class Ee extends W{}class Me extends Ee{}class Se extends Ee{async _call(C){return new Ar(await super._call(C))}}class we extends Ee{async _call(C){return new Tt(await super._call(C))}}class Ae extends Ee{async _call(C){return new vr(await super._call(C))}}class Be extends Ee{async _call(C){return new Br(await super._call(C))}}class Qe extends W{}class xe extends Qe{}class Ze extends Qe{async _call(C){return new Ar(await super._call(C))}}class Ke extends Qe{async _call(C){return new Tt(await super._call(C))}}class nt extends Qe{async _call(C){return new vr(await super._call(C))}}class Je extends Qe{async _call(C){return new Br(await super._call(C))}}class Oe extends W{}class Ye extends Oe{}class ot extends Oe{async _call(C){return new Ar(await super._call(C))}}class It extends Oe{async _call(C){return new Tt(await super._call(C))}}class St extends Oe{async _call(C){return new vr(await super._call(C))}}class wt extends W{}class Mr extends wt{}class Pr extends wt{}class jr extends W{}class us extends jr{}class qt extends W{}class Cr extends qt{}class Xs extends qt{async _call(C){return new Ar(await super._call(C))}}class Js extends qt{async _call(C){return new Tt(await super._call(C))}}class Ys extends qt{async _call(C){return new vr(await super._call(C))}}class Zs extends qt{async _call(C){return new Br(await super._call(C))}}class pt extends W{}class As extends pt{}class Fs extends pt{async _call(C){return new Ar(await super._call(C))}}class Ct extends pt{async _call(C){return new Tt(await super._call(C))}}class Qt extends pt{async _call(C){return new vr(await super._call(C))}}class S extends pt{async _call(C){return new Br(await super._call(C))}}class Q extends W{}class B extends Q{}class q extends Q{async _call(C){return new Ar(await super._call(C))}}class re extends Q{async _call(C){return new Tt(await super._call(C))}}class ge extends Q{async _call(C){return new vr(await super._call(C))}}class Fe extends Q{async _call(C){return new Br(await super._call(C))}}class rt extends W{}class ft extends rt{}class ht extends rt{async _call(C){return new Ar(await super._call(C))}}class vt extends rt{async _call(C){return new Tt(await super._call(C))}}class st extends rt{async _call(C){return new vr(await super._call(C))}}class zt extends rt{async _call(C){return new Br(await super._call(C))}}class Ut extends W{}class Nr extends Ut{}class Xr extends Ut{async _call(C){return new Ar(await super._call(C))}}class rr extends Ut{async _call(C){return new Tt(await super._call(C))}}class Sr extends Ut{async _call(C){return new vr(await super._call(C))}}class $r extends Ut{async _call(C){return new Br(await super._call(C))}}class Vr extends W{}class ds extends Vr{}class kr extends Vr{async _call(C){return new Ar(await super._call(C))}}class Os extends Vr{async _call(C){return new Tt(await super._call(C))}}class Ds extends Vr{async _call(C){return new vr(await super._call(C))}}class Ur extends Vr{async _call(C){return new Br(await super._call(C))}}class Wr extends W{}class ts extends Wr{}class Dr extends Wr{async _call(C){return new Tt(await super._call(C))}}class Ts extends Wr{async _call(C){return new vr(await super._call(C))}}class pr extends Wr{async _call(C){return new Br(await super._call(C))}}class mr extends Wr{async _call(C){return new Ar(await super._call(C))}}class Jr extends W{}class Ns extends Jr{}class Gr extends Jr{async _call(C){return new Ar(await super._call(C))}}class Re extends Jr{async _call(C){return new Tt(await super._call(C))}}class je extends Jr{async _call(C){return new vr(await super._call(C))}}class et extends W{}class Xt extends et{}class Vs extends et{async _call(C){return new Ar(await super._call(C))}}class Es extends et{async _call(C){return new Tt(await super._call(C))}}class Us extends et{async _call(C){return new Br(await super._call(C))}}class Ps extends W{}class yn extends Ps{}class vn extends Ps{async _call(C){return new Ar(await super._call(C))}}class xn extends Ps{async _call(C){return new Tt(await super._call(C))}}class pe extends Ps{async _call(C){return new vr(await super._call(C))}}class I extends Ps{async _call(C){return new Br(await super._call(C))}}class N extends W{}class Y extends N{}class le extends N{async _call(C){return new Ar(await super._call(C))}}class de extends N{async _call(C){return new Tt(await super._call(C))}}class Te extends N{async _call(C){return new Br(await super._call(C))}}class Ne extends W{}class qe extends Ne{}class We extends Ne{async _call(C){return new Tt(await super._call(C))}}class tt extends Ne{async _call(C){return new Br(await super._call(C))}}class Mt extends Ne{async _call(C){return new Ar(await super._call(C))}}class Bt extends W{constructor(){super(...arguments);J(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Lt extends Bt{}class sr extends Bt{}class Wt extends W{}class _r extends Wt{}class br extends Wt{}class ir extends W{}class fr extends ir{}class Lr extends ir{}class Yr extends W{}class Zt extends Yr{}class gr extends Yr{}class Kr extends Yr{async _call(C){return new Tt(await super._call(C))}}class zr extends W{}class Cs extends zr{}class Ir extends zr{}class ps extends zr{async _call(C){return new Tt(await super._call(C))}}class ur extends zr{}class ar extends W{}class hr extends ar{}class nr extends ar{}class Hr extends W{}class Ws extends Hr{}class Hn extends Hr{}class en extends W{}class Ti extends en{}class Po extends en{async _call(C){return new Ar(await super._call(C))}}class Ei extends en{async _call(C){return new Tt(await super._call(C))}}class Pi extends en{async _call(C){return new vr(await super._call(C))}}class Ci extends en{async _call(C){return new Br(await super._call(C))}}class tn extends W{}class Si extends tn{}class $i extends tn{async _call(C){return new Ar(await super._call(C))}}class ki extends tn{async _call(C){return new Tt(await super._call(C))}}class Ii extends tn{async _call(C){return new vr(await super._call(C))}}class Ai extends tn{async _call(C){return new Br(await super._call(C))}}class rn extends W{}class Fi extends rn{}class Oi extends rn{async _call(C){return new Ar(await super._call(C))}}class Co extends rn{async _call(C){return new Tt(await super._call(C))}}class So extends rn{async _call(C){return new vr(await super._call(C))}}class $o extends rn{async _call(C){return new Br(await super._call(C))}}class ko extends W{}class Di extends ko{}class Io extends ko{}class qn extends W{constructor(){super(...arguments);J(this,"requires_attention_mask",!1);J(this,"main_input_name","input_features");J(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class sn extends qn{}class Ao extends qn{_prepare_generation_config(C,D){return super._prepare_generation_config(C,D,M.WhisperGenerationConfig)}_retrieve_init_tokens(C){const D=[C.decoder_start_token_id];let oe=C.language;const fe=C.task;if(C.is_multilingual){oe||(console.warn("No language specified - defaulting to English (en)."),oe="en");const Ce=`<|${(0,$.whisper_language_to_code)(oe)}|>`;D.push(C.lang_to_id[Ce]),D.push(C.task_to_id[fe??"transcribe"])}else if(oe||fe)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!C.return_timestamps&&C.no_timestamps_token_id&&D.at(-1)!==C.no_timestamps_token_id?D.push(C.no_timestamps_token_id):C.return_timestamps&&D.at(-1)===C.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),D.pop()),D.filter(he=>he!=null)}async generate({inputs:C=null,generation_config:D=null,logits_processor:oe=null,stopping_criteria:fe=null,...he}){D=this._prepare_generation_config(D,he);const Ce=he.decoder_input_ids??this._retrieve_init_tokens(D);if(D.return_timestamps&&(oe??(oe=new p.LogitsProcessorList),oe.push(new p.WhisperTimeStampLogitsProcessor(D,Ce))),D.begin_suppress_tokens&&(oe??(oe=new p.LogitsProcessorList),oe.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ce.length))),D.return_token_timestamps){if(!D.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");D.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),D.output_attentions=!0,D.return_dict_in_generate=!0}const Le=await super.generate({inputs:C,generation_config:D,logits_processor:oe,decoder_input_ids:Ce,...he});return D.return_token_timestamps&&(Le.token_timestamps=this._extract_token_timestamps(Le,D.alignment_heads,D.num_frames)),Le}_extract_token_timestamps(C,D,oe=null,fe=.02){if(!C.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");oe==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let he=this.config.median_filter_width;he===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),he=7);const Ce=C.cross_attentions,Le=Array.from({length:this.config.decoder_layers},($t,ut)=>(0,u.cat)(Ce.map(At=>At[ut]),2)),Ue=(0,u.stack)(D.map(([$t,ut])=>{if($t>=Le.length)throw new Error(`Layer index ${$t} is out of bounds for cross attentions (length ${Le.length}).`);return oe?Le[$t].slice(null,ut,null,[0,oe]):Le[$t].slice(null,ut)})).transpose(1,0,2,3),[Xe,mt]=(0,u.std_mean)(Ue,-2,0,!0),bt=Ue.clone();for(let $t=0;$tAt[Fr+1]-At[Fr]),dr=(0,a.mergeArrays)([1],er).map(wr=>!!wr),lr=[];for(let wr=0;wrArray.from({length:C.dims[0]},er=>Array.from({length:C.dims[1]},dr=>1))),_t=D?D.tolist():[],$t=oe?oe.tolist():[];let ut=0,At=0;for(let Ht=0;Htyt[Ht][Tr]==1),lr=er.reduce((tr,Tr,ln)=>(Tr==Ue&&tr.push(ln),tr),[]).map(tr=>er[tr+1]),wr=lr.filter(tr=>tr==Ce).length,Fr=lr.filter(tr=>tr==Le).length;let kt=[],xr=0,is=wr,On=Fr;for(let tr=0;tr$s>xr&&zn==Ce),ln=er.findIndex((zn,$s)=>$s>xr&&zn==Le),Ln=is>0&&Tr!==-1?Tr:er.length+1,ao=On>0&&ln!==-1?ln:er.length+1;let ma,$u,ku,Iu;Ln0?(0,_.max)(kt.at(-1))[0]+1:0;kt.push(Array.from({length:3*Fu},(zn,$s)=>hv+$s%Fu));const Ou=Fu+hv,fa=vT*Au*_a,xT=Array.from({length:fa},(zn,$s)=>Ou+Math.floor($s/(Au*_a))),TT=Array.from({length:fa},(zn,$s)=>Ou+Math.floor($s/_a)%Au),ET=Array.from({length:fa},(zn,$s)=>Ou+$s%_a);kt.push([xT,TT,ET].flat()),xr=ma+fa}if(xr0?(0,_.max)(kt.at(-1))[0]+1:0,Tr=er.length-xr;kt.push(Array.from({length:3*Tr},(ln,Ln)=>tr+Ln%Tr))}const Zr=kt.reduce((tr,Tr)=>tr+Tr.length,0),hs=new Array(Zr);let da=0;for(let tr=0;tr<3;++tr)for(let Tr=0;Trbt[ut%bt.length]),_t=Array.from({length:yt[0]},($t,ut)=>(0,_.max)(bt.subarray(yt[1]*ut,yt[1]*(ut+1)))[0]+1n+BigInt(yt[1]));return[new u.Tensor("int64",Ft,[3,...yt]),new u.Tensor("int64",_t,[_t.length,1])]}else{const[bt,yt]=C.dims,Ft=BigInt64Array.from({length:3*bt*yt},(_t,$t)=>BigInt(Math.floor($t%yt/bt)));return[new u.Tensor("int64",Ft,[3,...C.dims]),(0,u.zeros)([bt,1])]}}async encode_image({pixel_values:C,image_grid_thw:D}){return(await R(this.sessions.vision_encoder,{pixel_values:C,grid_thw:D})).image_features}_merge_input_ids_with_image_features(C){return F({image_token_id:this.config.image_token_id,...C})}prepare_inputs_for_generation(C,D,oe){if(D.attention_mask&&!D.position_ids)if(!D.past_key_values)[D.position_ids,D.rope_deltas]=this.get_rope_index(D.input_ids,D.image_grid_thw,D.video_grid_thw,D.attention_mask);else{D.pixel_values=null;const fe=BigInt(Object.values(D.past_key_values)[0].dims.at(-2)),he=D.rope_deltas.map(Ce=>fe+Ce);D.position_ids=(0,u.stack)([he,he,he],0)}return D}}class $c extends W{}class Iw extends $c{}class Aw extends $c{}class kc extends W{}class Fw extends kc{}class Ow extends kc{}class Ic extends W{}class Dw extends Ic{}class Lw extends Ic{}class Ac extends W{}class zw extends Ac{}class Bw extends Ac{}class Fc extends W{}class Rw extends Fc{}class jw extends Fc{}class Oc extends W{}class Nw extends Oc{}class Vw extends Oc{async _call(C){return new Tt(await super._call(C))}}class Dc extends W{}class Uw extends Dc{}class Ww extends Dc{async _call(C){return new Tt(await super._call(C))}}class Gw extends W{}class Kw extends Gw{}class Lc extends W{}class Hw extends Lc{}class qw extends Lc{async _call(C){return new Tt(await super._call(C))}}class Qw extends W{}class Xw extends Qw{}class zc extends W{}class Jw extends zc{}class Yw extends zc{async _call(C){return new Tt(await super._call(C))}}class Zw extends W{}class eM extends Zw{}class Bc extends W{}class tM extends Bc{}class rM extends Bc{async _call(C){return new Tt(await super._call(C))}}class sM extends W{}class nM extends sM{async _call(C){return new dv(await super._call(C))}}class Rc extends W{}class oM extends Rc{}class iM extends Rc{async _call(C){return new Tt(await super._call(C))}}class jc extends W{}class aM extends jc{}class lM extends jc{async _call(C){return new Tt(await super._call(C))}}class Nc extends W{}class cM extends Nc{}class uM extends Nc{}class Vc extends W{}class dM extends Vc{}class pM extends Vc{}class Uc extends W{}class hM extends Uc{}class mM extends Uc{async _call(C){return new Tt(await super._call(C))}}class Xi extends W{}class _M extends Xi{}class fM extends Xi{async _call(C){return new Gc(await super._call(C))}}class Wc extends Xi{async _call(C){return new gM(await super._call(C))}}class Gc extends be{constructor({logits:C,pred_boxes:D}){super(),this.logits=C,this.pred_boxes=D}}class gM extends be{constructor({logits:C,pred_boxes:D,pred_masks:oe}){super(),this.logits=C,this.pred_boxes=D,this.pred_masks=oe}}class Kc extends W{}class wM extends Kc{}class MM extends Kc{async _call(C){return new Jo(await super._call(C))}}class Jo extends be{constructor({logits:C,pred_boxes:D}){super(),this.logits=C,this.pred_boxes=D}}class Hc extends W{}class bM extends Hc{}class yM extends Hc{async _call(C){return new vM(await super._call(C))}}class vM extends Jo{}class qc extends W{}class xM extends qc{}class TM extends qc{async _call(C){return new EM(await super._call(C))}}class EM extends Jo{}class Qc extends W{}class PM extends Qc{}class CM extends Qc{async _call(C){return new Jo(await super._call(C))}}class Xc extends W{}class SM extends Xc{}class $M extends Xc{async _call(C){return new kM(await super._call(C))}}class kM extends Gc{}class Jc extends W{}class IM extends Jc{}class AM extends Jc{async _call(C){return new Tt(await super._call(C))}}class Yc extends W{}class FM extends Yc{}class OM extends Yc{async _call(C){return new Tt(await super._call(C))}}class Zc extends W{}class DM extends Zc{}class LM extends Zc{async _call(C){return new Tt(await super._call(C))}}class Ji extends W{}class zM extends Ji{}class BM extends Ji{async _call(C){return new Tt(await super._call(C))}}class RM extends Ji{}class eu extends W{}class jM extends eu{}class NM extends eu{}class tu extends W{}class VM extends tu{}class UM extends tu{}class WM extends W{}class GM extends WM{}class Yi extends W{}class KM extends Yi{}class HM extends Yi{}class qM extends Yi{}class QM extends W{}class XM extends QM{}class JM extends W{}class YM extends JM{}class ZM extends W{}class eb extends ZM{}class ru extends W{}class tb extends ru{}class rb extends ru{}class su extends W{}class sb extends su{}class nb extends su{}class ob extends W{}class ib extends ob{}class nu extends W{}class ab extends nu{}class lb extends nu{async _call(C){return new Tt(await super._call(C))}}class ou extends W{}class cb extends ou{}class ub extends ou{async _call(C){return new Tt(await super._call(C))}}class iu extends W{}class db extends iu{}class pb extends iu{async _call(C){return new Tt(await super._call(C))}}class au extends W{}class hb extends au{}class mb extends au{async _call(C){return new Tt(await super._call(C))}}class _b extends W{}class fb extends _b{}class lu extends W{}class gb extends lu{}class wb extends lu{async _call(C){return new Mb(await super._call(C))}}class Mb extends be{constructor({logits:C,pred_boxes:D}){super(),this.logits=C,this.pred_boxes=D}}class bb extends W{}class yb extends bb{async get_image_embeddings({pixel_values:C}){return await ne(this,{pixel_values:C})}async forward(C){if((!C.image_embeddings||!C.image_positional_embeddings)&&(C={...C,...await this.get_image_embeddings(C)}),!C.input_labels&&C.input_points){const oe=C.input_points.dims.slice(0,-1),fe=oe.reduce((he,Ce)=>he*Ce,1);C.input_labels=new u.Tensor("int64",new BigInt64Array(fe).fill(1n),oe)}const D={image_embeddings:C.image_embeddings,image_positional_embeddings:C.image_positional_embeddings};return C.input_points&&(D.input_points=C.input_points),C.input_labels&&(D.input_labels=C.input_labels),C.input_boxes&&(D.input_boxes=C.input_boxes),await R(this.sessions.prompt_encoder_mask_decoder,D)}async _call(C){return new vb(await super._call(C))}}class vb extends be{constructor({iou_scores:C,pred_masks:D}){super(),this.iou_scores=C,this.pred_masks=D}}class cu extends W{}class xb extends cu{}class Tb extends cu{}class uu extends W{}class Eb extends uu{}class Pb extends uu{}class an extends W{}class Cb extends an{}class Sb extends an{async _call(C){return new Fn(await super._call(C))}}class $b extends an{async _call(C){return new Tt(await super._call(C))}}class kb extends an{async _call(C){return new vr(await super._call(C))}}class du extends W{}class Ib extends du{}class Ab extends du{async _call(C){return new vr(await super._call(C))}}class Fb extends W{}class Ob extends Fb{}class Zi extends W{}class Db extends Zi{}class Lb extends Zi{async _call(C){return new Fn(await super._call(C))}}class zb extends Zi{async _call(C){return new Tt(await super._call(C))}}class Yo extends W{}class Bb extends Yo{}class Rb extends Yo{async _call(C){return new Fn(await super._call(C))}}class jb extends Yo{async _call(C){return new Tt(await super._call(C))}}class Nb extends Yo{async _call(C){return new vr(await super._call(C))}}class ea extends W{}class Vb extends ea{}class Ub extends ea{async _call(C){return new Fn(await super._call(C))}}class Wb extends ea{async _call(C){return new Tt(await super._call(C))}}class aT extends W{}class Gb extends an{}class Kb extends an{async _call(C){return new Fn(await super._call(C))}}class Hb extends an{async _call(C){return new Tt(await super._call(C))}}class oo extends W{}class qb extends oo{}class Qb extends oo{async _call(C){return new Fn(await super._call(C))}}class Xb extends oo{async _call(C){return new Tt(await super._call(C))}}class Jb extends oo{async _call(C){return new uv(await super._call(C))}}class Yb extends oo{async _call(C){return new vr(await super._call(C))}}class Zb extends W{}class ey extends Zb{}class ta extends W{}class lT extends ta{}class ty extends ta{}class ry extends ta{async generate_speech(C,D,{threshold:oe=.5,minlenratio:fe=0,maxlenratio:he=20,vocoder:Ce=null}={}){const Le={input_ids:C},{encoder_outputs:Ue,encoder_attention_mask:Xe}=await ne(this,Le),mt=Ue.dims[1]/this.config.reduction_factor,bt=Math.floor(mt*he),yt=Math.floor(mt*fe),Ft=this.config.num_mel_bins;let _t=[],$t=null,ut=null,At=0;for(;;){++At;const dr=ee(!!ut);let lr;ut?lr=ut.output_sequence_out:lr=new u.Tensor("float32",new Float32Array(Ft),[1,1,Ft]);let wr={use_cache_branch:dr,output_sequence:lr,encoder_attention_mask:Xe,speaker_embeddings:D,encoder_hidden_states:Ue};this.addPastKeyValues(wr,$t),ut=await R(this.sessions.decoder_model_merged,wr),$t=this.getPastKeyValues(ut,$t);const{prob:Fr,spectrum:kt}=ut;if(_t.push(kt),At>=yt&&(Array.from(Fr.data).filter(xr=>xr>=oe).length>0||At>=bt))break}const Ht=(0,u.cat)(_t),{waveform:er}=await R(Ce.sessions.model,{spectrogram:Ht});return{spectrogram:Ht,waveform:er}}}class sy extends W{constructor(){super(...arguments);J(this,"main_input_name","spectrogram")}}class ny extends W{}class oy extends ny{}class pu extends W{}class iy extends pu{}class ay extends pu{}class hu extends W{}class ly extends hu{}class cy extends hu{}class mu extends W{}class uy extends mu{}class dy extends mu{}class _u extends W{}class py extends _u{}class hy extends _u{}class ra extends W{}class my extends ra{}class _y extends ra{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"text_model"})}}class fy extends ra{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"audio_model"})}}class gy extends W{}class fu extends gy{async _call(C){return new pv(await super._call(C))}}class sa extends W{}class cT extends sa{}class wy extends sa{}class My extends sa{}class gu extends W{}class by extends gu{}class yy extends gu{}class wu extends W{}class vy extends wu{}class xy extends wu{async _call(C){return new Tt(await super._call(C))}}class Mu extends W{}class uT extends Mu{}class dT extends Mu{}class bu extends W{constructor(){super(...arguments);J(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(D){const[oe,fe]=D.dims,he=this.config.decoder.num_codebooks,Ce=fe-he;let Le=0;for(let mt=0;mt0&&Ft<=Ce&&(D.data[Le++]=D.data[mt])}const Ue=Math.floor(oe/he),Xe=Le/(Ue*he);return new u.Tensor(D.type,D.data.slice(0,Le),[Ue,he,Xe])}prepare_inputs_for_generation(D,oe,fe){let he=structuredClone(D);for(let Le=0;Le=Ue&&(he[Le][Ue]=BigInt(this.config.decoder.pad_token_id));return fe.guidance_scale!==null&&fe.guidance_scale>1&&(he=he.concat(he)),super.prepare_inputs_for_generation(he,oe,fe)}async generate(D){const oe=await super.generate(D),fe=this._apply_and_filter_by_delay_pattern_mask(oe).unsqueeze_(0),{audio_values:he}=await R(this.sessions.encodec_decode,{audio_codes:fe});return he}}class na extends W{}class Ty extends na{}class Ey extends na{async _call(C){return new Tt(await super._call(C))}}class Py extends na{}class oa extends W{}class Cy extends oa{}class Sy extends oa{async _call(C){return new Tt(await super._call(C))}}class $y extends oa{}class ia extends W{}class ky extends ia{}class Iy extends ia{async _call(C){return new Tt(await super._call(C))}}class Ay extends ia{}class aa extends W{}class Fy extends aa{}class Oy extends aa{async _call(C){return new Tt(await super._call(C))}}class Dy extends aa{}class Ly extends W{}class zy extends Ly{}class By extends W{}class Ry extends By{constructor(...D){super(...D);J(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(D){const oe=this._generation_mode??"text";let fe;if(oe==="text"||!D.past_key_values){const Xe=this.sessions.prepare_inputs_embeds,mt=(0,a.pick)(D,Xe.inputNames);fe=await R(Xe,mt)}else{const Xe=this.sessions.gen_img_embeds,mt=(0,a.pick)({image_ids:D.input_ids},Xe.inputNames);fe=await R(Xe,mt)}const he={...D,...fe},Ce=await ue(this,he),Le=this.sessions[oe==="text"?"lm_head":"gen_head"];if(!Le)throw new Error(`Unable to find "${Le}" generation head`);const Ue=await R(Le,(0,a.pick)(Ce,Le.inputNames));return{...fe,...Ce,...Ue}}async generate(D){return this._generation_mode="text",super.generate(D)}async generate_images(D){this._generation_mode="image";const oe=(D.inputs??D[this.main_input_name]).dims[1],he=(await super.generate(D)).slice(null,[oe,null]),Ce=this.sessions.image_decode,{decoded_image:Le}=await R(Ce,{generated_tokens:he}),Ue=Le.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Xe=[];for(const mt of Ue){const bt=f.RawImage.fromTensor(mt);Xe.push(bt)}return Xe}}class jy extends be{constructor({char_logits:C,bpe_logits:D,wp_logits:oe}){super(),this.char_logits=C,this.bpe_logits=D,this.wp_logits=oe}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Ny extends W{}class Vy extends Ny{async _call(C){return new jy(await super._call(C))}}class yu extends W{}class Uy extends yu{}class Wy extends yu{}class vu extends W{}class Gy extends vu{}class Ky extends vu{}class Hy extends W{constructor(){super(...arguments);J(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class xu extends Hy{_merge_input_ids_with_audio_features(C){const D=C.audio_features.dims.at(-1),oe=C.audio_features.view(-1,D);return U({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...C,audio_features:oe})}}class qy extends xu{}class la extends W{constructor(){super(...arguments);J(this,"main_input_name","input_values");J(this,"forward_params",["input_values"])}}class Qy extends be{constructor({audio_codes:C}){super(),this.audio_codes=C}}class Xy extends be{constructor({audio_values:C}){super(),this.audio_values=C}}class Jy extends la{async encode(C){return new Qy(await R(this.sessions.encoder_model,C))}async decode(C){return new Xy(await R(this.sessions.decoder_model,C))}}class Yy extends la{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class Zy extends la{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class ca extends W{constructor(){super(...arguments);J(this,"main_input_name","input_values");J(this,"forward_params",["input_values"])}}class e0 extends be{constructor({audio_codes:C}){super(),this.audio_codes=C}}class t0 extends be{constructor({audio_values:C}){super(),this.audio_values=C}}class r0 extends ca{async encode(C){return new e0(await R(this.sessions.encoder_model,C))}async decode(C){return new t0(await R(this.sessions.decoder_model,C))}}class s0 extends ca{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class n0 extends ca{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class ua extends W{constructor(){super(...arguments);J(this,"main_input_name","input_values");J(this,"forward_params",["input_values"])}}class o0 extends ua{async encode(C){return await R(this.sessions.encoder_model,C)}async decode(C){return await R(this.sessions.decoder_model,C)}}class i0 extends ua{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class a0 extends ua{static async from_pretrained(C,D={}){return super.from_pretrained(C,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class jt{static async from_pretrained(C,{progress_callback:D=null,config:oe=null,cache_dir:fe=null,local_files_only:he=!1,revision:Ce="main",model_file_name:Le=null,subfolder:Ue="onnx",device:Xe=null,dtype:mt=null,use_external_data_format:bt=null,session_options:yt={}}={}){const Ft={progress_callback:D,config:oe,cache_dir:fe,local_files_only:he,revision:Ce,model_file_name:Le,subfolder:Ue,device:Xe,dtype:mt,use_external_data_format:bt,session_options:yt};if(Ft.config=await s.AutoConfig.from_pretrained(C,Ft),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const _t=Ft.config.model_type;for(const $t of this.MODEL_CLASS_MAPPINGS){let ut=$t.get(_t);if(!ut){for(const At of $t.values())if(At[0]===_t){ut=At;break}if(!ut)continue}return await ut[1].from_pretrained(C,Ft)}if(this.BASE_IF_FAIL)return F0.has(_t)||console.warn(`Unknown model class "${_t}", attempting to construct from base class.`),await W.from_pretrained(C,Ft);throw Error(`Unsupported model type: ${_t}`)}}J(jt,"MODEL_CLASS_MAPPINGS",null),J(jt,"BASE_IF_FAIL",!1);const pT=new Map([["bert",["BertModel",Me]],["neobert",["NeoBertModel",xe]],["modernbert",["ModernBertModel",Ye]],["nomic_bert",["NomicBertModel",us]],["roformer",["RoFormerModel",Cr]],["electra",["ElectraModel",B]],["esm",["EsmModel",Ns]],["convbert",["ConvBertModel",As]],["camembert",["CamembertModel",ft]],["deberta",["DebertaModel",Nr]],["deberta-v2",["DebertaV2Model",ds]],["mpnet",["MPNetModel",yn]],["albert",["AlbertModel",qe]],["distilbert",["DistilBertModel",ts]],["roberta",["RobertaModel",Ti]],["xlm",["XLMModel",Si]],["xlm-roberta",["XLMRobertaModel",Fi]],["clap",["ClapModel",my]],["clip",["CLIPModel",Lo]],["clipseg",["CLIPSegModel",$n]],["chinese_clip",["ChineseCLIPModel",dt]],["siglip",["SiglipModel",qi]],["jina_clip",["JinaCLIPModel",No]],["mobilebert",["MobileBertModel",Xt]],["squeezebert",["SqueezeBertModel",Y]],["wav2vec2",["Wav2Vec2Model",Cb]],["wav2vec2-bert",["Wav2Vec2BertModel",Vb]],["unispeech",["UniSpeechModel",Db]],["unispeech-sat",["UniSpeechSatModel",Bb]],["hubert",["HubertModel",Gb]],["wavlm",["WavLMModel",qb]],["audio-spectrogram-transformer",["ASTModel",Di]],["vits",["VitsModel",fu]],["pyannote",["PyAnnoteModel",Ib]],["wespeaker-resnet",["WeSpeakerResNetModel",Ob]],["detr",["DetrModel",_M]],["rt_detr",["RTDetrModel",wM]],["rt_detr_v2",["RTDetrV2Model",bM]],["rf_detr",["RFDetrModel",xM]],["d_fine",["DFineModel",PM]],["table-transformer",["TableTransformerModel",SM]],["vit",["ViTModel",Nw]],["ijepa",["IJepaModel",Uw]],["pvt",["PvtModel",Hw]],["vit_msn",["ViTMSNModel",Jw]],["vit_mae",["ViTMAEModel",Xw]],["groupvit",["GroupViTModel",eM]],["fastvit",["FastViTModel",tM]],["mobilevit",["MobileViTModel",oM]],["mobilevitv2",["MobileViTV2Model",aM]],["owlvit",["OwlViTModel",cM]],["owlv2",["Owlv2Model",dM]],["beit",["BeitModel",hM]],["deit",["DeiTModel",IM]],["hiera",["HieraModel",FM]],["convnext",["ConvNextModel",ab]],["convnextv2",["ConvNextV2Model",cb]],["dinov2",["Dinov2Model",db]],["dinov2_with_registers",["Dinov2WithRegistersModel",hb]],["resnet",["ResNetModel",DM]],["swin",["SwinModel",zM]],["swin2sr",["Swin2SRModel",jM]],["donut-swin",["DonutSwinModel",ib]],["yolos",["YolosModel",gb]],["dpt",["DPTModel",VM]],["glpn",["GLPNModel",sb]],["hifigan",["SpeechT5HifiGan",sy]],["efficientnet",["EfficientNetModel",vy]],["decision_transformer",["DecisionTransformerModel",zy]],["patchtst",["PatchTSTForPrediction",Uy]],["patchtsmixer",["PatchTSMixerForPrediction",Gy]],["mobilenet_v1",["MobileNetV1Model",Ty]],["mobilenet_v2",["MobileNetV2Model",Cy]],["mobilenet_v3",["MobileNetV3Model",ky]],["mobilenet_v4",["MobileNetV4Model",Fy]],["maskformer",["MaskFormerModel",tb]],["mgp-str",["MgpstrForSceneTextRecognition",Vy]],["style_text_to_speech_2",["StyleTextToSpeech2Model",ey]]]),hT=new Map([["t5",["T5Model",Lt]],["longt5",["LongT5Model",_r]],["mt5",["MT5Model",fr]],["bart",["BartModel",Zt]],["mbart",["MBartModel",Cs]],["marian",["MarianModel",xb]],["whisper",["WhisperModel",sn]],["m2m_100",["M2M100Model",Eb]],["blenderbot",["BlenderbotModel",hr]],["blenderbot-small",["BlenderbotSmallModel",Ws]]]),mT=new Map([["mimi",["MimiModel",Jy]],["dac",["DacModel",r0]],["snac",["SnacModel",o0]]]),_T=new Map([["bloom",["BloomModel",Dw]],["jais",["JAISModel",Go]],["gpt2",["GPT2Model",Uo]],["gptj",["GPTJModel",Qo]],["gpt_bigcode",["GPTBigCodeModel",h]],["gpt_neo",["GPTNeoModel",In]],["gpt_neox",["GPTNeoXModel",Ho]],["codegen",["CodeGenModel",z]],["llama",["LlamaModel",Pe]],["arcee",["ArceeModel",at]],["lfm2",["Lfm2Model",Gt]],["smollm3",["SmolLM3Model",Qi]],["exaone",["ExaoneModel",ow]],["olmo",["OlmoModel",cw]],["olmo2",["Olmo2Model",dw]],["mobilellm",["MobileLLMModel",aw]],["granite",["GraniteModel",hw]],["cohere",["CohereModel",_w]],["gemma",["GemmaModel",gw]],["gemma2",["Gemma2Model",Mw]],["gemma3_text",["Gemma3Model",yw]],["helium",["HeliumModel",tw]],["glm",["GlmModel",sw]],["openelm",["OpenELMModel",xw]],["qwen2",["Qwen2Model",Ew]],["qwen3",["Qwen3Model",Cw]],["phi",["PhiModel",Iw]],["phi3",["Phi3Model",Fw]],["mpt",["MptModel",zw]],["opt",["OPTModel",Rw]],["mistral",["MistralModel",iy]],["ernie4_5",["Ernie4_5_Model",ly]],["starcoder2",["Starcoder2Model",uy]],["falcon",["FalconModel",py]],["stablelm",["StableLmModel",by]],["modernbert-decoder",["ModernBertDecoderModel",Mr]]]),Tu=new Map([["speecht5",["SpeechT5ForSpeechToText",ty]],["whisper",["WhisperForConditionalGeneration",Ao]],["lite-whisper",["LiteWhisperForConditionalGeneration",Fo]],["moonshine",["MoonshineForConditionalGeneration",Li]]]),l0=new Map([["speecht5",["SpeechT5ForTextToSpeech",ry]]]),c0=new Map([["vits",["VitsModel",fu]],["musicgen",["MusicgenForConditionalGeneration",bu]]]),u0=new Map([["bert",["BertForSequenceClassification",we]],["neobert",["NeoBertForSequenceClassification",Ke]],["modernbert",["ModernBertForSequenceClassification",It]],["roformer",["RoFormerForSequenceClassification",Js]],["electra",["ElectraForSequenceClassification",re]],["esm",["EsmForSequenceClassification",Re]],["convbert",["ConvBertForSequenceClassification",Ct]],["camembert",["CamembertForSequenceClassification",vt]],["deberta",["DebertaForSequenceClassification",rr]],["deberta-v2",["DebertaV2ForSequenceClassification",Os]],["mpnet",["MPNetForSequenceClassification",xn]],["albert",["AlbertForSequenceClassification",We]],["distilbert",["DistilBertForSequenceClassification",Dr]],["roberta",["RobertaForSequenceClassification",Ei]],["xlm",["XLMForSequenceClassification",ki]],["xlm-roberta",["XLMRobertaForSequenceClassification",Co]],["bart",["BartForSequenceClassification",Kr]],["mbart",["MBartForSequenceClassification",ps]],["mobilebert",["MobileBertForSequenceClassification",Es]],["squeezebert",["SqueezeBertForSequenceClassification",de]]]),d0=new Map([["bert",["BertForTokenClassification",Ae]],["neobert",["NeoBertForTokenClassification",nt]],["modernbert",["ModernBertForTokenClassification",St]],["roformer",["RoFormerForTokenClassification",Ys]],["electra",["ElectraForTokenClassification",ge]],["esm",["EsmForTokenClassification",je]],["convbert",["ConvBertForTokenClassification",Qt]],["camembert",["CamembertForTokenClassification",st]],["deberta",["DebertaForTokenClassification",Sr]],["deberta-v2",["DebertaV2ForTokenClassification",Ds]],["mpnet",["MPNetForTokenClassification",pe]],["distilbert",["DistilBertForTokenClassification",Ts]],["roberta",["RobertaForTokenClassification",Pi]],["xlm",["XLMForTokenClassification",Ii]],["xlm-roberta",["XLMRobertaForTokenClassification",So]]]),Eu=new Map([["t5",["T5ForConditionalGeneration",sr]],["longt5",["LongT5ForConditionalGeneration",br]],["mt5",["MT5ForConditionalGeneration",Lr]],["bart",["BartForConditionalGeneration",gr]],["mbart",["MBartForConditionalGeneration",Ir]],["marian",["MarianMTModel",Tb]],["m2m_100",["M2M100ForConditionalGeneration",Pb]],["blenderbot",["BlenderbotForConditionalGeneration",nr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Hn]]]),Pu=new Map([["bloom",["BloomForCausalLM",Lw]],["gpt2",["GPT2LMHeadModel",Wo]],["jais",["JAISLMHeadModel",Ko]],["gptj",["GPTJForCausalLM",Xo]],["gpt_bigcode",["GPTBigCodeForCausalLM",E]],["gpt_neo",["GPTNeoForCausalLM",ro]],["gpt_neox",["GPTNeoXForCausalLM",qo]],["codegen",["CodeGenForCausalLM",V]],["llama",["LlamaForCausalLM",De]],["arcee",["ArceeForCausalLM",xt]],["lfm2",["Lfm2ForCausalLM",yr]],["smollm3",["SmolLM3ForCausalLM",ew]],["exaone",["ExaoneForCausalLM",iw]],["olmo",["OlmoForCausalLM",uw]],["olmo2",["Olmo2ForCausalLM",pw]],["mobilellm",["MobileLLMForCausalLM",lw]],["granite",["GraniteForCausalLM",mw]],["cohere",["CohereForCausalLM",fw]],["gemma",["GemmaForCausalLM",ww]],["gemma2",["Gemma2ForCausalLM",bw]],["gemma3_text",["Gemma3ForCausalLM",vw]],["helium",["HeliumForCausalLM",rw]],["glm",["GlmForCausalLM",nw]],["openelm",["OpenELMForCausalLM",Tw]],["qwen2",["Qwen2ForCausalLM",Pw]],["qwen3",["Qwen3ForCausalLM",Sw]],["phi",["PhiForCausalLM",Aw]],["phi3",["Phi3ForCausalLM",Ow]],["mpt",["MptForCausalLM",Bw]],["opt",["OPTForCausalLM",jw]],["mbart",["MBartForCausalLM",ur]],["mistral",["MistralForCausalLM",ay]],["ernie4_5",["Ernie4_5_ForCausalLM",cy]],["starcoder2",["Starcoder2ForCausalLM",dy]],["falcon",["FalconForCausalLM",hy]],["trocr",["TrOCRForCausalLM",oy]],["stablelm",["StableLmForCausalLM",yy]],["modernbert-decoder",["ModernBertDecoderForCausalLM",Pr]],["phi3_v",["Phi3VForCausalLM",Pn]]]),fT=new Map([["multi_modality",["MultiModalityCausalLM",Ry]]]),p0=new Map([["bert",["BertForMaskedLM",Se]],["neobert",["NeoBertForMaskedLM",Ze]],["modernbert",["ModernBertForMaskedLM",ot]],["roformer",["RoFormerForMaskedLM",Xs]],["electra",["ElectraForMaskedLM",q]],["esm",["EsmForMaskedLM",Gr]],["convbert",["ConvBertForMaskedLM",Fs]],["camembert",["CamembertForMaskedLM",ht]],["deberta",["DebertaForMaskedLM",Xr]],["deberta-v2",["DebertaV2ForMaskedLM",kr]],["mpnet",["MPNetForMaskedLM",vn]],["albert",["AlbertForMaskedLM",Mt]],["distilbert",["DistilBertForMaskedLM",mr]],["roberta",["RobertaForMaskedLM",Po]],["xlm",["XLMWithLMHeadModel",$i]],["xlm-roberta",["XLMRobertaForMaskedLM",Oi]],["mobilebert",["MobileBertForMaskedLM",Vs]],["squeezebert",["SqueezeBertForMaskedLM",le]]]),h0=new Map([["bert",["BertForQuestionAnswering",Be]],["neobert",["NeoBertForQuestionAnswering",Je]],["roformer",["RoFormerForQuestionAnswering",Zs]],["electra",["ElectraForQuestionAnswering",Fe]],["convbert",["ConvBertForQuestionAnswering",S]],["camembert",["CamembertForQuestionAnswering",zt]],["deberta",["DebertaForQuestionAnswering",$r]],["deberta-v2",["DebertaV2ForQuestionAnswering",Ur]],["mpnet",["MPNetForQuestionAnswering",I]],["albert",["AlbertForQuestionAnswering",tt]],["distilbert",["DistilBertForQuestionAnswering",pr]],["roberta",["RobertaForQuestionAnswering",Ci]],["xlm",["XLMForQuestionAnswering",Ai]],["xlm-roberta",["XLMRobertaForQuestionAnswering",$o]],["mobilebert",["MobileBertForQuestionAnswering",Us]],["squeezebert",["SqueezeBertForQuestionAnswering",Te]]]),Cu=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Tn]],["idefics3",["Idefics3ForConditionalGeneration",En]],["smolvlm",["SmolVLMForConditionalGeneration",Do]]]),m0=new Map([["llava",["LlavaForConditionalGeneration",Xn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",zi]],["moondream1",["Moondream1ForConditionalGeneration",Bi]],["florence2",["Florence2ForConditionalGeneration",ji]],["qwen2-vl",["Qwen2VLForConditionalGeneration",kw]],["idefics3",["Idefics3ForConditionalGeneration",En]],["smolvlm",["SmolVLMForConditionalGeneration",Do]],["paligemma",["PaliGemmaForConditionalGeneration",Vi]],["llava_qwen2",["LlavaQwen2ForCausalLM",Ui]],["gemma3n",["Gemma3nForConditionalGeneration",nn]]]),_0=new Map([["ultravox",["UltravoxModel",xu]],["voxtral",["VoxtralForConditionalGeneration",qy]]]),gT=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Tn]]]),f0=new Map([["vit",["ViTForImageClassification",Vw]],["ijepa",["IJepaForImageClassification",Ww]],["pvt",["PvtForImageClassification",qw]],["vit_msn",["ViTMSNForImageClassification",Yw]],["fastvit",["FastViTForImageClassification",rM]],["mobilevit",["MobileViTForImageClassification",iM]],["mobilevitv2",["MobileViTV2ForImageClassification",lM]],["beit",["BeitForImageClassification",mM]],["deit",["DeiTForImageClassification",AM]],["hiera",["HieraForImageClassification",OM]],["convnext",["ConvNextForImageClassification",lb]],["convnextv2",["ConvNextV2ForImageClassification",ub]],["dinov2",["Dinov2ForImageClassification",pb]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",mb]],["resnet",["ResNetForImageClassification",LM]],["swin",["SwinForImageClassification",BM]],["segformer",["SegformerForImageClassification",wy]],["efficientnet",["EfficientNetForImageClassification",xy]],["mobilenet_v1",["MobileNetV1ForImageClassification",Ey]],["mobilenet_v2",["MobileNetV2ForImageClassification",Sy]],["mobilenet_v3",["MobileNetV3ForImageClassification",Iy]],["mobilenet_v4",["MobileNetV4ForImageClassification",Oy]]]),g0=new Map([["detr",["DetrForObjectDetection",fM]],["rt_detr",["RTDetrForObjectDetection",MM]],["rt_detr_v2",["RTDetrV2ForObjectDetection",yM]],["rf_detr",["RFDetrForObjectDetection",TM]],["d_fine",["DFineForObjectDetection",CM]],["table-transformer",["TableTransformerForObjectDetection",$M]],["yolos",["YolosForObjectDetection",wb]]]),w0=new Map([["owlvit",["OwlViTForObjectDetection",uM]],["owlv2",["Owlv2ForObjectDetection",pM]],["grounding-dino",["GroundingDinoForObjectDetection",fb]]]),io=new Map([["detr",["DetrForSegmentation",Wc]],["clipseg",["CLIPSegForImageSegmentation",Zn]]]),M0=new Map([["segformer",["SegformerForSemanticSegmentation",My]],["sapiens",["SapiensForSemanticSegmentation",KM]],["swin",["SwinForSemanticSegmentation",RM]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",Py]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",$y]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Ay]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Dy]]]),b0=new Map([["detr",["DetrForSegmentation",Wc]],["maskformer",["MaskFormerForInstanceSegmentation",rb]]]),y0=new Map([["sam",["SamModel",yb]]]),v0=new Map([["wav2vec2",["Wav2Vec2ForCTC",Sb]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Ub]],["unispeech",["UniSpeechForCTC",Lb]],["unispeech-sat",["UniSpeechSatForCTC",Rb]],["wavlm",["WavLMForCTC",Qb]],["hubert",["HubertForCTC",Kb]]]),x0=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",$b]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Wb]],["unispeech",["UniSpeechForSequenceClassification",zb]],["unispeech-sat",["UniSpeechSatForSequenceClassification",jb]],["wavlm",["WavLMForSequenceClassification",Xb]],["hubert",["HubertForSequenceClassification",Hb]],["audio-spectrogram-transformer",["ASTForAudioClassification",Io]]]),T0=new Map([["wavlm",["WavLMForXVector",Jb]]]),E0=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Nb]],["wavlm",["WavLMForAudioFrameClassification",Yb]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",kb]],["pyannote",["PyAnnoteForAudioFrameClassification",Ab]]]),P0=new Map([["vitmatte",["VitMatteForImageMatting",nM]]]),wT=new Map([["patchtst",["PatchTSTForPrediction",Wy]],["patchtsmixer",["PatchTSMixerForPrediction",Ky]]]),C0=new Map([["swin2sr",["Swin2SRForImageSuperResolution",NM]]]),S0=new Map([["dpt",["DPTForDepthEstimation",UM]],["depth_anything",["DepthAnythingForDepthEstimation",GM]],["glpn",["GLPNForDepthEstimation",nb]],["sapiens",["SapiensForDepthEstimation",HM]],["depth_pro",["DepthProForDepthEstimation",XM]],["metric3d",["Metric3DForDepthEstimation",YM]],["metric3dv2",["Metric3Dv2ForDepthEstimation",eb]]]),$0=new Map([["sapiens",["SapiensForNormalEstimation",qM]]]),k0=new Map([["vitpose",["VitPoseForPoseEstimation",Kw]]]),I0=new Map([["clip",["CLIPVisionModelWithProjection",Bo]],["siglip",["SiglipVisionModel",jo]],["jina_clip",["JinaCLIPVisionModel",Sn]]]),A0=[[pT,v.EncoderOnly],[hT,v.EncoderDecoder],[_T,v.DecoderOnly],[mT,v.AutoEncoder],[u0,v.EncoderOnly],[d0,v.EncoderOnly],[Eu,v.Seq2Seq],[Tu,v.Seq2Seq],[Pu,v.DecoderOnly],[fT,v.MultiModality],[p0,v.EncoderOnly],[h0,v.EncoderOnly],[Cu,v.Vision2Seq],[m0,v.ImageTextToText],[_0,v.AudioTextToText],[f0,v.EncoderOnly],[io,v.EncoderOnly],[b0,v.EncoderOnly],[M0,v.EncoderOnly],[P0,v.EncoderOnly],[wT,v.EncoderOnly],[C0,v.EncoderOnly],[S0,v.EncoderOnly],[$0,v.EncoderOnly],[k0,v.EncoderOnly],[g0,v.EncoderOnly],[w0,v.EncoderOnly],[y0,v.MaskGeneration],[v0,v.EncoderOnly],[x0,v.EncoderOnly],[l0,v.Seq2Seq],[c0,v.EncoderOnly],[T0,v.EncoderOnly],[E0,v.EncoderOnly],[I0,v.EncoderOnly]];for(const[w,C]of A0)for(const[D,oe]of w.values())y.set(D,C),x.set(oe,D),T.set(D,oe);const MT=[["MusicgenForConditionalGeneration",bu,v.Musicgen],["Phi3VForCausalLM",Pn,v.Phi3V],["CLIPTextModelWithProjection",zo,v.EncoderOnly],["SiglipTextModel",Ro,v.EncoderOnly],["JinaCLIPTextModel",Vo,v.EncoderOnly],["ClapTextModelWithProjection",_y,v.EncoderOnly],["ClapAudioModelWithProjection",fy,v.EncoderOnly],["DacEncoderModel",s0,v.EncoderOnly],["DacDecoderModel",n0,v.EncoderOnly],["MimiEncoderModel",Yy,v.EncoderOnly],["MimiDecoderModel",Zy,v.EncoderOnly],["SnacEncoderModel",i0,v.EncoderOnly],["SnacDecoderModel",a0,v.EncoderOnly],["Gemma3nForConditionalGeneration",nn,v.ImageAudioTextToText]];for(const[w,C,D]of MT)y.set(w,D),x.set(C,w),T.set(w,C);const F0=new Map([["modnet",io],["birefnet",io],["isnet",io],["ben",io]]);for(const[w,C]of F0.entries())C.set(w,["PreTrainedModel",W]),y.set(w,v.EncoderOnly),x.set(W,w),T.set(w,W);class Su extends jt{}J(Su,"MODEL_CLASS_MAPPINGS",A0.map(C=>C[0])),J(Su,"BASE_IF_FAIL",!0);class O0 extends jt{}J(O0,"MODEL_CLASS_MAPPINGS",[u0]);class D0 extends jt{}J(D0,"MODEL_CLASS_MAPPINGS",[d0]);class L0 extends jt{}J(L0,"MODEL_CLASS_MAPPINGS",[Eu]);class z0 extends jt{}J(z0,"MODEL_CLASS_MAPPINGS",[Tu]);class B0 extends jt{}J(B0,"MODEL_CLASS_MAPPINGS",[l0]);class R0 extends jt{}J(R0,"MODEL_CLASS_MAPPINGS",[c0]);class j0 extends jt{}J(j0,"MODEL_CLASS_MAPPINGS",[Pu]);class N0 extends jt{}J(N0,"MODEL_CLASS_MAPPINGS",[p0]);class V0 extends jt{}J(V0,"MODEL_CLASS_MAPPINGS",[h0]);class U0 extends jt{}J(U0,"MODEL_CLASS_MAPPINGS",[Cu]);class W0 extends jt{}J(W0,"MODEL_CLASS_MAPPINGS",[f0]);class G0 extends jt{}J(G0,"MODEL_CLASS_MAPPINGS",[io]);class K0 extends jt{}J(K0,"MODEL_CLASS_MAPPINGS",[M0]);class H0 extends jt{}J(H0,"MODEL_CLASS_MAPPINGS",[b0]);class q0 extends jt{}J(q0,"MODEL_CLASS_MAPPINGS",[g0]);class Q0 extends jt{}J(Q0,"MODEL_CLASS_MAPPINGS",[w0]);class X0 extends jt{}J(X0,"MODEL_CLASS_MAPPINGS",[y0]);class J0 extends jt{}J(J0,"MODEL_CLASS_MAPPINGS",[v0]);class Y0 extends jt{}J(Y0,"MODEL_CLASS_MAPPINGS",[x0]);class Z0 extends jt{}J(Z0,"MODEL_CLASS_MAPPINGS",[T0]);class ev extends jt{}J(ev,"MODEL_CLASS_MAPPINGS",[E0]);class tv extends jt{}J(tv,"MODEL_CLASS_MAPPINGS",[gT]);class rv extends jt{}J(rv,"MODEL_CLASS_MAPPINGS",[P0]);class sv extends jt{}J(sv,"MODEL_CLASS_MAPPINGS",[C0]);class nv extends jt{}J(nv,"MODEL_CLASS_MAPPINGS",[S0]);class ov extends jt{}J(ov,"MODEL_CLASS_MAPPINGS",[$0]);class iv extends jt{}J(iv,"MODEL_CLASS_MAPPINGS",[k0]);class av extends jt{}J(av,"MODEL_CLASS_MAPPINGS",[I0]);class lv extends jt{}J(lv,"MODEL_CLASS_MAPPINGS",[m0]);class cv extends jt{}J(cv,"MODEL_CLASS_MAPPINGS",[_0]);class bT extends be{constructor({logits:C,past_key_values:D,encoder_outputs:oe,decoder_attentions:fe=null,cross_attentions:he=null}){super(),this.logits=C,this.past_key_values=D,this.encoder_outputs=oe,this.decoder_attentions=fe,this.cross_attentions=he}}class Tt extends be{constructor({logits:C,...D}){super(),this.logits=C;const oe=Object.values(D);oe.length>0&&(this.attentions=oe)}}class uv extends be{constructor({logits:C,embeddings:D}){super(),this.logits=C,this.embeddings=D}}class vr extends be{constructor({logits:C}){super(),this.logits=C}}class Ar extends be{constructor({logits:C}){super(),this.logits=C}}class Br extends be{constructor({start_logits:C,end_logits:D}){super(),this.start_logits=C,this.end_logits=D}}class Fn extends be{constructor({logits:C}){super(),this.logits=C}}class yT extends be{constructor({logits:C,past_key_values:D}){super(),this.logits=C,this.past_key_values=D}}class dv extends be{constructor({alphas:C}){super(),this.alphas=C}}class pv extends be{constructor({waveform:C,spectrogram:D}){super(),this.waveform=C,this.spectrogram=D}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,c=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=c,this.window=(0,o.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(a,l){return(0,o.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:l,transpose:!0})}async _call(a){(0,s.validate_audio_inputs)(a,"ASTFeatureExtractor");const l=await this._extract_fbank_features(a,this.config.max_length);if(this.config.do_normalize){const c=this.std*2,p=l.data;for(let d=0;d{t.r(r),t.d(r,{AutoFeatureExtractor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var n=t("./src/models/feature_extractors.js");class i{static async from_pretrained(l,c={}){const p=await(0,o.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,c),d=p.feature_extractor_type,u=n[d];if(!u)throw new Error(`Unknown feature_extractor_type: '${d}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new u(p)}}},"./src/models/auto/image_processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoImageProcessor:()=>a});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js"),n=t("./src/base/image_processors_utils.js"),i=t("./src/models/image_processors.js");class a{static async from_pretrained(c,p={}){const d=await(0,o.getModelJSON)(c,s.IMAGE_PROCESSOR_NAME,!0,p),u=d.image_processor_type??d.feature_extractor_type;let f=i[u==null?void 0:u.replace(/Fast$/,"")];return f||(u!==void 0&&console.warn(`Image processor type '${u}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),f=n.ImageProcessor),new f(d)}}},"./src/models/auto/processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>c});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js"),n=t("./src/base/processing_utils.js"),i=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class c{static async from_pretrained(d,u={}){const f=await(0,o.getModelJSON)(d,s.IMAGE_PROCESSOR_NAME,!0,u),{image_processor_type:_,feature_extractor_type:b,processor_class:k}=f;if(k&&i[k])return i[k].from_pretrained(d,u);if(!_&&!b)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const g={};if(_){const $=a[_.replace(/Fast$/,"")];if(!$)throw new Error(`Unknown image_processor_type: '${_}'.`);g.image_processor=new $(f)}if(b){const $=a[b];if($)g.image_processor=new $(f);else{const v=l[b];if(!v)throw new Error(`Unknown feature_extractor_type: '${b}'.`);g.feature_extractor=new v(f)}}const M={};return new n.Processor(M,g,null)}}},"./src/models/beit/image_processing_beit.js":(e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(e,r,t)=>{t.r(r),t.d(r,{ClapFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,o.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,o.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,o.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,c,p){let d;const u=a.length-l;if(u>0)if(c==="rand_trunc"){const f=Math.floor(Math.random()*(u+1));a=a.subarray(f,f+l),d=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${c}" not implemented`);else{if(u<0){let f=new Float64Array(l);if(f.set(a),p==="repeat")for(let _=a.length;_{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>n,CLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/convnext/image_processing_convnext.js":(e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>n,ConvNextImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){var c;const l=(c=this.size)==null?void 0:c.shortest_edge;if(l===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(l<384){const p=Math.floor(l/this.crop_pct),[d,u]=this.get_resize_output_image_size(a,{shortest_edge:p});a=await a.resize(d,u,{resample:this.resample}),a=await a.center_crop(l,l)}else a=await a.resize(l,l,{resample:this.resample});return a}}class n extends o{}},"./src/models/dac/feature_extraction_dac.js":(e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>o});var s=t("./src/models/encodec/feature_extraction_encodec.js");class o extends s.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>n,DeiTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/detr/image_processing_detr.js":(e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(l){const c=await super._call(l),p=[c.pixel_values.dims[0],64,64],d=(0,o.full)(p,1n);return{...c,pixel_mask:d}}post_process_object_detection(...l){return(0,s.post_process_object_detection)(...l)}post_process_panoptic_segmentation(...l){return(0,s.post_process_panoptic_segmentation)(...l)}post_process_instance_segmentation(...l){return(0,s.post_process_instance_segmentation)(...l)}}class i extends n{}},"./src/models/donut/image_processing_donut.js":(e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>n,DonutImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(a,l,c,p={}){const[d,u,f]=l;let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(f).fill(_));let b=this.image_std;Array.isArray(b)||(b=new Array(f).fill(_));const k=_.map((g,M)=>-g/b[M]);return super.pad_image(a,l,c,{center:!0,constant_values:k,...p})}}class n extends o{}},"./src/models/dpt/image_processing_dpt.js":(e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>n,DPTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/efficientnet/image_processing_efficientnet.js":(e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super(i),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(a=>a*a))}}},"./src/models/encodec/feature_extraction_encodec.js":(e,r,t)=>{t.r(r),t.d(r,{EncodecFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"EncodecFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=this.config.feature_size;if(a.length%l!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${l}).`);const c=[1,l,a.length/l];return{input_values:new o.Tensor("float32",a,c)}}}},"./src/models/feature_extractors.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>n.ClapFeatureExtractor,DacFeatureExtractor:()=>i.DacFeatureExtractor,EncodecFeatureExtractor:()=>o.EncodecFeatureExtractor,Gemma3nAudioFeatureExtractor:()=>a.Gemma3nAudioFeatureExtractor,ImageFeatureExtractor:()=>k.ImageProcessor,MoonshineFeatureExtractor:()=>l.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>c.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>p.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>d.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>u.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>f.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>_.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>b.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),o=t("./src/models/encodec/feature_extraction_encodec.js"),n=t("./src/models/clap/feature_extraction_clap.js"),i=t("./src/models/dac/feature_extraction_dac.js"),a=t("./src/models/gemma3n/feature_extraction_gemma3n.js"),l=t("./src/models/moonshine/feature_extraction_moonshine.js"),c=t("./src/models/pyannote/feature_extraction_pyannote.js"),p=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),d=t("./src/models/snac/feature_extraction_snac.js"),u=t("./src/models/speecht5/feature_extraction_speecht5.js"),f=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),_=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),b=t("./src/models/whisper/feature_extraction_whisper.js"),k=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{constructor(l,c,p){super(l,c,p);const{tasks_answer_post_processing_type:d,task_prompts_without_inputs:u,task_prompts_with_input:f}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(d??{})),this.task_prompts_without_inputs=new Map(Object.entries(u??{})),this.task_prompts_with_input=new Map(Object.entries(f??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const c=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))c.push(this.task_prompts_without_inputs.get(p));else{for(const[d,u]of this.task_prompts_with_input)if(p.includes(d)){c.push(u.replaceAll("{input}",p).replaceAll(d,""));break}c.length!==l.length&&c.push(p)}return c}post_process_generation(l,c,p){const d=this.tasks_answer_post_processing_type.get(c)??"pure_text";l=l.replaceAll("","").replaceAll("","");let u;switch(d){case"pure_text":u=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const f=d==="ocr"?"quad_boxes":"bboxes",_=l.matchAll(this.regexes[f]),b=[],k=[];for(const[g,M,...$]of _)b.push(M?M.trim():b.at(-1)??""),k.push($.map((v,y)=>(Number(v)+.5)/this.size_per_bin*p[y%2]));u={labels:b,[f]:k};break;default:throw new Error(`Task "${c}" (of type "${d}") not yet implemented.`)}return{[c]:u}}async _call(l,c=null,p={}){if(!l&&!c)throw new Error("Either text or images must be provided");const d=await this.image_processor(l,p),u=c?this.tokenizer(this.construct_prompts(c),p):{};return{...d,...u}}}J(i,"tokenizer_class",n.AutoTokenizer),J(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/gemma3n/feature_extraction_gemma3n.js":(e,r,t)=>{t.r(r),t.d(r,{Gemma3nAudioFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const{fft_length:c,feature_size:p,min_frequency:d,max_frequency:u,sampling_rate:f,frame_length:_}=this.config,b=(0,n.mel_filter_bank)(Math.floor(1+c/2),p,d,u,f,null,"htk",!1);this.mel_filters=b,this.window=(0,n.window_function)(_,"hann")}async _extract_fbank_features(l,c){return(0,n.spectrogram)(l,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(l,{max_length:c=48e4,truncation:p=!0,padding:d=!0,pad_to_multiple_of:u=128}={}){if((0,s.validate_audio_inputs)(l,"Gemma3nAudioFeatureExtractor"),p&&l.length>c&&(l=l.slice(0,c)),d&&l.length%u!==0){const b=u-l.length%u,k=new Float64Array(l.length+b);k.set(l),this.config.padding_value!==0&&k.fill(this.config.padding_value,l.length),l=k}const f=await this._extract_fbank_features(l,this.config.max_length),_=(0,o.full)([1,f.dims[0]],!0);return{input_features:f.unsqueeze_(0),input_features_mask:_}}}},"./src/models/gemma3n/processing_gemma3n.js":(e,r,t)=>{t.r(r),t.d(r,{Gemma3nProcessor:()=>a});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js");t("./src/utils/image.js"),t("./src/utils/audio.js");class a extends s.Processor{constructor(c,p,d){super(c,p,d),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:u,boa_token:f,audio_token:_,eoa_token:b,image_token_id:k,boi_token:g,image_token:M,eoi_token:$}=this.tokenizer.config;this.audio_token_id=u,this.boa_token=f,this.audio_token=_;const v=_.repeat(this.audio_seq_length);this.full_audio_sequence=` + +${f}${v}${b} + +`,this.image_token_id=k,this.boi_token=g,this.image_token=M;const y=M.repeat(this.image_seq_length);this.full_image_sequence=` + +${g}${y}${$} + +`}async _call(c,p=null,d=null,u={}){typeof c=="string"&&(c=[c]);let f;d&&(f=await this.feature_extractor(d,u),c=c.map(k=>k.replaceAll(this.audio_token,this.full_audio_sequence)));let _;return p&&(_=await this.image_processor(p,u),c=c.map(k=>k.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(c,u),..._,...f}}}J(a,"image_processor_class",o.AutoImageProcessor),J(a,"feature_extractor_class",n.AutoFeatureExtractor),J(a,"tokenizer_class",i.AutoTokenizer),J(a,"uses_processor_config",!0),J(a,"uses_chat_template_file",!0)},"./src/models/glpn/image_processing_glpn.js":(e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a){const l=await super._call(a),c=l.pixel_values.dims,p=(0,o.ones)([c[0],c[2],c[3]]);return{...l,pixel_mask:p}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/base/image_processors_utils.js");function a(c,p){const u=c.dims.at(-1)-1,f=c.tolist();f.fill(!1,0,1),f.fill(!1,u);const _=p.tolist();return f.map((b,k)=>b?k:null).filter(b=>b!==null).map(b=>_[b])}class l extends s.Processor{async _call(p,d,u={}){const f=p?await this.image_processor(p,u):{};return{...d?this.tokenizer(d,u):{},...f}}post_process_grounded_object_detection(p,d,{box_threshold:u=.25,text_threshold:f=.25,target_sizes:_=null}={}){const{logits:b,pred_boxes:k}=p,g=b.dims[0];if(_!==null&&_.length!==g)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const M=b.dims.at(1),$=b.sigmoid(),v=$.max(-1).tolist(),y=k.tolist().map(x=>x.map(P=>(0,i.center_to_corners_format)(P))),T=[];for(let x=0;xR.map((te,H)=>te*P[(H+1)%2])));const O=v[x],L=[],G=[],K=[];for(let R=0;R{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{constructor(a){super(a),this.do_image_splitting=a.do_image_splitting??!0,this.max_image_size=a.max_image_size}get_resize_for_vision_encoder(a,l){let[c,p]=a.dims.slice(-2);const d=p/c;return p>=c?(p=Math.ceil(p/l)*l,c=Math.floor(p/d),c=Math.ceil(c/l)*l):(c=Math.ceil(c/l)*l,p=Math.floor(c*d),p=Math.ceil(p/l)*l),{height:c,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:c=!1}={}){let p;if(!Array.isArray(a))p=[[a]];else{if(a.length===0||!a[0])throw new Error("No images provided.");Array.isArray(a[0])?p=a:p=[a]}let d=[],u=[],f=[];const _=[],b=[];for(const x of p){let P=await Promise.all(x.map(G=>this.preprocess(G)));_.push(...P.map(G=>G.original_size)),b.push(...P.map(G=>G.reshaped_input_size)),P.forEach(G=>G.pixel_values.unsqueeze_(0));const{longest_edge:O}=this.max_image_size;let L;if(l??this.do_image_splitting){let G=new Array(P.length),K=new Array(P.length);L=await Promise.all(P.map(async(R,te)=>{const H=this.get_resize_for_vision_encoder(R.pixel_values,O),ee=await(0,o.interpolate_4d)(R.pixel_values,{size:[H.height,H.width]}),{frames:Z,num_splits_h:ne,num_splits_w:me}=await this.split_image(ee,this.max_image_size);return G[te]=ne,K[te]=me,(0,o.cat)(Z,0)})),u.push(G),f.push(K)}else{const G=[O,O];L=await Promise.all(P.map(K=>(0,o.interpolate_4d)(K.pixel_values,{size:G}))),u.push(new Array(P.length).fill(0)),f.push(new Array(P.length).fill(0))}d.push((0,o.cat)(L,0))}const k=d.length,[g,M,$,v]=d[0].dims;let y,T;if(k===1)y=d[0].unsqueeze_(0),T=(0,o.full)([k,g,$,v],!0);else{const x=Math.max(...d.map(L=>L.dims.at(0)));T=(0,o.full)([k,x,$,v],!0);const P=T.data,O=x*$*v;for(let L=0;Lc||f>p){_=Math.ceil(u/c),b=Math.ceil(f/p);const k=Math.ceil(u/_),g=Math.ceil(f/b);for(let v=0;v<_;++v)for(let y=0;y{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");var i=t("./src/utils/core.js");function a(d,u,f,_,b,k){let g="";for(let M=0;M`+b.repeat(d);g+=` +`}return g+=` +${_}${k}`+b.repeat(d)+`${_}`,g}function l(d,u,f,_){return`${u}${_}`+f.repeat(d)+`${u}`}function c(d,u,f,_,b,k){return d===0&&u===0?l(f,_,b,k):a(f,d,u,_,b,k)}class p extends s.Processor{constructor(){super(...arguments);J(this,"fake_image_token","");J(this,"image_token","");J(this,"global_img_token","")}async _call(f,_=null,b={}){b.return_row_col_info??(b.return_row_col_info=!0);let k;_&&(k=await this.image_processor(_,b)),Array.isArray(f)||(f=[f]);const g=k.rows??[new Array(f.length).fill(0)],M=k.cols??[new Array(f.length).fill(0)],$=this.config.image_seq_len,v=[],y=[];for(let x=0;xc(te,L[H],$,this.fake_image_token,this.image_token,this.global_img_token)),K=P.split(this.image_token);if(K.length===0)throw new Error("The image token should be present in the text.");let R=K[0];for(let te=0;te{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>o.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>n.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>d.DPTFeatureExtractor,DPTImageProcessor:()=>d.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>c.DetrFeatureExtractor,DetrImageProcessor:()=>c.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>u.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>f.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>b.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>g.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>M.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>$.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>v.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>v.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>y.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>y.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>T.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>T.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>x.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>x.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>P.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>P.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>O.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>O.MobileViTImageProcessor,NougatImageProcessor:()=>L.NougatImageProcessor,OwlViTFeatureExtractor:()=>K.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>K.OwlViTImageProcessor,Owlv2ImageProcessor:()=>G.Owlv2ImageProcessor,Phi3VImageProcessor:()=>R.Phi3VImageProcessor,PvtImageProcessor:()=>te.PvtImageProcessor,Qwen2VLImageProcessor:()=>H.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>ee.RTDetrImageProcessor,SamImageProcessor:()=>Z.SamImageProcessor,SegformerFeatureExtractor:()=>ne.SegformerFeatureExtractor,SegformerImageProcessor:()=>ne.SegformerImageProcessor,SiglipImageProcessor:()=>me.SiglipImageProcessor,SmolVLMImageProcessor:()=>ue.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>j.Swin2SRImageProcessor,VLMImageProcessor:()=>k.VLMImageProcessor,ViTFeatureExtractor:()=>F.ViTFeatureExtractor,ViTImageProcessor:()=>F.ViTImageProcessor,VitMatteImageProcessor:()=>U.VitMatteImageProcessor,VitPoseImageProcessor:()=>se.VitPoseImageProcessor,YolosFeatureExtractor:()=>_e.YolosFeatureExtractor,YolosImageProcessor:()=>_e.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),o=t("./src/models/bit/image_processing_bit.js"),n=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),i=t("./src/models/clip/image_processing_clip.js"),a=t("./src/models/convnext/image_processing_convnext.js"),l=t("./src/models/deit/image_processing_deit.js"),c=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/donut/image_processing_donut.js"),d=t("./src/models/dpt/image_processing_dpt.js"),u=t("./src/models/efficientnet/image_processing_efficientnet.js"),f=t("./src/models/glpn/image_processing_glpn.js"),_=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),b=t("./src/models/idefics3/image_processing_idefics3.js"),k=t("./src/models/janus/image_processing_janus.js"),g=t("./src/models/jina_clip/image_processing_jina_clip.js"),M=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),$=t("./src/models/mask2former/image_processing_mask2former.js"),v=t("./src/models/maskformer/image_processing_maskformer.js"),y=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),T=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),x=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),P=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),O=t("./src/models/mobilevit/image_processing_mobilevit.js"),L=t("./src/models/nougat/image_processing_nougat.js"),G=t("./src/models/owlv2/image_processing_owlv2.js"),K=t("./src/models/owlvit/image_processing_owlvit.js"),R=t("./src/models/phi3_v/image_processing_phi3_v.js"),te=t("./src/models/pvt/image_processing_pvt.js"),H=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),ee=t("./src/models/rt_detr/image_processing_rt_detr.js"),Z=t("./src/models/sam/image_processing_sam.js"),ne=t("./src/models/segformer/image_processing_segformer.js"),me=t("./src/models/siglip/image_processing_siglip.js"),ue=t("./src/models/smolvlm/image_processing_smolvlm.js"),j=t("./src/models/swin2sr/image_processing_swin2sr.js"),F=t("./src/models/vit/image_processing_vit.js"),U=t("./src/models/vitmatte/image_processing_vitmatte.js"),se=t("./src/models/vitpose/image_processing_vitpose.js"),_e=t("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLMImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super({do_pad:!0,pad_size:{width:i.image_size,height:i.image_size},...i}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(i,a,l,c){return super.pad_image(i,a,l,{constant_values:this.constant_values,center:!0,...c})}}},"./src/models/janus/processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>c});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class c extends s.Processor{constructor(d,u,f){super(d,u,f),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(d,{images:u=null,chat_template:f="default"}={}){u?Array.isArray(u)||(u=[u]):u=await Promise.all(d.filter(L=>L.images).flatMap(L=>L.images).map(L=>l.RawImage.read(L)));const _=this.tokenizer,b=_.apply_chat_template(d,{tokenize:!1,add_generation_prompt:!0,chat_template:f}),k=L=>_.encode(L,{add_special_tokens:!1}),g=b.split(this.image_tag),M=g.length-1;if(u.length!==M)throw new Error(`Number of images provided (${u.length}) does not match number of "${this.image_tag}" image tags (${M})`);const[$,v,y]=_.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let T=k(g[0]),x=new Array(T.length).fill(!1);for(let L=1;L0){const L=await this.image_processor(u);return L.pixel_values.unsqueeze_(0),{...O,...L}}return O}}J(c,"image_processor_class",o.AutoImageProcessor),J(c,"tokenizer_class",n.AutoTokenizer),J(c,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){const{resize_mode:a,fill_color:l,interpolation:c,size:p,...d}=i,u=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},f=c==="bicubic"?3:2;super({...d,size:u,resample:f,do_center_crop:!0,crop_size:p,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{async _call(l=null,c=null,p={}){if(!l&&!c)throw new Error("Either text or images must be provided");const d=l?this.tokenizer(l,p):{},u=c?await this.image_processor(c,p):{};return{...d,...u}}}J(i,"tokenizer_class",n.AutoTokenizer),J(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/llava/processing_llava.js":(e,r,t)=>{t.r(r),t.d(r,{LlavaProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{async _call(l,c=null,p={}){const d=await this.image_processor(l,p);if(c){const[f,_]=d.pixel_values.dims.slice(-2),{image_token:b,patch_size:k,num_additional_image_tokens:g}=this.config,M=Math.floor(f/k)*Math.floor(_/k)+g;c=structuredClone(c),Array.isArray(c)||(c=[c]);for(let $=0;${t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>o});var s=t("./src/models/maskformer/image_processing_maskformer.js");class o extends s.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>n,MaskFormerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_panoptic_segmentation(...a){return(0,s.post_process_panoptic_segmentation)(...a)}post_process_instance_segmentation(...a){return(0,s.post_process_instance_segmentation)(...a)}}class n extends o{}},"./src/models/mgp_str/processing_mgp_str.js":(e,r,t)=>{t.r(r),t.d(r,{MgpstrProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/utils/maths.js");const a={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class l extends s.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(p,d){if(!a.hasOwnProperty(d))throw new Error(`Format ${d} is not supported.`);const[u,f]=a[d],_=this[u].bind(this),[b,k]=p.dims,g=[],M=[],$=p.tolist();for(let y=0;y0?P.reduce((L,G)=>L*G,1):0;M.push(x),g.push(O)}return[_(M),g]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}batch_decode([p,d,u]){const[f,_]=this._decode_helper(p,"char"),[b,k]=this._decode_helper(d,"bpe"),[g,M]=this._decode_helper(u,"wp"),$=[],v=[];for(let y=0;y{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>n,MobileNetV1ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>n,MobileNetV2ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>n,MobileNetV3ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>n,MobileNetV4ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilevit/image_processing_mobilevit.js":(e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>n,MobileViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/moonshine/feature_extraction_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"MoonshineFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=[1,a.length];return{input_values:new o.Tensor("float32",a,l)}}}},"./src/models/moonshine/processing_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}J(i,"tokenizer_class",o.AutoTokenizer),J(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>o});var s=t("./src/models/donut/image_processing_donut.js");class o extends s.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>o});var s=t("./src/models/owlvit/image_processing_owlvit.js");class o extends s.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>n,OwlViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/models/owlvit/processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{}J(i,"tokenizer_class",n.AutoTokenizer),J(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(e,r,t)=>{t.r(r),t.d(r,{PaliGemmaProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");const i="";function a(c,p,d,u,f){return`${u.repeat(d*f)}${p}${c} +`}class l extends s.Processor{async _call(p,d=null,u={}){d||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),d=""),Array.isArray(p)||(p=[p]),Array.isArray(d)||(d=[d]);const f=this.tokenizer.bos_token,_=this.image_processor.config.image_seq_length;let b;d.some(M=>M.includes(i))?b=d.map(M=>{const $=M.replaceAll(i,i.repeat(_)),v=$.lastIndexOf(i),y=v===-1?0:v+i.length;return $.slice(0,y)+f+$.slice(y)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),b=d.map(M=>a(M,f,_,i,p.length)));const k=this.tokenizer(b,u);return{...await this.image_processor(p,u),...k}}}J(l,"tokenizer_class",n.AutoTokenizer),J(l,"image_processor_class",o.AutoImageProcessor),J(l,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VImageProcessor:()=>p});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");const n=336,i=[2,3],{ceil:a,floor:l,sqrt:c}=Math;class p extends s.ImageProcessor{constructor(u){super({...u,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=u.num_crops}calc_num_image_tokens_from_image_size(u,f){const{num_img_tokens:_}=this.config;return l((l(f/n)*l(u/n)+1)*_+1+(l(f/n)+1)*c(_))}get_resize_output_image_size(u,f){const _=this._num_crops,[b,k]=u.size;let g=b/k,M=1;for(;M*Math.ceil(M/g)<=_;)M+=1;M-=1;const $=Math.floor(M*336),v=Math.floor($/g);return[$,v]}pad_image(u,f,_,b={}){const[k,g]=f,M=n*a(k/n),$=n*a(g/n),v=[1,1,1].map((y,T)=>(y-this.image_mean[T])/this.image_std[T]);return super.pad_image(u,f,{width:$,height:M},{center:!0,constant_values:v,...b})}async _call(u,{num_crops:f=null}={}){if(this._num_crops=f??(f=this.config.num_crops),f<4||c(f)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(u)||(u=[u]);const _=u.length,b=await Promise.all(u.map(x=>this.preprocess(x))),k=b.map(x=>x.original_size),g=b.map(x=>x.reshaped_input_size),M=[];for(const{pixel_values:x}of b){x.unsqueeze_(0);const[P,O]=x.dims.slice(-2),L=await(0,o.interpolate_4d)(x,{size:[n,n],mode:"bicubic"});if(f>0){const G=[],K=c(f),R=l(O/K),te=l(P/K);for(let ee=0;eex.map(P=>n*a(P/n))),y=new o.Tensor("int64",v.flat(),[_,2]),T=v.map(([x,P])=>this.calc_num_image_tokens_from_image_size(P,x));return{pixel_values:$,original_sizes:k,reshaped_input_sizes:g,image_sizes:y,num_img_tokens:T}}}},"./src/models/phi3_v/processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");const i="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{async _call(p,d=null,{padding:u=!0,truncation:f=!0,num_crops:_=null}={}){Array.isArray(p)||(p=[p]);let b,k;if(d){k=await this.image_processor(d,{num_crops:_});const{num_img_tokens:g}=k,M=p.map((v,y)=>v.split(a).join(i.repeat(g[y])));b=this.tokenizer(M,{padding:u,truncation:f});const $=this.tokenizer.model.convert_tokens_to_ids([i])[0];b.input_ids.map_(v=>v==$?-v:v)}else b=this.tokenizer(p);return{...b,...k}}}J(l,"image_processor_class",o.AutoImageProcessor),J(l,"tokenizer_class",n.AutoTokenizer)},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,Gemma3nProcessor:()=>o.Gemma3nProcessor,GroundingDinoProcessor:()=>n.GroundingDinoProcessor,Idefics3Processor:()=>i.Idefics3Processor,JinaCLIPProcessor:()=>l.JinaCLIPProcessor,LlavaProcessor:()=>c.LlavaProcessor,MgpstrProcessor:()=>p.MgpstrProcessor,MoonshineProcessor:()=>d.MoonshineProcessor,OwlViTProcessor:()=>u.OwlViTProcessor,PaliGemmaProcessor:()=>_.PaliGemmaProcessor,Phi3VProcessor:()=>f.Phi3VProcessor,PyAnnoteProcessor:()=>b.PyAnnoteProcessor,Qwen2VLProcessor:()=>k.Qwen2VLProcessor,SamProcessor:()=>g.SamProcessor,SmolVLMProcessor:()=>M.SmolVLMProcessor,SpeechT5Processor:()=>$.SpeechT5Processor,UltravoxProcessor:()=>v.UltravoxProcessor,VLChatProcessor:()=>a.VLChatProcessor,VoxtralProcessor:()=>y.VoxtralProcessor,Wav2Vec2Processor:()=>T.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>x.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>P.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),o=t("./src/models/gemma3n/processing_gemma3n.js"),n=t("./src/models/grounding_dino/processing_grounding_dino.js"),i=t("./src/models/idefics3/processing_idefics3.js"),a=t("./src/models/janus/processing_janus.js"),l=t("./src/models/jina_clip/processing_jina_clip.js"),c=t("./src/models/llava/processing_llava.js"),p=t("./src/models/mgp_str/processing_mgp_str.js"),d=t("./src/models/moonshine/processing_moonshine.js"),u=t("./src/models/owlvit/processing_owlvit.js"),f=t("./src/models/phi3_v/processing_phi3_v.js"),_=t("./src/models/paligemma/processing_paligemma.js"),b=t("./src/models/pyannote/processing_pyannote.js"),k=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),g=t("./src/models/sam/processing_sam.js"),M=t("./src/models/smolvlm/processing_smolvlm.js"),$=t("./src/models/speecht5/processing_speecht5.js"),v=t("./src/models/ultravox/processing_ultravox.js"),y=t("./src/models/voxtral/processing_voxtral.js"),T=t("./src/models/wav2vec2/processing_wav2vec2.js"),x=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),P=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const c=[1,1,l.length];return{input_values:new o.Tensor("float32",l,c)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,c){const p=c/this.samples_to_frames(c)/this.config.sampling_rate,d=[];for(const u of l.tolist()){const f=[];let _=-1;for(let b=0;b({id:b,start:k*p,end:g*p,confidence:M/(g-k)})))}return d}}},"./src/models/pyannote/processing_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteProcessor:()=>n});var s=t("./src/base/processing_utils.js"),o=t("./src/models/pyannote/feature_extraction_pyannote.js");class n extends s.Processor{async _call(a){return await this.feature_extractor(a)}post_process_speaker_diarization(...a){return this.feature_extractor.post_process_speaker_diarization(...a)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}J(n,"feature_extractor_class",o.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,...l){const{pixel_values:c,original_sizes:p,reshaped_input_sizes:d}=await super._call(a,...l);let u=c;const{temporal_patch_size:f,merge_size:_,patch_size:b}=this.config;u.dims[0]===1&&(u=(0,o.cat)(Array.from({length:f},()=>u),0));const k=u.dims[0]/f,g=u.dims[1],M=Math.floor(u.dims[2]/b),$=Math.floor(u.dims[3]/b),v=u.view(k,f,g,Math.floor(M/_),_,b,Math.floor($/_),_,b).permute(0,3,6,4,7,2,1,5,8).view(k*M*$,g*f*b*b),y=new o.Tensor("int64",[k,M,$],[1,3]);return{pixel_values:v,image_grid_thw:y,original_sizes:p,reshaped_input_sizes:d}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");class i extends s.Processor{async _call(l,c=null,...p){Array.isArray(l)||(l=[l]);let d,u;if(c&&(d=await this.image_processor(c),u=d.image_grid_thw),u){let _=this.image_processor.config.merge_size**2,b=0;const k=u.tolist();l=l.map(g=>{for(;g.includes("<|image_pad|>");){const M=Number(k[b++].reduce(($,v)=>$*v,1n));g=g.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(M/_)))}return g.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...d}}}J(i,"image_processor_class",o.AutoImageProcessor),J(i,"tokenizer_class",n.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...i){return(0,s.post_process_object_detection)(...i)}}},"./src/models/sam/image_processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/core.js"),n=t("./src/utils/tensor.js");class i extends s.ImageProcessor{reshape_input_points(l,c,p,d=!1){l=structuredClone(l);let u=(0,o.calculateDimensions)(l);if(u.length===3)d||(u=[1,...u]),l=[l];else if(u.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let f=0;fd!==c.dims[u]))throw Error(`The first ${p.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new n.Tensor("int64",l.flat(1/0).map(BigInt),p)}async _call(l,{input_points:c=null,input_labels:p=null,input_boxes:d=null}={}){const u=await super._call(l);if(c&&(u.input_points=this.reshape_input_points(c,u.original_sizes,u.reshaped_input_sizes)),p){if(!u.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");u.input_labels=this.add_input_labels(p,u.input_points)}return d&&(u.input_boxes=this.reshape_input_points(d,u.original_sizes,u.reshaped_input_sizes,!0)),u}async post_process_masks(l,c,p,{mask_threshold:d=0,binarize:u=!0,pad_size:f=null}={}){const _=[];f=f??this.pad_size;const b=[f.height,f.width];for(let k=0;kd&&(y[T]=1);$=new n.Tensor("bool",y,$.dims)}_.push($)}return _}generate_crop_boxes(l,c,{crop_n_layers:p=0,overlap_ratio:d=512/1500,points_per_crop:u=32,crop_n_points_downscale_factor:f=1}={}){}}},"./src/models/sam/processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamProcessor:()=>n});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js");class n extends s.Processor{async _call(...a){return await this.image_processor(...a)}post_process_masks(...a){return this.image_processor.post_process_masks(...a)}reshape_input_points(...a){return this.image_processor.reshape_input_points(...a)}}J(n,"image_processor_class",o.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const c=this.config.sampling_rate,p=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(c/2),c,null,"kaldi",!0);this.mel_filters=p,this.window=(0,n.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(l,c){return l=l.map(p=>p*32768),(0,n.spectrogram)(l,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:c,transpose:!0})}async _call(l,{padding:c=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:d=!0,return_attention_mask:u=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let f=await this._extract_fbank_features(l,this.config.max_length);if(d){const[y,T]=f.dims,x=f.data;for(let P=0;P0){const O=new Float32Array(T*(y+P));O.set(x),O.fill(this.config.padding_value,x.length);const L=y+P;f=new o.Tensor(f.type,O,[L,T]),u&&(_=new o.Tensor("int64",new BigInt64Array(L),[1,L]),_.data.fill(1n,0,y))}}const[b,k]=f.dims,g=this.config.stride;if(b%g!==0)throw new Error(`The number of frames (${b}) must be a multiple of the stride (${g}).`);const $=f.view(1,Math.floor(b/g),k*g),v={input_features:$};if(u){const y=$.dims[1],T=new BigInt64Array(y);if(_){const x=_.data;for(let P=1,O=0;P{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>n,SegformerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class n extends o{}},"./src/models/siglip/image_processing_siglip.js":(e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/smolvlm/image_processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMImageProcessor:()=>s.Idefics3ImageProcessor});var s=t("./src/models/idefics3/image_processing_idefics3.js")},"./src/models/smolvlm/processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMProcessor:()=>s.Idefics3Processor});var s=t("./src/models/idefics3/processing_idefics3.js")},"./src/models/snac/feature_extraction_snac.js":(e,r,t)=>{t.r(r),t.d(r,{SnacFeatureExtractor:()=>o});var s=t("./src/models/dac/feature_extraction_dac.js");class o extends s.DacFeatureExtractor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");class o extends s.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js");class i extends s.Processor{async _call(l){return await this.feature_extractor(l)}}J(i,"tokenizer_class",o.AutoTokenizer),J(i,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(i,a,l,c={}){const[p,d,u]=a;return super.pad_image(i,a,{width:d+(l-d%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...c})}}},"./src/models/ultravox/processing_ultravox.js":(e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l,c=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let d={};if(c){const f=c.length,{input_features:_}=await this.feature_extractor(c,{...p,max_length:f}),b=Math.round(f/this.config.encoder_ds_factor+1e-4),k=1+Math.ceil(b/this.config.stack_factor);d.audio_token_len=[k],d.audio_values=_;const g=this.config.audio_placeholder;if(!l.includes(g))throw new Error(`The input text does not contain the image token ${g}.`);l=l.replaceAll(g,g.repeat(k))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...d}}}J(i,"tokenizer_class",o.AutoTokenizer),J(i,"feature_extractor_class",s.AutoFeatureExtractor),J(i,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>n,ViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/vitmatte/image_processing_vitmatte.js":(e,r,t)=>{t.r(r),t.d(r,{VitMatteImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,l){Array.isArray(a)||(a=[a]),Array.isArray(l)||(l=[l]);const c=await Promise.all(a.map(u=>this.preprocess(u))),p=await Promise.all(l.map(u=>this.preprocess(u,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,o.stack)(c.map((u,f)=>(0,o.cat)([u.pixel_values,p[f].pixel_values],0)),0),original_sizes:c.map(u=>u.original_size),reshaped_input_sizes:c.map(u=>u.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_pose_estimation(i,a,{threshold:l=null}={}){const c=i.tolist(),[p,d,u,f]=i.dims,_=[];for(let b=0;b{t.r(r),t.d(r,{VoxtralProcessor:()=>d});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js"),i=t("./src/utils/tensor.js");const a="[AUDIO]",l="[BEGIN_AUDIO]",c=375;function p(u,f){const _=[];for(let b=0;bp(L,v)),T=y.map(L=>L.length),x=y.flat(),P=(await Promise.all(x.map(L=>this.feature_extractor(L,b)))).map(L=>L.input_features);k.audio_values=P.length>1?(0,i.cat)(P,0):P[0];let O=M[0];for(let L=0;L{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const c=a.reduce((d,u)=>d+u,0)/a.length,p=a.reduce((d,u)=>d+(u-c)**2,0)/a.length;return a.map(d=>(d-c)/Math.sqrt(p+1e-7))}async _call(a){(0,s.validate_audio_inputs)(a,"Wav2Vec2FeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));let l=a;this.config.do_normalize&&(l=this._zero_mean_unit_var_norm(l));const c=[1,l.length];return{input_values:new o.Tensor("float32",l,c),attention_mask:new o.Tensor("int64",new BigInt64Array(l.length).fill(1n),c)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}J(i,"tokenizer_class",s.AutoTokenizer),J(i,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}J(i,"tokenizer_class",s.AutoTokenizer),J(i,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(e,r,t)=>{t.r(r),t.d(r,{WeSpeakerFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,c=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=c,this.window=(0,o.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(a){return a=a.map(l=>l*32768),(0,o.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(a){(0,s.validate_audio_inputs)(a,"WeSpeakerFeatureExtractor");const l=(await this._extract_fbank_features(a)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const c=l.mean(1).data,p=l.data,[d,u,f]=l.dims;for(let _=0;_{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>o,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>n,whisper_language_to_code:()=>i});const s=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],o=new Map(s),n=new Map([...s.map(([a,l])=>[l,a]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function i(a){a=a.toLowerCase();let l=n.get(a);if(l===void 0){const c=a.match(/^<\|([a-z]{2})\|>$/);if(c&&(a=c[1]),o.has(a))l=a;else{const d=a.length===2?o.keys():o.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(d))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{constructor(l){var c;super(l),(c=this.config).mel_filters??(c.mel_filters=(0,o.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,o.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const c=await(0,o.spectrogram)(l,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(l.length/this.config.hop_length),this.config.nb_max_frames)}),p=c.data,d=(0,n.max)(p)[0];for(let u=0;ud?(l.length>this.config.n_samples&&console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),p=l.slice(0,d)):(p=new Float32Array(d),p.set(l)),{input_features:(await this._extract_fbank_features(p)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperGenerationConfig:()=>o});var s=t("./src/generation/configuration_utils.js");class o extends s.GenerationConfig{constructor(){super(...arguments);J(this,"return_timestamps",null);J(this,"return_token_timestamps",null);J(this,"num_frames",null);J(this,"alignment_heads",null);J(this,"task",null);J(this,"language",null);J(this,"no_timestamps_token_id",null);J(this,"prompt_ids",null);J(this,"is_multilingual",null);J(this,"lang_to_id",null);J(this,"task_to_id",null);J(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}J(i,"tokenizer_class",o.AutoTokenizer),J(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>n,YolosImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),o=t("./src/utils/tensor.js"),n=t("./src/env.js");const i=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV,a=async(c,p,d)=>{const u=await(0,s.createInferenceSession)(new Uint8Array(c),p);let f=Promise.resolve();return async _=>{const b=(0,s.isONNXProxy)(),k=Object.fromEntries(Object.entries(_).map(([M,$])=>[M,(b?$.clone():$).ort_tensor])),g=await(f=i?f.then(()=>u.run(k)):u.run(k));return Array.isArray(d)?d.map(M=>new o.Tensor(g[M])):new o.Tensor(g[d])}};class l{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=a([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=a([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=a([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=a([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=a([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=a([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=a([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=a([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}J(l,"session_options",{})},"./src/pipelines.js":(e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>K,AutomaticSpeechRecognitionPipeline:()=>te,BackgroundRemovalPipeline:()=>ne,DepthEstimationPipeline:()=>_e,DocumentQuestionAnsweringPipeline:()=>F,FeatureExtractionPipeline:()=>L,FillMaskPipeline:()=>$,ImageClassificationPipeline:()=>ee,ImageFeatureExtractionPipeline:()=>G,ImageSegmentationPipeline:()=>Z,ImageToImagePipeline:()=>se,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>ue,Pipeline:()=>b,QuestionAnsweringPipeline:()=>M,SummarizationPipeline:()=>y,Text2TextGenerationPipeline:()=>v,TextClassificationPipeline:()=>k,TextGenerationPipeline:()=>P,TextToAudioPipeline:()=>U,TokenClassificationPipeline:()=>g,TranslationPipeline:()=>T,ZeroShotAudioClassificationPipeline:()=>R,ZeroShotClassificationPipeline:()=>O,ZeroShotImageClassificationPipeline:()=>me,ZeroShotObjectDetectionPipeline:()=>j,pipeline:()=>ze});var s=t("./src/tokenizers.js"),o=t("./src/models.js"),n=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),c=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),d=t("./src/utils/image.js");async function u(Ie){return Array.isArray(Ie)||(Ie=[Ie]),await Promise.all(Ie.map(X=>d.RawImage.read(X)))}async function f(Ie,X){return Array.isArray(Ie)||(Ie=[Ie]),await Promise.all(Ie.map(ae=>typeof ae=="string"||ae instanceof URL?(0,c.read_audio)(ae,X):ae instanceof Float64Array?new Float32Array(ae):ae))}function _(Ie,X){X&&(Ie=Ie.map(Ee=>Ee|0));const[ae,W,be,ke]=Ie;return{xmin:ae,ymin:W,xmax:be,ymax:ke}}class b extends i.Callable{constructor({task:X,model:ae,tokenizer:W=null,processor:be=null}){super(),this.task=X,this.model=ae,this.tokenizer=W,this.processor=be}async dispose(){await this.model.dispose()}}class k extends b{constructor(X){super(X)}async _call(X,{top_k:ae=1}={}){const W=this.tokenizer(X,{padding:!0,truncation:!0}),be=await this.model(W),ke=this.model.config.problem_type==="multi_label_classification"?Se=>Se.sigmoid():Se=>new p.Tensor("float32",(0,l.softmax)(Se.data),Se.dims),Ee=this.model.config.id2label,Me=[];for(const Se of be.logits){const we=ke(Se),Ae=await(0,p.topk)(we,ae),Be=Ae[0].tolist(),xe=Ae[1].tolist().map((Ze,Ke)=>({label:Ee?Ee[Ze]:`LABEL_${Ze}`,score:Be[Ke]}));ae===1?Me.push(...xe):Me.push(xe)}return Array.isArray(X)||ae===1?Me:Me[0]}}class g extends b{constructor(X){super(X)}async _call(X,{ignore_labels:ae=["O"]}={}){const W=Array.isArray(X),be=this.tokenizer(W?X:[X],{padding:!0,truncation:!0}),Ee=(await this.model(be)).logits,Me=this.model.config.id2label,Se=[];for(let we=0;weYe==this.tokenizer.sep_token_id);Se[Be].map((Ye,ot)=>Ye==1&&(ot===0||ot>xe&&we.findIndex(It=>It==Qe[ot])===-1));const Ze=ke[Be].tolist(),Ke=Ee[Be].tolist();for(let Ye=1;Yeot==Qe[Ye])!==-1)&&(Ze[Ye]=-1/0,Ke[Ye]=-1/0);const nt=(0,l.softmax)(Ze).map((Ye,ot)=>[Ye,ot]),Je=(0,l.softmax)(Ke).map((Ye,ot)=>[Ye,ot]);nt[0][0]=0,Je[0][0]=0;const Oe=(0,a.product)(nt,Je).filter(Ye=>Ye[0][1]<=Ye[1][1]).map(Ye=>[Ye[0][1],Ye[1][1],Ye[0][0]*Ye[1][0]]).sort((Ye,ot)=>ot[2]-Ye[2]);for(let Ye=0;YeZe==this.tokenizer.mask_token_id);if(we===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ae=be[Me][we],Be=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ae.data),Ae.dims),ae),Qe=Be[0].tolist(),xe=Be[1].tolist();ke.push(xe.map((Ze,Ke)=>{const nt=Se.slice();return nt[we]=Ze,{score:Qe[Ke],token:Number(Ze),token_str:this.tokenizer.decode([Ze]),sequence:this.tokenizer.decode(nt,{skip_special_tokens:!0})}}))}return Array.isArray(X)?ke:ke[0]}}class v extends b{constructor(ae){super(ae);J(this,"_key","generated_text")}async _call(ae,W={}){Array.isArray(ae)||(ae=[ae]),this.model.config.prefix&&(ae=ae.map(we=>this.model.config.prefix+we));const be=this.model.config.task_specific_params;be&&be[this.task]&&be[this.task].prefix&&(ae=ae.map(we=>be[this.task].prefix+we));const ke=this.tokenizer,Ee={padding:!0,truncation:!0};let Me;this instanceof T&&"_build_translation_inputs"in ke?Me=ke._build_translation_inputs(ae,Ee,W):Me=ke(ae,Ee);const Se=await this.model.generate({...Me,...W});return ke.batch_decode(Se,{skip_special_tokens:!0}).map(we=>({[this._key]:we}))}}class y extends v{constructor(ae){super(ae);J(this,"_key","summary_text")}}class T extends v{constructor(ae){super(ae);J(this,"_key","translation_text")}}function x(Ie){return Array.isArray(Ie)&&Ie.every(X=>"role"in X&&"content"in X)}class P extends b{constructor(X){super(X)}async _call(X,ae={}){let W=!1,be=!1,ke=ae.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,Ee;if(typeof X=="string")Ee=X=[X];else if(Array.isArray(X)&&X.every(xe=>typeof xe=="string"))W=!0,Ee=X;else{if(x(X))X=[X];else if(Array.isArray(X)&&X.every(x))W=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");be=!0,Ee=X.map(xe=>this.tokenizer.apply_chat_template(xe,{tokenize:!1,add_generation_prompt:!0})),ke=!1}const Me=be?!1:ae.return_full_text??!0;this.tokenizer.padding_side="left";const Se=this.tokenizer(Ee,{add_special_tokens:ke,padding:!0,truncation:!0}),we=await this.model.generate({...Se,...ae}),Ae=this.tokenizer.batch_decode(we,{skip_special_tokens:!0});let Be;!Me&&Se.input_ids.dims.at(-1)>0&&(Be=this.tokenizer.batch_decode(Se.input_ids,{skip_special_tokens:!0}).map(xe=>xe.length));const Qe=Array.from({length:X.length},xe=>[]);for(let xe=0;xe[ae.toLowerCase(),W])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(X,ae,{hypothesis_template:W="This example is {}.",multi_label:be=!1}={}){const ke=Array.isArray(X);ke||(X=[X]),Array.isArray(ae)||(ae=[ae]);const Ee=ae.map(we=>W.replace("{}",we)),Me=be||ae.length===1,Se=[];for(const we of X){const Ae=[];for(const xe of Ee){const Ze=this.tokenizer(we,{text_pair:xe,padding:!0,truncation:!0}),Ke=await this.model(Ze);Me?Ae.push([Ke.logits.data[this.contradiction_id],Ke.logits.data[this.entailment_id]]):Ae.push(Ke.logits.data[this.entailment_id])}const Qe=(Me?Ae.map(xe=>(0,l.softmax)(xe)[1]):(0,l.softmax)(Ae)).map((xe,Ze)=>[xe,Ze]).sort((xe,Ze)=>Ze[0]-xe[0]);Se.push({sequence:we,labels:Qe.map(xe=>ae[xe[1]]),scores:Qe.map(xe=>xe[0])})}return ke?Se:Se[0]}}class L extends b{constructor(X){super(X)}async _call(X,{pooling:ae="none",normalize:W=!1,quantize:be=!1,precision:ke="binary"}={}){const Ee=this.tokenizer(X,{padding:!0,truncation:!0}),Me=await this.model(Ee);let Se=Me.last_hidden_state??Me.logits??Me.token_embeddings;switch(ae){case"none":break;case"mean":Se=(0,p.mean_pooling)(Se,Ee.attention_mask);break;case"first_token":case"cls":Se=Se.slice(null,0);break;case"last_token":case"eos":Se=Se.slice(null,-1);break;default:throw Error(`Pooling method '${ae}' not supported.`)}return W&&(Se=Se.normalize(2,-1)),be&&(Se=(0,p.quantize_embeddings)(Se,ke)),Se}}class G extends b{constructor(X){super(X)}async _call(X,{pool:ae=null}={}){const W=await u(X),{pixel_values:be}=await this.processor(W),ke=await this.model({pixel_values:be});let Ee;if(ae){if(!("pooler_output"in ke))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ee=ke.pooler_output}else Ee=ke.last_hidden_state??ke.logits??ke.image_embeds;return Ee}}class K extends b{constructor(X){super(X)}async _call(X,{top_k:ae=5}={}){const W=this.processor.feature_extractor.config.sampling_rate,be=await f(X,W),ke=this.model.config.id2label,Ee=[];for(const Me of be){const Se=await this.processor(Me),Ae=(await this.model(Se)).logits[0],Be=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ae.data),Ae.dims),ae),Qe=Be[0].tolist(),Ze=Be[1].tolist().map((Ke,nt)=>({label:ke?ke[Ke]:`LABEL_${Ke}`,score:Qe[nt]}));Ee.push(Ze)}return Array.isArray(X)?Ee:Ee[0]}}class R extends b{constructor(X){super(X)}async _call(X,ae,{hypothesis_template:W="This is a sound of {}."}={}){const be=!Array.isArray(X);be&&(X=[X]);const ke=ae.map(Ae=>W.replace("{}",Ae)),Ee=this.tokenizer(ke,{padding:!0,truncation:!0}),Me=this.processor.feature_extractor.config.sampling_rate,Se=await f(X,Me),we=[];for(const Ae of Se){const Be=await this.processor(Ae),Qe=await this.model({...Ee,...Be}),xe=(0,l.softmax)(Qe.logits_per_audio.data);we.push([...xe].map((Ze,Ke)=>({score:Ze,label:ae[Ke]})))}return be?we[0]:we}}class te extends b{constructor(X){super(X)}async _call(X,ae={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(X,ae);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(X,ae);case"moonshine":return this._call_moonshine(X,ae);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(X,ae){ae.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),ae.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const W=!Array.isArray(X);W&&(X=[X]);const be=this.processor.feature_extractor.config.sampling_rate,ke=await f(X,be),Ee=[];for(const Me of ke){const Se=await this.processor(Me),Ae=(await this.model(Se)).logits[0],Be=[];for(const xe of Ae)Be.push((0,l.max)(xe.data)[1]);const Qe=this.tokenizer.decode(Be);Ee.push({text:Qe})}return W?Ee[0]:Ee}async _call_whisper(X,ae){const W=ae.return_timestamps??!1,be=ae.chunk_length_s??0,ke=ae.force_full_sequences??!1;let Ee=ae.stride_length_s??null;const Me={...ae};W==="word"&&(Me.return_token_timestamps=!0,Me.return_timestamps=!1);const Se=!Array.isArray(X);Se&&(X=[X]);const we=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ae=this.processor.feature_extractor.config.hop_length,Be=this.processor.feature_extractor.config.sampling_rate,Qe=await f(X,Be),xe=[];for(const Ze of Qe){let Ke=[];if(be>0){if(Ee===null)Ee=be/6;else if(be<=Ee)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Oe=Be*be,Ye=Be*Ee,ot=Oe-2*Ye;let It=0;for(;;){const St=It+Oe,wt=Ze.subarray(It,St),Mr=await this.processor(wt),Pr=It===0,jr=St>=Ze.length;if(Ke.push({stride:[wt.length,Pr?0:Ye,jr?0:Ye],input_features:Mr.input_features,is_last:jr}),jr)break;It+=ot}}else Ke=[{stride:[Ze.length,0,0],input_features:(await this.processor(Ze)).input_features,is_last:!0}];for(const Oe of Ke){Me.num_frames=Math.floor(Oe.stride[0]/Ae);const Ye=await this.model.generate({inputs:Oe.input_features,...Me});W==="word"?(Oe.tokens=Ye.sequences.tolist()[0],Oe.token_timestamps=Ye.token_timestamps.tolist()[0].map(ot=>(0,l.round)(ot,2))):Oe.tokens=Ye[0].tolist(),Oe.stride=Oe.stride.map(ot=>ot/Be)}const[nt,Je]=this.tokenizer._decode_asr(Ke,{time_precision:we,return_timestamps:W,force_full_sequences:ke});xe.push({text:nt,...Je})}return Se?xe[0]:xe}async _call_moonshine(X,ae){const W=!Array.isArray(X);W&&(X=[X]);const be=this.processor.feature_extractor.config.sampling_rate,ke=await f(X,be),Ee=[];for(const Me of ke){const Se=await this.processor(Me),we=Math.floor(Me.length/be)*6,Ae=await this.model.generate({max_new_tokens:we,...ae,...Se}),Be=this.processor.batch_decode(Ae,{skip_special_tokens:!0})[0];Ee.push({text:Be})}return W?Ee[0]:Ee}}class H extends b{constructor(X){super(X)}async _call(X,ae={}){const W=Array.isArray(X),be=await u(X),{pixel_values:ke}=await this.processor(be),Ee=[];for(const Me of ke){Me.dims=[1,...Me.dims];const Se=await this.model.generate({inputs:Me,...ae}),we=this.tokenizer.batch_decode(Se,{skip_special_tokens:!0}).map(Ae=>({generated_text:Ae.trim()}));Ee.push(we)}return W?Ee:Ee[0]}}class ee extends b{constructor(X){super(X)}async _call(X,{top_k:ae=5}={}){const W=await u(X),{pixel_values:be}=await this.processor(W),ke=await this.model({pixel_values:be}),Ee=this.model.config.id2label,Me=[];for(const Se of ke.logits){const we=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Se.data),Se.dims),ae),Ae=we[0].tolist(),Qe=we[1].tolist().map((xe,Ze)=>({label:Ee?Ee[xe]:`LABEL_${xe}`,score:Ae[Ze]}));Me.push(Qe)}return Array.isArray(X)?Me:Me[0]}}class Z extends b{constructor(X){super(X),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(X,{threshold:ae=.5,mask_threshold:W=.5,overlap_mask_area_threshold:be=.8,label_ids_to_fuse:ke=null,target_sizes:Ee=null,subtask:Me=null}={}){if(Array.isArray(X)&&X.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const we=await u(X),Ae=we.map(Oe=>[Oe.height,Oe.width]),Be=await this.processor(we),{inputNames:Qe,outputNames:xe}=this.model.sessions.model;if(!Qe.includes("pixel_values")){if(Qe.length!==1)throw Error(`Expected a single input name, but got ${Qe.length} inputs: ${Qe}.`);const Oe=Qe[0];if(Oe in Be)throw Error(`Input name ${Oe} already exists in the inputs.`);Be[Oe]=Be.pixel_values}const Ze=await this.model(Be);let Ke=null;if(Me!==null)Ke=this.subtasks_mapping[Me];else if(this.processor.image_processor){for(const[Oe,Ye]of Object.entries(this.subtasks_mapping))if(Ye in this.processor.image_processor){Ke=this.processor.image_processor[Ye].bind(this.processor.image_processor),Me=Oe;break}}const nt=this.model.config.id2label,Je=[];if(Me)if(Me==="panoptic"||Me==="instance"){const Oe=Ke(Ze,ae,W,be,ke,Ee??Ae)[0],Ye=Oe.segmentation;for(const ot of Oe.segments_info){const It=new Uint8ClampedArray(Ye.data.length);for(let wt=0;wtMr<-1e-5||Mr>1+1e-5)&&St.sigmoid_();const wt=await d.RawImage.fromTensor(St.mul_(255).to("uint8")).resize(It[1],It[0]);Je.push({label:null,score:null,mask:wt})}}return Je}}class ne extends Z{constructor(X){super(X)}async _call(X,ae={}){if(Array.isArray(X)&&X.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const be=await u(X),ke=await super._call(X,ae);return be.map((Me,Se)=>{const we=Me.clone();return we.putAlpha(ke[Se].mask),we})}}class me extends b{constructor(X){super(X)}async _call(X,ae,{hypothesis_template:W="This is a photo of {}"}={}){const be=Array.isArray(X),ke=await u(X),Ee=ae.map(Qe=>W.replace("{}",Qe)),Me=this.tokenizer(Ee,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:Se}=await this.processor(ke),we=await this.model({...Me,pixel_values:Se}),Ae=this.model.config.model_type==="siglip"?Qe=>Qe.sigmoid().data:Qe=>(0,l.softmax)(Qe.data),Be=[];for(const Qe of we.logits_per_image){const Ze=[...Ae(Qe)].map((Ke,nt)=>({score:Ke,label:ae[nt]}));Ze.sort((Ke,nt)=>nt.score-Ke.score),Be.push(Ze)}return be?Be:Be[0]}}class ue extends b{constructor(X){super(X)}async _call(X,{threshold:ae=.9,percentage:W=!1}={}){const be=Array.isArray(X);if(be&&X.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const ke=await u(X),Ee=W?null:ke.map(xe=>[xe.height,xe.width]),{pixel_values:Me,pixel_mask:Se}=await this.processor(ke),we=await this.model({pixel_values:Me,pixel_mask:Se}),Ae=this.processor.image_processor.post_process_object_detection(we,ae,Ee),Be=this.model.config.id2label,Qe=Ae.map(xe=>xe.boxes.map((Ze,Ke)=>({score:xe.scores[Ke],label:Be[xe.classes[Ke]],box:_(Ze,!W)})));return be?Qe:Qe[0]}}class j extends b{constructor(X){super(X)}async _call(X,ae,{threshold:W=.1,top_k:be=null,percentage:ke=!1}={}){const Ee=Array.isArray(X),Me=await u(X),Se=this.tokenizer(ae,{padding:!0,truncation:!0}),we=await this.processor(Me),Ae=[];for(let Be=0;Be({score:Je.scores[Ye],label:Je.labels[Ye],box:_(Oe,!ke)}))}else{const Je=this.processor.image_processor.post_process_object_detection(Ke,W,xe,!0)[0];nt=Je.boxes.map((Oe,Ye)=>({score:Je.scores[Ye],label:ae[Je.classes[Ye]],box:_(Oe,!ke)}))}nt.sort((Je,Oe)=>Oe.score-Je.score),be!==null&&(nt=nt.slice(0,be)),Ae.push(nt)}return Ee?Ae:Ae[0]}}class F extends b{constructor(X){super(X)}async _call(X,ae,W={}){const be=(await u(X))[0],{pixel_values:ke}=await this.processor(be),Ee=`${ae}`,Me=this.tokenizer(Ee,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,Se=await this.model.generate({inputs:ke,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Me,...W}),Ae=this.tokenizer.batch_decode(Se)[0].match(/(.*?)<\/s_answer>/);let Be=null;return Ae&&Ae.length>=2&&(Be=Ae[1].trim()),[{answer:Be}]}}class U extends b{constructor(ae){super(ae);J(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=ae.vocoder??null}async _call(ae,{speaker_embeddings:W=null}={}){return this.processor?this._call_text_to_spectrogram(ae,{speaker_embeddings:W}):this._call_text_to_waveform(ae)}async _call_text_to_waveform(ae){const W=this.tokenizer(ae,{padding:!0,truncation:!0}),{waveform:be}=await this.model(W),ke=this.model.config.sampling_rate;return new c.RawAudio(be.data,ke)}async _call_text_to_spectrogram(ae,{speaker_embeddings:W}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await o.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof W=="string"||W instanceof URL)&&(W=new Float32Array(await(await fetch(W)).arrayBuffer())),W instanceof Float32Array)W=new p.Tensor("float32",W,[1,W.length]);else if(!(W instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:be}=this.tokenizer(ae,{padding:!0,truncation:!0}),{waveform:ke}=await this.model.generate_speech(be,W,{vocoder:this.vocoder}),Ee=this.processor.feature_extractor.config.sampling_rate;return new c.RawAudio(ke.data,Ee)}}class se extends b{constructor(X){super(X)}async _call(X){const ae=await u(X),W=await this.processor(ae),be=await this.model(W),ke=[];for(const Ee of be.reconstruction){const Me=Ee.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");ke.push(d.RawImage.fromTensor(Me))}return ke.length>1?ke:ke[0]}}class _e extends b{constructor(X){super(X)}async _call(X){const ae=await u(X),W=await this.processor(ae),{predicted_depth:be}=await this.model(W),ke=[];for(let Ee=0;Ee1?ke:ke[0]}}const ie=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:k,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:g,model:o.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:M,model:o.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:$,model:o.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:y,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:T,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:v,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:P,model:o.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:O,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:K,model:o.AutoModelForAudioClassification,processor:n.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:R,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:te,model:[o.AutoModelForSpeechSeq2Seq,o.AutoModelForCTC],processor:n.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:U,model:[o.AutoModelForTextToWaveform,o.AutoModelForTextToSpectrogram],processor:[n.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:H,model:o.AutoModelForVision2Seq,processor:n.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:ee,model:o.AutoModelForImageClassification,processor:n.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Z,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:ne,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:me,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ue,model:o.AutoModelForObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:j,model:o.AutoModelForZeroShotObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:F,model:o.AutoModelForDocumentQuestionAnswering,processor:n.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:se,model:o.AutoModelForImageToImage,processor:n.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:_e,model:o.AutoModelForDepthEstimation,processor:n.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:L,model:o.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:n.AutoProcessor,pipeline:G,model:[o.AutoModelForImageFeatureExtraction,o.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),ve=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ze(Ie,X=null,{progress_callback:ae=null,config:W=null,cache_dir:be=null,local_files_only:ke=!1,revision:Ee="main",device:Me=null,dtype:Se=null,subfolder:we="onnx",use_external_data_format:Ae=null,model_file_name:Be=null,session_options:Qe={}}={}){Ie=ve[Ie]??Ie;const xe=ie[Ie.split("_",1)[0]];if(!xe)throw Error(`Unsupported pipeline: ${Ie}. Must be one of [${Object.keys(ie)}]`);X||(X=xe.default.model,console.log(`No model specified. Using default model: "${X}".`));const Ze={progress_callback:ae,config:W,cache_dir:be,local_files_only:ke,revision:Ee,device:Me,dtype:Se,subfolder:we,use_external_data_format:Ae,model_file_name:Be,session_options:Qe},Ke=new Map([["tokenizer",xe.tokenizer],["model",xe.model],["processor",xe.processor]]),nt=await Ge(Ke,X,Ze);nt.task=Ie,(0,a.dispatchCallback)(ae,{status:"ready",task:Ie,model:X});const Je=xe.pipeline;return new Je(nt)}async function Ge(Ie,X,ae){const W=Object.create(null),be=[];for(const[ke,Ee]of Ie.entries()){if(!Ee)continue;let Me;Array.isArray(Ee)?Me=new Promise(async(Se,we)=>{var Be,Qe;let Ae;for(const xe of Ee){if(xe===null){Se(null);return}try{Se(await xe.from_pretrained(X,ae));return}catch(Ze){if((Be=Ze.message)!=null&&Be.includes("Unsupported model type"))Ae=Ze;else if((Qe=Ze.message)!=null&&Qe.includes("Could not locate file"))Ae=Ze;else{we(Ze);return}}}we(Ae)}):Me=Ee.from_pretrained(X,ae),W[ke]=Me,be.push(Me)}await Promise.all(be);for(const[ke,Ee]of Object.entries(W))W[ke]=await Ee;return W}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Fs,AutoTokenizer:()=>xn,BartTokenizer:()=>st,BertTokenizer:()=>As,BlenderbotSmallTokenizer:()=>Xt,BlenderbotTokenizer:()=>et,BloomTokenizer:()=>Xr,CLIPTokenizer:()=>Ns,CamembertTokenizer:()=>Fe,CodeGenTokenizer:()=>Jr,CodeLlamaTokenizer:()=>$r,CohereTokenizer:()=>Ps,ConvBertTokenizer:()=>q,DebertaTokenizer:()=>S,DebertaV2Tokenizer:()=>Q,DistilBertTokenizer:()=>ge,ElectraTokenizer:()=>ft,Ernie4_5_Tokenizer:()=>vn,EsmTokenizer:()=>Ds,FalconTokenizer:()=>kr,GPT2Tokenizer:()=>vt,GPTNeoXTokenizer:()=>Os,GemmaTokenizer:()=>Wr,Grok1Tokenizer:()=>ts,HerbertTokenizer:()=>B,LlamaTokenizer:()=>Sr,M2M100Tokenizer:()=>pr,MBart50Tokenizer:()=>Ut,MBartTokenizer:()=>zt,MPNetTokenizer:()=>ds,MarianTokenizer:()=>Re,MgpstrTokenizer:()=>yn,MobileBertTokenizer:()=>Ct,NllbTokenizer:()=>Ts,NougatTokenizer:()=>Es,PreTrainedTokenizer:()=>pt,Qwen2Tokenizer:()=>Ur,RoFormerTokenizer:()=>re,RobertaTokenizer:()=>Nr,SiglipTokenizer:()=>Gr,SpeechT5Tokenizer:()=>Vs,SqueezeBertTokenizer:()=>Qt,T5Tokenizer:()=>ht,TokenizerModel:()=>G,VitsTokenizer:()=>Us,Wav2Vec2CTCTokenizer:()=>je,WhisperTokenizer:()=>mr,XLMRobertaTokenizer:()=>Vr,XLMTokenizer:()=>rt,is_chinese_char:()=>$});var s=t("./src/utils/generic.js"),o=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),c=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function d(pe,I){const N=await Promise.all([(0,n.getModelJSON)(pe,"tokenizer.json",!0,I),(0,n.getModelJSON)(pe,"tokenizer_config.json",!0,I)]);return I.legacy!==null&&(N[1].legacy=I.legacy),N}function u(pe,I){const N=[];let Y=0;for(const le of pe.matchAll(I)){const de=le[0];Y0&&N.push(de),Y=le.index+de.length}return Y=19968&&pe<=40959||pe>=13312&&pe<=19903||pe>=131072&&pe<=173791||pe>=173824&&pe<=177983||pe>=177984&&pe<=178207||pe>=178208&&pe<=183983||pe>=63744&&pe<=64255||pe>=194560&&pe<=195103}function v(pe,I,N){const Y=[];let le=0;for(;lethis.tokens_to_ids.get(N)??this.unk_token_id)}convert_ids_to_tokens(I){return I.map(N=>this.vocab[N]??this.unk_token)}}class K extends G{constructor(I){super(I),this.tokens_to_ids=_(I.vocab),this.unk_token_id=this.tokens_to_ids.get(I.unk_token),this.unk_token=I.unk_token,this.max_input_chars_per_word=I.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[N,Y]of this.tokens_to_ids)this.vocab[Y]=N}encode(I){const N=[];for(const Y of I){const le=[...Y];if(le.length>this.max_input_chars_per_word){N.push(this.unk_token);continue}let de=!1,Te=0;const Ne=[];for(;Te0&&(tt=this.config.continuing_subword_prefix+tt),this.tokens_to_ids.has(tt)){We=tt;break}--qe}if(We===null){de=!0;break}Ne.push(We),Te=qe}de?N.push(this.unk_token):N.push(...Ne)}return N}}class R extends G{constructor(I,N){super(I);const Y=I.vocab.length;this.vocab=new Array(Y),this.scores=new Array(Y);for(let le=0;le[le,de])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,i.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(I){const N=I.chars,Y=1;let le=0;for(;le{const pe=[...Array.from({length:94},(le,de)=>de+33),...Array.from({length:12},(le,de)=>de+161),...Array.from({length:82},(le,de)=>de+174)],I=pe.slice();let N=0;for(let le=0;le<256;++le)pe.includes(le)||(pe.push(le),I.push(256+N),N+=1);const Y=I.map(le=>String.fromCharCode(le));return Object.fromEntries(pe.map((le,de)=>[le,Y[de]]))})(),H=(0,o.reverseDictionary)(te);class ee extends G{constructor(I){super(I),this.tokens_to_ids=_(I.vocab),this.unk_token_id=this.tokens_to_ids.get(I.unk_token),this.unk_token=I.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[Y,le]of this.tokens_to_ids)this.vocab[le]=Y;const N=Array.isArray(I.merges[0]);this.merges=N?I.merges:I.merges.map(Y=>Y.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((Y,le)=>[JSON.stringify(Y),le])),this.end_of_word_suffix=I.end_of_word_suffix,this.continuing_subword_suffix=I.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new l.LRUCache(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(I){if(I.length===0)return[];const N=this.cache.get(I);if(N!==void 0)return N;const Y=Array.from(I);this.end_of_word_suffix&&(Y[Y.length-1]+=this.end_of_word_suffix);let le=[];if(Y.length>1){const de=new l.PriorityQueue((qe,We)=>qe.score`<0x${Ne.toString(16).toUpperCase().padStart(2,"0")}>`);Te.every(Ne=>this.tokens_to_ids.has(Ne))?N.push(...Te):N.push(this.unk_token)}else N.push(this.unk_token)}return N}}class Z extends G{constructor(I,N){super(I),this.tokens_to_ids=_(N.target_lang?I.vocab[N.target_lang]:I.vocab),this.bos_token=N.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=N.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=N.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[Y,le]of this.tokens_to_ids)this.vocab[le]=Y}encode(I){return I}}class ne extends s.Callable{constructor(I){super(),this.config=I}static fromConfig(I){if(I===null)return null;switch(I.type){case"BertNormalizer":return new Ie(I);case"Precompiled":return new jr(I);case"Sequence":return new Ge(I);case"Replace":return new me(I);case"NFC":return new j(I);case"NFD":return new F(I);case"NFKC":return new U(I);case"NFKD":return new se(I);case"Strip":return new _e(I);case"StripAccents":return new ie(I);case"Lowercase":return new ve(I);case"Prepend":return new ze(I);default:throw new Error(`Unknown Normalizer type: ${I.type}`)}}normalize(I){throw Error("normalize should be implemented in subclass.")}_call(I){return this.normalize(I)}}class me extends ne{normalize(I){const N=f(this.config.pattern);return N===null?I:I.replaceAll(N,this.config.content)}}class ue extends ne{constructor(){super(...arguments);J(this,"form")}normalize(N){return N=N.normalize(this.form),N}}class j extends ue{constructor(){super(...arguments);J(this,"form","NFC")}}class F extends ue{constructor(){super(...arguments);J(this,"form","NFD")}}class U extends ue{constructor(){super(...arguments);J(this,"form","NFKC")}}class se extends ue{constructor(){super(...arguments);J(this,"form","NFKD")}}class _e extends ne{normalize(I){return this.config.strip_left&&this.config.strip_right?I=I.trim():(this.config.strip_left&&(I=I.trimStart()),this.config.strip_right&&(I=I.trimEnd())),I}}class ie extends ne{normalize(I){return I=g(I),I}}class ve extends ne{normalize(I){return I=I.toLowerCase(),I}}class ze extends ne{normalize(I){return I=this.config.prepend+I,I}}class Ge extends ne{constructor(I){super(I),this.normalizers=I.normalizers.map(N=>ne.fromConfig(N))}normalize(I){return this.normalizers.reduce((N,Y)=>Y.normalize(N),I)}}class Ie extends ne{_tokenize_chinese_chars(I){const N=[];for(let Y=0;Ythis.pre_tokenize_text(Y,N)):this.pre_tokenize_text(I,N)).flat()}_call(I,N){return this.pre_tokenize(I,N)}}class ae extends X{constructor(I){super(),this.pattern=new RegExp(`[^\\s${T}]+|[${T}]`,"gu")}pre_tokenize_text(I,N){return I.trim().match(this.pattern)||[]}}class W extends X{constructor(I){super(),this.config=I,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=te,this.text_encoder=new TextEncoder}pre_tokenize_text(I,N){return this.add_prefix_space&&!I.startsWith(" ")&&(I=" "+I),(this.use_regex?I.match(this.pattern)||[]:[I]).map(le=>Array.from(this.text_encoder.encode(le),de=>this.byte_encoder[de]).join(""))}}class be extends X{constructor(I){super(),this.config=I,this.pattern=f(this.config.pattern,this.config.invert)}pre_tokenize_text(I,N){var Y;return this.pattern===null?[]:this.config.invert?I.match(this.pattern)||[]:((Y=this.config.behavior)==null?void 0:Y.toLowerCase())==="removed"?I.split(this.pattern).filter(le=>le):u(I,this.pattern)}}class ke extends X{constructor(I){super(),this.config=I,this.pattern=new RegExp(`[^${T}]+|[${T}]+`,"gu")}pre_tokenize_text(I,N){return I.match(this.pattern)||[]}}class Ee extends X{constructor(I){super(),this.config=I;const N=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(N,"gu")}pre_tokenize_text(I,N){return I.match(this.pattern)||[]}}class Me extends s.Callable{constructor(I){super(),this.config=I}static fromConfig(I){if(I===null)return null;switch(I.type){case"TemplateProcessing":return new Ae(I);case"ByteLevel":return new Be(I);case"RobertaProcessing":return new we(I);case"BertProcessing":return new Se(I);case"Sequence":return new Qe(I);default:throw new Error(`Unknown PostProcessor type: ${I.type}`)}}post_process(I,...N){throw Error("post_process should be implemented in subclass.")}_call(I,...N){return this.post_process(I,...N)}}class Se extends Me{constructor(I){super(I),this.cls=I.cls[0],this.sep=I.sep[0]}post_process(I,N=null,{add_special_tokens:Y=!0}={}){Y&&(I=(0,o.mergeArrays)([this.cls],I,[this.sep]));let le=new Array(I.length).fill(0);if(N!==null){const de=Y&&this instanceof we?[this.sep]:[],Te=Y?[this.sep]:[];I=(0,o.mergeArrays)(I,de,N,Te),le=(0,o.mergeArrays)(le,new Array(N.length+de.length+Te.length).fill(1))}return{tokens:I,token_type_ids:le}}}class we extends Se{}class Ae extends Me{constructor(I){super(I),this.single=I.single,this.pair=I.pair}post_process(I,N=null,{add_special_tokens:Y=!0}={}){const le=N===null?this.single:this.pair;let de=[],Te=[];for(const Ne of le)"SpecialToken"in Ne?Y&&(de.push(Ne.SpecialToken.id),Te.push(Ne.SpecialToken.type_id)):"Sequence"in Ne&&(Ne.Sequence.id==="A"?(de=(0,o.mergeArrays)(de,I),Te=(0,o.mergeArrays)(Te,new Array(I.length).fill(Ne.Sequence.type_id))):Ne.Sequence.id==="B"&&(de=(0,o.mergeArrays)(de,N),Te=(0,o.mergeArrays)(Te,new Array(N.length).fill(Ne.Sequence.type_id))));return{tokens:de,token_type_ids:Te}}}class Be extends Me{post_process(I,N=null){return N&&(I=(0,o.mergeArrays)(I,N)),{tokens:I}}}class Qe extends Me{constructor(I){super(I),this.processors=I.processors.map(N=>Me.fromConfig(N))}post_process(I,N=null,Y={}){let le;for(const de of this.processors)if(de instanceof Be)I=de.post_process(I).tokens,N&&(N=de.post_process(N).tokens);else{const Te=de.post_process(I,N,Y);I=Te.tokens,le=Te.token_type_ids}return{tokens:I,token_type_ids:le}}}class xe extends s.Callable{constructor(I){super(),this.config=I,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=I.trim_offsets}static fromConfig(I){if(I===null)return null;switch(I.type){case"WordPiece":return new Oe(I);case"Metaspace":return new Pr(I);case"ByteLevel":return new Ye(I);case"Replace":return new Ze(I);case"ByteFallback":return new Ke(I);case"Fuse":return new nt(I);case"Strip":return new Je(I);case"Sequence":return new It(I);case"CTC":return new ot(I);case"BPEDecoder":return new St(I);default:throw new Error(`Unknown Decoder type: ${I.type}`)}}_call(I){return this.decode(I)}decode(I){return this.decode_chain(I).join("")}decode_chain(I){throw Error("`decode_chain` should be implemented in subclass.")}}class Ze extends xe{decode_chain(I){const N=f(this.config.pattern);return N===null?I:I.map(Y=>Y.replaceAll(N,this.config.content))}}class Ke extends xe{constructor(I){super(I),this.text_decoder=new TextDecoder}decode_chain(I){const N=[];let Y=[];for(const le of I){let de=null;if(le.length===6&&le.startsWith("<0x")&&le.endsWith(">")){const Te=parseInt(le.slice(3,5),16);isNaN(Te)||(de=Te)}if(de!==null)Y.push(de);else{if(Y.length>0){const Te=this.text_decoder.decode(Uint8Array.from(Y));N.push(Te),Y=[]}N.push(le)}}if(Y.length>0){const le=this.text_decoder.decode(Uint8Array.from(Y));N.push(le),Y=[]}return N}}class nt extends xe{decode_chain(I){return[I.join("")]}}class Je extends xe{constructor(I){super(I),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(I){return I.map(N=>{let Y=0;for(let de=0;de(Y!==0&&(N.startsWith(this.config.prefix)?N=N.replace(this.config.prefix,""):N=" "+N),this.cleanup&&(N=k(N)),N))}}class Ye extends xe{constructor(I){super(I),this.byte_decoder=H,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(I){const N=I.join(""),Y=new Uint8Array([...N].map(de=>this.byte_decoder[de]));return this.text_decoder.decode(Y)}decode_chain(I){const N=[];let Y=[];for(const le of I)this.added_tokens.find(de=>de.content===le)!==void 0?(Y.length>0&&(N.push(this.convert_tokens_to_string(Y)),Y=[]),N.push(le)):Y.push(le);return Y.length>0&&N.push(this.convert_tokens_to_string(Y)),N}}class ot extends xe{constructor(I){super(I),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string(I){if(I.length===0)return"";const N=[I[0]];for(let de=1;dede!==this.pad_token).join("");return this.cleanup&&(le=k(le).replaceAll(this.word_delimiter_token," ").trim()),le}decode_chain(I){return[this.convert_tokens_to_string(I)]}}class It extends xe{constructor(I){super(I),this.decoders=I.decoders.map(N=>xe.fromConfig(N))}decode_chain(I){return this.decoders.reduce((N,Y)=>Y.decode_chain(N),I)}}class St extends xe{constructor(I){super(I),this.suffix=this.config.suffix}decode_chain(I){return I.map((N,Y)=>N.replaceAll(this.suffix,Y===I.length-1?"":" "))}}class wt extends xe{decode_chain(I){let N="";for(let Y=1;YY.normalize("NFKC")).join("~"):I=I.normalize("NFKC"),I}}class us extends X{constructor(I){super(),this.tokenizers=I.pretokenizers.map(N=>X.fromConfig(N))}pre_tokenize_text(I,N){return this.tokenizers.reduce((Y,le)=>le.pre_tokenize(Y,N),[I])}}class qt extends X{constructor(I){super()}pre_tokenize_text(I,N){return I.match(/\w+|[^\w\s]+/g)||[]}}class Cr extends X{constructor(I){super()}pre_tokenize_text(I,N){return y(I)}}class Xs extends X{constructor(I){super(),this.config=I,this.pattern=f(this.config.pattern),this.content=this.config.content}pre_tokenize_text(I,N){return this.pattern===null?[I]:[I.replaceAll(this.pattern,this.config.content)]}}const Js=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Ys(pe,I,N,Y){for(const le of Object.keys(pe)){const de=I-pe[le].length,Te=N(le),Ne=new Array(de).fill(Te);pe[le]=Y==="right"?(0,o.mergeArrays)(pe[le],Ne):(0,o.mergeArrays)(Ne,pe[le])}}function Zs(pe,I){for(const N of Object.keys(pe))pe[N].length=I}class pt extends s.Callable{constructor(N,Y){super();J(this,"return_token_type_ids",!1);J(this,"padding_side","right");this.config=Y,this.normalizer=ne.fromConfig(N.normalizer),this.pre_tokenizer=X.fromConfig(N.pre_tokenizer),this.model=G.fromConfig(N.model,Y),this.post_processor=Me.fromConfig(N.post_processor),this.decoder=xe.fromConfig(N.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const le of N.added_tokens){const de=new L(le);this.added_tokens.push(de),this.model.tokens_to_ids.set(de.content,de.id),this.model.vocab[de.id]=de.content,de.special&&(this.special_tokens.push(de.content),this.all_special_ids.push(de.id))}if(this.additional_special_tokens=Y.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new l.DictionarySplitter(this.added_tokens.map(le=>le.content)),this.added_tokens_map=new Map(this.added_tokens.map(le=>[le.content,le])),this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=Y.model_max_length,this.remove_space=Y.remove_space,this.clean_up_tokenization_spaces=Y.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Y.do_lowercase_and_remove_accent??!1,Y.padding_side&&(this.padding_side=Y.padding_side),this.add_bos_token=Y.add_bos_token,this.add_eos_token=Y.add_eos_token,this.legacy=!1,this.chat_template=Y.chat_template??null,Array.isArray(this.chat_template)){const le=Object.create(null);for(const{name:de,template:Te}of this.chat_template){if(typeof de!="string"||typeof Te!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');le[de]=Te}this.chat_template=le}this._compiled_template_cache=new Map}getToken(...N){for(const Y of N){const le=this.config[Y];if(le)if(typeof le=="object"){if(le.__type==="AddedToken")return le.content;throw Error(`Unknown token: ${le}`)}else return le}return null}static async from_pretrained(N,{progress_callback:Y=null,config:le=null,cache_dir:de=null,local_files_only:Te=!1,revision:Ne="main",legacy:qe=null}={}){const We=await d(N,{progress_callback:Y,config:le,cache_dir:de,local_files_only:Te,revision:Ne,legacy:qe});return new this(...We)}_call(N,{text_pair:Y=null,add_special_tokens:le=!0,padding:de=!1,truncation:Te=null,max_length:Ne=null,return_tensor:qe=!0,return_token_type_ids:We=null}={}){const tt=Array.isArray(N);let Mt;if(tt){if(N.length===0)throw Error("text array must be non-empty");if(Y!==null){if(Array.isArray(Y)){if(N.length!==Y.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Mt=N.map((Lt,sr)=>this._encode_plus(Lt,{text_pair:Y[sr],add_special_tokens:le,return_token_type_ids:We}))}else Mt=N.map(Lt=>this._encode_plus(Lt,{add_special_tokens:le,return_token_type_ids:We}))}else{if(N==null)throw Error("text may not be null or undefined");if(Array.isArray(Y))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Mt=[this._encode_plus(N,{text_pair:Y,add_special_tokens:le,return_token_type_ids:We})]}if(Ne===null?Ne=this.model_max_length:Te===null&&(de===!0?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),Ne=this.model_max_length):de===!1&&(console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),Te=!0)),de===!0&&(Ne=Math.min((0,i.max)(Mt.map(Lt=>Lt.input_ids.length))[0],Ne??1/0)),Ne=Math.min(Ne,this.model_max_length??1/0),de||Te)for(let Lt=0;LtNe?Te&&Zs(Mt[Lt],Ne):de&&Ys(Mt[Lt],Ne,sr=>sr==="input_ids"?this.pad_token_id:0,this.padding_side));const Bt={};if(qe){if(!(de&&Te)&&Mt.some(sr=>{var Wt;for(const _r of Object.keys(sr))if(sr[_r].length!==((Wt=Mt[0][_r])==null?void 0:Wt.length))return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const Lt=[Mt.length,Mt[0].input_ids.length];for(const sr of Object.keys(Mt[0]))Bt[sr]=new a.Tensor("int64",BigInt64Array.from(Mt.flatMap(Wt=>Wt[sr]).map(BigInt)),Lt)}else{for(const Lt of Object.keys(Mt[0]))Bt[Lt]=Mt.map(sr=>sr[Lt]);if(!tt)for(const Lt of Object.keys(Bt))Bt[Lt]=Bt[Lt][0]}return Bt}_encode_text(N){if(N===null)return null;const Y=this.added_tokens_splitter.split(N);for(let de=0;de0&&(Y[de-1]=Y[de-1].trimEnd()),Te.rstrip&&de{if(de.length===0)return[];if(this.added_tokens_map.has(de))return[de];if(this.remove_space===!0&&(de=de.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(de=M(de)),this.normalizer!==null&&(de=this.normalizer(de)),de.length===0)return[];const Ne=this.pre_tokenizer!==null?this.pre_tokenizer(de,{section_index:Te}):[de];return this.model(Ne)})}_encode_plus(N,{text_pair:Y=null,add_special_tokens:le=!0,return_token_type_ids:de=null}={}){const{tokens:Te,token_type_ids:Ne}=this._tokenize_helper(N,{pair:Y,add_special_tokens:le}),qe=this.model.convert_tokens_to_ids(Te),We={input_ids:qe,attention_mask:new Array(qe.length).fill(1)};return(de??this.return_token_type_ids)&&Ne&&(We.token_type_ids=Ne),We}_tokenize_helper(N,{pair:Y=null,add_special_tokens:le=!1}={}){const de=this._encode_text(N),Te=this._encode_text(Y);return this.post_processor?this.post_processor(de,Te,{add_special_tokens:le}):{tokens:(0,o.mergeArrays)(de??[],Te??[])}}tokenize(N,{pair:Y=null,add_special_tokens:le=!1}={}){return this._tokenize_helper(N,{pair:Y,add_special_tokens:le}).tokens}encode(N,{text_pair:Y=null,add_special_tokens:le=!0,return_token_type_ids:de=null}={}){return this._encode_plus(N,{text_pair:Y,add_special_tokens:le,return_token_type_ids:de}).input_ids}batch_decode(N,Y={}){return N instanceof a.Tensor&&(N=N.tolist()),N.map(le=>this.decode(le,Y))}decode(N,Y={}){if(N instanceof a.Tensor&&(N=b(N)),!Array.isArray(N)||N.length===0||!(0,o.isIntegralNumber)(N[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(N,Y)}decode_single(N,{skip_special_tokens:Y=!1,clean_up_tokenization_spaces:le=null}){let de=this.model.convert_ids_to_tokens(N);Y&&(de=de.filter(Ne=>!this.special_tokens.includes(Ne)));let Te=this.decoder?this.decoder(de):de.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Te=Te.replaceAll(this.decoder.end_of_word_suffix," "),Y&&(Te=Te.trim())),(le??this.clean_up_tokenization_spaces)&&(Te=k(Te)),Te}get_chat_template({chat_template:N=null,tools:Y=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const le=this.chat_template;if(N!==null&&Object.hasOwn(le,N))N=le[N];else if(N===null)if(Y!==null&&"tool_use"in le)N=le.tool_use;else if("default"in le)N=le.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(le).sort()}.`)}else if(N===null)if(this.chat_template)N=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return N}apply_chat_template(N,{tools:Y=null,documents:le=null,chat_template:de=null,add_generation_prompt:Te=!1,tokenize:Ne=!0,padding:qe=!1,truncation:We=!1,max_length:tt=null,return_tensor:Mt=!0,return_dict:Bt=!1,tokenizer_kwargs:Lt={},...sr}={}){if(de=this.get_chat_template({chat_template:de,tools:Y}),typeof de!="string")throw Error(`chat_template must be a string, but got ${typeof de}`);let Wt=this._compiled_template_cache.get(de);Wt===void 0&&(Wt=new c.Template(de),this._compiled_template_cache.set(de,Wt));const _r=Object.create(null);for(const ir of Js){const fr=this.getToken(ir);fr&&(_r[ir]=fr)}const br=Wt.render({messages:N,add_generation_prompt:Te,tools:Y,documents:le,..._r,...sr});if(Ne){const ir=this._call(br,{add_special_tokens:!1,padding:qe,truncation:We,max_length:tt,return_tensor:Mt,...Lt});return Bt?ir:ir.input_ids}return br}}class As extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class Fs extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class Ct extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class Qt extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class S extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class Q extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class B extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class q extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class re extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class ge extends pt{}class Fe extends pt{}class rt extends pt{constructor(N,Y){super(N,Y);J(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class ft extends pt{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class ht extends pt{}class vt extends pt{}class st extends pt{}class zt extends pt{constructor(I,N){super(I,N),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)),this.lang_to_token=Y=>Y}_build_translation_inputs(I,N,Y){return Dr(this,I,N,Y)}}class Ut extends zt{}class Nr extends pt{}class Xr extends pt{}const rr="▁";class Sr extends pt{constructor(N,Y){super(N,Y);J(this,"padding_side","left");this.legacy=Y.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new Mr({replacement:rr,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(N){if(N===null)return null;if(this.legacy||N.length===0)return super._encode_text(N);let Y=super._encode_text(rr+N.replaceAll(rr," "));return Y.length>1&&Y[0]===rr&&this.special_tokens.includes(Y[1])&&(Y=Y.slice(1)),Y}}class $r extends pt{}class Vr extends pt{}class ds extends pt{}class kr extends pt{}class Os extends pt{}class Ds extends pt{}class Ur extends pt{}class Wr extends pt{}class ts extends pt{}function Dr(pe,I,N,Y){if(!("language_codes"in pe)||!Array.isArray(pe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in pe)||!(pe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in pe)||typeof pe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const le=Y.src_lang,de=Y.tgt_lang;if(!pe.language_codes.includes(de))throw new Error(`Target language code "${de}" is not valid. Must be one of: {${pe.language_codes.join(", ")}}`);if(le!==void 0){if(!pe.language_codes.includes(le))throw new Error(`Source language code "${le}" is not valid. Must be one of: {${pe.language_codes.join(", ")}}`);for(const Te of pe.post_processor.config.single)if("SpecialToken"in Te&&pe.languageRegex.test(Te.SpecialToken.id)){Te.SpecialToken.id=pe.lang_to_token(le);break}}return Y.forced_bos_token_id=pe.model.convert_tokens_to_ids([pe.lang_to_token(de)])[0],pe._call(I,N)}class Ts extends pt{constructor(I,N){super(I,N),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)),this.lang_to_token=Y=>Y}_build_translation_inputs(I,N,Y){return Dr(this,I,N,Y)}}class pr extends pt{constructor(I,N){super(I,N),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Y=>this.languageRegex.test(Y)).map(Y=>Y.slice(2,-2)),this.lang_to_token=Y=>`__${Y}__`}_build_translation_inputs(I,N,Y){return Dr(this,I,N,Y)}}class mr extends pt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(I,{return_timestamps:N=!1,return_language:Y=!1,time_precision:le=null,force_full_sequences:de=!0}={}){if(le===null)throw Error("Must specify time_precision");let Te=null;const Ne=N==="word";function qe(){return{language:Te,timestamp:[null,null],text:""}}const We=[];let tt=qe(),Mt=0;const Bt=this.timestamp_begin,sr=Bt+1500;let Wt=[],_r=[],br=!1,ir=null;const fr=new Set(this.all_special_ids);for(const Zt of I){const gr=Zt.tokens,Kr=Ne?Zt.token_timestamps:null;let zr=null,Cs=Bt;if("stride"in Zt){const[ur,ar,hr]=Zt.stride;if(Mt-=ar,ir=ur-hr,ar&&(Cs=ar/le+Bt),hr)for(let nr=gr.length-1;nr>=0;--nr){const Hr=Number(gr[nr]);if(Hr>=Bt){if(zr!==null&&(Hr-Bt)*le=Bt&&ar<=sr){const hr=(ar-Bt)*le+Mt,nr=(0,i.round)(hr,2);if(zr!==null&&ar>=zr)br=!0;else if(br||Wt.length>0&&ar0?(Wt.push(Ir),Ne&&_r.push(ps)):Wt.every(ur=>ur.length===0)&&(tt=qe(),Wt=[],Ir=[],_r=[],ps=[])}if(Wt.length>0){if(de&&N)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Zt,gr]=this.findLongestCommonSequence(Wt,_r),Kr=this.decode(Zt);tt.text=Kr,Ne&&(tt.words=this.collateWordTimestamps(Zt,gr,Te)),We.push(tt)}let Lr=Object.create(null);const Yr=We.map(Zt=>Zt.text).join("");if(N||Y){for(let Zt=0;Zt0;let Ne=Te?[]:null,qe=Te?N[0]:null;for(let We=1;Wear===Cs[hr]&&qe[Yr+hr]<=N[We][Kr+hr]).length:Ir=gr.filter((ar,hr)=>ar===Cs[hr]).length;const ps=Lr/1e4,ur=Ir/Lr+ps;Ir>1&&ur>Mt&&(Mt=ur,Bt=[Yr,Zt,Kr,zr])}const[sr,Wt,_r,br]=Bt,ir=Math.floor((Wt+sr)/2),fr=Math.floor((br+_r)/2);de.push(...Y.slice(0,ir)),Y=tt.slice(fr),le=Y.length,Te&&(Ne.push(...qe.slice(0,ir)),qe=N[We].slice(fr))}return de.push(...Y),Te?(Ne.push(...qe),[de,Ne]):[de,[]]}collateWordTimestamps(I,N,Y){const[le,de,Te]=this.combineTokensIntoWords(I,Y),Ne=[];for(let qe=0;qe=le){const Ne=((Te-le)*Y).toFixed(2);de.push(`<|${Ne}|>`),de.push([])}else de[de.length-1].push(Te);return de=de.map(Te=>typeof Te=="string"?Te:super.decode(Te,N)),de.join("")}splitTokensOnUnicode(I){const N=this.decode(I,{decode_with_timestamps:!0}),Y="�",le=[],de=[],Te=[];let Ne=[],qe=[],We=0;for(let tt=0;tt=this.model.tokens_to_ids.get("<|endoftext|>"),sr=tt.startsWith(" "),Wt=tt.trim(),_r=qe.test(Wt);if(Lt||sr||_r||de.length===0)de.push(tt),Te.push(Mt),Ne.push(Bt);else{const br=de.length-1;de[br]+=tt,Te[br].push(...Mt),Ne[br].push(...Bt)}}return[de,Te,Ne]}mergePunctuations(I,N,Y,le,de){const Te=structuredClone(I),Ne=structuredClone(N),qe=structuredClone(Y);let We=Te.length-2,tt=Te.length-1;for(;We>=0;)Te[We].startsWith(" ")&&le.includes(Te[We].trim())?(Te[tt]=Te[We]+Te[tt],Ne[tt]=(0,o.mergeArrays)(Ne[We],Ne[tt]),qe[tt]=(0,o.mergeArrays)(qe[We],qe[tt]),Te[We]="",Ne[We]=[],qe[We]=[]):tt=We,--We;for(We=0,tt=1;ttMt),Ne.filter(Mt=>Mt.length>0),qe.filter(Mt=>Mt.length>0)]}}class Jr extends pt{}class Ns extends pt{}class Gr extends pt{}class Re extends pt{constructor(I,N){super(I,N),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Y=>this.languageRegex.test(Y)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(I){if(I===null)return null;const[N,...Y]=I.trim().split(this.languageRegex);if(Y.length===0)return super._encode_text(N);if(Y.length===2){const[le,de]=Y;return this.supported_language_codes.includes(le)||console.warn(`Unsupported language code "${le}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,o.mergeArrays)([le],super._encode_text(de))}}}class je extends pt{}class et extends pt{}class Xt extends pt{}class Vs extends pt{}class Es extends pt{}class Us extends pt{constructor(I,N){super(I,N),this.decoder=new wt({})}}class Ps extends pt{}class yn extends pt{}class vn extends pt{}class xn{static async from_pretrained(I,{progress_callback:N=null,config:Y=null,cache_dir:le=null,local_files_only:de=!1,revision:Te="main",legacy:Ne=null}={}){var Bt;const[qe,We]=await d(I,{progress_callback:N,config:Y,cache_dir:le,local_files_only:de,revision:Te,legacy:Ne}),tt=((Bt=We.tokenizer_class)==null?void 0:Bt.replace(/Fast$/,""))??"PreTrainedTokenizer";let Mt=this.TOKENIZER_CLASS_MAPPING[tt];return Mt||(console.warn(`Unknown tokenizer class "${tt}", attempting to construct from base class.`),Mt=pt),new Mt(qe,We)}}J(xn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:ht,DistilBertTokenizer:ge,CamembertTokenizer:Fe,DebertaTokenizer:S,DebertaV2Tokenizer:Q,BertTokenizer:As,HerbertTokenizer:B,ConvBertTokenizer:q,RoFormerTokenizer:re,XLMTokenizer:rt,ElectraTokenizer:ft,MobileBertTokenizer:Ct,SqueezeBertTokenizer:Qt,AlbertTokenizer:Fs,GPT2Tokenizer:vt,BartTokenizer:st,MBartTokenizer:zt,MBart50Tokenizer:Ut,RobertaTokenizer:Nr,WhisperTokenizer:mr,CodeGenTokenizer:Jr,CLIPTokenizer:Ns,SiglipTokenizer:Gr,MarianTokenizer:Re,BloomTokenizer:Xr,NllbTokenizer:Ts,M2M100Tokenizer:pr,LlamaTokenizer:Sr,CodeLlamaTokenizer:$r,XLMRobertaTokenizer:Vr,MPNetTokenizer:ds,FalconTokenizer:kr,GPTNeoXTokenizer:Os,EsmTokenizer:Ds,Wav2Vec2CTCTokenizer:je,BlenderbotTokenizer:et,BlenderbotSmallTokenizer:Xt,SpeechT5Tokenizer:Vs,NougatTokenizer:Es,VitsTokenizer:Us,Qwen2Tokenizer:Ur,GemmaTokenizer:Wr,Grok1Tokenizer:ts,CohereTokenizer:Ps,MgpstrTokenizer:yn,Ernie4_5_Tokenizer:vn,PreTrainedTokenizer:pt})},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>K,hamming:()=>u,hanning:()=>d,mel_filter_bank:()=>$,read_audio:()=>c,spectrogram:()=>P,window_function:()=>O});var s=t("./src/utils/hub.js"),o=t("./src/utils/maths.js"),n=t("./src/utils/core.js"),i=t("./src/env.js"),a=t("./src/utils/tensor.js"),l=t("?7992");async function c(R,te){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const H=await(await(0,s.getFile)(R)).arrayBuffer(),ee=new AudioContext({sampleRate:te});typeof te>"u"&&console.warn(`No sampling rate provided, using default of ${ee.sampleRate}Hz.`);const Z=await ee.decodeAudioData(H);let ne;if(Z.numberOfChannels===2){const me=Math.sqrt(2),ue=Z.getChannelData(0),j=Z.getChannelData(1);ne=new Float32Array(ue.length);for(let F=0;F2595*Math.log10(1+R/700),kaldi:R=>1127*Math.log(1+R/700),slaney:(R,te=1e3,H=15,ee=27/Math.log(6.4))=>R>=te?H+Math.log(R/te)*ee:3*R/200};function _(R,te="htk"){const H=f[te];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof R=="number"?H(R):R.map(ee=>H(ee))}const b={htk:R=>700*(10**(R/2595)-1),kaldi:R=>700*(Math.exp(R/1127)-1),slaney:(R,te=1e3,H=15,ee=Math.log(6.4)/27)=>R>=H?te*Math.exp(ee*(R-H)):200*R/3};function k(R,te="htk"){const H=b[te];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof R=="number"?H(R):R.map(ee=>H(ee))}function g(R,te){const H=Float64Array.from({length:te.length-1},(me,ue)=>te[ue+1]-te[ue]),ee=Array.from({length:R.length},()=>new Array(te.length));for(let me=0;menew Array(R.length));for(let me=0;meR+ee*ne)}function $(R,te,H,ee,Z,ne=null,me="htk",ue=!1){if(ne!==null&&ne!=="slaney")throw new Error('norm must be one of null or "slaney"');if(R<2)throw new Error(`Require num_frequency_bins: ${R} >= 2`);if(H>ee)throw new Error(`Require min_frequency: ${H} <= max_frequency: ${ee}`);const j=_(H,me),F=_(ee,me),U=M(j,F,te+2);let se=k(U,me),_e;if(ue){const ve=Z/((R-1)*2);_e=_(Float64Array.from({length:R},(ze,Ge)=>Ge*ve),me),se=U}else _e=M(0,Math.floor(Z/2),R);const ie=g(_e,se);if(ne!==null&&ne==="slaney")for(let ve=0;veZ)throw Error(`frame_length (${H}) may not be larger than fft_length (${Z})`);if(ke!==H)throw new Error(`Length of the window (${ke}) must equal frame_length (${H})`);if(ee<=0)throw new Error("hop_length must be greater than zero");if(ne===null&&se!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!U)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(me){if(ue!=="reflect")throw new Error(`pad_mode="${ue}" not implemented yet.`);const Je=Math.floor((Z-1)/2)+1;R=v(R,Je,Je)}let Ee=Math.floor(1+Math.floor((R.length-H)/ee));X!==null&&EeEe?W&&(we=ae):we=Se=ae);const Ae=new o.FFT(Z),Be=new Float64Array(Z),Qe=new Float64Array(Ae.outputBufferSize),xe=new Float32Array(Me*we);for(let Je=0;Je=1;--ot)Be[ot]-=F*Be[ot-1];Be[0]*=1-F}for(let ot=0;otMath.pow(ue,.85));break;default:throw new Error(`Unknown window type ${te}.`)}if(H&&(me=me.subarray(0,R)),ee===null)return me;if(R>ee)throw new Error(`Length of the window (${R}) may not be larger than frame_length (${ee})`);return me}function L(R,te){let H=44;const ee=new ArrayBuffer(H+R.length*4),Z=new DataView(ee);G(Z,0,"RIFF"),Z.setUint32(4,36+R.length*4,!0),G(Z,8,"WAVE"),G(Z,12,"fmt "),Z.setUint32(16,16,!0),Z.setUint16(20,3,!0),Z.setUint16(22,1,!0),Z.setUint32(24,te,!0),Z.setUint32(28,te*4,!0),Z.setUint16(32,4,!0),Z.setUint16(34,32,!0),G(Z,36,"data"),Z.setUint32(40,R.length*4,!0);for(let ne=0;ne{let ne=await Z.arrayBuffer();l.writeFileSync(ee,Buffer.from(ne))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await H(te,this.toBlob())}}},"./src/utils/constants.js":(e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>o,FEATURE_EXTRACTOR_NAME:()=>n,GENERATION_CONFIG_NAME:()=>c,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",o="config.json",n="preprocessor_config.json",i=n,a="processor_config.json",l="chat_template.jinja",c="generation_config.json"},"./src/utils/core.js":(e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>c,calculateReflectOffset:()=>f,count:()=>g,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>k,mergeArrays:()=>d,pick:()=>b,pop:()=>p,product:()=>u,reverseDictionary:()=>o,saveBlob:()=>_});function s(M,$){M&&M($)}function o(M){return Object.fromEntries(Object.entries(M).map(([$,v])=>[v,$]))}function n(M){return M.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(M){var $,v,y;return((y=(v=($=M==null?void 0:M.prototype)==null?void 0:$.__proto__)==null?void 0:v.constructor)==null?void 0:y.name)==="TypedArray"}function a(M){return Number.isInteger(M)||typeof M=="bigint"}function l(M){return M==null||M===-1}function c(M){const $=[];let v=M;for(;Array.isArray(v);)$.push(v.length),v=v[0];return $}function p(M,$,v=void 0){const y=M[$];if(y!==void 0)return delete M[$],y;if(v===void 0)throw Error(`Key ${$} does not exist in object.`);return v}function d(...M){return Array.prototype.concat.apply([],M)}function u(...M){return M.reduce(($,v)=>$.flatMap(y=>v.map(T=>[y,T])))}function f(M,$){return Math.abs((M+$)%(2*$)-$)}function _(M,$){const v=URL.createObjectURL($),y=document.createElement("a");y.href=v,y.download=M,y.click(),y.remove(),URL.revokeObjectURL(v)}function b(M,$){return Object.assign({},...$.map(v=>{if(M[v]!==void 0)return{[v]:M[v]}}))}function k(M){let $=0;for(const v of M)++$;return $}function g(M,$){let v=0;for(const y of M)y===$&&++v;return v}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>o,DictionarySplitter:()=>l,LRUCache:()=>c,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(d=(f,_)=>f>_,u=1/0){this._heap=[],this._comparator=d,this._maxSize=u}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...d){return this.extend(d)}extend(d){for(const u of d)if(this.size0&&this._swap(0,u),this._heap.pop(),this._siftDown(),d}replace(d){const u=this.peek();return this._heap[0]=d,this._siftDown(),u}_parent(d){return(d+1>>>1)-1}_left(d){return(d<<1)+1}_right(d){return d+1<<1}_greater(d,u){return this._comparator(this._heap[d],this._heap[u])}_swap(d,u){const f=this._heap[d];this._heap[d]=this._heap[u],this._heap[u]=f}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(d){for(;d>0&&this._greater(d,this._parent(d));)this._swap(d,this._parent(d)),d=this._parent(d)}_siftDown(){let d=0;for(;this._left(d)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const _=new a(this.bosTokenId,0,0,0,0),b=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(_.clone()),this.nodes.push(b.clone()),this.beginNodes[this.len].push(b),this.endNodes[0].push(_)}insert(d,u,f,_){const b=this.nodes.length,k=new a(_,b,d,u,f);this.beginNodes[d].push(k),this.endNodes[d+u].push(k),this.nodes.push(k)}viterbi(){const d=this.len;let u=0;for(;u<=d;){if(this.beginNodes[u].length==0)return[];for(let g of this.beginNodes[u]){g.prev=null;let M=0,$=null;for(let v of this.endNodes[u]){const y=v.backtraceScore+g.score;($===null||y>M)&&($=v.clone(),M=y)}if($!==null)g.prev=$,g.backtraceScore=M;else return[]}++u}const f=[],b=this.beginNodes[d][0].prev;if(b===null)return[];let k=b.clone();for(;k.prev!==null;)f.push(k.clone()),k=k.clone().prev.clone();return f.reverse(),f}piece(d){return this.chars.slice(d.pos,d.pos+d.length).join("")}tokens(){return this.viterbi().map(u=>this.piece(u))}tokenIds(){return this.viterbi().map(u=>u.tokenId)}}class a{constructor(d,u,f,_,b){this.tokenId=d,this.nodeId=u,this.pos=f,this.length=_,this.score=b,this.prev=null,this.backtraceScore=0}clone(){const d=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return d.prev=this.prev,d.backtraceScore=this.backtraceScore,d}}class l{constructor(d){this.trie=this._buildTrie(d)}_buildTrie(d){var f;const u=Object.create(null);for(const _ of d){let b=u;for(let k=0;k<_.length;++k)b=b[f=_[k]]??(b[f]=Object.create(null));b.end=_}return u}split(d){const u=[],f=d.length;let _=0,b=0;for(;b_&&u.push(d.slice(_,b)),u.push(g),b+=g.length,_=b):++b}return _this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}},"./src/utils/devices.js":(e,r,t)=>{t.r(r),t.d(r,{DEVICE_TYPES:()=>s});const s=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(e,r,t)=>{t.r(r),t.d(r,{DATA_TYPES:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>n});var s=t("./src/env.js"),o=t("./src/utils/devices.js");const n=function(){let c;return async function(){if(c===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)c=!1;else try{c=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{c=!1}return c}}(),i=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[o.DEVICE_TYPES.wasm]:i.q8}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized",[i.q4]:"_q4",[i.q4f16]:"_q4f16",[i.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let o=function(...n){return o._call(...n)};return Object.setPrototypeOf(o,new.target.prototype)}_call(...o){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(e,r,t)=>{t.r(r),t.d(r,{MAX_EXTERNAL_DATA_CHUNKS:()=>a,getFile:()=>f,getModelFile:()=>M,getModelJSON:()=>v,getModelText:()=>$});var s=t("?7992"),o=t("?5af5"),n=t("./src/env.js"),i=t("./src/utils/core.js");const a=100,l={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class c{constructor(P){if(this.filePath=P,this.headers=new Headers,this.exists=s.existsSync(P),this.exists){this.status=200,this.statusText="OK";let O=s.statSync(P);this.headers.set("content-length",O.size.toString()),this.updateContentType();const L=s.createReadStream(P);this.body=new ReadableStream({start(G){L.on("data",K=>G.enqueue(K)),L.on("end",()=>G.close()),L.on("error",K=>G.error(K))},cancel(){L.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const P=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[P]??"application/octet-stream")}clone(){let P=new c(this.filePath);return P.exists=this.exists,P.status=this.status,P.statusText=this.statusText,P.headers=new Headers(this.headers),P}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const P=await s.promises.readFile(this.filePath);return new Blob([P],{type:this.headers.get("content-type")})}async text(){return await s.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function p(x,P=null,O=null){let L;try{L=new URL(x)}catch{return!1}return!(P&&!P.includes(L.protocol)||O&&!O.includes(L.hostname))}const d=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function u(x){return!(!d.test(x)||x.includes("..")||x.includes("--")||x.endsWith(".git")||x.endsWith(".ipynb"))}async function f(x){var P;if(n.env.useFS&&!p(x,["http:","https:","blob:"]))return new c(x instanceof URL?x.protocol==="file:"?x.pathname:x.toString():x);if(typeof process<"u"&&((P=process==null?void 0:process.release)==null?void 0:P.name)==="node"){const O=!!(js!=null&&js.TESTING_REMOTELY),L=n.env.version,G=new Headers;if(G.set("User-Agent",`transformers.js/${L}; is_ci/${O};`),p(x,["http:","https:"],["huggingface.co","hf.co"])){const R=(js==null?void 0:js.HF_TOKEN)??(js==null?void 0:js.HF_ACCESS_TOKEN);R&&G.set("Authorization",`Bearer ${R}`)}return fetch(x,{headers:G})}else return fetch(x)}const _={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function b(x,P,O){if(!O)return null;const L=_[x]??`Error (${x}) occurred while trying to load file`;throw Error(`${L}: "${P}".`)}class k{constructor(P){this.path=P}async match(P){let O=o.join(this.path,P),L=new c(O);if(L.exists)return L}async put(P,O,L=void 0){let G=o.join(this.path,P);try{const K=O.headers.get("Content-Length"),R=parseInt(K??"0");let te=0;await s.promises.mkdir(o.dirname(G),{recursive:!0});const H=s.createWriteStream(G),ee=O.body.getReader();for(;;){const{done:Z,value:ne}=await ee.read();if(Z)break;await new Promise((ue,j)=>{H.write(ne,F=>{if(F){j(F);return}ue()})}),te+=ne.length;const me=R?te/R*100:0;L==null||L({progress:me,loaded:te,total:R})}H.close()}catch(K){try{await s.promises.unlink(G)}catch{}throw K}}}async function g(x,...P){for(let O of P)try{let L=await x.match(O);if(L)return L}catch{continue}}async function M(x,P,O=!0,L={},G=!1){if(!n.env.allowLocalModels){if(L.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!n.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,i.dispatchCallback)(L.progress_callback,{status:"initiate",name:x,file:P});let K;if(!K&&n.env.useCustomCache){if(!n.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!n.env.customCache.match||!n.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");K=n.env.customCache}if(!K&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{K=await caches.open("transformers-cache")}catch(_e){console.warn("An error occurred while opening the browser cache:",_e)}}if(!K&&n.env.useFSCache){if(!n.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");K=new k(L.cache_dir??n.env.cacheDir)}const R=L.revision??"main",te=T(x,P),H=u(x),ee=H?T(n.env.localModelPath,te):te,Z=T(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",x).replaceAll("{revision}",encodeURIComponent(R)),P);let ne;const me=K instanceof k?R==="main"?te:T(x,R,P):Z;let ue=!1,j;K&&(j=await g(K,ee,me));const F=j!==void 0;if(j===void 0){if(n.env.allowLocalModels)if(p(te,["http:","https:"])){if(L.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${te}.`);if(!n.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${te}.`)}else try{j=await f(ee),ne=ee}catch(ie){console.warn(`Unable to load from local path "${ee}": "${ie}"`)}if(j===void 0||j.status===404){if(L.local_files_only||!n.env.allowRemoteModels){if(O)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${ee}".`);return null}if(!H)throw Error(`Local file missing at "${ee}" and download aborted due to invalid model ID "${x}".`);if(j=await f(Z),j.status!==200)return b(j.status,Z,O);ne=me}ue=K&&typeof Response<"u"&&j instanceof Response&&j.status===200}(0,i.dispatchCallback)(L.progress_callback,{status:"download",name:x,file:P});let U;if(!(n.apis.IS_NODE_ENV&&G)){let _e;L.progress_callback?F&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(_e=new Uint8Array(await j.arrayBuffer()),(0,i.dispatchCallback)(L.progress_callback,{status:"progress",name:x,file:P,progress:100,loaded:_e.length,total:_e.length})):_e=await y(j,ie=>{(0,i.dispatchCallback)(L.progress_callback,{status:"progress",name:x,file:P,...ie})}):_e=new Uint8Array(await j.arrayBuffer()),U=_e}if(ue&&ne&&await K.match(ne)===void 0&&(U?await K.put(ne,new Response(U,{headers:j.headers})).catch(_e=>{console.warn(`Unable to add response to browser cache: ${_e}.`)}):await K.put(ne,j,L.progress_callback)),(0,i.dispatchCallback)(L.progress_callback,{status:"done",name:x,file:P}),U){if(!n.apis.IS_NODE_ENV&&G)throw new Error("Cannot return path in a browser environment.");return U}if(j instanceof c)return j.filePath;const se=await(K==null?void 0:K.match(ne));if(se instanceof c)return se.filePath;if(se instanceof Response)return new Uint8Array(await se.arrayBuffer());if(typeof se=="string")return se;throw new Error("Unable to get model file path or buffer.")}async function $(x,P,O=!0,L={}){const G=await M(x,P,O,L,!1);return G===null?null:new TextDecoder("utf-8").decode(G)}async function v(x,P,O=!0,L={}){const G=await $(x,P,O,L);return G===null?{}:JSON.parse(G)}async function y(x,P){const O=x.headers.get("Content-Length");O===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let L=parseInt(O??"0"),G=new Uint8Array(L),K=0;const R=x.body.getReader();async function te(){const{done:H,value:ee}=await R.read();if(H)return;const Z=K+ee.length;if(Z>L){L=Z;const me=new Uint8Array(L);me.set(G),G=me}G.set(ee,K),K=Z;const ne=K/L*100;return P({progress:ne,loaded:K,total:L}),te()}return await te(),G}function T(...x){return x=x.map((P,O)=>(O&&(P=P.replace(new RegExp("^/"),"")),O!==x.length-1&&(P=P.replace(new RegExp("/$"),"")),P)),x.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>_,load_image:()=>b});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),n=t("./src/env.js"),i=t("./src/utils/tensor.js"),a=t("?2b25");let l,c,p;const d=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;if(d)l=(k,g)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(k,g)},p=self.createImageBitmap,c=self.ImageData;else if(a)p=async k=>{const M=(await k.metadata()).channels,{data:$,info:v}=await k.rotate().raw().toBuffer({resolveWithObject:!0}),y=new _(new Uint8ClampedArray($),v.width,v.height,v.channels);return M!==void 0&&M!==v.channels&&y.convert(M),y};else throw new Error("Unable to load image processing library.");const u={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},f=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _{constructor(g,M,$,v){this.data=g,this.width=M,this.height=$,this.channels=v}get size(){return[this.width,this.height]}static async read(g){if(g instanceof _)return g;if(typeof g=="string"||g instanceof URL)return await this.fromURL(g);if(g instanceof Blob)return await this.fromBlob(g);if(typeof HTMLCanvasElement<"u"&&g instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&g instanceof OffscreenCanvas)return this.fromCanvas(g);throw new Error(`Unsupported input type: ${typeof g}`)}static fromCanvas(g){if(!d)throw new Error("fromCanvas() is only supported in browser environments.");const $=g.getContext("2d").getImageData(0,0,g.width,g.height).data;return new _($,g.width,g.height,4)}static async fromURL(g){const M=await(0,o.getFile)(g);if(M.status!==200)throw new Error(`Unable to read image from "${g}" (${M.status} ${M.statusText})`);const $=await M.blob();return this.fromBlob($)}static async fromBlob(g){if(d){const M=await p(g),$=l(M.width,M.height).getContext("2d");return $.drawImage(M,0,0),new this($.getImageData(0,0,M.width,M.height).data,M.width,M.height,4)}else{const M=a(await g.arrayBuffer());return await p(M)}}static fromTensor(g,M="CHW"){if(g.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${g.dims.length} dimensions.`);if(M==="CHW")g=g.transpose(1,2,0);else if(M!=="HWC")throw new Error(`Unsupported channel format: ${M}`);if(!(g.data instanceof Uint8ClampedArray||g.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${g.type}`);switch(g.dims[2]){case 1:case 2:case 3:case 4:return new _(g.data,g.dims[1],g.dims[0],g.dims[2]);default:throw new Error(`Unsupported number of channels: ${g.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const g=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let M=0,$=0;M=0?P=$:L=-$,v>=0?O=v:G=-v,x.drawImage(T,P,O,g,M,L,G,g,M),new _(x.getImageData(0,0,g,M).data,g,M,4).convert(y)}else{let y=this.toSharp();if($>=0&&v>=0)y=y.extract({left:Math.floor($),top:Math.floor(v),width:g,height:M});else if($<=0&&v<=0){const T=Math.floor(-v),x=Math.floor(-$);y=y.extend({top:T,left:x,right:g-this.width-x,bottom:M-this.height-T})}else{let T=[0,0],x=0;v<0?(T[0]=Math.floor(-v),T[1]=M-this.height-T[0]):x=Math.floor(v);let P=[0,0],O=0;$<0?(P[0]=Math.floor(-$),P[1]=g-this.width-P[0]):O=Math.floor($),y=y.extend({top:T[0],bottom:T[1],left:P[0],right:P[1]}).extract({left:O,top:x,width:g,height:M})}return await p(y)}}async toBlob(g="image/png",M=1){if(!d)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:g,quality:M})}toTensor(g="CHW"){let M=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(g!=="HWC")if(g==="CHW")M=M.permute(2,0,1);else throw new Error(`Unsupported channel format: ${g}`);return M}toCanvas(){if(!d)throw new Error("toCanvas() is only supported in browser environments.");const g=this.clone().rgba(),M=l(g.width,g.height),$=new c(g.data,g.width,g.height);return M.getContext("2d").putImageData($,0,0),M}split(){const{data:g,width:M,height:$,channels:v}=this,y=g.constructor,T=g.length/v,x=Array.from({length:v},()=>new y(T));for(let P=0;Pnew _(P,M,$,1))}_update(g,M,$,v=null){return this.data=g,this.width=M,this.height=$,v!==null&&(this.channels=v),this}clone(){return new _(this.data.slice(),this.width,this.height,this.channels)}convert(g){if(this.channels===g)return this;switch(g){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(g){if(d){if(n.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const M=g.split(".").pop().toLowerCase(),$=f.get(M)??"image/png",v=await this.toBlob($);(0,s.saveBlob)(g,v)}else{if(n.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(g);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(d)throw new Error("toSharp() is only supported in server-side environments.");return a(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const b=_.read.bind(_)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>b,bankers_round:()=>M,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>$,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>c,max:()=>d,medianFilter:()=>k,min:()=>p,permute_data:()=>o,round:()=>g,softmax:()=>n});function s(v,[y,T,x],[P,O],L="bilinear",G=!1){const K=O/x,R=P/T,te=new v.constructor(P*O*y),H=T*x,ee=P*O;for(let Z=0;Z=0;--G)P[G]=K,x[G]=y[T[G]],K*=x[G];const O=T.map((G,K)=>P[T.indexOf(K)]),L=new v.constructor(v.length);for(let G=0;G=0;--R)K+=te%y[R]*O[R],te=Math.floor(te/y[R]);L[K]=v[G]}return[L,x]}function n(v){const y=d(v)[0],T=v.map(O=>Math.exp(O-y)),x=T.reduce((O,L)=>O+L,0);return T.map(O=>O/x)}function i(v){const y=d(v)[0];let T=0;for(let O=0;OO-y-x)}function a(v,y){let T=0;for(let x=0;xy+T*T,0))}function p(v){if(v.length===0)throw Error("Array must not be empty");let y=v[0],T=0;for(let x=1;xy&&(y=v[x],T=x);return[y,T]}function u(v){return v>0&&(v&v-1)===0}class f{constructor(y){if(this.size=y|0,this.size<=1||!u(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=y<<1,this.table=new Float64Array(this.size*2);for(let x=0;xx;x<<=1)++T;this._width=T%2===0?T-1:T,this._bitrev=new Int32Array(1<>>P&3)<>>1);for(let P=0;P>>1]=y[P];return x}toComplexArray(y,T){const x=T||this.createComplexArray();for(let P=0;P>>1],x[P+1]=0;return x}transform(y,T){if(y===T)throw new Error("Input and output buffers must be different");this._transform4(y,T,1)}realTransform(y,T){if(y===T)throw new Error("Input and output buffers must be different");this._realTransform4(y,T,1)}inverseTransform(y,T){if(y===T)throw new Error("Input and output buffers must be different");this._transform4(y,T,-1);for(let x=0;x>=2;L>=2;L>>=2){G=P/L<<1;const ee=G>>>2;for(K=0;K>>1,L>>>1)}else for(K=0,R=0;K>>1,L>>>1,x)}const H=this.table;for(L>>=2;L>=2;L>>=2){G=P/L<<1;const Z=G>>>1,ne=Z>>>1,me=ne>>>1;for(K=0;K>>1;for(let Z=2;Z>1;++te){const H=(te+1-y)**2/2,ee=Math.sqrt(K**2+R**2)**H,Z=H*Math.atan2(R,K),ne=2*te;O[ne]=ee*Math.cos(Z),O[ne+1]=ee*Math.sin(Z),L[ne]=O[ne],L[ne+1]=-O[ne+1]}this._slicedChirpBuffer=O.subarray(T,x),this._f=new f(P>>1),this._f.transform(this._chirpBuffer,L)}_transform(y,T,x){const P=this._buffer1,O=this._buffer2,L=this._outBuffer1,G=this._outBuffer2,K=this._chirpBuffer,R=this._slicedChirpBuffer,te=this._a;if(x)for(let H=0;H>1,ne=T[Z];P[H]=ne*R[H],P[ee]=ne*R[ee]}else for(let H=0;H=v.length&&(K=2*(v.length-1)-K),x[L++]=v[K]}x.sort(),T[O]=x[P]}return T}function g(v,y){const T=Math.pow(10,y);return Math.round(v*T)/T}function M(v){const y=Math.round(v);return Math.abs(v)%1===.5?y%2===0?y:y-1:y}function $(v){const y=v.length,T=v[0].length,x=[y+1,T+1],P=Array.from({length:x[0]},()=>Array(x[1]).fill(1/0));P[0][0]=0;const O=Array.from({length:x[0]},()=>Array(x[1]).fill(-1));for(let te=1;te0||G>0;)switch(K.push(L-1),R.push(G-1),O[L][G]){case 0:--L,--G;break;case 1:--L;break;case 2:--G;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${L}, ${G}]. Please file a bug report.`)}return K.reverse(),R.reverse(),[K,R]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>T,full:()=>R,full_like:()=>te,interpolate:()=>p,interpolate_4d:()=>d,layer_norm:()=>M,matmul:()=>u,mean:()=>L,mean_pooling:()=>g,ones:()=>H,ones_like:()=>ee,permute:()=>c,quantize_embeddings:()=>ue,rand:()=>me,rfft:()=>f,slice:()=>k,stack:()=>x,std_mean:()=>O,topk:()=>_,zeros:()=>Z,zeros_like:()=>ne});var s=t("./src/utils/maths.js"),o=t("./src/backends/onnx.js"),n=t("./src/ops/registry.js");const i=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class a{constructor(...F){J(this,"ort_tensor");return(0,o.isONNXTensor)(F[0])?this.ort_tensor=F[0]:this.ort_tensor=new o.Tensor(F[0],F[1],F[2]),new Proxy(this,{get:(U,se)=>{if(typeof se=="string"){let _e=Number(se);if(Number.isInteger(_e))return U._getitem(_e)}return U[se]},set:(U,se,_e)=>U[se]=_e})}get dims(){return this.ort_tensor.dims}set dims(F){this.ort_tensor.dims=F}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[F,...U]=this.dims;if(U.length>0){const se=U.reduce((_e,ie)=>_e*ie);for(let _e=0;_e0){const _e=se.reduce((ie,ve)=>ie*ve);return this._subarray(F,_e,se)}else return new a(this.type,[this.data[F]],se)}indexOf(F){const U=this.data;for(let se=0;sebe)throw new Error(`Invalid slice: ${ae}`);const ke=[Math.max(W,0),Math.min(be,this.dims[X])];se.push(ke),U.push(ke[1]-ke[0])}else throw new Error(`Invalid slice: ${ae}`)}const _e=se.map(([X,ae])=>ae-X),ie=_e.reduce((X,ae)=>X*ae),ve=this.data,ze=new ve.constructor(ie),Ge=this.stride();let Ie=!0;for(let X=1;X<_e.length;++X)if(se[X][0]!==0||se[X][1]!==this.dims[X]){Ie=!1;break}if(Ie){const X=se[0][0]*Ge[0],ae=se[0][1]*Ge[0];if(ArrayBuffer.isView(ve))ze.set(ve.subarray(X,ae));else if(Array.isArray(ve)){const W=ve.slice(X,ae);for(let be=0;be=0;--W){const ke=_e[W];ae+=(be%ke+se[W][0])*Ge[W],be=Math.floor(be/ke)}ze[X]=ve[ae]}return new a(this.type,ze,U)}permute(...F){return c(this,F)}transpose(...F){return this.permute(...F)}sum(F=null,U=!1){return this.norm(1,F,U)}norm(F="fro",U=null,se=!1){if(F==="fro")F=2;else if(typeof F=="string")throw Error(`Unsupported norm: ${F}`);const _e=this.data,ie=(Ie,X)=>Ie+X**F;if(U===null){const Ie=_e.reduce(ie,0)**(1/F);return new a(this.type,[Ie],[])}const[ve,ze,Ge]=P(ie,this,U,se);if(F!==1)for(let Ie=0;Ie=0;--Ge){const ae=this.dims[Ge];if(Ge!==U){const W=Ie%ae;ze+=W*X,X*=this.dims[Ge]}Ie=Math.floor(Ie/ae)}_e[ve]/=ie[ze]}return this}normalize(F=2,U=1){return this.clone().normalize_(F,U)}stride(){return G(this.dims)}squeeze(F=null){return new a(this.type,this.data,$(this.dims,F))}squeeze_(F=null){return this.dims=$(this.dims,F),this}unsqueeze(F=null){return new a(this.type,this.data,v(this.dims,F))}unsqueeze_(F=null){return this.dims=v(this.dims,F),this}flatten_(F=0,U=-1){U=(U+this.dims.length)%this.dims.length;let se=this.dims.slice(0,F),_e=this.dims.slice(F,U+1),ie=this.dims.slice(U+1);return this.dims=[...se,_e.reduce((ve,ze)=>ve*ze,1),...ie],this}flatten(F=0,U=-1){return this.clone().flatten_(F,U)}view(...F){let U=-1;for(let _e=0;_eze!==U?ie*ve:ie,1);F[U]=se.length/_e}return new a(this.type,se,F)}neg_(){const F=this.data;for(let U=0;UF?1:0;return new a("bool",U,this.dims)}lt(F){const U=new Uint8Array(this.data.length),se=this.data;for(let _e=0;_eMath.min(ve,ze),this,F,U,1/0);return new a(se,_e,ie)}max(F=null,U=!1){if(F===null){const ve=(0,s.max)(this.data)[0];return new a(this.type,[ve],[])}const[se,_e,ie]=P((ve,ze)=>Math.max(ve,ze),this,F,U,-1/0);return new a(se,_e,ie)}argmin(F=null,U=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const se=(0,s.min)(this.data)[1];return new a("int64",[BigInt(se)],[])}argmax(F=null,U=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const se=(0,s.max)(this.data)[1];return new a("int64",[BigInt(se)],[])}to(F){if(this.type===F)return this;if(!i.hasOwnProperty(F))throw new Error(`Unsupported type: ${F}`);let U;const se=["int64","uint64"].includes(this.type),_e=["int64","uint64"].includes(F);return se&&!_e?U=Number:!se&&_e&&(U=BigInt),new a(F,i[F].from(this.data,U),this.dims)}}function l(j,F){const U=j.length,se=F.reduce((ie,ve)=>ie*ve);if(U!==se)throw Error(`cannot reshape array of size ${U} into shape (${F})`);let _e=j;for(let ie=F.length-1;ie>=0;ie--)_e=_e.reduce((ve,ze)=>{let Ge=ve[ve.length-1];return Ge.lengthnew a("int64",j,[j.length]);async function k(j,F,U,se,_e){return await(await n.TensorOpRegistry.slice)({x:j,s:b(F),e:b(U),a:b(se),t:b(_e??new Array(se.length).fill(1))})}function g(j,F){const U=j.data,se=F.data,_e=[j.dims[0],j.dims[2]],ie=new U.constructor(_e[0]*_e[1]),[ve,ze,Ge]=j.dims;let Ie=0;for(let X=0;XU!==1):typeof F=="number"?j[F]===1&&j.splice(F,1):Array.isArray(F)&&(j=j.filter((U,se)=>U!==1||!F.includes(se))),j}function v(j,F){return F=y(F,j.length+1),j=j.slice(),j.splice(F,0,1),j}function y(j,F,U=null,se=!0){if(j<-F||j>=F){if(se)throw new Error(`IndexError: index ${j} is out of bounds for dimension${U===null?"":" "+U} with size ${F}`);return j<-F?0:F}return j<0&&(j=(j%F+F)%F),j}function T(j,F=0){F=y(F,j[0].dims.length);const U=j[0].dims.slice();U[F]=j.reduce((ve,ze)=>ve+ze.dims[F],0);const se=U.reduce((ve,ze)=>ve*ze,1),_e=new j[0].data.constructor(se),ie=j[0].type;if(F===0){let ve=0;for(const ze of j){const Ge=ze.data;_e.set(Ge,ve),ve+=Ge.length}}else{let ve=0;for(let ze=0;ze=0;--W){const Ee=Ie[W];let Me=be%Ee;W===F&&(Me+=ve),ae+=Me*ke,ke*=U[W],be=Math.floor(be/Ee)}_e[ae]=Ge[X]}ve+=Ie[F]}}return new a(ie,_e,U)}function x(j,F=0){return T(j.map(U=>U.unsqueeze(F)),F)}function P(j,F,U=null,se=!1,_e=null){const ie=F.data,ve=F.dims;U=y(U,ve.length);const ze=ve.slice();ze[U]=1;const Ge=new ie.constructor(ie.length/ve[U]);_e!==null&&Ge.fill(_e);for(let Ie=0;Ie=0;--ae){const ke=ve[ae];if(ae!==U){const Ee=W%ke;X+=Ee*be,be*=ze[ae]}W=Math.floor(W/ke)}Ge[X]=j(Ge[X],ie[Ie],Ie,X)}return se||ze.splice(U,1),[F.type,Ge,ze]}function O(j,F=null,U=1,se=!1){const _e=j.data,ie=j.dims;if(F===null){const be=_e.reduce((Se,we)=>Se+we,0)/_e.length,ke=Math.sqrt(_e.reduce((Se,we)=>Se+(we-be)**2,0)/(_e.length-U)),Ee=new a(j.type,[be],[]);return[new a(j.type,[ke],[]),Ee]}F=y(F,ie.length);const ve=L(j,F,se),ze=ve.data,[Ge,Ie,X]=P((W,be,ke,Ee)=>W+(be-ze[Ee])**2,j,F,se);for(let W=0;WIe+X,0);return new a(j.type,[Ge/_e.length],[])}F=y(F,se.length);const[ie,ve,ze]=P((Ge,Ie)=>Ge+Ie,j,F,U);if(se[F]!==1)for(let Ge=0;Ge=0;--U)F[U]=se,se*=j[U];return F}function K(j,F,U,se){const _e=j.reduce((ie,ve)=>ie*ve,1);return new a(U,new se(_e).fill(F),j)}function R(j,F){let U,se;if(typeof F=="number")U="float32",se=Float32Array;else if(typeof F=="bigint")U="int64",se=BigInt64Array;else if(typeof F=="boolean")U="bool",se=Uint8Array;else throw new Error(`Unsupported data type: ${typeof F}`);return K(j,F,U,se)}function te(j,F){return R(j.dims,F)}function H(j){return K(j,1n,"int64",BigInt64Array)}function ee(j){return H(j.dims)}function Z(j){return K(j,0n,"int64",BigInt64Array)}function ne(j){return Z(j.dims)}function me(j){const F=j.reduce((U,se)=>U*se,1);return new a("float32",Float32Array.from({length:F},()=>Math.random()),j)}function ue(j,F){if(j.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(j.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(F))throw new Error("The precision must be either 'binary' or 'ubinary'");const U=F==="binary",se=U?"int8":"uint8",_e=U?Int8Array:Uint8Array,ie=j.data,ve=new _e(ie.length/8);for(let ze=0;ze0?1:0,Ie=Math.floor(ze/8),X=ze%8;ve[Ie]|=Ge<<7-X,U&&X===0&&(ve[Ie]-=128)}return new a(se,ve,[j.dims[0],j.dims[1]/8])}},"./src/utils/video.js":(e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>i,RawVideoFrame:()=>n,load_video:()=>a});var s=t("./src/utils/image.js"),o=t("./src/env.js");class n{constructor(c,p){this.image=c,this.timestamp=p}}class i{constructor(c,p){c.length>0&&c[0]instanceof s.RawImage&&(c=c.map((d,u)=>new n(d,(u+1)/(c.length+1)*p))),this.frames=c,this.duration=p}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function a(l,{num_frames:c=null,fps:p=null}={}){if(!o.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(c==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const d=[],u=document.createElement("video");if(u.crossOrigin="anonymous",u.muted=!0,typeof l=="string")u.src=l;else if(l instanceof Blob)u.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)u.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise($=>u.onloadedmetadata=$),u.seekable.start(0)===u.seekable.end(0)){const v=await(await fetch(u.src)).blob();u.src=URL.createObjectURL(v),await new Promise(y=>u.onloadedmetadata=y)}const f=u.duration;let _,b;c!=null?(_=c,b=c===1?0:f/(c-1)):(b=1/p,_=Math.floor(f/b));let k=[];for(let $=0;$<_;++$)k.push(c===1?f/2:$*b);const g=document.createElement("canvas");g.width=u.videoWidth,g.height=u.videoHeight;const M=g.getContext("2d",{willReadFrequently:!0});for(const $ of k){u.currentTime=$,await new Promise(x=>{u.onseeked=x}),M.drawImage(u,0,0,g.width,g.height);const v=M.getImageData(0,0,g.width,g.height),y=new s.RawImage(v.data,g.width,g.height,4),T=new n(y,$);d.push(T)}return u.remove(),new i(d,f)}}},Zg={};function Vt(e){var r=Zg[e];if(r!==void 0)return r.exports;var t=Zg[e]={exports:{}};return Zx[e](t,t.exports,Vt),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;Vt.t=function(t,s){if(s&1&&(t=this(t)),s&8||typeof t=="object"&&t&&(s&4&&t.__esModule||s&16&&typeof t.then=="function"))return t;var o=Object.create(null);Vt.r(o);var n={};r=r||[null,e({}),e([]),e(e)];for(var i=s&2&&t;typeof i=="object"&&!~r.indexOf(i);i=e(i))Object.getOwnPropertyNames(i).forEach(a=>n[a]=()=>t[a]);return n.default=()=>t,Vt.d(o,n),o}})(),Vt.d=(e,r)=>{for(var t in r)Vt.o(r,t)&&!Vt.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},Vt.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),Vt.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var m={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/Vt.r(m),Vt.d(m,{ASTFeatureExtractor:()=>d.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,ArceeForCausalLM:()=>t.ArceeForCausalLM,ArceeModel:()=>t.ArceeModel,ArceePreTrainedModel:()=>t.ArceePreTrainedModel,AudioClassificationPipeline:()=>r.AudioClassificationPipeline,AutoConfig:()=>o.AutoConfig,AutoFeatureExtractor:()=>u.AutoFeatureExtractor,AutoImageProcessor:()=>b.AutoImageProcessor,AutoModel:()=>t.AutoModel,AutoModelForAudioClassification:()=>t.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>t.AutoModelForAudioFrameClassification,AutoModelForAudioTextToText:()=>t.AutoModelForAudioTextToText,AutoModelForCTC:()=>t.AutoModelForCTC,AutoModelForCausalLM:()=>t.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>t.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>t.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>t.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>t.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>t.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>t.AutoModelForImageSegmentation,AutoModelForImageTextToText:()=>t.AutoModelForImageTextToText,AutoModelForImageToImage:()=>t.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>t.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>t.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>t.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>t.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>t.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>t.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>t.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>t.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>t.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>t.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>t.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>t.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>t.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>t.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>t.AutoModelForVision2Seq,AutoModelForXVector:()=>t.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>t.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>M.AutoProcessor,AutoTokenizer:()=>s.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>r.AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline:()=>r.BackgroundRemovalPipeline,BartForConditionalGeneration:()=>t.BartForConditionalGeneration,BartForSequenceClassification:()=>t.BartForSequenceClassification,BartModel:()=>t.BartModel,BartPretrainedModel:()=>t.BartPretrainedModel,BartTokenizer:()=>s.BartTokenizer,BaseModelOutput:()=>t.BaseModelOutput,BaseStreamer:()=>$.BaseStreamer,BeitFeatureExtractor:()=>_.BeitFeatureExtractor,BeitForImageClassification:()=>t.BeitForImageClassification,BeitModel:()=>t.BeitModel,BeitPreTrainedModel:()=>t.BeitPreTrainedModel,BertForMaskedLM:()=>t.BertForMaskedLM,BertForQuestionAnswering:()=>t.BertForQuestionAnswering,BertForSequenceClassification:()=>t.BertForSequenceClassification,BertForTokenClassification:()=>t.BertForTokenClassification,BertModel:()=>t.BertModel,BertPreTrainedModel:()=>t.BertPreTrainedModel,BertTokenizer:()=>s.BertTokenizer,BitImageProcessor:()=>_.BitImageProcessor,BlenderbotForConditionalGeneration:()=>t.BlenderbotForConditionalGeneration,BlenderbotModel:()=>t.BlenderbotModel,BlenderbotPreTrainedModel:()=>t.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>t.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>t.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>t.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>s.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>s.BlenderbotTokenizer,BloomForCausalLM:()=>t.BloomForCausalLM,BloomModel:()=>t.BloomModel,BloomPreTrainedModel:()=>t.BloomPreTrainedModel,BloomTokenizer:()=>s.BloomTokenizer,CLIPFeatureExtractor:()=>_.CLIPFeatureExtractor,CLIPImageProcessor:()=>_.CLIPImageProcessor,CLIPModel:()=>t.CLIPModel,CLIPPreTrainedModel:()=>t.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>t.CLIPSegForImageSegmentation,CLIPSegModel:()=>t.CLIPSegModel,CLIPSegPreTrainedModel:()=>t.CLIPSegPreTrainedModel,CLIPTextModel:()=>t.CLIPTextModel,CLIPTextModelWithProjection:()=>t.CLIPTextModelWithProjection,CLIPTokenizer:()=>s.CLIPTokenizer,CLIPVisionModel:()=>t.CLIPVisionModel,CLIPVisionModelWithProjection:()=>t.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>t.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>t.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>t.CamembertForSequenceClassification,CamembertForTokenClassification:()=>t.CamembertForTokenClassification,CamembertModel:()=>t.CamembertModel,CamembertPreTrainedModel:()=>t.CamembertPreTrainedModel,CamembertTokenizer:()=>s.CamembertTokenizer,CausalLMOutput:()=>t.CausalLMOutput,CausalLMOutputWithPast:()=>t.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>_.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>d.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>y.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>s.CodeGenTokenizer,CodeLlamaTokenizer:()=>s.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>s.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>s.ConvBertTokenizer,ConvNextFeatureExtractor:()=>_.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>_.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DFineForObjectDetection:()=>t.DFineForObjectDetection,DFineModel:()=>t.DFineModel,DFinePreTrainedModel:()=>t.DFinePreTrainedModel,DPTFeatureExtractor:()=>_.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>_.DPTImageProcessor,DPTModel:()=>t.DPTModel,DPTPreTrainedModel:()=>t.DPTPreTrainedModel,DacDecoderModel:()=>t.DacDecoderModel,DacDecoderOutput:()=>t.DacDecoderOutput,DacEncoderModel:()=>t.DacEncoderModel,DacEncoderOutput:()=>t.DacEncoderOutput,DacFeatureExtractor:()=>d.DacFeatureExtractor,DacModel:()=>t.DacModel,DacPreTrainedModel:()=>t.DacPreTrainedModel,DataTypeMap:()=>l.DataTypeMap,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>s.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>s.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>_.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>_.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>r.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>_.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>_.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>s.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>r.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>_.DonutFeatureExtractor,DonutImageProcessor:()=>_.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>_.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>s.ElectraTokenizer,EncodecFeatureExtractor:()=>d.EncodecFeatureExtractor,EosTokenCriteria:()=>v.EosTokenCriteria,Ernie4_5_ForCausalLM:()=>t.Ernie4_5_ForCausalLM,Ernie4_5_Model:()=>t.Ernie4_5_Model,Ernie4_5_PretrainedModel:()=>t.Ernie4_5_PretrainedModel,Ernie4_5_Tokenizer:()=>s.Ernie4_5_Tokenizer,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>s.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>c.FFT,FalconForCausalLM:()=>t.FalconForCausalLM,FalconModel:()=>t.FalconModel,FalconPreTrainedModel:()=>t.FalconPreTrainedModel,FalconTokenizer:()=>s.FalconTokenizer,FastViTForImageClassification:()=>t.FastViTForImageClassification,FastViTModel:()=>t.FastViTModel,FastViTPreTrainedModel:()=>t.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>r.FeatureExtractionPipeline,FeatureExtractor:()=>p.FeatureExtractor,FillMaskPipeline:()=>r.FillMaskPipeline,Florence2ForConditionalGeneration:()=>t.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>t.Florence2PreTrainedModel,Florence2Processor:()=>g.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>y.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>y.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>t.GLPNForDepthEstimation,GLPNModel:()=>t.GLPNModel,GLPNPreTrainedModel:()=>t.GLPNPreTrainedModel,GPT2LMHeadModel:()=>t.GPT2LMHeadModel,GPT2Model:()=>t.GPT2Model,GPT2PreTrainedModel:()=>t.GPT2PreTrainedModel,GPT2Tokenizer:()=>s.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>t.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>t.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>t.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>t.GPTJForCausalLM,GPTJModel:()=>t.GPTJModel,GPTJPreTrainedModel:()=>t.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>t.GPTNeoForCausalLM,GPTNeoModel:()=>t.GPTNeoModel,GPTNeoPreTrainedModel:()=>t.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>t.GPTNeoXForCausalLM,GPTNeoXModel:()=>t.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>t.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>s.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>t.Gemma2ForCausalLM,Gemma2Model:()=>t.Gemma2Model,Gemma2PreTrainedModel:()=>t.Gemma2PreTrainedModel,Gemma3ForCausalLM:()=>t.Gemma3ForCausalLM,Gemma3Model:()=>t.Gemma3Model,Gemma3PreTrainedModel:()=>t.Gemma3PreTrainedModel,Gemma3nAudioFeatureExtractor:()=>d.Gemma3nAudioFeatureExtractor,Gemma3nForConditionalGeneration:()=>t.Gemma3nForConditionalGeneration,Gemma3nPreTrainedModel:()=>t.Gemma3nPreTrainedModel,Gemma3nProcessor:()=>g.Gemma3nProcessor,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>s.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>g.GroundingDinoProcessor,GroupViTModel:()=>t.GroupViTModel,GroupViTPreTrainedModel:()=>t.GroupViTPreTrainedModel,HeliumForCausalLM:()=>t.HeliumForCausalLM,HeliumModel:()=>t.HeliumModel,HeliumPreTrainedModel:()=>t.HeliumPreTrainedModel,HerbertTokenizer:()=>s.HerbertTokenizer,HieraForImageClassification:()=>t.HieraForImageClassification,HieraModel:()=>t.HieraModel,HieraPreTrainedModel:()=>t.HieraPreTrainedModel,HubertForCTC:()=>t.HubertForCTC,HubertForSequenceClassification:()=>t.HubertForSequenceClassification,HubertModel:()=>t.HubertModel,HubertPreTrainedModel:()=>t.HubertPreTrainedModel,IJepaForImageClassification:()=>t.IJepaForImageClassification,IJepaModel:()=>t.IJepaModel,IJepaPreTrainedModel:()=>t.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>t.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>_.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>g.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>d.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>f.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>v.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>_.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>g.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,Lfm2ForCausalLM:()=>t.Lfm2ForCausalLM,Lfm2Model:()=>t.Lfm2Model,Lfm2PreTrainedModel:()=>t.Lfm2PreTrainedModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>_.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LlavaProcessor:()=>g.LlavaProcessor,LlavaQwen2ForCausalLM:()=>t.LlavaQwen2ForCausalLM,LogitsProcessor:()=>y.LogitsProcessor,LogitsProcessorList:()=>y.LogitsProcessorList,LogitsWarper:()=>y.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,Mask2FormerImageProcessor:()=>_.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>_.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>_.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>v.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>g.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>y.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>y.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>_.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>_.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>_.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>_.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>_.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>_.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>_.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>_.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>_.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>_.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertDecoderForCausalLM:()=>t.ModernBertDecoderForCausalLM,ModernBertDecoderModel:()=>t.ModernBertDecoderModel,ModernBertDecoderPreTrainedModel:()=>t.ModernBertDecoderPreTrainedModel,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>d.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>g.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NeoBertForMaskedLM:()=>t.NeoBertForMaskedLM,NeoBertForQuestionAnswering:()=>t.NeoBertForQuestionAnswering,NeoBertForSequenceClassification:()=>t.NeoBertForSequenceClassification,NeoBertForTokenClassification:()=>t.NeoBertForTokenClassification,NeoBertModel:()=>t.NeoBertModel,NeoBertPreTrainedModel:()=>t.NeoBertPreTrainedModel,NllbTokenizer:()=>s.NllbTokenizer,NoBadWordsLogitsProcessor:()=>y.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>y.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>_.NougatImageProcessor,NougatTokenizer:()=>s.NougatTokenizer,OPTForCausalLM:()=>t.OPTForCausalLM,OPTModel:()=>t.OPTModel,OPTPreTrainedModel:()=>t.OPTPreTrainedModel,ObjectDetectionPipeline:()=>r.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>t.Olmo2ForCausalLM,Olmo2Model:()=>t.Olmo2Model,Olmo2PreTrainedModel:()=>t.Olmo2PreTrainedModel,OlmoForCausalLM:()=>t.OlmoForCausalLM,OlmoModel:()=>t.OlmoModel,OlmoPreTrainedModel:()=>t.OlmoPreTrainedModel,OpenELMForCausalLM:()=>t.OpenELMForCausalLM,OpenELMModel:()=>t.OpenELMModel,OpenELMPreTrainedModel:()=>t.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>_.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>_.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>g.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>_.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>g.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>_.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>g.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>o.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>k.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>_.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>d.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>g.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>t.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>r.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>t.Qwen2ForCausalLM,Qwen2Model:()=>t.Qwen2Model,Qwen2PreTrainedModel:()=>t.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>s.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>t.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>_.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>g.Qwen2VLProcessor,Qwen3ForCausalLM:()=>t.Qwen3ForCausalLM,Qwen3Model:()=>t.Qwen3Model,Qwen3PreTrainedModel:()=>t.Qwen3PreTrainedModel,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>_.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>n.RawAudio,RawImage:()=>i.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>y.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>s.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>s.RobertaTokenizer,SamImageProcessor:()=>_.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>g.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>_.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>_.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>_.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>s.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SmolLM3ForCausalLM:()=>t.SmolLM3ForCausalLM,SmolLM3Model:()=>t.SmolLM3Model,SmolLM3PreTrainedModel:()=>t.SmolLM3PreTrainedModel,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>_.SmolVLMImageProcessor,SmolVLMProcessor:()=>g.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>d.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>g.SpeechT5Processor,SpeechT5Tokenizer:()=>s.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>s.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>v.StoppingCriteria,StoppingCriteriaList:()=>v.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>y.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>_.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinForSemanticSegmentation:()=>t.SwinForSemanticSegmentation,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>s.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>y.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>$.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>y.TopKLogitsWarper,TopPLogitsWarper:()=>y.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>g.UltravoxProcessor,UniSpeechForCTC:()=>t.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>t.UniSpeechForSequenceClassification,UniSpeechModel:()=>t.UniSpeechModel,UniSpeechPreTrainedModel:()=>t.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>t.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>t.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>t.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>t.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>t.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>g.VLChatProcessor,VLMImageProcessor:()=>_.VLMImageProcessor,ViTFeatureExtractor:()=>_.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>_.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>_.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>_.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,VoxtralForConditionalGeneration:()=>t.VoxtralForConditionalGeneration,VoxtralProcessor:()=>g.VoxtralProcessor,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>s.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>d.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>g.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>g.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>d.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>d.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>g.WhisperProcessor,WhisperTextStreamer:()=>$.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>y.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>s.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>s.XLMRobertaTokenizer,XLMTokenizer:()=>s.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>_.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>_.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>r.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>r.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>r.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>r.ZeroShotObjectDetectionPipeline,bankers_round:()=>c.bankers_round,cat:()=>l.cat,cos_sim:()=>c.cos_sim,dot:()=>c.dot,dynamic_time_warping:()=>c.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getCacheShapes:()=>o.getCacheShapes,hamming:()=>n.hamming,hanning:()=>n.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>c.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>i.load_image,load_video:()=>a.load_video,log_softmax:()=>c.log_softmax,magnitude:()=>c.magnitude,matmul:()=>l.matmul,max:()=>c.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>c.medianFilter,mel_filter_bank:()=>n.mel_filter_bank,min:()=>c.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>c.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,read_audio:()=>n.read_audio,rfft:()=>l.rfft,round:()=>c.round,slice:()=>l.slice,softmax:()=>c.softmax,spectrogram:()=>n.spectrogram,stack:()=>l.stack,std_mean:()=>l.std_mean,topk:()=>l.topk,window_function:()=>n.window_function,zeros:()=>l.zeros,zeros_like:()=>l.zeros_like});var e=Vt("./src/env.js"),r=Vt("./src/pipelines.js"),t=Vt("./src/models.js"),s=Vt("./src/tokenizers.js"),o=Vt("./src/configs.js"),n=Vt("./src/utils/audio.js"),i=Vt("./src/utils/image.js"),a=Vt("./src/utils/video.js"),l=Vt("./src/utils/tensor.js"),c=Vt("./src/utils/maths.js"),p=Vt("./src/base/feature_extraction_utils.js"),d=Vt("./src/models/feature_extractors.js"),u=Vt("./src/models/auto/feature_extraction_auto.js"),f=Vt("./src/base/image_processors_utils.js"),_=Vt("./src/models/image_processors.js"),b=Vt("./src/models/auto/image_processing_auto.js"),k=Vt("./src/base/processing_utils.js"),g=Vt("./src/models/processors.js"),M=Vt("./src/models/auto/processing_auto.js"),$=Vt("./src/generation/streamers.js"),v=Vt("./src/generation/stopping_criteria.js"),y=Vt("./src/generation/logits_process.js")})(),m.ASTFeatureExtractor,m.ASTForAudioClassification,m.ASTModel,m.ASTPreTrainedModel,m.AlbertForMaskedLM,m.AlbertForQuestionAnswering,m.AlbertForSequenceClassification,m.AlbertModel,m.AlbertPreTrainedModel,m.AlbertTokenizer,m.ArceeForCausalLM,m.ArceeModel,m.ArceePreTrainedModel,m.AudioClassificationPipeline,m.AutoConfig,m.AutoFeatureExtractor,m.AutoImageProcessor,m.AutoModel,m.AutoModelForAudioClassification,m.AutoModelForAudioFrameClassification,m.AutoModelForAudioTextToText,m.AutoModelForCTC;var eT=m.AutoModelForCausalLM;m.AutoModelForDepthEstimation,m.AutoModelForDocumentQuestionAnswering,m.AutoModelForImageClassification,m.AutoModelForImageFeatureExtraction,m.AutoModelForImageMatting,m.AutoModelForImageSegmentation,m.AutoModelForImageTextToText,m.AutoModelForImageToImage,m.AutoModelForMaskGeneration,m.AutoModelForMaskedLM,m.AutoModelForNormalEstimation,m.AutoModelForObjectDetection,m.AutoModelForPoseEstimation,m.AutoModelForQuestionAnswering,m.AutoModelForSemanticSegmentation,m.AutoModelForSeq2SeqLM,m.AutoModelForSequenceClassification,m.AutoModelForSpeechSeq2Seq,m.AutoModelForTextToSpectrogram,m.AutoModelForTextToWaveform,m.AutoModelForTokenClassification,m.AutoModelForUniversalSegmentation,m.AutoModelForVision2Seq,m.AutoModelForXVector,m.AutoModelForZeroShotObjectDetection,m.AutoProcessor;var tT=m.AutoTokenizer;m.AutomaticSpeechRecognitionPipeline,m.BackgroundRemovalPipeline,m.BartForConditionalGeneration,m.BartForSequenceClassification,m.BartModel,m.BartPretrainedModel,m.BartTokenizer,m.BaseModelOutput,m.BaseStreamer,m.BeitFeatureExtractor,m.BeitForImageClassification,m.BeitModel,m.BeitPreTrainedModel,m.BertForMaskedLM,m.BertForQuestionAnswering,m.BertForSequenceClassification,m.BertForTokenClassification,m.BertModel,m.BertPreTrainedModel,m.BertTokenizer,m.BitImageProcessor,m.BlenderbotForConditionalGeneration,m.BlenderbotModel,m.BlenderbotPreTrainedModel,m.BlenderbotSmallForConditionalGeneration,m.BlenderbotSmallModel,m.BlenderbotSmallPreTrainedModel,m.BlenderbotSmallTokenizer,m.BlenderbotTokenizer,m.BloomForCausalLM,m.BloomModel,m.BloomPreTrainedModel,m.BloomTokenizer,m.CLIPFeatureExtractor,m.CLIPImageProcessor,m.CLIPModel,m.CLIPPreTrainedModel,m.CLIPSegForImageSegmentation,m.CLIPSegModel,m.CLIPSegPreTrainedModel,m.CLIPTextModel,m.CLIPTextModelWithProjection,m.CLIPTokenizer,m.CLIPVisionModel,m.CLIPVisionModelWithProjection,m.CamembertForMaskedLM,m.CamembertForQuestionAnswering,m.CamembertForSequenceClassification,m.CamembertForTokenClassification,m.CamembertModel,m.CamembertPreTrainedModel,m.CamembertTokenizer,m.CausalLMOutput,m.CausalLMOutputWithPast,m.ChineseCLIPFeatureExtractor,m.ChineseCLIPModel,m.ChineseCLIPPreTrainedModel,m.ClapAudioModelWithProjection,m.ClapFeatureExtractor,m.ClapModel,m.ClapPreTrainedModel,m.ClapTextModelWithProjection,m.ClassifierFreeGuidanceLogitsProcessor,m.CodeGenForCausalLM,m.CodeGenModel,m.CodeGenPreTrainedModel,m.CodeGenTokenizer,m.CodeLlamaTokenizer,m.CohereForCausalLM,m.CohereModel,m.CoherePreTrainedModel,m.CohereTokenizer,m.ConvBertForMaskedLM,m.ConvBertForQuestionAnswering,m.ConvBertForSequenceClassification,m.ConvBertForTokenClassification,m.ConvBertModel,m.ConvBertPreTrainedModel,m.ConvBertTokenizer,m.ConvNextFeatureExtractor,m.ConvNextForImageClassification,m.ConvNextImageProcessor,m.ConvNextModel,m.ConvNextPreTrainedModel,m.ConvNextV2ForImageClassification,m.ConvNextV2Model,m.ConvNextV2PreTrainedModel,m.DFineForObjectDetection,m.DFineModel,m.DFinePreTrainedModel,m.DPTFeatureExtractor,m.DPTForDepthEstimation,m.DPTImageProcessor,m.DPTModel,m.DPTPreTrainedModel,m.DacDecoderModel,m.DacDecoderOutput,m.DacEncoderModel,m.DacEncoderOutput,m.DacFeatureExtractor,m.DacModel,m.DacPreTrainedModel,m.DataTypeMap,m.DebertaForMaskedLM,m.DebertaForQuestionAnswering,m.DebertaForSequenceClassification,m.DebertaForTokenClassification,m.DebertaModel,m.DebertaPreTrainedModel,m.DebertaTokenizer,m.DebertaV2ForMaskedLM,m.DebertaV2ForQuestionAnswering,m.DebertaV2ForSequenceClassification,m.DebertaV2ForTokenClassification,m.DebertaV2Model,m.DebertaV2PreTrainedModel,m.DebertaV2Tokenizer,m.DecisionTransformerModel,m.DecisionTransformerPreTrainedModel,m.DeiTFeatureExtractor,m.DeiTForImageClassification,m.DeiTImageProcessor,m.DeiTModel,m.DeiTPreTrainedModel,m.DepthAnythingForDepthEstimation,m.DepthAnythingPreTrainedModel,m.DepthEstimationPipeline,m.DepthProForDepthEstimation,m.DepthProPreTrainedModel,m.DetrFeatureExtractor,m.DetrForObjectDetection,m.DetrForSegmentation,m.DetrImageProcessor,m.DetrModel,m.DetrObjectDetectionOutput,m.DetrPreTrainedModel,m.DetrSegmentationOutput,m.Dinov2ForImageClassification,m.Dinov2Model,m.Dinov2PreTrainedModel,m.Dinov2WithRegistersForImageClassification,m.Dinov2WithRegistersModel,m.Dinov2WithRegistersPreTrainedModel,m.DistilBertForMaskedLM,m.DistilBertForQuestionAnswering,m.DistilBertForSequenceClassification,m.DistilBertForTokenClassification,m.DistilBertModel,m.DistilBertPreTrainedModel,m.DistilBertTokenizer,m.DocumentQuestionAnsweringPipeline,m.DonutFeatureExtractor,m.DonutImageProcessor,m.DonutSwinModel,m.DonutSwinPreTrainedModel,m.EfficientNetForImageClassification,m.EfficientNetImageProcessor,m.EfficientNetModel,m.EfficientNetPreTrainedModel,m.ElectraForMaskedLM,m.ElectraForQuestionAnswering,m.ElectraForSequenceClassification,m.ElectraForTokenClassification,m.ElectraModel,m.ElectraPreTrainedModel,m.ElectraTokenizer,m.EncodecFeatureExtractor,m.EosTokenCriteria,m.Ernie4_5_ForCausalLM,m.Ernie4_5_Model,m.Ernie4_5_PretrainedModel,m.Ernie4_5_Tokenizer,m.EsmForMaskedLM,m.EsmForSequenceClassification,m.EsmForTokenClassification,m.EsmModel,m.EsmPreTrainedModel,m.EsmTokenizer,m.ExaoneForCausalLM,m.ExaoneModel,m.ExaonePreTrainedModel,m.FFT,m.FalconForCausalLM,m.FalconModel,m.FalconPreTrainedModel,m.FalconTokenizer,m.FastViTForImageClassification,m.FastViTModel,m.FastViTPreTrainedModel,m.FeatureExtractionPipeline,m.FeatureExtractor,m.FillMaskPipeline,m.Florence2ForConditionalGeneration,m.Florence2PreTrainedModel,m.Florence2Processor,m.ForcedBOSTokenLogitsProcessor,m.ForcedEOSTokenLogitsProcessor,m.GLPNFeatureExtractor,m.GLPNForDepthEstimation,m.GLPNModel,m.GLPNPreTrainedModel,m.GPT2LMHeadModel,m.GPT2Model,m.GPT2PreTrainedModel,m.GPT2Tokenizer,m.GPTBigCodeForCausalLM,m.GPTBigCodeModel,m.GPTBigCodePreTrainedModel,m.GPTJForCausalLM,m.GPTJModel,m.GPTJPreTrainedModel,m.GPTNeoForCausalLM,m.GPTNeoModel,m.GPTNeoPreTrainedModel,m.GPTNeoXForCausalLM,m.GPTNeoXModel,m.GPTNeoXPreTrainedModel,m.GPTNeoXTokenizer,m.Gemma2ForCausalLM,m.Gemma2Model,m.Gemma2PreTrainedModel,m.Gemma3ForCausalLM,m.Gemma3Model,m.Gemma3PreTrainedModel,m.Gemma3nAudioFeatureExtractor,m.Gemma3nForConditionalGeneration,m.Gemma3nPreTrainedModel,m.Gemma3nProcessor,m.GemmaForCausalLM,m.GemmaModel,m.GemmaPreTrainedModel,m.GemmaTokenizer,m.GlmForCausalLM,m.GlmModel,m.GlmPreTrainedModel,m.GraniteForCausalLM,m.GraniteModel,m.GranitePreTrainedModel,m.Grok1Tokenizer,m.GroundingDinoForObjectDetection,m.GroundingDinoImageProcessor,m.GroundingDinoPreTrainedModel,m.GroundingDinoProcessor,m.GroupViTModel,m.GroupViTPreTrainedModel,m.HeliumForCausalLM,m.HeliumModel,m.HeliumPreTrainedModel,m.HerbertTokenizer,m.HieraForImageClassification,m.HieraModel,m.HieraPreTrainedModel,m.HubertForCTC,m.HubertForSequenceClassification,m.HubertModel,m.HubertPreTrainedModel,m.IJepaForImageClassification,m.IJepaModel,m.IJepaPreTrainedModel,m.Idefics3ForConditionalGeneration,m.Idefics3ImageProcessor,m.Idefics3PreTrainedModel,m.Idefics3Processor,m.ImageClassificationPipeline,m.ImageFeatureExtractionPipeline,m.ImageFeatureExtractor,m.ImageMattingOutput,m.ImageProcessor,m.ImageSegmentationPipeline,m.ImageToImagePipeline,m.ImageToTextPipeline;var rT=m.InterruptableStoppingCriteria;m.JAISLMHeadModel,m.JAISModel,m.JAISPreTrainedModel,m.JinaCLIPImageProcessor,m.JinaCLIPModel,m.JinaCLIPPreTrainedModel,m.JinaCLIPProcessor,m.JinaCLIPTextModel,m.JinaCLIPVisionModel,m.Lfm2ForCausalLM,m.Lfm2Model,m.Lfm2PreTrainedModel,m.LiteWhisperForConditionalGeneration,m.LlamaForCausalLM,m.LlamaModel,m.LlamaPreTrainedModel,m.LlamaTokenizer,m.LlavaForConditionalGeneration,m.LlavaOnevisionForConditionalGeneration,m.LlavaOnevisionImageProcessor,m.LlavaPreTrainedModel,m.LlavaProcessor,m.LlavaQwen2ForCausalLM,m.LogitsProcessor,m.LogitsProcessorList,m.LogitsWarper,m.LongT5ForConditionalGeneration,m.LongT5Model,m.LongT5PreTrainedModel,m.M2M100ForConditionalGeneration,m.M2M100Model,m.M2M100PreTrainedModel,m.M2M100Tokenizer,m.MBart50Tokenizer,m.MBartForCausalLM,m.MBartForConditionalGeneration,m.MBartForSequenceClassification,m.MBartModel,m.MBartPreTrainedModel,m.MBartTokenizer,m.MPNetForMaskedLM,m.MPNetForQuestionAnswering,m.MPNetForSequenceClassification,m.MPNetForTokenClassification,m.MPNetModel,m.MPNetPreTrainedModel,m.MPNetTokenizer,m.MT5ForConditionalGeneration,m.MT5Model,m.MT5PreTrainedModel,m.MarianMTModel,m.MarianModel,m.MarianPreTrainedModel,m.MarianTokenizer,m.Mask2FormerImageProcessor,m.MaskFormerFeatureExtractor,m.MaskFormerForInstanceSegmentation,m.MaskFormerImageProcessor,m.MaskFormerModel,m.MaskFormerPreTrainedModel,m.MaskedLMOutput,m.MaxLengthCriteria,m.Metric3DForDepthEstimation,m.Metric3DPreTrainedModel,m.Metric3Dv2ForDepthEstimation,m.Metric3Dv2PreTrainedModel,m.MgpstrForSceneTextRecognition,m.MgpstrModelOutput,m.MgpstrPreTrainedModel,m.MgpstrProcessor,m.MgpstrTokenizer,m.MimiDecoderModel,m.MimiDecoderOutput,m.MimiEncoderModel,m.MimiEncoderOutput,m.MimiModel,m.MimiPreTrainedModel,m.MinLengthLogitsProcessor,m.MinNewTokensLengthLogitsProcessor,m.MistralForCausalLM,m.MistralModel,m.MistralPreTrainedModel,m.MobileBertForMaskedLM,m.MobileBertForQuestionAnswering,m.MobileBertForSequenceClassification,m.MobileBertModel,m.MobileBertPreTrainedModel,m.MobileBertTokenizer,m.MobileLLMForCausalLM,m.MobileLLMModel,m.MobileLLMPreTrainedModel,m.MobileNetV1FeatureExtractor,m.MobileNetV1ForImageClassification,m.MobileNetV1ForSemanticSegmentation,m.MobileNetV1ImageProcessor,m.MobileNetV1Model,m.MobileNetV1PreTrainedModel,m.MobileNetV2FeatureExtractor,m.MobileNetV2ForImageClassification,m.MobileNetV2ForSemanticSegmentation,m.MobileNetV2ImageProcessor,m.MobileNetV2Model,m.MobileNetV2PreTrainedModel,m.MobileNetV3FeatureExtractor,m.MobileNetV3ForImageClassification,m.MobileNetV3ForSemanticSegmentation,m.MobileNetV3ImageProcessor,m.MobileNetV3Model,m.MobileNetV3PreTrainedModel,m.MobileNetV4FeatureExtractor,m.MobileNetV4ForImageClassification,m.MobileNetV4ForSemanticSegmentation,m.MobileNetV4ImageProcessor,m.MobileNetV4Model,m.MobileNetV4PreTrainedModel,m.MobileViTFeatureExtractor,m.MobileViTForImageClassification,m.MobileViTImageProcessor,m.MobileViTModel,m.MobileViTPreTrainedModel,m.MobileViTV2ForImageClassification,m.MobileViTV2Model,m.MobileViTV2PreTrainedModel,m.ModelOutput,m.ModernBertDecoderForCausalLM,m.ModernBertDecoderModel,m.ModernBertDecoderPreTrainedModel,m.ModernBertForMaskedLM,m.ModernBertForSequenceClassification,m.ModernBertForTokenClassification,m.ModernBertModel,m.ModernBertPreTrainedModel,m.Moondream1ForConditionalGeneration,m.MoonshineFeatureExtractor,m.MoonshineForConditionalGeneration,m.MoonshineModel,m.MoonshinePreTrainedModel,m.MoonshineProcessor,m.MptForCausalLM,m.MptModel,m.MptPreTrainedModel,m.MultiModalityCausalLM,m.MultiModalityPreTrainedModel,m.MusicgenForCausalLM,m.MusicgenForConditionalGeneration,m.MusicgenModel,m.MusicgenPreTrainedModel,m.NeoBertForMaskedLM,m.NeoBertForQuestionAnswering,m.NeoBertForSequenceClassification,m.NeoBertForTokenClassification,m.NeoBertModel,m.NeoBertPreTrainedModel,m.NllbTokenizer,m.NoBadWordsLogitsProcessor,m.NoRepeatNGramLogitsProcessor,m.NomicBertModel,m.NomicBertPreTrainedModel,m.NougatImageProcessor,m.NougatTokenizer,m.OPTForCausalLM,m.OPTModel,m.OPTPreTrainedModel,m.ObjectDetectionPipeline,m.Olmo2ForCausalLM,m.Olmo2Model,m.Olmo2PreTrainedModel,m.OlmoForCausalLM,m.OlmoModel,m.OlmoPreTrainedModel,m.OpenELMForCausalLM,m.OpenELMModel,m.OpenELMPreTrainedModel,m.OwlViTFeatureExtractor,m.OwlViTForObjectDetection,m.OwlViTImageProcessor,m.OwlViTModel,m.OwlViTPreTrainedModel,m.OwlViTProcessor,m.Owlv2ForObjectDetection,m.Owlv2ImageProcessor,m.Owlv2Model,m.Owlv2PreTrainedModel,m.PaliGemmaForConditionalGeneration,m.PaliGemmaPreTrainedModel,m.PaliGemmaProcessor,m.PatchTSMixerForPrediction,m.PatchTSMixerModel,m.PatchTSMixerPreTrainedModel,m.PatchTSTForPrediction,m.PatchTSTModel,m.PatchTSTPreTrainedModel,m.Phi3ForCausalLM,m.Phi3Model,m.Phi3PreTrainedModel,m.Phi3VForCausalLM,m.Phi3VImageProcessor,m.Phi3VPreTrainedModel,m.Phi3VProcessor,m.PhiForCausalLM,m.PhiModel,m.PhiPreTrainedModel,m.Pipeline,m.PreTrainedModel,m.PreTrainedTokenizer,m.PretrainedConfig,m.PretrainedMixin,m.Processor,m.PvtForImageClassification,m.PvtImageProcessor,m.PvtModel,m.PvtPreTrainedModel,m.PyAnnoteFeatureExtractor,m.PyAnnoteForAudioFrameClassification,m.PyAnnoteModel,m.PyAnnotePreTrainedModel,m.PyAnnoteProcessor,m.QuestionAnsweringModelOutput,m.QuestionAnsweringPipeline,m.Qwen2ForCausalLM,m.Qwen2Model,m.Qwen2PreTrainedModel,m.Qwen2Tokenizer,m.Qwen2VLForConditionalGeneration,m.Qwen2VLImageProcessor,m.Qwen2VLPreTrainedModel,m.Qwen2VLProcessor,m.Qwen3ForCausalLM,m.Qwen3Model,m.Qwen3PreTrainedModel,m.RFDetrForObjectDetection,m.RFDetrModel,m.RFDetrObjectDetectionOutput,m.RFDetrPreTrainedModel,m.RTDetrForObjectDetection,m.RTDetrImageProcessor,m.RTDetrModel,m.RTDetrObjectDetectionOutput,m.RTDetrPreTrainedModel,m.RTDetrV2ForObjectDetection,m.RTDetrV2Model,m.RTDetrV2ObjectDetectionOutput,m.RTDetrV2PreTrainedModel,m.RawAudio,m.RawImage,m.RawVideo,m.RawVideoFrame,m.RepetitionPenaltyLogitsProcessor,m.ResNetForImageClassification,m.ResNetModel,m.ResNetPreTrainedModel,m.RoFormerForMaskedLM,m.RoFormerForQuestionAnswering,m.RoFormerForSequenceClassification,m.RoFormerForTokenClassification,m.RoFormerModel,m.RoFormerPreTrainedModel,m.RoFormerTokenizer,m.RobertaForMaskedLM,m.RobertaForQuestionAnswering,m.RobertaForSequenceClassification,m.RobertaForTokenClassification,m.RobertaModel,m.RobertaPreTrainedModel,m.RobertaTokenizer,m.SamImageProcessor,m.SamImageSegmentationOutput,m.SamModel,m.SamPreTrainedModel,m.SamProcessor,m.SapiensForDepthEstimation,m.SapiensForNormalEstimation,m.SapiensForSemanticSegmentation,m.SapiensPreTrainedModel,m.SeamlessM4TFeatureExtractor,m.SegformerFeatureExtractor,m.SegformerForImageClassification,m.SegformerForSemanticSegmentation,m.SegformerImageProcessor,m.SegformerModel,m.SegformerPreTrainedModel,m.Seq2SeqLMOutput,m.SequenceClassifierOutput,m.SiglipImageProcessor,m.SiglipModel,m.SiglipPreTrainedModel,m.SiglipTextModel,m.SiglipTokenizer,m.SiglipVisionModel,m.SmolLM3ForCausalLM,m.SmolLM3Model,m.SmolLM3PreTrainedModel,m.SmolVLMForConditionalGeneration,m.SmolVLMImageProcessor,m.SmolVLMProcessor,m.SnacDecoderModel,m.SnacEncoderModel,m.SnacFeatureExtractor,m.SnacModel,m.SnacPreTrainedModel,m.SpeechT5FeatureExtractor,m.SpeechT5ForSpeechToText,m.SpeechT5ForTextToSpeech,m.SpeechT5HifiGan,m.SpeechT5Model,m.SpeechT5PreTrainedModel,m.SpeechT5Processor,m.SpeechT5Tokenizer,m.SqueezeBertForMaskedLM,m.SqueezeBertForQuestionAnswering,m.SqueezeBertForSequenceClassification,m.SqueezeBertModel,m.SqueezeBertPreTrainedModel,m.SqueezeBertTokenizer,m.StableLmForCausalLM,m.StableLmModel,m.StableLmPreTrainedModel,m.Starcoder2ForCausalLM,m.Starcoder2Model,m.Starcoder2PreTrainedModel,m.StoppingCriteria,m.StoppingCriteriaList,m.StyleTextToSpeech2Model,m.StyleTextToSpeech2PreTrainedModel,m.SummarizationPipeline,m.SuppressTokensAtBeginLogitsProcessor,m.Swin2SRForImageSuperResolution,m.Swin2SRImageProcessor,m.Swin2SRModel,m.Swin2SRPreTrainedModel,m.SwinForImageClassification,m.SwinForSemanticSegmentation,m.SwinModel,m.SwinPreTrainedModel,m.T5ForConditionalGeneration,m.T5Model,m.T5PreTrainedModel,m.T5Tokenizer,m.TableTransformerForObjectDetection,m.TableTransformerModel,m.TableTransformerObjectDetectionOutput,m.TableTransformerPreTrainedModel,m.TemperatureLogitsWarper,m.Tensor,m.Text2TextGenerationPipeline,m.TextClassificationPipeline,m.TextGenerationPipeline;var sT=m.TextStreamer;m.TextToAudioPipeline,m.TokenClassificationPipeline,m.TokenClassifierOutput,m.TokenizerModel,m.TopKLogitsWarper,m.TopPLogitsWarper,m.TrOCRForCausalLM,m.TrOCRPreTrainedModel,m.TranslationPipeline,m.UltravoxModel,m.UltravoxPreTrainedModel,m.UltravoxProcessor,m.UniSpeechForCTC,m.UniSpeechForSequenceClassification,m.UniSpeechModel,m.UniSpeechPreTrainedModel,m.UniSpeechSatForAudioFrameClassification,m.UniSpeechSatForCTC,m.UniSpeechSatForSequenceClassification,m.UniSpeechSatModel,m.UniSpeechSatPreTrainedModel,m.VLChatProcessor,m.VLMImageProcessor,m.ViTFeatureExtractor,m.ViTForImageClassification,m.ViTImageProcessor,m.ViTMAEModel,m.ViTMAEPreTrainedModel,m.ViTMSNForImageClassification,m.ViTMSNModel,m.ViTMSNPreTrainedModel,m.ViTModel,m.ViTPreTrainedModel,m.VisionEncoderDecoderModel,m.VitMatteForImageMatting,m.VitMatteImageProcessor,m.VitMattePreTrainedModel,m.VitPoseForPoseEstimation,m.VitPoseImageProcessor,m.VitPosePreTrainedModel,m.VitsModel,m.VitsModelOutput,m.VitsPreTrainedModel,m.VitsTokenizer,m.VoxtralForConditionalGeneration,m.VoxtralProcessor,m.Wav2Vec2BertForCTC,m.Wav2Vec2BertForSequenceClassification,m.Wav2Vec2BertModel,m.Wav2Vec2BertPreTrainedModel,m.Wav2Vec2CTCTokenizer,m.Wav2Vec2FeatureExtractor,m.Wav2Vec2ForAudioFrameClassification,m.Wav2Vec2ForCTC,m.Wav2Vec2ForSequenceClassification,m.Wav2Vec2Model,m.Wav2Vec2PreTrainedModel,m.Wav2Vec2Processor,m.Wav2Vec2ProcessorWithLM,m.WavLMForAudioFrameClassification,m.WavLMForCTC,m.WavLMForSequenceClassification,m.WavLMForXVector,m.WavLMModel,m.WavLMPreTrainedModel,m.WeSpeakerFeatureExtractor,m.WeSpeakerResNetModel,m.WeSpeakerResNetPreTrainedModel,m.WhisperFeatureExtractor,m.WhisperForConditionalGeneration,m.WhisperModel,m.WhisperPreTrainedModel,m.WhisperProcessor,m.WhisperTextStreamer,m.WhisperTimeStampLogitsProcessor,m.WhisperTokenizer,m.XLMForQuestionAnswering,m.XLMForSequenceClassification,m.XLMForTokenClassification,m.XLMModel,m.XLMPreTrainedModel,m.XLMRobertaForMaskedLM,m.XLMRobertaForQuestionAnswering,m.XLMRobertaForSequenceClassification,m.XLMRobertaForTokenClassification,m.XLMRobertaModel,m.XLMRobertaPreTrainedModel,m.XLMRobertaTokenizer,m.XLMTokenizer,m.XLMWithLMHeadModel,m.XVectorOutput,m.YolosFeatureExtractor,m.YolosForObjectDetection,m.YolosImageProcessor,m.YolosModel,m.YolosObjectDetectionOutput,m.YolosPreTrainedModel,m.ZeroShotAudioClassificationPipeline,m.ZeroShotClassificationPipeline,m.ZeroShotImageClassificationPipeline,m.ZeroShotObjectDetectionPipeline,m.bankers_round,m.cat,m.cos_sim,m.dot,m.dynamic_time_warping,m.env,m.full,m.full_like,m.getCacheShapes,m.hamming,m.hanning,m.interpolate,m.interpolate_4d,m.interpolate_data,m.is_chinese_char,m.layer_norm,m.load_image,m.load_video,m.log_softmax,m.magnitude,m.matmul,m.max,m.mean,m.mean_pooling,m.medianFilter,m.mel_filter_bank,m.min,m.ones,m.ones_like,m.permute,m.permute_data,m.pipeline,m.quantize_embeddings,m.rand,m.read_audio,m.rfft,m.round,m.slice,m.softmax,m.spectrogram,m.stack,m.std_mean,m.topk,m.window_function,m.zeros,m.zeros_like;async function nT(){try{if(!await navigator.gpu.requestAdapter())throw new Error("WebGPU is not supported (no adapter found)")}catch(e){self.postMessage({status:"error",data:e.toString()})}}class pc{static async getInstance(r=null){return this.tokenizer??(this.tokenizer=tT.from_pretrained(this.model_id,{progress_callback:r})),this.model??(this.model=eT.from_pretrained(this.model_id,{dtype:"q4",device:"webgpu",progress_callback:r})),Promise.all([this.tokenizer,this.model])}}J(pc,"model_id","HuggingFaceTB/SmolLM2-360M-Instruct");const xi=new rT;let hc=null;async function oT(e){const[r,t]=await pc.getInstance(),s=r.apply_chat_template(e,{add_generation_prompt:!0,return_dict:!0});let o,n=0,i;const a=()=>{o??(o=performance.now()),n++>0&&(i=n/(performance.now()-o)*1e3)},l=f=>{self.postMessage({status:"update",output:f,tps:i,numTokens:n})},c=new sT(r,{skip_prompt:!0,skip_special_tokens:!0,callback_function:l,token_callback_function:a});self.postMessage({status:"start"});const{past_key_values:p,sequences:d}=await t.generate({...s,past_key_values:hc,do_sample:!0,temperature:.9,max_new_tokens:256,streamer:c,stopping_criteria:xi,return_dict_in_generate:!0});hc=p;const u=r.batch_decode(d,{skip_special_tokens:!0});self.postMessage({status:"complete",output:u})}async function iT(){self.postMessage({status:"loading",data:"Loading model..."});const[e,r]=await pc.getInstance(s=>{self.postMessage(s)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const t=e("a");await r.generate({...t,max_new_tokens:1}),self.postMessage({status:"ready"})}self.addEventListener("message",async e=>{const{type:r,data:t}=e.data;switch(r){case"check":nT();break;case"load":iT();break;case"generate":xi.reset(),oT(t);break;case"interrupt":xi.interrupt();break;case"reset":hc=null,xi.reset();break}})})(); diff --git a/banner.png b/banner.png new file mode 100644 index 0000000000000000000000000000000000000000..059bb1d3aa6f4d72a33e917e1ff6e195ec39b441 --- /dev/null +++ b/banner.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4dfad2e227a78d139c5dc4767f82b2e4c96350644282d601805a89b00d207201 +size 436421 diff --git a/index.html b/index.html index b0c4b3666032a737f3903db53e6a8a9272483e28..9a4f7d6bce16db0560d236d8f34052544ae959c9 100644 --- a/index.html +++ b/index.html @@ -1,19 +1,33 @@ - - - - - My static Space - - - -
    - + + + + + + SmolLM2 WebGPU + + + + + +
    + + + + diff --git a/logo.png b/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..56aeb11bf21cfebdbb401a8f3ba57e8b559f53d5 --- /dev/null +++ b/logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c28aed1f05f06a776baa4a7be540fc48797d8e9547b9a5e0453552110b96462 +size 417007