diff --git "a/dist/assets/worker-Cs0ykk65.js" "b/dist/assets/worker-Cs0ykk65.js" new file mode 100644--- /dev/null +++ "b/dist/assets/worker-Cs0ykk65.js" @@ -0,0 +1,2896 @@ +var zT=Object.defineProperty;var BT=(Is,Gr,zn)=>Gr in Is?zT(Is,Gr,{enumerable:!0,configurable:!0,writable:!0,value:zn}):Is[Gr]=zn;var J=(Is,Gr,zn)=>BT(Is,typeof Gr!="symbol"?Gr+"":Gr,zn);(function(){"use strict";const Is=new Map,Gr=[],zn=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=Is.get(e);if(s===void 0)Is.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=Gr.indexOf(e);o!==-1&&Gr.splice(o,1);for(let n=0;n{const r=Is.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}}},$v=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Gr:t;let o;const n=[],i=new Set;for(const l of s){const c=await Sv(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)})]},kv="1.21.0";let zu="warning";const fs={wasm:{},webgl:{},webgpu:{},versions:{common:kv},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}`);zu=e}},get logLevel(){return zu}};Object.defineProperty(fs,"logLevel",{enumerable:!0});const Iv=fs,Av=(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 M=0;M{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,M=2,k=3,w=0,b=d,$=d*2,E=-1;a==="RGBA"?(w=0,b=d,$=d*2,E=d*3):a==="RGB"?(w=0,b=d,$=d*2):a==="RBG"&&(w=0,$=d,b=d*2),s=t.createImageData(o,n);for(let v=0;v{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,M=3,k=0,w=c,b=c*2,$=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,M=-1),l==="RGBA"?$=c*3:l==="RBG"?(k=0,b=c,w=c*2):l==="BGR"&&(b=0,w=c,k=c*2);for(let v=0;v{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 M=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(wa(M.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")},Dv=(e,r)=>{const{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new is({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},Lv=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new is({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},zv=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new is({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},Bv=(e,r,t)=>new is({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),Bn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Jo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Bu=!1;const Rv=()=>{if(!Bu){Bu=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(Bn.set("int64",BigInt64Array),Jo.set(BigInt64Array,"int64")),r&&(Bn.set("uint64",BigUint64Array),Jo.set(BigUint64Array,"uint64")),s?(Bn.set("float16",t),Jo.set(t,"float16")):Bn.set("float16",Uint16Array)}},jv=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new is(e.type,e.data,r);case"cpu-pinned":return new is({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new is({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new is({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new is({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let is=class{constructor(r,t,s){Rv();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=Bn.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=Bn.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=Jo.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=jv(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 Ov(r,t)}static fromTexture(r,t){return Dv(r,t)}static fromGpuBuffer(r,t){return Lv(r,t)}static fromMLTensor(r,t){return zv(r,t)}static fromPinnedBuffer(r,t,s){return Bv(r,t,s)}toDataURL(r){return Av(this,r)}toImageData(r){return Fv(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 Nv(this,r)}};const Rn=is,Ru=(e,r)=>{(typeof fs.trace>"u"?!fs.wasm.trace:!fs.trace)||console.timeStamp(`${e}::ORT::${r}`)},ju=(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 fs.trace>"u"?!fs.wasm.trace:!fs.trace)||ju("BEGIN",e)},ba=e=>{(typeof fs.trace>"u"?!fs.wasm.trace:!fs.trace)||ju("END",e)};var Vv=Object.freeze({__proto__:null,InferenceSession:class Ev{constructor(r){this.handler=r}async run(r,t,s){Ma();const o={};let n={};if(typeof r!="object"||r===null||r instanceof Rn||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 Rn)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 Rn)&&(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 Rn?l[c]=p:l[c]=new Rn(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 $v(i),c=await a.createInferenceSessionHandler(n,l);return ba(),new Ev(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}},TRACE:Ru,TRACE_FUNC_BEGIN:Ma,TRACE_FUNC_END:ba,Tensor:Rn,env:Iv,registerBackend:zn});/*! + * 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,Uv=Object.getOwnPropertyDescriptor,Wv=Object.getOwnPropertyNames,Gv=Object.prototype.hasOwnProperty,Kv=(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')}),Ne=(e,r)=>()=>(e&&(r=e(e=0)),r),jn=(e,r)=>{for(var t in r)ya(e,t,{get:r[t],enumerable:!0})},Hv=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of Wv(r))!Gv.call(e,o)&&o!==t&&ya(e,o,{get:()=>r[o],enumerable:!(s=Uv(r,o))||s.enumerable});return e},ao=e=>Hv(ya({},"__esModule",{value:!0}),e),lo,qs,ln,Nu,Vu,Uu=Ne(()=>{lo=new Map,qs=[],ln=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=lo.get(e);if(s===void 0)lo.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=qs.indexOf(e);o!==-1&&qs.splice(o,1);for(let n=0;n{let r=lo.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}}},Vu=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?qs:t,o,n=[],i=new Set;for(let l of s){let c=await Nu(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)})]}}),qv=Ne(()=>{Uu()}),Wu,Qv=Ne(()=>{Wu="1.22.0-dev.20250409-89f8206ba4"}),va,as,Gu=Ne(()=>{Qv(),va="warning",as={wasm:{},webgl:{},webgpu:{},versions:{common:Wu},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(as,"logLevel",{enumerable:!0})}),Jt,Xv=Ne(()=>{Gu(),Jt=as}),Ku,Hu,Jv=Ne(()=>{Ku=(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 M=0;M{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,M=2,k=3,w=0,b=d,$=d*2,E=-1;a==="RGBA"?(w=0,b=d,$=d*2,E=d*3):a==="RGB"?(w=0,b=d,$=d*2):a==="RBG"&&(w=0,$=d,b=d*2),s=t.createImageData(o,n);for(let v=0;v{Ta(),Yo=(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,M=3,k=0,w=c,b=c*2,$=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,M=-1),l==="RGBA"?$=c*3:l==="RBG"?(k=0,b=c,w=c*2):l==="BGR"&&(b=0,w=c,k=c*2);for(let E=0;E{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,Yo(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 M=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(Yo(M.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Yo(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Qu=(e,r)=>{let{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Zr({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},Xu=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Zr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},Ju=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Zr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},Yu=(e,r,t)=>new Zr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),cn,co,xa,Zu,Zv=Ne(()=>{cn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),co=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),xa=!1,Zu=()=>{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&&(cn.set("int64",BigInt64Array),co.set(BigInt64Array,"int64")),r&&(cn.set("uint64",BigUint64Array),co.set(BigUint64Array,"uint64")),s?(cn.set("float16",t),co.set(t,"float16")):cn.set("float16",Uint16Array)}}}),ed,td,ex=Ne(()=>{Ta(),ed=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Zr(e.type,e.data,r);case"cpu-pinned":return new Zr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Zr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Zr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Zr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Zr,Ta=Ne(()=>{Jv(),Yv(),Zv(),ex(),Zr=class{constructor(e,r,t){Zu();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=cn.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=cn.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=co.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=ed(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 qu(e,r)}static fromTexture(e,r){return Qu(e,r)}static fromGpuBuffer(e,r){return Xu(e,r)}static fromMLTensor(e,r){return Ju(e,r)}static fromPinnedBuffer(e,r,t){return Yu(e,r,t)}toDataURL(e){return Ku(this,e)}toImageData(e){return Hu(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 td(this,e)}}}),gs,rd=Ne(()=>{Ta(),gs=Zr}),uo,Ea,ws,ls,sd=Ne(()=>{Gu(),uo=(e,r)=>{(typeof as.trace>"u"?!as.wasm.trace:!as.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 as.trace>"u"?!as.wasm.trace:!as.trace)||Ea("BEGIN",e)},ls=e=>{(typeof as.trace>"u"?!as.wasm.trace:!as.trace)||Ea("END",e)}}),nd,tx=Ne(()=>{Uu(),rd(),sd(),nd=class Pv{constructor(r){this.handler=r}async run(r,t,s){ws();let o={},n={};if(typeof r!="object"||r===null||r instanceof gs||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 gs)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 gs)&&(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 gs?l[c]=p:l[c]=new gs(p.type,p.data,p.dims)}return ls(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){ws();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 Vu(i),c=await a.createInferenceSessionHandler(n,l);return ls(),new Pv(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,rx=Ne(()=>{tx(),Pa=nd}),sx=Ne(()=>{}),nx=Ne(()=>{}),ox=Ne(()=>{}),ix=Ne(()=>{}),od={};jn(od,{InferenceSession:()=>Pa,TRACE:()=>uo,TRACE_FUNC_BEGIN:()=>ws,TRACE_FUNC_END:()=>ls,Tensor:()=>gs,env:()=>Jt,registerBackend:()=>ln});var Ms=Ne(()=>{qv(),Xv(),rx(),rd(),sx(),nx(),sd(),ox(),ix()}),Ca=Ne(()=>{}),id={};jn(id,{default:()=>ad});var Sa,$a,ad,ax=Ne(()=>{var e;Ng(),un(),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=gi(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})}}),ad=$a?null:r=>new Worker(r??es,{type:"module",name:Sa})}),ld={};jn(ld,{default:()=>cd});var ka,Ia,cd,ud,lx=Ne(()=>{var e,r;Ia=(ka=self.location.href,async function(t={}){var Ko;var s,o,n=t,i=new Promise((m,T)=>{s=m,o=T}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",c=l&&((Ko=self.name)==null?void 0:Ko.startsWith("em-pthread"));n.mountExternalData=(m,T)=>{m.startsWith("./")&&(m=m.substring(2)),(n.Eb||(n.Eb=new Map)).set(m,T)},n.unmountExternalData=()=>{delete n.Eb};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let d=m=>async(...T)=>{var A;try{if(n.Fb)throw Error("Session already started");let z=n.Fb={dc:T[0],errors:[]},U=await m(...T);if(n.Fb!==z)throw Error("Session mismatch");(A=n.Jb)==null||A.flush();let le=z.errors;if(0De),0{if(m==="webgpu"){[n.Jb,n.Ub,n.Yb,n.Kb,n.Xb,n.jb,n.Zb,n.ac,n.Vb,n.Wb,n.$b]=T;let A=n.Jb;n.jsepRegisterBuffer=(z,U,le,Te)=>A.registerBuffer(z,U,le,Te),n.jsepGetBuffer=z=>A.getBuffer(z),n.jsepCreateDownloader=(z,U,le)=>A.createDownloader(z,U,le),n.jsepOnCreateSession=z=>{A.onCreateSession(z)},n.jsepOnReleaseSession=z=>{A.onReleaseSession(z)},n.jsepOnRunStart=z=>A.onRunStart(z),n.bc=(z,U)=>{A.upload(z,U)}}else if(m==="webnn"){let A=T[0];[n.nc,n.Nb,n.webnnEnsureTensor,n.Ob,n.webnnDownloadTensor]=T.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,U)=>{A.registerMLContext(z,U)},n.webnnOnReleaseSession=z=>{A.onReleaseSession(z)},n.webnnCreateMLTensorDownloader=(z,U)=>A.createMLTensorDownloader(z,U),n.webnnRegisterMLTensor=(z,U,le,Te)=>A.registerMLTensor(z,U,le,Te),n.webnnCreateMLContext=z=>A.createMLContext(z),n.webnnRegisterMLConstant=(z,U,le,Te,De,qe)=>A.registerMLConstant(z,U,le,Te,De,n.Eb,qe),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 m=(T,A,z)=>(...U)=>{let le=wr,Te=A==null?void 0:A();U=T(...U);let De=A==null?void 0:A();return Te!==De&&(T=De,z(Te),A=z=null),wr!=le?new Promise((qe,it)=>{Yr={resolve:qe,reject:it}}):U};(()=>{for(let T of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])n[T]=m(n[T],()=>n[T],A=>n[T]=A)})(),d!==void 0&&(n._OrtRun=d(n._OrtRun),n._OrtRunWithBinding=d(n._OrtRunWithBinding)),u=void 0};n.asyncInit=()=>{u==null||u()};var f,_,M=Object.assign({},n),k=(m,T)=>{throw T},w="";(a||l)&&(l?w=self.location.href:typeof document<"u"&&document.currentScript&&(w=document.currentScript.src),ka&&(w=ka),w=w.startsWith("blob:")?"":w.slice(0,w.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(_=m=>{var T=new XMLHttpRequest;return T.open("GET",m,!1),T.responseType="arraybuffer",T.send(null),new Uint8Array(T.response)}),f=async m=>{if(j(m))return new Promise((A,z)=>{var U=new XMLHttpRequest;U.open("GET",m,!0),U.responseType="arraybuffer",U.onload=()=>{U.status==200||U.status==0&&U.response?A(U.response):z(U.status)},U.onerror=z,U.send(null)});var T=await fetch(m,{credentials:"same-origin"});if(T.ok)return T.arrayBuffer();throw Error(T.status+" : "+T.url)});var b=console.log.bind(console),$=console.error.bind(console),E=b,v=$;Object.assign(n,M),M=null;var x,y,P,O,D,K,G,N,te,H,ee,Z,oe,pe=n.wasmBinary,ue=!1,j=m=>m.startsWith("file://");function F(){return x.buffer!=O.buffer&&B(),O}function W(){return x.buffer!=O.buffer&&B(),D}function se(){return x.buffer!=O.buffer&&B(),K}function _e(){return x.buffer!=O.buffer&&B(),G}function ie(){return x.buffer!=O.buffer&&B(),N}function ve(){return x.buffer!=O.buffer&&B(),te}function Le(){return x.buffer!=O.buffer&&B(),H}function Ge(){return x.buffer!=O.buffer&&B(),oe}if(c){let m=function(T){try{var A=T.data,z=A.Bb;if(z==="load"){let U=[];self.onmessage=le=>U.push(le),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let le of U)m(le);self.onmessage=m};for(let le of A.Rb)n[le]&&!n[le].proxy||(n[le]=(...Te)=>{postMessage({Bb:"callHandler",Qb:le,args:Te})},le=="print"&&(E=n[le]),le=="printErr"&&(v=n[le]));x=A.kc,B(),Ie(A.lc)}else if(z==="run"){Zs(A.Ab),$n(A.Ab,0,0,1,0,0),Vr(),ce(A.Ab),Q||(Bo(),Q=!0);try{en(A.fc,A.Hb)}catch(U){if(U!="unwind")throw U}}else A.target!=="setimmediate"&&(z==="checkMailbox"?Q&&xe():z&&(v(`worker: received unknown command ${z}`),v(A)))}catch(U){throw Ro(),U}};var Ie,Q=!1;v=function(...T){T=T.join(" "),console.error(T)},self.alert=function(...T){postMessage({Bb:"alert",text:T.join(" "),ic:nn()})},self.onunhandledrejection=T=>{throw T.reason||T},self.onmessage=m}function B(){var m=x.buffer;n.HEAP8=O=new Int8Array(m),n.HEAP16=K=new Int16Array(m),n.HEAPU8=D=new Uint8Array(m),n.HEAPU16=G=new Uint16Array(m),n.HEAP32=N=new Int32Array(m),n.HEAPU32=te=new Uint32Array(m),n.HEAPF32=H=new Float32Array(m),n.HEAPF64=oe=new Float64Array(m),n.HEAP64=ee=new BigInt64Array(m),n.HEAPU64=Z=new BigUint64Array(m)}function me(){c?startWorker(n):ut.Ca()}c||(x=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),B());var Ce,Pe=0,Se=null;function Me(){if(--Pe==0&&Se){var m=Se;Se=null,m()}}function $e(m){throw v(m="Aborted("+m+")"),ue=!0,m=new WebAssembly.RuntimeError(m+". Build with -sASSERTIONS for more info."),o(m),m}function we(){return{a:{L:Ye,Aa:Oe,b:cs,$:Fs,A:S,pa:X,X:re,Z:ge,qa:Ae,na:ot,ga:ft,ma:pt,J:vt,Y:tt,V:At,oa:qt,W:Ur,va:Ir,E:Ls,Q:ps,O:Wr,D:je,u:rt,r:Qt,P:Ws,z:I,R:V,ja:Y,T:Ve,aa:We,M:et,F:wt,ia:ce,sa:Bt,t:Gt,Ba:fr,w:hs,o:pr,l:qr,c:Ps,n:zs,j:xi,v:Ti,p:rn,f:Ei,s:Pi,m:Ci,e:Si,k:$i,i:sn,g:ki,d:Ii,da:Ai,ea:Fi,fa:Oi,ba:Hn,ca:So,N:qn,xa:hc,ua:$o,h:zi,C:Bi,G:Ri,ta:Li,x:ji,ra:Ni,U:Vi,q:Di,y:Ui,K:Wi,S:ko,za:Gi,ya:Io,ka:Ao,la:Hi,_:It,B:Fo,I:Jn,ha:Oo,H:Do,a:x,wa:Je}}}var Fe={829644:(m,T,A,z,U)=>{if(n===void 0||!n.Eb)return 1;if((m=Ht(Number(m>>>0))).startsWith("./")&&(m=m.substring(2)),!(m=n.Eb.get(m)))return 2;if(T=Number(T>>>0),A=Number(A>>>0),z=Number(z>>>0),T+A>m.byteLength)return 3;try{let le=m.subarray(T,T+A);switch(U){case 0:W().set(le,z>>>0);break;case 1:n.mc?n.mc(z,le):n.bc(z,le);break;default:return 4}return 0}catch{return 4}},830468:(m,T,A)=>{n.Ob(m,W().subarray(T>>>0,T+A>>>0))},830532:()=>n.nc(),830574:m=>{n.Nb(m)},830611:()=>{n.Vb()},830642:()=>{n.Wb()},830671:()=>{n.$b()},830696:m=>n.Ub(m),830729:m=>n.Yb(m),830761:(m,T,A)=>{n.Kb(Number(m),Number(T),Number(A),!0)},830824:(m,T,A)=>{n.Kb(Number(m),Number(T),Number(A))},830881:()=>typeof wasmOffsetConverter<"u",830938:m=>{n.jb("Abs",m,void 0)},830989:m=>{n.jb("Neg",m,void 0)},831040:m=>{n.jb("Floor",m,void 0)},831093:m=>{n.jb("Ceil",m,void 0)},831145:m=>{n.jb("Reciprocal",m,void 0)},831203:m=>{n.jb("Sqrt",m,void 0)},831255:m=>{n.jb("Exp",m,void 0)},831306:m=>{n.jb("Erf",m,void 0)},831357:m=>{n.jb("Sigmoid",m,void 0)},831412:(m,T,A)=>{n.jb("HardSigmoid",m,{alpha:T,beta:A})},831491:m=>{n.jb("Log",m,void 0)},831542:m=>{n.jb("Sin",m,void 0)},831593:m=>{n.jb("Cos",m,void 0)},831644:m=>{n.jb("Tan",m,void 0)},831695:m=>{n.jb("Asin",m,void 0)},831747:m=>{n.jb("Acos",m,void 0)},831799:m=>{n.jb("Atan",m,void 0)},831851:m=>{n.jb("Sinh",m,void 0)},831903:m=>{n.jb("Cosh",m,void 0)},831955:m=>{n.jb("Asinh",m,void 0)},832008:m=>{n.jb("Acosh",m,void 0)},832061:m=>{n.jb("Atanh",m,void 0)},832114:m=>{n.jb("Tanh",m,void 0)},832166:m=>{n.jb("Not",m,void 0)},832217:(m,T,A)=>{n.jb("Clip",m,{min:T,max:A})},832286:m=>{n.jb("Clip",m,void 0)},832338:(m,T)=>{n.jb("Elu",m,{alpha:T})},832396:m=>{n.jb("Gelu",m,void 0)},832448:m=>{n.jb("Relu",m,void 0)},832500:(m,T)=>{n.jb("LeakyRelu",m,{alpha:T})},832564:(m,T)=>{n.jb("ThresholdedRelu",m,{alpha:T})},832634:(m,T)=>{n.jb("Cast",m,{to:T})},832692:m=>{n.jb("Add",m,void 0)},832743:m=>{n.jb("Sub",m,void 0)},832794:m=>{n.jb("Mul",m,void 0)},832845:m=>{n.jb("Div",m,void 0)},832896:m=>{n.jb("Pow",m,void 0)},832947:m=>{n.jb("Equal",m,void 0)},833e3:m=>{n.jb("Greater",m,void 0)},833055:m=>{n.jb("GreaterOrEqual",m,void 0)},833117:m=>{n.jb("Less",m,void 0)},833169:m=>{n.jb("LessOrEqual",m,void 0)},833228:(m,T,A,z,U)=>{n.jb("ReduceMean",m,{keepDims:!!T,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(U)>>>0)):[]})},833403:(m,T,A,z,U)=>{n.jb("ReduceMax",m,{keepDims:!!T,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(U)>>>0)):[]})},833577:(m,T,A,z,U)=>{n.jb("ReduceMin",m,{keepDims:!!T,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(U)>>>0)):[]})},833751:(m,T,A,z,U)=>{n.jb("ReduceProd",m,{keepDims:!!T,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(U)>>>0)):[]})},833926:(m,T,A,z,U)=>{n.jb("ReduceSum",m,{keepDims:!!T,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(U)>>>0)):[]})},834100:(m,T,A,z,U)=>{n.jb("ReduceL1",m,{keepDims:!!T,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(U)>>>0)):[]})},834273:(m,T,A,z,U)=>{n.jb("ReduceL2",m,{keepDims:!!T,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(U)>>>0)):[]})},834446:(m,T,A,z,U)=>{n.jb("ReduceLogSum",m,{keepDims:!!T,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(U)>>>0)):[]})},834623:(m,T,A,z,U)=>{n.jb("ReduceSumSquare",m,{keepDims:!!T,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(U)>>>0)):[]})},834803:(m,T,A,z,U)=>{n.jb("ReduceLogSumExp",m,{keepDims:!!T,noopWithEmptyAxes:!!A,axes:z?Array.from(ie().subarray(Number(z)>>>0,Number(U)>>>0)):[]})},834983:m=>{n.jb("Where",m,void 0)},835036:(m,T,A)=>{n.jb("Transpose",m,{perm:T?Array.from(ie().subarray(Number(T)>>>0,Number(A)>>>0)):[]})},835160:(m,T,A,z)=>{n.jb("DepthToSpace",m,{blocksize:T,mode:Ht(A),format:z?"NHWC":"NCHW"})},835293:(m,T,A,z)=>{n.jb("DepthToSpace",m,{blocksize:T,mode:Ht(A),format:z?"NHWC":"NCHW"})},835426:(m,T,A,z,U,le,Te,De,qe,it,xt,zt,Ut,Tr,Hs)=>{n.jb("ConvTranspose",m,{format:qe?"NHWC":"NCHW",autoPad:T,dilations:[A],group:z,kernelShape:[U],pads:[le,Te],strides:[De],wIsConst:()=>!!F()[it>>>0],outputPadding:xt?Array.from(ie().subarray(Number(xt)>>>0,Number(zt)>>>0)):[],outputShape:Ut?Array.from(ie().subarray(Number(Ut)>>>0,Number(Tr)>>>0)):[],activation:Ht(Hs)})},835859:(m,T,A,z,U,le,Te,De,qe,it,xt,zt,Ut,Tr)=>{n.jb("ConvTranspose",m,{format:De?"NHWC":"NCHW",autoPad:T,dilations:Array.from(ie().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:z,kernelShape:Array.from(ie().subarray(Number(U)>>>0,2+(Number(U)>>>0)>>>0)),pads:Array.from(ie().subarray(Number(le)>>>0,4+(Number(le)>>>0)>>>0)),strides:Array.from(ie().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!F()[qe>>>0],outputPadding:it?Array.from(ie().subarray(Number(it)>>>0,Number(xt)>>>0)):[],outputShape:zt?Array.from(ie().subarray(Number(zt)>>>0,Number(Ut)>>>0)):[],activation:Ht(Tr)})},836520:(m,T,A,z,U,le,Te,De,qe,it,xt,zt,Ut,Tr,Hs)=>{n.jb("ConvTranspose",m,{format:qe?"NHWC":"NCHW",autoPad:T,dilations:[A],group:z,kernelShape:[U],pads:[le,Te],strides:[De],wIsConst:()=>!!F()[it>>>0],outputPadding:xt?Array.from(ie().subarray(Number(xt)>>>0,Number(zt)>>>0)):[],outputShape:Ut?Array.from(ie().subarray(Number(Ut)>>>0,Number(Tr)>>>0)):[],activation:Ht(Hs)})},836953:(m,T,A,z,U,le,Te,De,qe,it,xt,zt,Ut,Tr)=>{n.jb("ConvTranspose",m,{format:De?"NHWC":"NCHW",autoPad:T,dilations:Array.from(ie().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:z,kernelShape:Array.from(ie().subarray(Number(U)>>>0,2+(Number(U)>>>0)>>>0)),pads:Array.from(ie().subarray(Number(le)>>>0,4+(Number(le)>>>0)>>>0)),strides:Array.from(ie().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!F()[qe>>>0],outputPadding:it?Array.from(ie().subarray(Number(it)>>>0,Number(xt)>>>0)):[],outputShape:zt?Array.from(ie().subarray(Number(zt)>>>0,Number(Ut)>>>0)):[],activation:Ht(Tr)})},837614:(m,T)=>{n.jb("GlobalAveragePool",m,{format:T?"NHWC":"NCHW"})},837705:(m,T,A,z,U,le,Te,De,qe,it,xt,zt,Ut,Tr)=>{n.jb("AveragePool",m,{format:Tr?"NHWC":"NCHW",auto_pad:T,ceil_mode:A,count_include_pad:z,storage_order:U,dilations:le?Array.from(ie().subarray(Number(le)>>>0,Number(Te)>>>0)):[],kernel_shape:De?Array.from(ie().subarray(Number(De)>>>0,Number(qe)>>>0)):[],pads:it?Array.from(ie().subarray(Number(it)>>>0,Number(xt)>>>0)):[],strides:zt?Array.from(ie().subarray(Number(zt)>>>0,Number(Ut)>>>0)):[]})},838184:(m,T)=>{n.jb("GlobalAveragePool",m,{format:T?"NHWC":"NCHW"})},838275:(m,T,A,z,U,le,Te,De,qe,it,xt,zt,Ut,Tr)=>{n.jb("AveragePool",m,{format:Tr?"NHWC":"NCHW",auto_pad:T,ceil_mode:A,count_include_pad:z,storage_order:U,dilations:le?Array.from(ie().subarray(Number(le)>>>0,Number(Te)>>>0)):[],kernel_shape:De?Array.from(ie().subarray(Number(De)>>>0,Number(qe)>>>0)):[],pads:it?Array.from(ie().subarray(Number(it)>>>0,Number(xt)>>>0)):[],strides:zt?Array.from(ie().subarray(Number(zt)>>>0,Number(Ut)>>>0)):[]})},838754:(m,T)=>{n.jb("GlobalMaxPool",m,{format:T?"NHWC":"NCHW"})},838841:(m,T,A,z,U,le,Te,De,qe,it,xt,zt,Ut,Tr)=>{n.jb("MaxPool",m,{format:Tr?"NHWC":"NCHW",auto_pad:T,ceil_mode:A,count_include_pad:z,storage_order:U,dilations:le?Array.from(ie().subarray(Number(le)>>>0,Number(Te)>>>0)):[],kernel_shape:De?Array.from(ie().subarray(Number(De)>>>0,Number(qe)>>>0)):[],pads:it?Array.from(ie().subarray(Number(it)>>>0,Number(xt)>>>0)):[],strides:zt?Array.from(ie().subarray(Number(zt)>>>0,Number(Ut)>>>0)):[]})},839316:(m,T)=>{n.jb("GlobalMaxPool",m,{format:T?"NHWC":"NCHW"})},839403:(m,T,A,z,U,le,Te,De,qe,it,xt,zt,Ut,Tr)=>{n.jb("MaxPool",m,{format:Tr?"NHWC":"NCHW",auto_pad:T,ceil_mode:A,count_include_pad:z,storage_order:U,dilations:le?Array.from(ie().subarray(Number(le)>>>0,Number(Te)>>>0)):[],kernel_shape:De?Array.from(ie().subarray(Number(De)>>>0,Number(qe)>>>0)):[],pads:it?Array.from(ie().subarray(Number(it)>>>0,Number(xt)>>>0)):[],strides:zt?Array.from(ie().subarray(Number(zt)>>>0,Number(Ut)>>>0)):[]})},839878:(m,T,A,z,U)=>{n.jb("Gemm",m,{alpha:T,beta:A,transA:z,transB:U})},839982:m=>{n.jb("MatMul",m,void 0)},840036:(m,T,A,z)=>{n.jb("ArgMax",m,{keepDims:!!T,selectLastIndex:!!A,axis:z})},840144:(m,T,A,z)=>{n.jb("ArgMin",m,{keepDims:!!T,selectLastIndex:!!A,axis:z})},840252:(m,T)=>{n.jb("Softmax",m,{axis:T})},840315:(m,T)=>{n.jb("Concat",m,{axis:T})},840375:(m,T,A,z,U)=>{n.jb("Split",m,{axis:T,numOutputs:A,splitSizes:z?Array.from(ie().subarray(Number(z)>>>0,Number(U)>>>0)):[]})},840531:m=>{n.jb("Expand",m,void 0)},840585:(m,T)=>{n.jb("Gather",m,{axis:Number(T)})},840656:(m,T)=>{n.jb("GatherElements",m,{axis:Number(T)})},840735:(m,T)=>{n.jb("GatherND",m,{batch_dims:Number(T)})},840814:(m,T,A,z,U,le,Te,De,qe,it,xt)=>{n.jb("Resize",m,{antialias:T,axes:A?Array.from(ie().subarray(Number(A)>>>0,Number(z)>>>0)):[],coordinateTransformMode:Ht(U),cubicCoeffA:le,excludeOutside:Te,extrapolationValue:De,keepAspectRatioPolicy:Ht(qe),mode:Ht(it),nearestMode:Ht(xt)})},841176:(m,T,A,z,U,le,Te)=>{n.jb("Slice",m,{starts:T?Array.from(ie().subarray(Number(T)>>>0,Number(A)>>>0)):[],ends:z?Array.from(ie().subarray(Number(z)>>>0,Number(U)>>>0)):[],axes:le?Array.from(ie().subarray(Number(le)>>>0,Number(Te)>>>0)):[]})},841440:m=>{n.jb("Tile",m,void 0)},841492:(m,T,A)=>{n.jb("InstanceNormalization",m,{epsilon:T,format:A?"NHWC":"NCHW"})},841606:(m,T,A)=>{n.jb("InstanceNormalization",m,{epsilon:T,format:A?"NHWC":"NCHW"})},841720:m=>{n.jb("Range",m,void 0)},841773:(m,T)=>{n.jb("Einsum",m,{equation:Ht(T)})},841854:(m,T,A,z,U)=>{n.jb("Pad",m,{mode:T,value:A,pads:z?Array.from(ie().subarray(Number(z)>>>0,Number(U)>>>0)):[]})},841997:(m,T,A,z,U,le)=>{n.jb("BatchNormalization",m,{epsilon:T,momentum:A,spatial:!!U,trainingMode:!!z,format:le?"NHWC":"NCHW"})},842166:(m,T,A,z,U,le)=>{n.jb("BatchNormalization",m,{epsilon:T,momentum:A,spatial:!!U,trainingMode:!!z,format:le?"NHWC":"NCHW"})},842335:(m,T,A)=>{n.jb("CumSum",m,{exclusive:Number(T),reverse:Number(A)})},842432:(m,T,A)=>{n.jb("DequantizeLinear",m,{axis:T,blockSize:A})},842522:(m,T,A,z,U)=>{n.jb("GridSample",m,{align_corners:T,mode:Ht(A),padding_mode:Ht(z),format:U?"NHWC":"NCHW"})},842692:(m,T,A,z,U)=>{n.jb("GridSample",m,{align_corners:T,mode:Ht(A),padding_mode:Ht(z),format:U?"NHWC":"NCHW"})},842862:(m,T)=>{n.jb("ScatterND",m,{reduction:Ht(T)})},842947:(m,T,A,z,U,le,Te,De,qe)=>{n.jb("Attention",m,{numHeads:T,isUnidirectional:A,maskFilterValue:z,scale:U,doRotary:le,qkvHiddenSizes:Te?Array.from(ie().subarray(Number(De)>>>0,Number(De)+Te>>>0)):[],pastPresentShareBuffer:!!qe})},843219:m=>{n.jb("BiasAdd",m,void 0)},843274:m=>{n.jb("BiasSplitGelu",m,void 0)},843335:m=>{n.jb("FastGelu",m,void 0)},843391:(m,T,A,z,U,le,Te,De,qe,it,xt,zt,Ut,Tr,Hs,Ho)=>{n.jb("Conv",m,{format:zt?"NHWC":"NCHW",auto_pad:T,dilations:A?Array.from(ie().subarray(Number(A)>>>0,Number(z)>>>0)):[],group:U,kernel_shape:le?Array.from(ie().subarray(Number(le)>>>0,Number(Te)>>>0)):[],pads:De?Array.from(ie().subarray(Number(De)>>>0,Number(qe)>>>0)):[],strides:it?Array.from(ie().subarray(Number(it)>>>0,Number(xt)>>>0)):[],w_is_const:()=>!!F()[Number(Ut)>>>0],activation:Ht(Tr),activation_params:Hs?Array.from(Le().subarray(Number(Hs)>>>0,Number(Ho)>>>0)):[]})},843975:m=>{n.jb("Gelu",m,void 0)},844027:(m,T,A,z,U,le,Te,De,qe)=>{n.jb("GroupQueryAttention",m,{numHeads:T,kvNumHeads:A,scale:z,softcap:U,doRotary:le,rotaryInterleaved:Te,smoothSoftmax:De,localWindowSize:qe})},844244:(m,T,A,z)=>{n.jb("LayerNormalization",m,{axis:T,epsilon:A,simplified:!!z})},844355:(m,T,A,z)=>{n.jb("LayerNormalization",m,{axis:T,epsilon:A,simplified:!!z})},844466:(m,T,A,z,U,le)=>{n.jb("MatMulNBits",m,{k:T,n:A,accuracyLevel:z,bits:U,blockSize:le})},844593:(m,T,A,z,U,le)=>{n.jb("MultiHeadAttention",m,{numHeads:T,isUnidirectional:A,maskFilterValue:z,scale:U,doRotary:le})},844752:(m,T)=>{n.jb("QuickGelu",m,{alpha:T})},844816:(m,T,A,z,U)=>{n.jb("RotaryEmbedding",m,{interleaved:!!T,numHeads:A,rotaryEmbeddingDim:z,scale:U})},844955:(m,T,A)=>{n.jb("SkipLayerNormalization",m,{epsilon:T,simplified:!!A})},845057:(m,T,A)=>{n.jb("SkipLayerNormalization",m,{epsilon:T,simplified:!!A})},845159:(m,T,A,z)=>{n.jb("GatherBlockQuantized",m,{gatherAxis:T,quantizeAxis:A,blockSize:z})},845280:m=>{n.Zb(m)},845314:(m,T)=>n.ac(Number(m),Number(T),n.Fb.dc,n.Fb.errors)};function Oe(m,T,A){return Or(async()=>{await n.Xb(Number(m),Number(T),Number(A))})}function Ye(){return typeof wasmOffsetConverter<"u"}class ye{constructor(T){J(this,"name","ExitStatus");this.message=`Program terminated with exit(${T})`,this.status=T}}var Ze=m=>{m.terminate(),m.onmessage=()=>{}},Ke=[],st=m=>{Ct.length==0&&(kr(),sr(Ct[0]));var T=Ct.pop();if(!T)return 6;Mt.push(T),$r[m.Ab]=T,T.Ab=m.Ab;var A={Bb:"run",fc:m.ec,Hb:m.Hb,Ab:m.Ab};return T.postMessage(A,m.Mb),0},Qe=0,ze=(m,T,...A)=>{for(var z=2*A.length,U=to(),le=In(8*z),Te=le>>>3,De=0;De>>0]=qe)}return m=jo(m,0,z,le,T),kn(U),m};function Je(m){if(c)return ze(0,1,m);if(P=m,!(0{if(P=m,c)throw nt(m),"unwind";Je(m)},Ct=[],Mt=[],yr=[],$r={},Nr=m=>{var T=m.Ab;delete $r[T],Ct.push(m),Mt.splice(Mt.indexOf(m),1),m.Ab=0,Yn(T)};function Vr(){yr.forEach(m=>m())}var sr=m=>new Promise(T=>{m.onmessage=U=>{var le=(U=U.data).Bb;if(U.Gb&&U.Gb!=nn()){var Te=$r[U.Gb];Te?Te.postMessage(U,U.Mb):v(`Internal error! Worker sent a message "${le}" to target pthread ${U.Gb}, but that thread no longer exists!`)}else le==="checkMailbox"?xe():le==="spawnThread"?st(U):le==="cleanupThread"?Nr($r[U.hc]):le==="loaded"?(m.loaded=!0,T(m)):le==="alert"?alert(`Thread ${U.ic}: ${U.text}`):U.target==="setimmediate"?m.postMessage(U):le==="callHandler"?n[U.Qb](...U.args):le&&v(`worker sent an unknown command ${le}`)},m.onerror=U=>{throw v(`worker sent an error! ${U.filename}:${U.lineno}: ${U.message}`),U};var A,z=[];for(A of[])n.propertyIsEnumerable(A)&&z.push(A);m.postMessage({Bb:"load",Rb:z,kc:x,lc:y})});function kr(){var m=new Worker((()=>{let T=URL;return self.location.href>"file:"&&self.location.href<"file;"?new T("ort.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Ct.push(m)}var Zs=m=>{B();var T=ve()[m+52>>>2>>>0];m=ve()[m+56>>>2>>>0],Vo(T,T-m),kn(T)},en=(m,T)=>{Qe=0,m=Uo(m,T),0>>=0);throw T>>>=0,A>>>=0,ve()[z.Ib+16>>>2>>>0]=0,ve()[z.Ib+4>>>2>>>0]=T,ve()[z.Ib+8>>>2>>>0]=A,m}function ht(m,T,A,z){return c?ze(2,1,m,T,A,z):Fs(m,T,A,z)}function Fs(m,T,A,z){if(m>>>=0,A>>>=0,z>>>=0,p===void 0)return 6;var U=[];return c&&U.length===0?ht(m,T>>>=0,A,z):(m={ec:A,Ab:m,Hb:z,Mb:U},c?(m.Bb="spawnThread",postMessage(m,U),0):st(m))}var Os=typeof TextDecoder<"u"?new TextDecoder:void 0,St=(m,T=0,A=NaN)=>{var z=(T>>>=0)+A;for(A=T;m[A]&&!(A>=z);)++A;if(16(U=(240&U)==224?(15&U)<<12|le<<6|Te:(7&U)<<18|le<<12|Te<<6|63&m[T++])?z+=String.fromCharCode(U):(U-=65536,z+=String.fromCharCode(55296|U>>10,56320|1023&U))}}else z+=String.fromCharCode(U)}return z},Ht=(m,T)=>(m>>>=0)?St(W(),m,T):"";function S(m,T,A){return c?ze(3,1,m,T,A):0}function X(m,T){if(c)return ze(4,1,m,T)}var R=m=>{for(var T=0,A=0;A=z?T++:2047>=z?T+=2:55296<=z&&57343>=z?(T+=4,++A):T+=3}return T},q=(m,T,A)=>{var z=W();if(T>>>=0,0=Te&&(Te=65536+((1023&Te)<<10)|1023&m.charCodeAt(++le)),127>=Te){if(T>=A)break;z[T++>>>0]=Te}else{if(2047>=Te){if(T+1>=A)break;z[T++>>>0]=192|Te>>6}else{if(65535>=Te){if(T+2>=A)break;z[T++>>>0]=224|Te>>12}else{if(T+3>=A)break;z[T++>>>0]=240|Te>>18,z[T++>>>0]=128|Te>>12&63}z[T++>>>0]=128|Te>>6&63}z[T++>>>0]=128|63&Te}}z[T>>>0]=0,m=T-U}else m=0;return m};function re(m,T){if(c)return ze(5,1,m,T)}function ge(m,T,A){if(c)return ze(6,1,m,T,A)}function Ae(m,T,A){return c?ze(7,1,m,T,A):0}function ot(m,T){if(c)return ze(8,1,m,T)}function ft(m,T,A){if(c)return ze(9,1,m,T,A)}function pt(m,T,A,z){if(c)return ze(10,1,m,T,A,z)}function vt(m,T,A,z){if(c)return ze(11,1,m,T,A,z)}function tt(m,T,A,z){if(c)return ze(12,1,m,T,A,z)}function At(m){if(c)return ze(13,1,m)}function qt(m,T){if(c)return ze(14,1,m,T)}function Ur(m,T,A){if(c)return ze(15,1,m,T,A)}var Hr,nr,Ir=()=>$e(""),ur=m=>{for(var T="";W()[m>>>0];)T+=Hr[W()[m++>>>0]];return T},us={},ds={};function Ar(m,T,A={}){return(function(z,U,le={}){var Te=U.name;if(!z)throw new nr(`type "${Te}" must have a positive integer typeid pointer`);if(ds.hasOwnProperty(z)){if(le.Sb)return;throw new nr(`Cannot register type '${Te}' twice`)}ds[z]=U,us.hasOwnProperty(z)&&(U=us[z],delete us[z],U.forEach(De=>De()))})(m,T,A)}var Ds=(m,T,A)=>{switch(T){case 1:return A?z=>F()[z>>>0]:z=>W()[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 (${T}): ${m}`)}};function Ls(m,T,A){A>>>=0,Ar(m>>>=0,{name:T=ur(T>>>0),fromWireType:z=>z,toWireType:function(z,U){if(typeof U!="bigint"&&typeof U!="number")throw U=U===null?"null":(z=typeof U)=="object"||z==="array"||z==="function"?U.toString():""+U,new TypeError(`Cannot convert "${U}" to ${this.name}`);return typeof U=="number"&&(U=BigInt(U)),U},Cb:vr,readValueFromPointer:Ds(T,A,T.indexOf("u")==-1),Db:null})}var vr=8;function ps(m,T,A,z){Ar(m>>>=0,{name:T=ur(T>>>0),fromWireType:function(U){return!!U},toWireType:function(U,le){return le?A:z},Cb:vr,readValueFromPointer:function(U){return this.fromWireType(W()[U>>>0])},Db:null})}var Jr=[],Br=[];function Ps(m){9<(m>>>=0)&&--Br[m+1]==0&&(Br[m]=void 0,Jr.push(m))}var hr=m=>{if(!m)throw new nr("Cannot use deleted val. handle = "+m);return Br[m]},ir=m=>{switch(m){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let T=Jr.pop()||Br.length;return Br[T]=m,Br[T+1]=1,T}};function ms(m){return this.fromWireType(ve()[m>>>2>>>0])}var Us={name:"emscripten::val",fromWireType:m=>{var T=hr(m);return Ps(m),T},toWireType:(m,T)=>ir(T),Cb:vr,readValueFromPointer:ms,Db:null};function Wr(m){return Ar(m>>>0,Us)}var Re=(m,T)=>{switch(T){case 4:return function(A){return this.fromWireType(Le()[A>>>2>>>0])};case 8:return function(A){return this.fromWireType(Ge()[A>>>3>>>0])};default:throw new TypeError(`invalid float width (${T}): ${m}`)}};function je(m,T,A){A>>>=0,Ar(m>>>=0,{name:T=ur(T>>>0),fromWireType:z=>z,toWireType:(z,U)=>U,Cb:vr,readValueFromPointer:Re(T,A),Db:null})}function rt(m,T,A,z,U){if(m>>>=0,A>>>=0,T=ur(T>>>0),U===-1&&(U=4294967295),U=De=>De,z===0){var le=32-8*A;U=De=>De<>>le}var Te=T.includes("unsigned")?function(De,qe){return qe>>>0}:function(De,qe){return qe};Ar(m,{name:T,fromWireType:U,toWireType:Te,Cb:vr,readValueFromPointer:Ds(T,A,z!==0),Db:null})}function Qt(m,T,A){function z(le){var Te=ve()[le>>>2>>>0];return le=ve()[le+4>>>2>>>0],new U(F().buffer,le,Te)}var U=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][T];Ar(m>>>=0,{name:A=ur(A>>>0),fromWireType:z,Cb:vr,readValueFromPointer:z},{Sb:!0})}function Ws(m,T){Ar(m>>>=0,{name:T=ur(T>>>0),fromWireType:function(A){for(var z,U=ve()[A>>>2>>>0],le=A+4,Te=le,De=0;De<=U;++De){var qe=le+De;De!=U&&W()[qe>>>0]!=0||(Te=Ht(Te,qe-Te),z===void 0?z=Te:(z+="\0",z+=Te),Te=qe+1)}return ns(A),z},toWireType:function(A,z){z instanceof ArrayBuffer&&(z=new Uint8Array(z));var U=typeof z=="string";if(!(U||z instanceof Uint8Array||z instanceof Uint8ClampedArray||z instanceof Int8Array))throw new nr("Cannot pass non-string to std::string");var le=U?R(z):z.length,Te=Sn(4+le+1),De=Te+4;if(ve()[Te>>>2>>>0]=le,U)q(z,De,le+1);else if(U)for(U=0;U>>0]=qe}else for(U=0;U>>0]=z[U];return A!==null&&A.push(ns,Te),Te},Cb:vr,readValueFromPointer:ms,Db(A){ns(A)}})}var Cs=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,rs=(m,T)=>{for(var A=m>>1,z=A+T/2;!(A>=z)&&_e()[A>>>0];)++A;if(32<(A<<=1)-m&&Cs)return Cs.decode(W().slice(m,A));for(A="",z=0;!(z>=T/2);++z){var U=se()[m+2*z>>>1>>>0];if(U==0)break;A+=String.fromCharCode(U)}return A},bn=(m,T,A)=>{if(A??(A=2147483647),2>A)return 0;var z=T;A=(A-=2)<2*m.length?A/2:m.length;for(var U=0;U>>1>>>0]=le,T+=2}return se()[T>>>1>>>0]=0,T-z},yn=m=>2*m.length,vn=(m,T)=>{for(var A=0,z="";!(A>=T/4);){var U=ie()[m+4*A>>>2>>>0];if(U==0)break;++A,65536<=U?(U-=65536,z+=String.fromCharCode(55296|U>>10,56320|1023&U)):z+=String.fromCharCode(U)}return z},xn=(m,T,A)=>{if(T>>>=0,A??(A=2147483647),4>A)return 0;var z=T;A=z+A-4;for(var U=0;U=le&&(le=65536+((1023&le)<<10)|1023&m.charCodeAt(++U)),ie()[T>>>2>>>0]=le,(T+=4)+4>A)break}return ie()[T>>>2>>>0]=0,T-z},de=m=>{for(var T=0,A=0;A=z&&++A,T+=4}return T};function I(m,T,A){if(m>>>=0,T>>>=0,A=ur(A>>>=0),T===2)var z=rs,U=bn,le=yn,Te=De=>_e()[De>>>1>>>0];else T===4&&(z=vn,U=xn,le=de,Te=De=>ve()[De>>>2>>>0]);Ar(m,{name:A,fromWireType:De=>{for(var qe,it=ve()[De>>>2>>>0],xt=De+4,zt=0;zt<=it;++zt){var Ut=De+4+zt*T;zt!=it&&Te(Ut)!=0||(xt=z(xt,Ut-xt),qe===void 0?qe=xt:(qe+="\0",qe+=xt),xt=Ut+T)}return ns(De),qe},toWireType:(De,qe)=>{if(typeof qe!="string")throw new nr(`Cannot pass non-string to C++ string type ${A}`);var it=le(qe),xt=Sn(4+it+T);return ve()[xt>>>2>>>0]=it/T,U(qe,xt+4,it+T),De!==null&&De.push(ns,xt),xt},Cb:vr,readValueFromPointer:ms,Db(De){ns(De)}})}function V(m,T){Ar(m>>>=0,{Tb:!0,name:T=ur(T>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function Y(m){$n(m>>>0,!l,1,!a,131072,!1),Vr()}var ae=m=>{if(!ue)try{if(m(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(ie(),m>>>2,m).value.then(xe),m+=128,Atomics.store(ie(),m>>>2,1))}var xe=()=>{var m=nn();m&&(ce(m),ae(eo))};function Ve(m,T){(m>>>=0)==T>>>0?setTimeout(xe):c?postMessage({Gb:m,Bb:"checkMailbox"}):(m=$r[m])&&m.postMessage({Bb:"checkMailbox"})}var He=[];function We(m,T,A,z,U){for(T>>>=0,z/=2,He.length=z,A=U>>>0>>>3,U=0;U>>0];return(T?Fe[T]:Qi[m])(...He)}var et=()=>{Qe=0};function wt(m){m>>>=0,c?postMessage({Bb:"cleanupThread",hc:m}):Nr($r[m])}function Bt(m){}var Lt=(m,T)=>{var A=ds[m];if(A===void 0)throw m=zo(m),A=ur(m),ns(m),new nr(`${T} has unknown type ${A}`);return A},Zt=(m,T,A)=>{var z=[];return m=m.toWireType(z,A),z.length&&(ve()[T>>>2>>>0]=ir(z)),m};function Gt(m,T,A){return T>>>=0,A>>>=0,m=hr(m>>>0),T=Lt(T,"emval::as"),Zt(T,A,m)}function fr(m,T){return T>>>=0,m=hr(m>>>0),(T=Lt(T,"emval::as")).toWireType(null,m)}var gr=m=>{try{m()}catch(T){$e(T)}},dr=0,wr=null,xr=0,ss=[],Yt={},Mr={},Fr=0,Yr=null,Ss=[];function Or(m){return(function(T){if(!ue){if(dr===0){var A=!1,z=!1;T((U=0)=>{if(!ue&&(xr=U,A=!0,z)){dr=2,gr(()=>Go(wr)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),U=!1;try{var le=(function(){var qe=ie()[wr+8>>>2>>>0];return qe=ut[Mr[qe]],--Qe,qe()})()}catch(qe){le=qe,U=!0}var Te=!1;if(!wr){var De=Yr;De&&(Yr=null,(U?De.reject:De.resolve)(le),Te=!0)}if(U&&!Te)throw le}}),z=!0,A||(dr=1,wr=(function(){var U=Sn(65548),le=U+12;ve()[U>>>2>>>0]=le,ve()[U+4>>>2>>>0]=le+65536,le=ss[0];var Te=Yt[le];return Te===void 0&&(Te=Fr++,Yt[le]=Te,Mr[Te]=le),le=Te,ie()[U+8>>>2>>>0]=le,U})(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),gr(()=>ro(wr)))}else dr===2?(dr=0,gr(so),ns(wr),wr=null,Ss.forEach(ae)):$e(`invalid state: ${dr}`);return xr}})(T=>{m().then(T)})}function hs(m){return m>>>=0,Or(async()=>{var T=await hr(m);return ir(T)})}var ar=[];function pr(m,T,A,z){return A>>>=0,z>>>=0,(m=ar[m>>>0])(null,T=hr(T>>>0),A,z)}var _r={},er=m=>{var T=_r[m];return T===void 0?ur(m):T};function qr(m,T,A,z,U){return A>>>=0,z>>>=0,U>>>=0,(m=ar[m>>>0])(T=hr(T>>>0),T[A=er(A)],z,U)}var Gs=()=>typeof globalThis=="object"?globalThis:Function("return this")();function zs(m){return(m>>>=0)==0?ir(Gs()):(m=er(m),ir(Gs()[m]))}var yi=m=>{var T=ar.length;return ar.push(m),T},vi=(m,T)=>{for(var A=Array(m),z=0;z>>2>>>0],"parameter "+z);return A},Eo=(m,T)=>Object.defineProperty(T,"name",{value:m});function xi(m,T,A){var z=(T=vi(m,T>>>0)).shift();m--;var U=`return function (obj, func, destructorsRef, args) { +`,le=0,Te=[];A===0&&Te.push("obj");for(var De=["retType"],qe=[z],it=0;itxt.name).join(", ")}) => ${z.name}>`,yi(Eo(A,m))}function Ti(m){return m=er(m>>>0),ir(n[m])}function rn(m,T){return T>>>=0,m=hr(m>>>0),T=hr(T),ir(m[T])}function Ei(m){9<(m>>>=0)&&(Br[m+1]+=1)}function Pi(){return ir([])}function Ci(m){m=hr(m>>>0);for(var T=Array(m.length),A=0;A>>0))}function $i(){return ir({})}function sn(m){for(var T=hr(m>>>=0);T.length;){var A=T.pop();T.pop()(A)}Ps(m)}function ki(m,T,A){T>>>=0,A>>>=0,m=hr(m>>>0),T=hr(T),A=hr(A),m[T]=A}function Ii(m,T){return T>>>=0,m=(m=Lt(m>>>0,"_emval_take_value")).readValueFromPointer(T),ir(m)}function Ai(m,T){m=-9007199254740992>m||9007199254740992>>=0,m=new Date(1e3*m),ie()[T>>>2>>>0]=m.getUTCSeconds(),ie()[T+4>>>2>>>0]=m.getUTCMinutes(),ie()[T+8>>>2>>>0]=m.getUTCHours(),ie()[T+12>>>2>>>0]=m.getUTCDate(),ie()[T+16>>>2>>>0]=m.getUTCMonth(),ie()[T+20>>>2>>>0]=m.getUTCFullYear()-1900,ie()[T+24>>>2>>>0]=m.getUTCDay(),m=(m.getTime()-Date.UTC(m.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,ie()[T+28>>>2>>>0]=m}var Po=m=>m%4==0&&(m%100!=0||m%400==0),Co=[0,31,60,91,121,152,182,213,244,274,305,335],Kn=[0,31,59,90,120,151,181,212,243,273,304,334];function Fi(m,T){m=-9007199254740992>m||9007199254740992>>=0,m=new Date(1e3*m),ie()[T>>>2>>>0]=m.getSeconds(),ie()[T+4>>>2>>>0]=m.getMinutes(),ie()[T+8>>>2>>>0]=m.getHours(),ie()[T+12>>>2>>>0]=m.getDate(),ie()[T+16>>>2>>>0]=m.getMonth(),ie()[T+20>>>2>>>0]=m.getFullYear()-1900,ie()[T+24>>>2>>>0]=m.getDay();var A=(Po(m.getFullYear())?Co:Kn)[m.getMonth()]+m.getDate()-1|0;ie()[T+28>>>2>>>0]=A,ie()[T+36>>>2>>>0]=-60*m.getTimezoneOffset(),A=new Date(m.getFullYear(),6,1).getTimezoneOffset();var z=new Date(m.getFullYear(),0,1).getTimezoneOffset();m=0|(A!=z&&m.getTimezoneOffset()==Math.min(z,A)),ie()[T+32>>>2>>>0]=m}function Oi(m){m>>>=0;var T=new Date(ie()[m+20>>>2>>>0]+1900,ie()[m+16>>>2>>>0],ie()[m+12>>>2>>>0],ie()[m+8>>>2>>>0],ie()[m+4>>>2>>>0],ie()[m>>>2>>>0],0),A=ie()[m+32>>>2>>>0],z=T.getTimezoneOffset(),U=new Date(T.getFullYear(),6,1).getTimezoneOffset(),le=new Date(T.getFullYear(),0,1).getTimezoneOffset(),Te=Math.min(le,U);return 0>A?ie()[m+32>>>2>>>0]=+(U!=le&&Te==z):0>>2>>>0]=T.getDay(),A=(Po(T.getFullYear())?Co:Kn)[T.getMonth()]+T.getDate()-1|0,ie()[m+28>>>2>>>0]=A,ie()[m>>>2>>>0]=T.getSeconds(),ie()[m+4>>>2>>>0]=T.getMinutes(),ie()[m+8>>>2>>>0]=T.getHours(),ie()[m+12>>>2>>>0]=T.getDate(),ie()[m+16>>>2>>>0]=T.getMonth(),ie()[m+20>>>2>>>0]=T.getYear(),m=T.getTime(),BigInt(isNaN(m)?-1:m/1e3)}function Hn(m,T,A,z,U,le,Te){return c?ze(16,1,m,T,A,z,U,le,Te):-52}function So(m,T,A,z,U,le){if(c)return ze(17,1,m,T,A,z,U,le)}var Ks={},Di=()=>performance.timeOrigin+performance.now();function qn(m,T){if(c)return ze(18,1,m,T);if(Ks[m]&&(clearTimeout(Ks[m].id),delete Ks[m]),!T)return 0;var A=setTimeout(()=>{delete Ks[m],ae(()=>No(m,performance.timeOrigin+performance.now()))},T);return Ks[m]={id:A,qc:T},0}function hc(m,T,A,z){m>>>=0,T>>>=0,A>>>=0,z>>>=0;var U=new Date().getFullYear(),le=new Date(U,0,1).getTimezoneOffset();U=new Date(U,6,1).getTimezoneOffset();var Te=Math.max(le,U);ve()[m>>>2>>>0]=60*Te,ie()[T>>>2>>>0]=+(le!=U),m=(T=De=>{var qe=Math.abs(De);return`UTC${0<=De?"-":"+"}${String(Math.floor(qe/60)).padStart(2,"0")}${String(qe%60).padStart(2,"0")}`})(le),T=T(U),UDate.now();function $o(m,T,A){return 0<=m&&3>=m?(m===0?m=Date.now():m=performance.timeOrigin+performance.now(),ee[A>>>0>>>3]=BigInt(Math.round(1e6*m)),0):28}var Tn=[],En=(m,T)=>{Tn.length=0;for(var A;A=W()[m++>>>0];){var z=A!=105;T+=(z&=A!=112)&&T%8?4:0,Tn.push(A==112?ve()[T>>>2>>>0]:A==106?ee[T>>>3]:A==105?ie()[T>>>2>>>0]:Ge()[T>>>3>>>0]),T+=z?8:4}return Tn};function zi(m,T,A){return m>>>=0,T=En(T>>>0,A>>>0),Fe[m](...T)}function Bi(m,T,A){return m>>>=0,T=En(T>>>0,A>>>0),Fe[m](...T)}var Ri=()=>{};function ji(m,T){return v(Ht(m>>>0,T>>>0))}var Ni=()=>{throw Qe+=1,"unwind"};function Vi(){return 4294901760}var Ui=()=>navigator.hardwareConcurrency;function Wi(){return $e("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function ko(m){m>>>=0;var T=W().length;if(m<=T||4294901760=A;A*=2){var z=T*(1+.2/A);z=Math.min(z,m+100663296);e:{z=(Math.min(4294901760,65536*Math.ceil(Math.max(m,z)/65536))-x.buffer.byteLength+65535)/65536|0;try{x.grow(z),B();var U=1;break e}catch{}U=void 0}if(U)return!0}return!1}var Pn=()=>($e("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Bs={},Qn=m=>{m.forEach(T=>{Pn()})};function Gi(){var m=Error().stack.toString().split(` +`);return m[0]=="Error"&&m.shift(),Qn(m),Bs.Lb=Pn(),Bs.cc=m,Bs.Lb}function Io(m,T,A){if(m>>>=0,T>>>=0,Bs.Lb==m)var z=Bs.cc;else(z=Error().stack.toString().split(` +`))[0]=="Error"&&z.shift(),Qn(z);for(var U=3;z[U]&&Pn()!=m;)++U;for(m=0;m>>2>>>0]=Pn();return m}var $s,Xn={},Ki=()=>{if(!$s){var m,T={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(m in Xn)Xn[m]===void 0?delete T[m]:T[m]=Xn[m];var A=[];for(m in T)A.push(`${m}=${T[m]}`);$s=A}return $s};function Ao(m,T){if(c)return ze(19,1,m,T);m>>>=0,T>>>=0;var A=0;return Ki().forEach((z,U)=>{var le=T+A;for(U=ve()[m+4*U>>>2>>>0]=le,le=0;le>>0]=z.charCodeAt(le);F()[U>>>0]=0,A+=z.length+1}),0}function Hi(m,T){if(c)return ze(20,1,m,T);m>>>=0,T>>>=0;var A=Ki();ve()[m>>>2>>>0]=A.length;var z=0;return A.forEach(U=>z+=U.length+1),ve()[T>>>2>>>0]=z,0}function Fo(m){return c?ze(21,1,m):52}function Jn(m,T,A,z){return c?ze(22,1,m,T,A,z):52}function Oo(m,T,A,z){return c?ze(23,1,m,T,A,z):70}var qi=[null,[],[]];function Do(m,T,A,z){if(c)return ze(24,1,m,T,A,z);T>>>=0,A>>>=0,z>>>=0;for(var U=0,le=0;le>>2>>>0],De=ve()[T+4>>>2>>>0];T+=8;for(var qe=0;qe>>0],xt=qi[m];it===0||it===10?((m===1?E:v)(St(xt)),xt.length=0):xt.push(it)}U+=De}return ve()[z>>>2>>>0]=U,0}c||(function(){for(var m=n.numThreads-1;m--;)kr();Ke.unshift(()=>{Pe++,(function(T){c?T():Promise.all(Ct.map(sr)).then(T)})(()=>Me())})})();for(var Lo=Array(256),Cn=0;256>Cn;++Cn)Lo[Cn]=String.fromCharCode(Cn);Hr=Lo,nr=n.BindingError=class extends Error{constructor(m){super(m),this.name="BindingError"}},n.InternalError=class extends Error{constructor(m){super(m),this.name="InternalError"}},Br.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>Br.length/2-5-Jr.length;var ut,Qi=[Je,nt,ht,S,X,re,ge,Ae,ot,ft,pt,vt,tt,At,qt,Ur,Hn,So,qn,Ao,Hi,Fo,Jn,Oo,Do];(async function(){function m(z,U){return ut=z.exports,ut=(function(){var le=ut,Te={};for(let[De,qe]of Object.entries(le))Te[De]=typeof qe=="function"?(...it)=>{ss.push(De);try{return qe(...it)}finally{ue||(ss.pop(),wr&&dr===1&&ss.length===0&&(dr=0,Qe+=1,gr(Wo),typeof Fibers<"u"&&Fibers.rc()))}}:qe;return Te})(),ut=(function(){var le=ut,Te=qe=>it=>qe(it)>>>0,De=qe=>()=>qe()>>>0;return(le=Object.assign({},le)).Da=Te(le.Da),le.fb=De(le.fb),le.hb=Te(le.hb),le.tb=Te(le.tb),le.ub=De(le.ub),le.__cxa_get_exception_ptr=Te(le.__cxa_get_exception_ptr),le})(),yr.push(ut.ib),y=U,Me(),ut}Pe++;var T=we();if(n.instantiateWasm)return new Promise(z=>{n.instantiateWasm(T,(U,le)=>{m(U,le),z(U.exports)})});if(c)return new Promise(z=>{Ie=U=>{var le=new WebAssembly.Instance(U,we());z(m(le,U))}});Ce??(Ce=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",w):w+"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 U=Ce;if(!pe&&typeof WebAssembly.instantiateStreaming=="function"&&!j(U))try{var le=fetch(U,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(le,z)}catch(Te){v(`wasm streaming compile failed: ${Te}`),v("falling back to ArrayBuffer instantiation")}return(async function(Te,De){try{var qe=await(async function(it){if(!pe)try{var xt=await f(it);return new Uint8Array(xt)}catch{}if(it==Ce&&pe)it=new Uint8Array(pe);else{if(!_)throw"both async and sync fetching of the wasm failed";it=_(it)}return it})(Te);return await WebAssembly.instantiate(qe,De)}catch(it){v(`failed to asynchronously prepare wasm: ${it}`),$e(it)}})(U,z)})(T);return m(A.instance,A.module)}catch(z){return o(z),Promise.reject(z)}})();var zo=m=>(zo=ut.Da)(m),Bo=()=>(Bo=ut.Ea)();n._OrtInit=(m,T)=>(n._OrtInit=ut.Fa)(m,T),n._OrtGetLastError=(m,T)=>(n._OrtGetLastError=ut.Ga)(m,T),n._OrtCreateSessionOptions=(m,T,A,z,U,le,Te,De,qe,it)=>(n._OrtCreateSessionOptions=ut.Ha)(m,T,A,z,U,le,Te,De,qe,it),n._OrtAppendExecutionProvider=(m,T,A,z,U)=>(n._OrtAppendExecutionProvider=ut.Ia)(m,T,A,z,U),n._OrtAddFreeDimensionOverride=(m,T,A)=>(n._OrtAddFreeDimensionOverride=ut.Ja)(m,T,A),n._OrtAddSessionConfigEntry=(m,T,A)=>(n._OrtAddSessionConfigEntry=ut.Ka)(m,T,A),n._OrtReleaseSessionOptions=m=>(n._OrtReleaseSessionOptions=ut.La)(m),n._OrtCreateSession=(m,T,A)=>(n._OrtCreateSession=ut.Ma)(m,T,A),n._OrtReleaseSession=m=>(n._OrtReleaseSession=ut.Na)(m),n._OrtGetInputOutputCount=(m,T,A)=>(n._OrtGetInputOutputCount=ut.Oa)(m,T,A),n._OrtGetInputOutputMetadata=(m,T,A,z)=>(n._OrtGetInputOutputMetadata=ut.Pa)(m,T,A,z),n._OrtFree=m=>(n._OrtFree=ut.Qa)(m),n._OrtCreateTensor=(m,T,A,z,U,le)=>(n._OrtCreateTensor=ut.Ra)(m,T,A,z,U,le),n._OrtGetTensorData=(m,T,A,z,U)=>(n._OrtGetTensorData=ut.Sa)(m,T,A,z,U),n._OrtReleaseTensor=m=>(n._OrtReleaseTensor=ut.Ta)(m),n._OrtCreateRunOptions=(m,T,A,z)=>(n._OrtCreateRunOptions=ut.Ua)(m,T,A,z),n._OrtAddRunConfigEntry=(m,T,A)=>(n._OrtAddRunConfigEntry=ut.Va)(m,T,A),n._OrtReleaseRunOptions=m=>(n._OrtReleaseRunOptions=ut.Wa)(m),n._OrtCreateBinding=m=>(n._OrtCreateBinding=ut.Xa)(m),n._OrtBindInput=(m,T,A)=>(n._OrtBindInput=ut.Ya)(m,T,A),n._OrtBindOutput=(m,T,A,z)=>(n._OrtBindOutput=ut.Za)(m,T,A,z),n._OrtClearBoundOutputs=m=>(n._OrtClearBoundOutputs=ut._a)(m),n._OrtReleaseBinding=m=>(n._OrtReleaseBinding=ut.$a)(m),n._OrtRunWithBinding=(m,T,A,z,U)=>(n._OrtRunWithBinding=ut.ab)(m,T,A,z,U),n._OrtRun=(m,T,A,z,U,le,Te,De)=>(n._OrtRun=ut.bb)(m,T,A,z,U,le,Te,De),n._OrtEndProfiling=m=>(n._OrtEndProfiling=ut.cb)(m),n._JsepOutput=(m,T,A)=>(n._JsepOutput=ut.db)(m,T,A),n._JsepGetNodeName=m=>(n._JsepGetNodeName=ut.eb)(m);var nn=()=>(nn=ut.fb)(),ns=n._free=m=>(ns=n._free=ut.gb)(m),Sn=n._malloc=m=>(Sn=n._malloc=ut.hb)(m),$n=(m,T,A,z,U,le)=>($n=ut.kb)(m,T,A,z,U,le),Ro=()=>(Ro=ut.lb)(),jo=(m,T,A,z,U)=>(jo=ut.mb)(m,T,A,z,U),Yn=m=>(Yn=ut.nb)(m),Zn=m=>(Zn=ut.ob)(m),No=(m,T)=>(No=ut.pb)(m,T),eo=()=>(eo=ut.qb)(),Vo=(m,T)=>(Vo=ut.rb)(m,T),kn=m=>(kn=ut.sb)(m),In=m=>(In=ut.tb)(m),to=()=>(to=ut.ub)(),Uo=n.dynCall_ii=(m,T)=>(Uo=n.dynCall_ii=ut.vb)(m,T),ro=m=>(ro=ut.wb)(m),Wo=()=>(Wo=ut.xb)(),Go=m=>(Go=ut.yb)(m),so=()=>(so=ut.zb)();return n.stackSave=()=>to(),n.stackRestore=m=>kn(m),n.stackAlloc=m=>In(m),n.setValue=function(m,T,A="i8"){switch(A.endsWith("*")&&(A="*"),A){case"i1":case"i8":F()[m>>>0]=T;break;case"i16":se()[m>>>1>>>0]=T;break;case"i32":ie()[m>>>2>>>0]=T;break;case"i64":ee[m>>>3]=BigInt(T);break;case"float":Le()[m>>>2>>>0]=T;break;case"double":Ge()[m>>>3>>>0]=T;break;case"*":ve()[m>>>2>>>0]=T;break;default:$e(`invalid type for setValue: ${A}`)}},n.getValue=function(m,T="i8"){switch(T.endsWith("*")&&(T="*"),T){case"i1":case"i8":return F()[m>>>0];case"i16":return se()[m>>>1>>>0];case"i32":return ie()[m>>>2>>>0];case"i64":return ee[m>>>3];case"float":return Le()[m>>>2>>>0];case"double":return Ge()[m>>>3>>>0];case"*":return ve()[m>>>2>>>0];default:$e(`invalid type for getValue: ${T}`)}},n.UTF8ToString=Ht,n.stringToUTF8=q,n.lengthBytesUTF8=R,(function m(){if(0{Ca(),Aa=typeof location>"u"?void 0:location.origin,Fa=self.location.href>"file:"&&self.location.href<"file;",dd=()=>{{if(Fa){let e=URL;return new URL(new e("ort.bundle.min.mjs",self.location.href).href,Aa).href}return self.location.href}},es=dd(),pd=()=>{if(es&&!es.startsWith("blob:"))return es.substring(0,es.lastIndexOf("/")+1)},Zo=(e,r)=>{try{let t=r??es;return(t?new URL(e,t):new URL(e)).origin===Aa}catch{return!1}},md=(e,r)=>{let t=r??es;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},hd=(e,r)=>`${r??"./"}${e}`,Oa=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},_d=async e=>(await import(e)).default,Da=(ax(),ao(id)).default,fd=async()=>{if(!es)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Zo(es))return[void 0,Da()];let e=await Oa(es);return[e,Da(e)]},La=(lx(),ao(ld)).default,gd=async(e,r,t)=>{if(!e&&!r&&La&&es&&Zo(es))return[void 0,La];{let s="ort-wasm-simd-threaded.jsep.mjs",o=e??md(s,r),n=t&&o&&!Zo(o,r),i=n?await Oa(o):o??hd(s,r);return[n?i:void 0,await _d(i)]}}}),Ba,ei,po,Ra,wd,Md,bd,ja,Xt,un=Ne(()=>{za(),ei=!1,po=!1,Ra=!1,wd=()=>{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}},Md=()=>{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}},bd=()=>{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(ei)return Promise.resolve();if(po)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ra)throw new Error("previous call to 'initializeWebAssembly()' failed.");po=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!bd())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Md())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=wd();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 gd(a,n,t>1),f=!1,_=[];if(r>0&&_.push(new Promise(M=>{setTimeout(()=>{f=!0,M()},r)})),_.push(new Promise((M,k)=>{let w={numThreads:t};if(p)w.wasmBinary=p;else if(c||n)w.locateFile=b=>c??n+b;else if(a&&a.indexOf("blob:")!==0)w.locateFile=b=>new URL(b,a).href;else if(d){let b=pd();b&&(w.locateFile=$=>b+$)}u(w).then(b=>{po=!1,ei=!0,Ba=b,M(),d&&URL.revokeObjectURL(d)},b=>{po=!1,Ra=!0,k(b)})})),await Promise.race(_),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},Xt=()=>{if(ei&&Ba)return Ba;throw new Error("WebAssembly is not initialized yet.")}}),bs,ti,Wt,Na=Ne(()=>{un(),bs=(e,r)=>{let t=Xt(),s=t.lengthBytesUTF8(e)+1,o=t._malloc(s);return t.stringToUTF8(e,o,s),r.push(o),o},ti=(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")ti(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}`)})},Wt=e=>{let r=Xt(),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)}}}),yd,cx=Ne(()=>{un(),Na(),yd=e=>{let r=Xt(),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=bs(e.tag,s)),t=r._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,n),t===0&&Wt("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&ti(e.extra,"",new WeakSet,(i,a)=>{let l=bs(i,s),c=bs(a,s);r._OrtAddRunConfigEntry(t,l,c)!==0&&Wt(`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}}}),vd,xd,Td,mo,Ed,Pd,ux=Ne(()=>{un(),Na(),vd=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}`)}},xd=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Td=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=bs(r,s),n=bs(t,s);Xt()._OrtAddSessionConfigEntry(e,o,n)!==0&&Wt(`Can't set a session config entry: ${r} - ${t}.`)},Ed=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=bs(o,t),a=n.length,l=0,c=0;if(a>0){l=Xt()._malloc(a*Xt().PTR_SIZE),t.push(l),c=Xt()._malloc(a*Xt().PTR_SIZE),t.push(c);for(let p=0;p{let r=Xt(),t=0,s=[],o=e||{};Td(o);try{let n=vd(o.graphOptimizationLevel??"all"),i=xd(o.executionMode??"sequential"),a=typeof o.logId=="string"?bs(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"?bs(o.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,a,l,c,p),t===0&&Wt("Can't create session options."),o.executionProviders&&await Ed(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=bs(d,s);r._OrtAddFreeDimensionOverride(t,f,u)!==0&&Wt(`Can't set a free dimension override: ${d} - ${u}.`)}return o.extra!==void 0&&ti(o.extra,"",new WeakSet,(d,u)=>{mo(t,d,u,s)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&Wt("Can't release session options."),s.forEach(i=>r._free(i)),n}}}),Nn,Rs,dn,Va,ri,Ua,Wa,Ga,gt=Ne(()=>{Nn=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}`)}},Rs=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}`)}},dn=(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}`)}},ri=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,Cd=Ne(()=>{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)}}),Sd,$d,kd,Id,Ha,Ad,Dt,js=Ne(()=>{gt(),Sd=["V","I","W","E","F"],$d=(e,r)=>{console.log(`[${Sd[e]},${new Date().toISOString()}]${r}`)},Ha=(e,r)=>{kd=e,Id=r},Ad=(e,r)=>{let t=ri(e),s=ri(kd);t>=s&&$d(t,typeof r=="function"?r():r)},Dt=(...e)=>{Id&&Ad(...e)}}),Fd,Vn,be,si,Od,Dd,Ld,Et=Ne(()=>{Fd=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},Vn=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=Fd.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}},be=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])}},si=class Xo{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,Bd,Ja,Rd,Ya,Za,el,jd,Nd,dx=Ne(()=>{js(),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},Bd=1,Ja=()=>Bd++,Rd=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=Rd.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)}},jd=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)}},Nd=(...e)=>new jd(...e)}),ni,Vd,Ud,px=Ne(()=>{gt(),un(),zd(),dx(),js(),ni=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Vd=(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])},Ud=class{constructor(e){this.tensorManager=Nd(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=>Vd(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=ni.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=ni.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(!Xt().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=ni.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=Ne(()=>{}),rl,oi,ii,Wd,Gd,sl,nl,Kd,Hd,mx=Ne(()=>{js(),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]]),oi=[],ii=e=>Math.ceil(Number(e)/16)*16,Wd=e=>{for(let r=0;rGd++,nl=async(e,r,t,s)=>{let o=ii(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()}},Kd=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)oi.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=ii(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=ii(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=Wd(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)}},Hd=(...e)=>new Kd(...e)}),qd,Nt,cr=Ne(()=>{qd=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 qd(e)}),Un,ai,Sr,jr,ct,or,ol,Wn,Qs,lt,ho,ke,at,Qd,il,Xd,Jd,Pt=Ne(()=>{gt(),Et(),Un=64,ai=(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}`)}},Sr=(e,r=1)=>{let t=ai(e,r);return typeof t=="string"?t:t[0]},jr=(e,r=1)=>{let t=ai(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:be.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})`,Wn=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,Qs=(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,ho=(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=ai(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},M=n?"uniforms.":"",k=`${M}${e}_shape`,w=`${M}${e}_strides`,b="";for(let j=0;j ${u.indices} { + var indices: ${u.indices}; + var current = offset; + ${b} + return indices; + }`,E=j=>(_.offsetToIndices=!0,i<2?j:`o2i_${e}(${j})`),v=[];if(i>=2)for(let j=i-1;j>=0;j--)v.push(`${lt(w,j,i)} * (indices[${j}])`);let x=i<2?"":` + fn i2o_${e}(indices: ${u.indices}) -> u32 { + return ${v.join("+")}; + }`,y=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)}`,D=(j,F,W)=>i<2?`${j}=${W};`:`${lt(j,F,i)}=${W};`,K={},G=(j,F)=>{_.broadcastedIndicesToOffset=!0;let W=`${F.name}broadcastedIndicesTo${e}Offset`;if(W in K)return`${W}(${j})`;let se=[];for(let _e=i-1;_e>=0;_e--){let ie=F.indicesGet("outputIndices",_e+F.rank-i);se.push(`${O(w,_e)} * (${ie} % ${O(k,_e)})`)}return K[W]=`fn ${W}(outputIndices: ${F.type.indices}) -> u32 { + return ${se.length>0?se.join("+"):"0u"}; + }`,`${W}(${j})`},N=(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(W=>`d${W}: u32`).join(", "),F=a.map(W=>`d${W}`).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})`)},oe=j=>i<2?te(j):(_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}ByIndices(${j})`),pe=i<2?"":` + fn set_${e}ByIndices(indices: ${u.indices}, value: ${p}) { + ${N(`i2o_${e}(indices)`,"value")} + }`,ue=i<2?"":(()=>{let j=a.map(W=>`d${W}: u32`).join(", "),F=a.map(W=>`d${W}`).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(x),F=!0),_.broadcastedIndicesToOffset&&(Object.values(K).forEach(W=>j.push(W)),F=!0),_.set&&(j.push(ue),F=!0),_.setByIndices&&(j.push(pe),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 ${w} = ${u.indices}(${be.computeStrides(t).join(",")});`),j.join(` +`)},type:u,offsetToIndices:E,indicesToOffset:y,broadcastedIndicesToOffset:G,indices:P,indicesGet:O,indicesSet:D,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 W=j.slice(0,i).map(f).join(",");return i===0?N("0u",F):i===1?N(W[0],F):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}(${W}, ${F})`)},setByOffset:N,setByIndices:(j,F)=>i<2?N(j,F):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}ByIndices(${j}, ${F});`),get:Z,getByOffset:te,getByIndices:oe,usage:s,name:e,strides:w,shape:k,rank:i}},ke=(e,r,t,s=1)=>ho(e,r,t,"input",s),at=(e,r,t,s=1)=>ho(e,r,t,"output",s),Qd=(e,r,t)=>ho(e,r,t,"atomicOutput",1),il=(e,r,t,s=1)=>ho(e,r,t,"internal",s),Xd=class{constructor(e,r){this.normalizedDispatchGroup=e,this.limits=r,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=Un){let r=typeof e=="number"?e:e[0],t=typeof e=="number"?1:e[1],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])}},Jd=(e,r)=>new Xd(e,r)}),Yd,al,Zd,ep,tp,rp,ts,sp,np,Xs=Ne(()=>{gt(),Et(),cr(),Pt(),Yd=(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(),Zd=(e,r)=>be.sortBasedOnPerm(e,al(e.length,r)),ep=(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=Zd(e.dims,o),i=e.dims,a=n,l=s<2||rp(o,e.dims),c;if(l)return c=_=>{let M=ke("input",t,i,4),k=at("output",t,a,4);return` + ${_.registerUniform("output_size","u32").declareVariables(M,k)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let _=be.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}=tp(e.dims,o),u=be.areEqual(d,[2,3,1]),f=be.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=M=>{let k=ke("a",t,i.length),w=at("output",t,a.length);return` + ${M.registerUniform("output_size","u32").declareVariables(k,w)} + var tile : array, ${_}>; + ${M.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]) { + ${w.setByIndices(`${w.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let M=be.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/_),y:Math.ceil(a[0]/_)},programUniforms:[{type:12,data:M},...ct(i,a)]}},getShaderSource:c}}return c=_=>{let M=ke("a",t,i.length),k=at("output",t,a.length);return` + ${_.registerUniform("output_size","u32").declareVariables(M,k)} + + ${ep(o,s,M,k)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${k.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${k.setByOffset("global_idx",M.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let _=be.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ct(i,a)]}},getShaderSource:c}},sp=(e,r)=>{Yd(e.inputs,r.perm),e.compute(ts(e.inputs[0],r.perm))},np=e=>Nt({perm:e.perm})}),op,ip,ap,lp,cp,up,dp,pp,mp,hp,ys,_p,fp,gp,wp,Mp,bp,yp,vp,xp,Tp,hx=Ne(()=>{gt(),Et(),Pt(),cl(),Xs(),op={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"},ip={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"},ap={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},lp={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},cp=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,o]},dp=(e,r)=>{let t=e.length+r.length,s=[],o=0;for(let n=0;n{for(let t=0;t{let t=[];if(!pp(e,r)){for(let s=0;st.push(s))}return t},hp=(e,r,t,s,o,n,i)=>{let a=t[0].dims,l=be.size(n),c=be.size(i),p=ke("_A",t[0].dataType,a),d=at("output",o,n),u=64;l===1&&(u=256);let f=` + var aBestValues : array; + `,_=M=>` + ${M.registerUniform("reduceSize","u32").declareVariables(p,d)} + ${f} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${M.mainStart(u)} + + let outputIndex = global_idx / ${u}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${ap[s]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${u}) { + let candidate = f32(${p.getByOffset("offset + k")}); + bestValue = ${op[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 = ${ip[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}(${lp[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}]})}},ys=(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=be.normalizeAxes(n,e.inputs[0].dims.length),a=i,l=e.inputs[0],c=mp(a,e.inputs[0].dims.length);c.length>0&&(l=e.compute(ts(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],a=cp(a.length,l.dims.length));let[p,d]=up(l.dims,a),u=p;o.keepDims&&(u=dp(p,i)),e.compute(hp(r,o.cacheKey,[l],s,e.inputs[0].dataType,u,d),{inputs:[l]})},_p=(e,r)=>{ys(e,"ReduceMeanShared",r,"mean")},fp=(e,r)=>{ys(e,"ReduceL1Shared",r,"l1")},gp=(e,r)=>{ys(e,"ReduceL2Shared",r,"l2")},wp=(e,r)=>{ys(e,"ReduceLogSumExpShared",r,"logSumExp")},Mp=(e,r)=>{ys(e,"ReduceMaxShared",r,"max")},bp=(e,r)=>{ys(e,"ReduceMinShared",r,"min")},yp=(e,r)=>{ys(e,"ReduceProdShared",r,"prod")},vp=(e,r)=>{ys(e,"ReduceSumShared",r,"sum")},xp=(e,r)=>{ys(e,"ReduceSumSquareShared",r,"sumSquare")},Tp=(e,r)=>{ys(e,"ReduceLogSumShared",r,"logSum")}}),vs,Ep,li,ll,xs,Pp,Cp,Sp,$p,kp,Ip,Ap,Fp,Op,Dp,Ts,Lp,zp,Bp,Rp,jp,Np,Vp,Up,Wp,Gp,cl=Ne(()=>{gt(),Et(),cr(),Pt(),hx(),vs=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.")},Ep=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],li=(e,r,t,s,o,n,i=!1,a=!1)=>{let l=[],c=t[0].dims,p=c.length,d=be.normalizeAxes(o,p),u=!a&&d.length===0;c.forEach((M,k)=>{u||d.indexOf(k)>=0?i&&l.push(1):l.push(M)});let f=l.length,_=be.size(l);return{name:e,shaderCache:r,getShaderSource:M=>{let k=[],w=ke("_A",t[0].dataType,p),b=at("output",n,f),$=s(w,b,d),E=$[2];for(let v=0,x=0;v=0?(i&&x++,E=`for(var j${v}: u32 = 0; j${v} < ${c[v]}; j${v}++) { + ${$[2].includes("last_index")?`let last_index = j${v};`:""} + ${w.indicesSet("input_indices",v,`j${v}`)} + ${E} + }`):(k.push(`${w.indicesSet("input_indices",v,b.indicesGet("output_indices",x))};`),x++);return` + + ${M.registerUniform("output_size","u32").declareVariables(w,b)} + + ${M.mainStart()} + ${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${w.type.indices}; + let output_indices = ${b.offsetToIndices("global_idx")}; + + ${k.join(` +`)} + ${$[0]} // init ops for reduce max/min + ${$[1]} + ${E} + ${$[3]} + ${$.length===4?b.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})},xs=(e,r,t,s)=>{let o=e.inputs,n=o.length===1?t:ll(o,t);e.compute(li(r,{hint:n.cacheKey,inputDependencies:["rank"]},[o[0]],n.noopWithEmptyAxes&&n.axes.length===0?Ep:s,n.axes,o[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},Pp=(e,r)=>{vs(e.inputs),xs(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},Cp=(e,r)=>{vs(e.inputs),xs(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},Sp=(e,r)=>{vs(e.inputs),xs(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);"])},$p=(e,r)=>{vs(e.inputs),xs(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},kp=(e,r)=>{vs(e.inputs),xs(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")});`,""]})},Ip=(e,r)=>{vs(e.inputs),xs(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});`]})},Ap=(e,r)=>{vs(e.inputs),xs(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")});`,""]})},Fp=(e,r)=>{vs(e.inputs),xs(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},Op=(e,r)=>{vs(e.inputs),xs(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},Dp=(e,r)=>{vs(e.inputs),xs(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;`,""])},Ts=(e,r,t)=>{if(r.length===0)return t;let s=1,o=1;for(let n=0;n1024},Lp=(e,r)=>{Ts(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Ip(e,r):_p(e,r)},zp=(e,r)=>{Ts(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Cp(e,r):fp(e,r)},Bp=(e,r)=>{Ts(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Sp(e,r):gp(e,r)},Rp=(e,r)=>{Ts(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?$p(e,r):wp(e,r)},jp=(e,r)=>{Ts(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?kp(e,r):Mp(e,r)},Np=(e,r)=>{Ts(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Ap(e,r):bp(e,r)},Vp=(e,r)=>{Ts(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Fp(e,r):yp(e,r)},Up=(e,r)=>{Ts(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Op(e,r):vp(e,r)},Wp=(e,r)=>{Ts(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Dp(e,r):xp(e,r)},Gp=(e,r)=>{Ts(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Pp(e,r):Tp(e,r)}}),ul,Kp,Hp,dl,_x=Ne(()=>{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.")},Kp=(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(li("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Hp=(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(li("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},dl=e=>Nt(e)}),qp,ci,Qp,Xp,Jp,_o,Yp,Zp,pl=Ne(()=>{gt(),Et(),tl(),Pt(),qp=(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 M=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||(M=i.dims[3])}let k=_+M,w=-1,b=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:M,kvSequenceLength:_,totalSequenceLength:k,maxSequenceLength:w,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:b,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ci=(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; + `,Qp=(e,r,t,s,o,n,i,a)=>{let l=or(i?1:n),c=64,p=n/l;p{let b=at("x",e.dataType,e.dims,l),$=[b],E=i?ke("seq_lens",i.dataType,i.dims):void 0;E&&$.push(E);let v=a?ke("total_sequence_length_input",a.dataType,a.dims):void 0;v&&$.push(v);let x=jr(e.dataType),y=[{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; + ${w.registerUniforms(y).declareVariables(...$)} + ${w.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; + ${ci(E,v,!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] = ${b.type.value}(${x}(1.0) / ${x}(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] = ${b.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] = ${b.type.value}(${x}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${f};${l}`,inputDependencies:M},getShaderSource:k,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:r*t},programUniforms:u})}},Xp=(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,M=n.scale===0?1/Math.sqrt(n.headSize):n.scale,k=or(n.headSize),w=n.headSize/k,b=12,$={x:Math.ceil(c/b),y:Math.ceil(n.sequenceLength/b),z:n.batchSize*n.numHeads},E=[{type:12,data:n.sequenceLength},{type:12,data:w},{type:12,data:c},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:M},{type:12,data:i},{type:12,data:n.kvSequenceLength},{type:12,data:_}],v=d&&s&&be.size(s.dims)>0,x=["type","type"];v&&x.push("type"),o&&x.push("type"),a&&x.push("type"),l&&x.push("type");let y=[{dims:p,dataType:r.dataType,gpuDataType:0}];d&&y.push({dims:f,dataType:r.dataType,gpuDataType:0});let P=O=>{let D=ke("q",r.dataType,r.dims,k),K=ke("key",t.dataType,t.dims,k),G=[D,K];if(v){let pe=ke("past_key",s.dataType,s.dims,k);G.push(pe)}o&&G.push(ke("attention_bias",o.dataType,o.dims));let N=a?ke("seq_lens",a.dataType,a.dims):void 0;N&&G.push(N);let te=l?ke("total_sequence_length_input",l.dataType,l.dims):void 0;te&&G.push(te);let H=at("output",r.dataType,p),ee=[H];d&&ee.push(at("present_key",r.dataType,f,k));let Z=jr(1,k),oe=[{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 = ${b}u; + + var tileQ: array<${D.type.storage}, ${b*b}>; + var tileK: array<${D.type.storage}, ${b*b}>; + ${O.registerUniforms(oe).declareVariables(...G,...ee)} + ${O.mainStart([b,b,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; + ${ci(N,te,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${v&&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; + ${v&&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:x},getRunData:()=>({outputs:y,dispatchGroup:$,programUniforms:E}),getShaderSource:P}},Jp=(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],M=12,k={x:Math.ceil(o.vHeadSize/M),y:Math.ceil(o.sequenceLength/M),z:o.batchSize*o.numHeads},w=[{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}],b=d&&s&&be.size(s.dims)>0,$=["type","type"];b&&$.push("type"),i&&$.push("type"),a&&$.push("type");let E=[{dims:_,dataType:r.dataType,gpuDataType:0}];d&&E.push({dims:f,dataType:r.dataType,gpuDataType:0});let v=x=>{let y=ke("probs",r.dataType,r.dims),P=ke("v",t.dataType,t.dims),O=[y,P];b&&O.push(ke("past_value",s.dataType,s.dims));let D=i?ke("seq_lens",i.dataType,i.dims):void 0;i&&O.push(D);let K=a?ke("total_sequence_length_input",a.dataType,a.dims):void 0;a&&O.push(K);let G=[at("output",r.dataType,_)];d&&G.push(at("present_value",r.dataType,f));let N=[{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 = ${M}u; + var tileQ: array<${y.type.value}, ${M*M}>; + var tileV: array<${y.type.value}, ${M*M}>; + ${x.registerUniforms(N).declareVariables(...O,...G)} + ${x.mainStart([M,M,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; + ${ci(D,K,!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 + ${b&&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 = ${y.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; + ${b&&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:E,dispatchGroup:k,programUniforms:w}),getShaderSource:v}},_o=(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,M=l&&be.size(l.dims)>0?l:void 0,k=[r,t];u>1&&i&&be.size(i.dims)>0&&k.push(i),M&&k.push(M),p&&k.push(p),d&&k.push(d);let w=e.compute(Xp(u,r,t,i,M,c,f,p,d),{inputs:k,outputs:u>1?[-1,1]:[-1]})[0];e.compute(Qp(w,c.batchSize,c.numHeads,f,c.sequenceLength,_,p,d),{inputs:p&&d?[w,p,d]:[w],outputs:[]});let b=[w,s];u>1&&a&&be.size(a.dims)>0&&b.push(a),p&&b.push(p),d&&b.push(d),e.compute(Jp(u,w,s,a,c,f,p,d),{inputs:b,outputs:u>1?[0,2]:[0]})},Yp=(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=at("output_q",l[0].dataType,t),f=at("output_k",l[0].dataType,t),_=at("output_v",l[0].dataType,t),M=ke("input",l[0].dataType,l[0].dims),k=ke("weight",l[1].dataType,l[1].dims),w=ke("bias",l[2].dataType,l[2].dims),b=M.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<${b}, ${i*i}>; + var tileWeightQ: array<${b}, ${i*i}>; + var tileWeightK: array<${b}, ${i*i}>; + var tileWeightV: array<${b}, ${i*i}>; + ${d.registerUniforms($).declareVariables(M,k,w,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 = ${b}(0); + var valueK = ${b}(0); + var valueV = ${b}(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]})},Zp=(e,r)=>{let t=qp(e.inputs,r),[s,o,n]=Yp(e,t);return _o(e,s,o,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),em,tm,rm,sm,fx=Ne(()=>{Ms(),gt(),Et(),cr(),Pt(),em=(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")},tm=(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=be.size(n)/i,c=s,p=c?n.length:n,d=ke("x",e[0].dataType,e[0].dims,i),u=ke("scale",e[1].dataType,e[1].dims,a),f=ke("bias",e[2].dataType,e[2].dims,a),_=ke("inputMean",e[3].dataType,e[3].dims,a),M=ke("inputVar",e[4].dataType,e[4].dims,a),k=at("y",e[0].dataType,p,i),w=()=>{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 E=1;E` + const epsilon = ${t}; + ${$.registerUniform("outputSize","u32").declareVariables(d,u,f,_,M,k)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${k.offsetToIndices(`global_idx * ${i}`)}; + ${w()} + let scale = ${u.getByOffset("cOffset")}; + let bias = ${f.getByOffset("cOffset")}; + let inputMean = ${_.getByOffset("cOffset")}; + let inputVar = ${M.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:b,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}]})}},rm=e=>Nt(e),sm=(e,r)=>{let{inputs:t,outputCount:s}=e,o=rm({...r,outputCount:s});if(Jt.webgpu.validateInputContent&&em(t,o),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(tm(t,o))}}),nm,om,im,gx=Ne(()=>{Et(),Pt(),nm=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")},om=e=>{let r=e[0].dims,t=e[0].dims[2],s=be.size(r)/4,o=e[0].dataType,n=ke("input",o,r,4),i=ke("bias",o,[t],4),a=ke("residual",o,r,4),l=at("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")} + }`}},im=e=>{nm(e.inputs),e.compute(om(e.inputs))}}),am,Rt,lm,cm,um,dm,pm,mm,hm,_m,fm,gm,wm,Mm,bm,ym,fo,vm,ui,xm,Tm,Em,Pm,Cm,Sm,$m,km,Im,Am,Fm,Om,Dm,Lm,zm,Bm,ml,Rm,hl,_l,jm,Nm,Vm,Um,Wm,Gm,fl=Ne(()=>{gt(),Et(),cr(),Pt(),am=(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=ke("inputData",t,[a],4),p=at("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(be.size(e.dims)/4)}];return i&&l.push(...i),{name:r,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:c=>am(c,be.size(e.dims),e.dataType,n,t,s,a),getRunData:c=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(be.size(c[0].dims)/64/4)},programUniforms:l})}},lm=e=>{e.compute(Rt(e.inputs[0],"Abs","abs"))},cm=e=>{e.compute(Rt(e.inputs[0],"Acos","acos"))},um=e=>{e.compute(Rt(e.inputs[0],"Acosh","acosh"))},dm=e=>{e.compute(Rt(e.inputs[0],"Asin","asin"))},pm=e=>{e.compute(Rt(e.inputs[0],"Asinh","asinh"))},mm=e=>{e.compute(Rt(e.inputs[0],"Atan","atan"))},hm=e=>{e.compute(Rt(e.inputs[0],"Atanh","atanh"))},_m=e=>Nt(e),fm=(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))},gm=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})},wm=(e,r)=>{let t=r||gm(e.inputs),s=jr(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]})},Mm=e=>{e.compute(Rt(e.inputs[0],"Ceil","ceil"))},bm=e=>{e.compute(Rt(e.inputs[0],"Cos","cos"))},ym=e=>{e.compute(Rt(e.inputs[0],"Cosh","cosh"))},fo=e=>Nt(e),vm=(e,r)=>{let t=jr(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))},ui=(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)); +}`,xm=e=>{let r=jr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,ui(r)))},Tm=e=>{e.compute(Rt(e.inputs[0],"Exp","exp"))},Em=e=>{e.compute(Rt(e.inputs[0],"Floor","floor"))},Pm=e=>{let r=jr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,ui(r)))},Cm=(e,r)=>{let t=jr(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))},Sm=e=>{e.compute(Rt(e.inputs[0],"Not",r=>`!${r}`))},$m=e=>{e.compute(Rt(e.inputs[0],"Neg",r=>`-${r}`))},km=e=>{e.compute(Rt(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},Im=e=>{let r=jr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},Am=e=>{e.compute(Rt(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},Fm=e=>Nt(e),Om=(e,r)=>{let t=jr(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))},Dm=e=>{e.compute(Rt(e.inputs[0],"Sin","sin"))},Lm=e=>{e.compute(Rt(e.inputs[0],"Sinh","sinh"))},zm=e=>{e.compute(Rt(e.inputs[0],"Sqrt","sqrt"))},Bm=e=>{e.compute(Rt(e.inputs[0],"Tan","tan"))},ml=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Rm=e=>{e.compute(Rt(e.inputs[0],"Tanh",ml))},hl=(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 ${ml("v")}; +} +`,_l=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,jm=e=>{let r=jr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"FastGelu",_l,hl(r),void 0,e.inputs[0].dataType))},Nm=(e,r)=>{let t=jr(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},Vm=e=>{e.compute(Rt(e.inputs[0],"Log","log"))},Um=(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; +} +`,Wm=e=>`quick_gelu_impl(${e})`,Gm=(e,r)=>{let t=jr(e.inputs[0].dataType);e.compute(Rt(e.inputs[0],"QuickGelu",Wm,Um(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),Km,Hm,qm,wx=Ne(()=>{Et(),Pt(),fl(),Km=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")},Hm=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=ke("input",e[0].dataType,e[0].dims,4),s=ke("bias",e[0].dataType,[e[0].dims[2]],4),o=at("output",e[0].dataType,r,4),n=be.size(r)/4,i=Sr(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)} + + ${ui(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")} + }`}},qm=e=>{Km(e.inputs),e.compute(Hm(e.inputs))}}),Qm,Xm,Es,Jm,Ym,Zm,eh,th,rh,sh,nh,oh,ih,Mx=Ne(()=>{gt(),Et(),Pt(),Qm=(e,r,t,s,o,n,i,a,l,c,p,d)=>{let u,f;typeof a=="string"?u=f=(b,$)=>`${a}((${b}),(${$}))`:typeof a=="function"?u=f=a:(u=a.scalar,f=a.vector);let _=at("outputData",p,s.length,4),M=ke("aData",l,r.length,4),k=ke("bData",c,t.length,4),w;if(o)if(n){let b=be.size(r)===1,$=be.size(t)===1,E=r.length>0&&r[r.length-1]%4===0,v=t.length>0&&t[t.length-1]%4===0;b||$?w=_.setByOffset("global_idx",f(b?`${M.type.value}(${M.getByOffset("0")}.x)`:M.getByOffset("global_idx"),$?`${k.type.value}(${k.getByOffset("0")}.x)`:k.getByOffset("global_idx"))):w=` + let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; + let offsetA = ${M.broadcastedIndicesToOffset("outputIndices",_)}; + let offsetB = ${k.broadcastedIndicesToOffset("outputIndices",_)}; + ${_.setByOffset("global_idx",f(i||E?M.getByOffset("offsetA / 4u"):`${M.type.value}(${M.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||v?k.getByOffset("offsetB / 4u"):`${k.type.value}(${k.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else w=_.setByOffset("global_idx",f(M.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 b=($,E,v="")=>{let x=`aData[indexA${E}][componentA${E}]`,y=`bData[indexB${E}][componentB${E}]`;return` + let outputIndices${E} = ${_.offsetToIndices(`global_idx * 4u + ${E}u`)}; + let offsetA${E} = ${M.broadcastedIndicesToOffset(`outputIndices${E}`,_)}; + let offsetB${E} = ${k.broadcastedIndicesToOffset(`outputIndices${E}`,_)}; + let indexA${E} = offsetA${E} / 4u; + let indexB${E} = offsetB${E} / 4u; + let componentA${E} = offsetA${E} % 4u; + let componentB${E} = offsetB${E} % 4u; + ${$}[${E}] = ${v}(${u(x,y)}); + `};p===9?w=` + var data = vec4(0); + ${b("data",0,"u32")} + ${b("data",1,"u32")} + ${b("data",2,"u32")} + ${b("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:w=` + ${b("outputData[global_idx]",0)} + ${b("outputData[global_idx]",1)} + ${b("outputData[global_idx]",2)} + ${b("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(M,k,_)} + + ${d??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${w} + }`},Xm=(e,r,t,s,o,n,i=t.dataType)=>{let a=t.dims.map(M=>Number(M)??1),l=s.dims.map(M=>Number(M)??1),c=!be.areEqual(a,l),p=a,d=be.size(a),u=!1,f=!1,_=[c];if(c){let M=Vn.calcShape(a,l,!1);if(!M)throw new Error("Can't perform binary op on the given tensors");p=M.slice(),d=be.size(p);let k=be.size(a)===1,w=be.size(l)===1,b=a.length>0&&a[a.length-1]%4===0,$=l.length>0&&l[l.length-1]%4===0;_.push(k),_.push(w),_.push(b),_.push($);let E=1;for(let v=1;vM.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:M=>Qm(M,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(be.size(p)/4)},...ct(a,l,p)]})}},Es=(e,r,t,s,o,n)=>{e.compute(Xm(r,o??"",e.inputs[0],e.inputs[1],t,s,n))},Jm=e=>{Es(e,"Add",(r,t)=>`${r}+${t}`)},Ym=e=>{Es(e,"Div",(r,t)=>`${r}/${t}`)},Zm=e=>{Es(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},eh=e=>{Es(e,"Mul",(r,t)=>`${r}*${t}`)},th=e=>{let r=ke("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Es(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)); + } + `)},rh=e=>{Es(e,"Sub",(r,t)=>`${r}-${t}`)},sh=e=>{Es(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},nh=e=>{Es(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},oh=e=>{Es(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},ih=e=>{Es(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),ah,lh,ch,uh,dh,ph,bx=Ne(()=>{gt(),Et(),cr(),Pt(),ah=(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")})}})},lh=(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; + }`,ch=(e,r)=>{let t=e.length,s=[];for(let o=0;o{let o=be.size(t),n=new Array(e.length),i=new Array(e.length),a=0,l=[],c=[],p=[{type:12,data:o}];for(let M=0;M`uniforms.sizeInConcatAxis${M}`).join(","),_=M=>` + + ${(()=>{M.registerUniform("outputSize","u32");for(let k=0;k(${f}); + ${u} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${ch(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:_}},dh=(e,r)=>{let t=e.inputs,s=t[0].dims,o=be.normalizeAxis(r.axis,s.length);ah(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=>be.size(a.dims)>0);e.compute(uh(i,o,n,t[0].dataType),{inputs:i})},ph=e=>Nt({axis:e.axis})}),pn,mn,hn,gl,_n=Ne(()=>{gt(),Et(),pn=(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})},hn=(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)||[Dd,Ld];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}}}),zr,mh,wl=Ne(()=>{zr=(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.`)}},mh=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),hh,yx=Ne(()=>{hh=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)); +} +`}),go,Ml,bl=Ne(()=>{gt(),Et(),Pt(),_n(),go=(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),_=be.size(t)/d/f,M=e.length>2,k=s?s.slice(0,-2):t.slice(0,-2),w=[be.size(k),l,c],b=[{type:12,data:_},{type:12,data:l},{type:12,data:c},{type:12,data:p}];mn(r,b),b.push(...ct(k,i,a)),M&&b.push(...ct(e[2].dims)),b.push(...ct(w));let $=E=>{let v=il("batch_dims",e[0].dataType,k.length),x=ke("a",e[0].dataType,i.length,u),y=ke("b",e[1].dataType,a.length,d),P=at("output",e[0].dataType,w.length,d),O=Sr(P.type.tensor),D=pn(r,P.type.value,O),K=[x,y],G="";if(M){let H=o?d:1;K.push(ke("bias",e[2].dataType,e[2].dims.length,H)),G=`${o?`value += bias[col / ${H}];`:`value += ${P.type.value}(bias[row + i]);`}`}let N=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];hn(r,N);let te=()=>{let H=`var a_data: ${x.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]; + ${G} + ${D} + 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:M?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:b}),getShaderSource:$}}}),_h,fh,yl,vl,gh,xl,wh,di,Tl=Ne(()=>{gt(),Et(),Pt(),_n(),bl(),wl(),_h=(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":""}); + `,fh=(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; + ${_h(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];"} + + ${fh(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":""}); + `,gh=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],M=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) * ${M}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var 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 < ${M}; 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) { + ${gh(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} + } +`},wh=(e,r,t,s,o=!1)=>{let[n,i,a,l]=s,c=Sr(s[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${zr(e,c)} { + var value = ${zr(e,c)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${i.type.indices}; + ${go("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}) -> ${zr(e,c)} { + var value = ${zr(e,c)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${a.type.indices}; + ${go("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: ${zr(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]":`${zr(e,c)}(bias[row])`};`:""} + ${t} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},di=(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=be.size(p),u=i[i.length-2],f=i[i.length-1],_=a[a.length-1],M=f%4===0&&_%4===0,k=u<=8?[4,1,1]:[4,4,1],w=[8,8,1],b=[Math.ceil(_/w[0]/k[0]),Math.ceil(u/w[1]/k[1]),Math.ceil(d/w[2]/k[2])],$=M?4:1,E=[...l,u,f/$],v=E.length,x=[...c,f,_/$],y=x.length,P=[d,u,_/$],O=[{type:6,data:u},{type:6,data:_},{type:6,data:f}];mn(r,O),O.push(...ct(p,E,x));let D=["rank","rank"],K=e.length>2;K&&(O.push(...ct(e[2].dims)),D.push("rank")),O.push(...ct(P));let G=N=>{let te=p.length,H=il("batchDims",e[0].dataType,te,1),ee=Sr(e[0].dataType),Z=ke("a",e[0].dataType,v,$),oe=ke("b",e[1].dataType,y,$),pe=at("result",e[0].dataType,P.length,$),ue=[Z,oe];if(K){let _e=o?$:1;ue.push(ke("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"}];hn(r,j);let F=Sr(pe.type.tensor),W=pn(r,pe.type.value,F),se=wh($,K,W,[H,Z,oe,pe],o);return` + ${N.registerUniforms(j).registerInternalVariables(H).declareVariables(...ue,pe)} + ${se} + ${M?yl(k,w,ee,H):xl(k,w,ee,H)} + `};return{name:"MatMul",shaderCache:{hint:`${k};${r.activation};${M};${o}`,inputDependencies:D},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:b[0],y:b[1],z:b[2]},programUniforms:O}),getShaderSource:G}}}),Mh,bh,vx=Ne(()=>{gt(),js(),Pt(),_n(),wl(),yx(),Tl(),Mh=(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])",M=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",k=e?"row":"col",w=e?"col":"row",b=` + 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 = ${w} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${w} / 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 = ${w} % inChannels; + var resData = ${zr(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 < ${M}) { + ${u} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${p(i)} + } + return resData;`,$=e?r&&s?` + let col = colIn * ${i}; + ${b}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${b} + } + return ${zr(i,c)}(0.0);`:s&&t?` + let col = colIn * ${i}; + ${b}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${b} + } + return ${zr(i,c)}(0.0);`,E=e?s&&t?d(a):` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${d(a)} + } + return ${zr(a,c)}(0.0);`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${d(a)} + } + return ${zr(a,c)}(0.0);`,v=zr(l,c),x=zr(e?i:a,c),y=zr(e?a:i,c),P=pn(n,v,c);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${x} { + ${e?$:E} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${y} { + ${e?E:$} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${v}) { + 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} + ${mh(o)} + ${P} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},bh=(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],M=c&&(p%4===0||p%3===0)&&_%4===0,k=c?_:u*f,w=c?u*f:_,b=[8,8,1],$=s<=8?[4,1,1]:[4,4,1],E=[Math.ceil(k/b[0]/$[0]),Math.ceil(w/b[1]/$[1]),Math.ceil(d/b[2]/$[2])];Dt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let v=M?c&&p%4!==0?3:4:1,x=b[1]*$[1],y=b[0]*$[0],P=Math.max(b[0]*v,b[1]),O=s%x===0,D=o%y===0,K=n%P===0,G=M?[v,4,4]:[1,1,1],N=[{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,N),N.push(...ct(e[0].dims,e[1].dims));let te=["rank","rank"];i&&(N.push(...ct(e[2].dims)),te.push("rank")),N.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}];hn(r,Z);let oe=M?4:1,pe=Sr(e[0].dataType),ue=` + fn setOutputAtIndex(flatIndex : i32, value : ${M?`vec4<${pe}>`:pe}) { + result[flatIndex] = ${M?`vec4<${pe}>`:pe}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${M?`vec4<${pe}>`:pe}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${M?"/ 4":""}, value); + }`,j=ke("x",e[0].dataType,e[0].dims.length,v===3?1:v),F=ke("w",e[1].dataType,e[1].dims.length,oe),W=[j,F],se=at("result",e[0].dataType,t.length,oe);if(i){let _e=ke("bias",e[2].dataType,e[2].dims.length,oe);W.push(_e),ue+=` + fn getBiasByOutputCoords(coords : vec4) -> ${M?`vec4<${pe}>`:pe} { + return bias[coords.${c?"w":"y"}${M?"/ 4":""}]; + }`}return` + ${hh("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(...W,se)} + ${ue} + ${Mh(c,O,D,K,i,r,G[0],G[1],G[2],pe)} + ${M?yl($,b,pe,void 0,!c,P):xl($,b,pe,void 0,!c,P,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${v};${M};${O};${D};${K};${x};${y};${P}`,inputDependencies:te},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:N}),getShaderSource:H}}}),yh,El,wo,vh,Pl,xh,Th,Eh,xx=Ne(()=>{gt(),js(),Et(),Pt(),_n(),wl(),yh=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,wo=(e,r)=>r<=1?e:e+(e-1)*(r-1),vh=(e,r,t,s=1)=>{let o=wo(r,s);return Math.floor((e[0]*(t-1)-t+o)/2)},Pl=(e,r,t,s,o)=>{o==null&&(o=vh(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},xh=(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((M,k,w)=>M===w[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,M=(u-1)*n+l-t,k=(f-1)*i+c-s,w=Math.floor(_/2),b=_-w,$=Math.floor(M/2),E=M-$,v=Math.floor(k/2),x=k-v;p={top:$,bottom:E,left:v,right:x,front:w,back:b}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:u,outWidth:f}},Th=(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,_,M]=r,[k,w,b]=El(t),[$,E,v]=El(s),x=wo(f,$),y=wo(_,E),P=wo(M,v),{padInfo:O,outDepth:D,outHeight:K,outWidth:G}=xh(o,l,c,p,k,w,b,x,y,P),N=n?u*d:u,te=[0,0,0,0,0];return i==="channelsFirst"?te=[a,N,D,K,G]:i==="channelsLast"&&(te=[a,D,K,G,N]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:c,inWidth:p,inChannels:d,outDepth:D,outHeight:K,outWidth:G,outChannels:N,padInfo:O,strideDepth:k,strideHeight:w,strideWidth:b,filterDepth:f,filterHeight:_,filterWidth:M,effectiveFilterDepth:x,effectiveFilterHeight:y,effectiveFilterWidth:P,dilationDepth:$,dilationHeight:E,dilationWidth:v,inShape:e,outShape:te,filterShape:r}},Eh=(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,w)=>w)},c=[Math.ceil(yh(l.x.map(k=>t[k]))/a[0]),1,1];Dt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${c}`);let p=1,d=be.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 M=k=>{let w=[{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}];hn(r,w);let b=1,$=Sr(e[0].dataType),E=ke("x",e[0].dataType,e[0].dims.length,p),v=ke("W",e[1].dataType,e[1].dims.length,b),x=[E,v],y=at("result",e[0].dataType,t.length,b),P="";if(_){let K=ke("bias",e[2].dataType,e[2].dims.length,b);x.push(K),P+=` + fn getBiasByOutputCoords(coords : array) -> ${$} { + return bias[${i?lt("coords",4,5):lt("coords",1,5)}]; + }`}let O=zr(p,$),D=pn(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 ${E.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${v.getByIndices("aIndices")}; + } + ${k.registerUniforms(w).declareVariables(...x,y)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${y.offsetToIndices("global_idx")}; + let batch = ${lt("coords",0,E.rank)}; + let d2 = ${i?lt("coords",E.rank-1,E.rank):lt("coords",1,E.rank)}; + let xFRCCorner = vec3(${i?lt("coords",1,E.rank):lt("coords",2,E.rank)}, + ${i?lt("coords",2,E.rank):lt("coords",3,E.rank)}, + ${i?lt("coords",3,E.rank):lt("coords",4,E.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,E.rank):lt("uniforms.x_shape",2,E.rank)}; + let xShapeZ = ${i?lt("uniforms.x_shape",2,E.rank):lt("uniforms.x_shape",3,E.rank)}; + let xShapeW = ${i?lt("uniforms.x_shape",3,E.rank):lt("uniforms.x_shape",4,E.rank)}; + let xShapeU = ${i?lt("uniforms.x_shape",4,E.rank):lt("uniforms.x_shape",1,E.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)":""}; + ${D} + 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:M}}}),Ph,Ch,Tx=Ne(()=>{gt(),Et(),Pt(),_n(),Ph=(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=be.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 M=k=>{let w=at("output",e[0].dataType,t.length,d),b=Sr(w.type.tensor),$=pn(r,w.type.value,b),E=ke("x",e[0].dataType,i.length),v=ke("w",e[1].dataType,a.length,d),x=[E,v];o&&x.push(ke("b",e[2].dataType,e[2].dims,d));let y=[{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"}];hn(r,y);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 = ${E.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${v.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 = ${E.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${v.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${k.registerUniforms(y).declareVariables(...x,w)} + + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${w.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: ${w.type.value} = ${w.type.value}(0); + ${P} + ${n} + ${$} + ${w.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:M}},Ch=(e,r,t,s)=>{let o=e.length>2,n=or(t[3]),i=or(t[2]),a=be.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 M=at("output",e[0].dataType,p.length,n),k=Sr(M.type.tensor),w=pn(r,M.type.value,k),b=ke("x",e[0].dataType,l.length,n),$=ke("w",e[1].dataType,c.length,n),E=[b,$];o&&E.push(ke("b",e[2].dataType,e[2].dims,n));let v=o?"value += b[output_channel];":"",x=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return hn(r,x),` + ${_.registerUniforms(x).declareVariables(...E,M)} + ${_.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<${b.type.value}, ${u}>; + var values: array<${M.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] = ${b.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${b.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]; + ${v} + ${w} + ${M.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}}}),Sh,pi,$h,mi,Cl,Sl,kh,Ih,$l,Ex=Ne(()=>{Et(),vx(),xx(),Tl(),Tx(),_n(),bl(),Xs(),Sh=(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},pi=[2,3,1,0],$h=(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")},mi=(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=Sh(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,o);if(t.group!==1){let x=[r[0]];if(o){let y=e.kernelCustomData.wT??e.compute(ts(r[1],pi),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=y),x.push(y)}else x.push(r[1]);r.length===3&&x.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(Ch(x,t,n,s),{inputs:x}):e.compute(Ph(x,t,n,s),{inputs:x});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],M=o&&p===a&&d===l&&t.pads[0]===0&&t.pads[1]===0;if(M||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 x=n[0],y,P,O,D=[];if(o){let N=e.kernelCustomData.wT??e.compute(ts(r[1],pi),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=N),M){let te=a*l*c;y=r[0].reshape([1,x,te]),P=N.reshape([1,te,_]),O=[1,x,_]}else y=r[0].reshape([x,a*l,c]),P=N.reshape([1,c,_]),O=[x,u*f,_];D.push(y),D.push(P)}else y=r[0].reshape([x,c,a*l]),P=r[1].reshape([1,_,c]),O=[x,_,u*f],D.push(P),D.push(y);i&&D.push(r[2]);let K=O[2],G=D[0].dims[D[0].dims.length-1];K<8&&G<8?e.compute(Ml(D,t,n,O,o,s),{inputs:D}):e.compute(di(D,t,n,O,o,s),{inputs:D});return}let k=!0,w=e.kernelCustomData.wT??e.compute(ts(r[1],pi),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=w);let b=[r[0],w];i&&b.push(r[2]);let $=o?u*f:_,E=o?_:u*f,v=p*d*c;e.compute(bh(b,t,n,$,E,v,i,k,s),{inputs:b})},kh=(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=mi({...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]])},Ih=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",o=mi(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=Th(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(Eh(r,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},$l=(e,r)=>{if($h(e.inputs,r),e.inputs[0].dims.length===3)kh(e,r);else if(e.inputs[0].dims.length===5)Ih(e,e.inputs,r);else{let t=mi(r,e.inputs);Sl(e,e.inputs,t)}}}),Ah,Px=Ne(()=>{gt(),js(),Et(),Pt(),Ah=(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,M=n?c===1?p:_:1,k=be.size(o)/_,w=[Math.ceil(k/64),1,1];Dt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${w}`);let b=["rank","rank"],$=[r.strides[0],r.strides[1]],E=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],v=[r.dilations[0],r.dilations[1]],x=[E[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),E[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],y=[x[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),x[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],P=[{type:12,data:k},{type:12,data:$},{type:12,data:E},{type:12,data:v},{type:12,data:x},{type:6,data:y},{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)),b.push("rank")),P.push(...ct(o));let O=D=>{let K=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:$.length},{name:"filter_dims",type:"u32",length:E.length},{name:"dilations",type:"u32",length:E.length},{name:"effective_filter_dims",type:"u32",length:x.length},{name:"pads",type:"i32",length:y.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],G=Sr(e[0].dataType),N=n?1:2,te=n?2:3,H=n?3:1,ee=ke("W",e[1].dataType,e[1].dims.length,M),Z=ke("Dy",e[0].dataType,e[0].dims.length,p),oe=[Z,ee];s&&oe.push(ke("bias",e[2].dataType,[o[H]].length,_));let pe=at("result",e[0].dataType,o.length,_),ue=()=>{let W="";if(d)p===4?W+=` + 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?W+=` + dotProd = dotProd + dot(vec4<${G}>(${Z.getByOffset("x_offset")}, ${Z.getByOffset("x_offset + 1u")}), vec4<${G}>(${ee.getByOffset("w_offset")}, ${ee.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;`:p===1&&(W+=` + dotProd = dotProd + dot(vec4<${G}>(${Z.getByOffset("x_offset")}, ${Z.getByOffset("x_offset + 1u")}, ${Z.getByOffset("x_offset + 2u")}, ${Z.getByOffset("x_offset + 3u")}), vec4<${G}>(${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(W+=` + let xValue = ${n?Z.getByOffset(`${Z.indicesToOffset(`${Z.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):Z.get("batch","inputChannel","idyR","idyC")}; + `,p===1)W+=` + let w_offset = ${ee.indicesToOffset(`${ee.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${ee.getByOffset(`w_offset / ${M}`)}; + 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 W="";if(p===1){W+="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 = ${pe.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 = (${G}(dyRCorner) + ${G}(wR)) / ${G}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${G}(uniforms.Dy_shape[${N}]) || 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 = (${G}(dyCCorner) + ${G}(wC)) / ${G}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${G}(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)`)} / ${M}; + `:""} + 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 / ${_}]`:""}; + ${pe.setByOffset("global_idx","value")}; + `;return` + ${D.registerUniforms(K).declareVariables(...oe,pe)} + ${D.mainStart()} + ${D.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${F}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${M}${_}${d}${f}`,inputDependencies:b},getRunData:()=>({dispatchGroup:{x:w[0],y:w[1],z:w[2]},outputs:[{dims:t?t(o):o,dataType:e[0].dataType}],programUniforms:P}),getShaderSource:O}}}),Fh,Oh,Dh,kl,Lh,zh,Il,Bh,Rh,Cx=Ne(()=>{Px(),_n(),Xs(),Fh=(e,r,t,s,o,n)=>(e-1)*r+t+(s-1)*o+1-n,Oh=(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)},Dh=(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)}Dh(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},Lh=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};`}},zh=(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(ts(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(Ah(n,t,s),{inputs:n})},Bh=(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]])},Rh=(e,r)=>{if(zh(e.inputs,r),e.inputs[0].dims.length===3)Bh(e,r);else{let t=kl(r,e.inputs);Il(e,e.inputs,t)}}}),jh,Nh,Vh,Sx=Ne(()=>{gt(),Et(),cr(),Pt(),jh=(e,r,t,s)=>{let o=be.size(r),n=r.length,i=ke("input",e,n),a=at("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),c=be.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",M=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 = ${M}; + 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}},Nh=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,o=e.inputs[1];e.compute(jh(s,t,o,r),{inputs:[0]})},Vh=e=>{let r=e.exclusive===1,t=e.reverse===1;return Nt({exclusive:r,reverse:t})}}),Uh,Wh,Gh,Kh,Hh,$x=Ne(()=>{gt(),Et(),cr(),Pt(),Uh=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.")},Wh=(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,_=ke("a",f,u),M=at("output",f,u),k=w=>` + ${w.registerUniform("output_size","u32").declareVariables(_,M)} + + ${Wh(a,u,_,M)} + + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${M.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${M.setByOffset("global_idx",_.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:w=>{let b=l?[t,s*c,o*c,n/c**2]:[t,n/c**2,s*c,o*c],$=be.size(b),E=d.dims,v=be.sortBasedOnPerm(E,a);return{outputs:[{dims:b,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:[{type:12,data:$},...ct(E,v)]}},getShaderSource:k}},Kh=(e,r)=>{Uh(e.inputs),e.compute(Gh(e.inputs[0],r))},Hh=e=>Nt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),hi,Mo,Al,qh,Qh,Xh,Jh,Fl,Yh,Zh,e_,kx=Ne(()=>{gt(),Et(),cr(),Pt(),hi="[a-zA-Z]|\\.\\.\\.",Mo="("+hi+")+",Al="^"+Mo+"$",qh="("+Mo+",)*"+Mo,Qh="^"+qh+"$",Xh=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)}},Jh=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(Qh)))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(Mo)))throw new Error("Invalid RHS");(o=s.match(RegExp(hi,"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(hi,"g")),c=new Xh(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",Yh=(e,r,t,s)=>{let o=e.map(c=>c.length).map((c,p)=>ke(`input${p}`,r,c)),n=be.size(s),i=at("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;",_=[],M=[],k=[],w=[],b=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((E,v)=>{var x;if(t.rhs.symbolToIndices.has(v)){let y=(x=t.rhs.symbolToIndices.get(v))==null?void 0:x[0];y!==void 0&&t.lhs.forEach((P,O)=>{if(E.inputIndices.includes(O)){let D=P.symbolToIndices.get(v);if(D===void 0)throw new Error("Invalid symbol error");D.forEach(K=>{p.push(`${o[O].indicesSet(`input${O}Indices`,K,i.indicesGet("outputIndices",y))}`)})}})}else t.lhs.forEach((y,P)=>{if(E.inputIndices.includes(P)){let O=y.symbolToIndices.get(v);if(O===void 0)throw new Error("Invalid symbol error");O.forEach(D=>{_.push(`${o[P].indicesSet(`input${P}Indices`,D,`${v}`)}`)}),w.push(`prod *= ${o[P].getByIndices(`input${P}Indices`)};`)}}),M.push(`for(var ${v}: u32 = 0; ${v} < uniforms.${Fl(v)}; ${v}++) {`),k.push("}")});let $=b?[...p,`let sum = ${o.map((E,v)=>E.getByIndices(`input${v}Indices`)).join(" * ")};`]:[...p,u,...M,..._,d,...w,f,...k];return` + ${c.registerUniforms(a.map(E=>({name:`${Fl(E)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${o.map((E,v)=>`var input${v}Indices: ${o[v].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}},Zh=(e,r)=>{let t=new Jh(e.inputs,r.equation),s=t.outputDims,o=e.inputs.map((n,i)=>n.dims);e.compute(Yh(o,e.inputs[0].dataType,t,s))},e_=e=>{let r=e.equation.replace(/\s+/g,"");return Nt({equation:r})}}),t_,Ol,r_,s_,n_,Ix=Ne(()=>{gt(),Et(),Pt(),t_=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),s_=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=r_(r,t),o=e[0].dataType,n=o===9||be.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(be.size(s)/a),c=d=>{let u=ke("input",o,r.length,i),f=at("output",o,s.length,a),_;if(o===9){let M=(k,w,b="")=>` + let outputIndices${w} = ${f.offsetToIndices(`outputOffset + ${w}u`)}; + let offset${w} = ${u.broadcastedIndicesToOffset(`outputIndices${w}`,f)}; + let index${w} = offset${w} / 4u; + let component${w} = offset${w} % 4u; + ${k}[${w}] = ${b}(${u.getByOffset(`index${w}`)}[component${w}]); + `;_=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${M("data",0,"u32")} + ${M("data",1,"u32")} + ${M("data",2,"u32")} + ${M("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})}},n_=e=>{t_(e.inputs),e.compute(s_(e.inputs),{inputs:[0]})}}),o_,i_,Ax=Ne(()=>{gt(),Et(),Pt(),fl(),o_=e=>{let r=e[0].dataType,t=be.size(e[0].dims),s=be.size(e[1].dims),o=s%4===0,n=i=>{let a=ke("x",r,[1],4),l=ke("bias",r,[1],4),c=at("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)} + + ${hl(jr(r))} + + ${i.mainStart(Un)} + ${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/Un/4)}})}},i_=e=>{e.inputs.length<2||be.size(e.inputs[1].dims)===0?jm(e):e.compute(o_(e.inputs))}}),a_,l_,c_,u_,Fx=Ne(()=>{gt(),Et(),cr(),Pt(),a_=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},l_=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=be.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(be.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=ke("data",e[0].dataType,e[0].dims.length,l),_=ke("inputIndices",e[1].dataType,e[1].dims.length),M=at("output",e[0].dataType,i.length,l),k=b=>{let $=s.length,E=`var indicesIndices${b} = ${_.type.indices}(0);`;for(let v=0;v<$;v++)E+=`${$>1?`indicesIndices${b}[${v}]`:`indicesIndices${b}`} = ${i.length>1?`outputIndices${b}[uniforms.axis + ${v}]`:`outputIndices${b}`};`;E+=` + var idx${b} = ${_.getByIndices(`indicesIndices${b}`)}; + if (idx${b} < 0) { + idx${b} = idx${b} + uniforms.axisDimLimit; + } + var dataIndices${b} : ${f.type.indices}; + `;for(let v=0,x=0;v1?`dataIndices${b}[${v}]`:`dataIndices${b}`} = u32(idx${b});`,x+=$):(E+=`${o>1?`dataIndices${b}[${v}]`:`dataIndices${b}`} = ${i.length>1?`outputIndices${b}[${x}]`:`outputIndices${b}`};`,x++);return E},w;if(e[0].dataType===9){let b=($,E,v="")=>` + let outputIndices${E} = ${M.offsetToIndices(`outputOffset + ${E}u`)}; + ${k(E)}; + let offset${E} = ${f.indicesToOffset(`dataIndices${E}`)}; + let index${E} = offset${E} / 4u; + let component${E} = offset${E} % 4u; + ${$}[${E}] = ${v}(${f.getByOffset(`index${E}`)}[component${E}]); + `;w=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${b("value",0,"u32")} + ${b("value",1,"u32")} + ${b("value",2,"u32")} + ${b("value",3,"u32")} + ${M.setByOffset("global_idx","value")} + `}else w=` + let outputIndices = ${M.offsetToIndices("global_idx")}; + ${k("")}; + let value = ${f.getByIndices("dataIndices")}; + ${M.setByOffset("global_idx","value")}; + `;return` + ${u.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(f,_,M)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${w} + }`};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}},c_=e=>Nt({axis:e.axis}),u_=(e,r)=>{let t=e.inputs;a_(t),e.compute(l_(e.inputs,r))}}),d_,p_,m_,Ox=Ne(()=>{gt(),Et(),Pt(),d_=(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=ke("indices_data",r.dataType,r.dims.length),_=at("input_slice_offsets_data",12,1,1),M=[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(...M)} + ${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]},p_=(e,r)=>{let t=e.inputs,s=t[0].dims,o=t[0].dataType,n=t[1].dims,i=n[n.length-1],a=be.sizeToDimension(n,n.length-1),l=be.sizeFromDimension(s,r.batchDims+i),c=be.sizeToDimension(s,r.batchDims),p=be.sizeFromDimension(s,r.batchDims),d=a/c,u=new Array(i),f=l;for(let E=0;Es.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(M)),w=be.size(k),b=[{type:12,data:w},{type:12,data:l},...ct(t[0].dims,_.dims,k)],$=E=>{let v=ke("data",t[0].dataType,t[0].dims.length),x=ke("slice_offsets",12,_.dims.length),y=at("output",t[0].dataType,k.length);return` + ${E.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(v,x,y)} + ${E.mainStart()} + ${E.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(w/64)},programUniforms:b}),getShaderSource:$},{inputs:[t[0],_]})},m_=e=>({batchDims:e.batch_dims,cacheKey:""})}),h_,__,f_,g_,Dx=Ne(()=>{gt(),Et(),cr(),Pt(),h_=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=be.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.")}},__=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=be.normalizeAxis(r.gatherAxis,o),i=be.normalizeAxis(r.quantizeAxis,o),a=t.slice(0);a.splice(n,1,...s);let l=be.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 _=ke("data",e[0].dataType,e[0].dims.length),M=ke("inputIndices",e[1].dataType,e[1].dims.length),k=ke("scales",e[2].dataType,e[2].dims.length),w=e.length>3?ke("zeroPoint",e[3].dataType,e[3].dims.length):void 0,b=at("output",c,a.length),$=[_,M,k];w&&$.push(w);let E=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${f.registerUniforms(E).declareVariables(...$,b)} + ${f.mainStart()} + let output_indices = ${b.offsetToIndices("global_idx")}; + var indices_indices = ${M.type.indices}(0); + ${s.length>1?` + for (var i: u32 = 0; i < ${s.length}; i++) { + let index = ${b.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${M.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${b.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${_.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${b.indicesGet("output_indices","i")}; + ${_.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${M.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 = ${b.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")}; + ${w?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${w.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${w.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 = ${jr(c)}(quantized_data - zero_point) * scale; + ${b.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}},f_=(e,r)=>{let t=e.inputs;h_(t,r),e.compute(__(e.inputs,r))},g_=e=>Nt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),w_,M_,b_,y_,Lx=Ne(()=>{gt(),Et(),cr(),Pt(),w_=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.`)},M_=(e,r)=>{let t=e[0].dims,s=e[0].dataType,o=t.length,n=e[1].dims,i=e[1].dataType,a=be.normalizeAxis(r.axis,o),l=t[a],c=n.slice(0),p=be.size(c),d=ke("input",s,o),u=ke("indicesInput",i,n.length),f=at("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:M=>` + ${M.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,u,f)} + ${M.mainStart()} + ${M.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")}; + }`}},b_=e=>Nt({axis:e.axis}),y_=(e,r)=>{let t=e.inputs;w_(t),e.compute(M_(e.inputs,r))}}),v_,x_,T_,E_,zx=Ne(()=>{gt(),Et(),Pt(),v_=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")},x_=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[o,n,i]=Od.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=be.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 M=w=>{let b="";r.transA&&r.transB?b="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?b="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?b="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(b="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let $=r.alpha===1?"":"value *= uniforms.alpha;",E=ke("a",e[0].dataType,e[0].dims),v=ke("b",e[1].dataType,e[1].dims),x=E.type.value,y=null,P=[E,v];e.length===3&&(y=ke("c",e[2].dataType,e[2].dims.length),P.push(y));let O=at("output",e[0].dataType,a.length);P.push(O);let D=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` + ${w.registerUniforms(D).declareVariables(...P)} + + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${x}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${b} + } + + ${$} + ${y!=null?`let cOffset = ${y.broadcastedIndicesToOffset("vec2(m, n)",O)}; value += ${x}(uniforms.beta) * ${y.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},k=w=>{let b=ke("a",e[0].dataType,e[0].dims),$=ke("b",e[1].dataType,e[1].dims),E=null,v=[b,$];e.length===3&&(E=ke("c",e[2].dataType,e[2].dims.length),v.push(E));let x=at("output",e[0].dataType,a.length);v.push(x);let y=[{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] = ${b.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] = ${b.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] = ${b.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] = ${b.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 D=r.alpha===1?"":"value *= uniforms.alpha;";return` + ${w.registerUniforms(y).declareVariables(...v)} + var tile_a: array, ${l}>; + var tile_b: array, ${l}>; + ${w.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 = ${x.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(); + } + + ${D} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${E!=null?`let cOffset = ${E.broadcastedIndicesToOffset("vec2(m, n)",x)}; value += ${x.type.value}(uniforms.beta) * ${E.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:M}},T_=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}`}},E_=(e,r)=>{v_(e.inputs),e.compute(x_(e.inputs,r))}}),As,Ns,fn,gn,P_,C_,S_,$_,k_,I_,A_,F_,O_,D_,Bx=Ne(()=>{gt(),Et(),cr(),Pt(),[As,Ns,fn,gn]=[0,1,2,3],P_=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")},C_=` + 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; + } +`,S_=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=>` + 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)); + `} + } +`,k_=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); + }`:""} +`,I_=(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[${As}] = batch; + indices[${Ns}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${fn}] = u32(r); + indices[${gn}] = u32(c); + } else { + return ${r}(0); + } + `;case"border":return` + indices[${fn}] = u32(clamp(r, 0, H - 1)); + indices[${gn}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${fn}] = gs_reflect(r, border[1], border[3]); + indices[${gn}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,A_=(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[${As}], indices[${Ns}], 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[${As}], indices[${Ns}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${As}], indices[${Ns}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${As}], indices[${Ns}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${As}], indices[${Ns}], 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[${As}], indices[${Ns}], 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")}`,F_=(e,r)=>{let t=ke("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=ke("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]],[As,Ns,fn,gn]=[0,3,1,2]);let i=at("output",e[0].dataType,n.length),a=t.type.value,l=be.size(n),c=[{type:12,data:l},...ct(e[0].dims,s,n)],p=d=>` + ${d.registerUniform("output_size","u32").declareVariables(t,o,i)} + ${C_} + ${S_(a)} + ${$_(r)} + ${k_(r)} + ${I_(t,a,r)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${fn}]); + let W_in = i32(uniforms.x_shape[${gn}]); + + ${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[${As}], indices[${fn}], indices[${gn}]); + let nxy = ${o.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${A_(i,a,r)} + }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:d=>{let u=be.size(n);return{outputs:[{dims:n,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}},getShaderSource:p}},O_=(e,r)=>{P_(e.inputs),e.compute(F_(e.inputs,r))},D_=e=>Nt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Kr,L_,z_,Dl,B_,bo,R_,j_=Ne(()=>{gt(),Et(),cr(),tl(),pl(),Pt(),Xs(),Kr=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,L_=(e,r)=>{let t=e[0],s=Kr(e,1),o=Kr(e,2),n=Kr(e,3),i=Kr(e,4),a=Kr(e,5),l=Kr(e,6),c=Kr(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,M=0,k=Math.floor(u/r.numHeads);if(l&&c&&be.size(l.dims)&&be.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],M=l.dims[2]}else if(l&&be.size(l.dims)||c&&be.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(s&&be.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)');w=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.');w=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');w=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');w=3}if(n&&be.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 b=_+f,$=0;if(i&&be.size(i.dims)>0){$=8;let y=i.dims;throw y.length===1?y[0]===p?$=1:y[0]===3*p+2&&($=3):y.length===2&&y[0]===p&&y[1]===b&&($=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 E=!1,v=u;if(o&&be.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)');v=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)');v=o.dims[1]*o.dims[3],E=!0}}let x=!1;if(i&&be.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(a&&be.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]!==b)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:b,maxSequenceLength:M,inputHiddenSize:0,hiddenSize:u,vHiddenSize:v,headSize:k,vHeadSize:Math.floor(v/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:$,scale:r.scale,broadcastResPosBias:x,passPastInKv:E,qkvFormat:w}},z_=e=>Nt({...e}),Dl=Nt({perm:[0,2,1,3]}),B_=(e,r,t,s,o,n,i)=>{let a=[s,o,n],l=be.size(a),c=[{type:12,data:l},{type:12,data:i},{type:12,data:n}],p=d=>{let u=at("qkv_with_bias",r.dataType,a),f=ke("qkv",r.dataType,a),_=ke("bias",t.dataType,a),M=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${d.registerUniforms(M).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]},bo=(e,r,t,s,o,n,i,a)=>{let l=n;if(i&&be.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=B_(e,n,i,r,s,t*o,a),l=l.reshape([r,s,t,o]),t===1||s===1?l:e.compute(ts(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(ts(l,Dl.perm),{inputs:[l],outputs:[-1]})[0]},R_=(e,r)=>{let t=L_(e.inputs,r),s=e.inputs[0],o=Kr(e.inputs,1),n=Kr(e.inputs,2),i=Kr(e.inputs,3),a=Kr(e.inputs,4),l=Kr(e.inputs,5),c=Kr(e.inputs,6),p=Kr(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=bo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(d)return _o(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=bo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,o,i,t.hiddenSize),_=bo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,i,2*t.hiddenSize);_o(e,u,f,_,a,void 0,c,p,l,t)}}),N_,V_,U_,W_,Ll,G_,K_,H_=Ne(()=>{gt(),Et(),cr(),Pt(),N_=e=>{if(!e||e.length<1)throw new Error("too few inputs")},V_=(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})},U_=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; +}`,W_=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=be.size(t),o=e[0].dataType,n=be.normalizeAxis(r.axis,t.length),i=new Array(r.numOutputs),a=ke("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)} + ${U_(l.length)} + ${W_(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})}},G_=(e,r)=>{N_(e.inputs);let t=e.inputs.length===1?r:V_(e.inputs,r);e.compute(Ll(e.inputs,t),{inputs:[0]})},K_=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})}}),q_,_i,Q_,X_=Ne(()=>{gt(),Et(),cr(),Pt(),q_=(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(!be.areEqual(s.dims,[])&&!be.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(!be.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=be.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")},_i=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:o,scale:n}=r,i=e[0].dims[0],a=be.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=be.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)],M=k=>{let w=ke("input",e[0].dataType,e[0].dims.length),b=ke("position_ids",e[1].dataType,e[1].dims.length),$=ke("cos_cache",e[2].dataType,e[2].dims.length),E=ke("sin_cache",e[3].dataType,e[3].dims.length),v=at("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(w,b,$,E,v)} + + ${k.mainStart(Un)} + 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 = + ${b.broadcastedIndicesToOffset("bsnh.xy",at("",b.type.tensor,2))}; + let position_id = + u32(${b.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 = ${w.getByOffset("i")} * ${$.get("position_id","bsnh[3]")} - + ${w.getByOffset("j")} * ${E.get("position_id","bsnh[3]")}; + ${v.setByOffset("i","re")} + let im = ${w.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} + + ${w.getByOffset("j")} * ${$.get("position_id","bsnh[3]")}; + ${v.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${v.setByOffset("k",w.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Nt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:M,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(be.size(u)/Un)},programUniforms:_})}},Q_=(e,r)=>{q_(e.inputs,r),e.compute(_i(e.inputs,r))}}),J_,Y_,zl,Z_,ef,Rx=Ne(()=>{cr(),gt(),pl(),j_(),H_(),Xs(),X_(),Pt(),J_=(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 M=n&&n.dims.length!==0,k=i&&i.dims.length!==0;if(M&&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(M&&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(M||k)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w=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');w=3}let b=0,$=!1,E=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)');E=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)');E=o.dims[1]*o.dims[3],$=!0}}let v=e.length>4?e[5]:void 0;if(v&&v.dims.length!==1&&v.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:E,headSize:_,vHeadSize:Math.floor(E/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:b,scale:r.scale,broadcastResPosBias:!1,passPastInKv:$,qkvFormat:w}},Y_=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(ts(s,Y_.perm),{inputs:[s],outputs:[-1]})[0]),s},Z_=(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=ke("seq_lens",t.dataType,t.dims),u=ke("total_seq_lens",s.dataType,s.dims),f=at("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}},ef=(e,r)=>{var E;let t=J_(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((E=e.inputs[1])==null?void 0:E.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],M,k;if(r.doRotary){let v=e.compute(Z_(t.batchSize,t.sequenceLength,l,c),{inputs:[l,c],outputs:[-1]})[0],x=e.inputs[7],y=e.inputs[8],P=Nt({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),O=[u,v,x,y],D=[-1];M=e.compute(_i(O,P),{inputs:O,outputs:D})[0],O.splice(0,1,f);let K=Nt({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});k=e.compute(_i(O,K),{inputs:O,outputs:D})[0]}let w=bo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?M:u,void 0,0),b=zl(e,r.doRotary?k:f,t),$=zl(e,_,t);_o(e,w,b,$,void 0,void 0,i,a,void 0,t,l,c)}}),Bl,tf,rf,sf,jx=Ne(()=>{gt(),Et(),Xs(),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],M=["rank","type","type"],k=[];k.push(...ct(f,_));let w=b=>{let $=ke("x",r.dataType,3,l),E=ke("scale",t.dataType,t.dims),v=ke("bias",s.dataType,s.dims),x=at("output",1,3,2),y=[$,E,v,x];return` + var workgroup_shared : array<${p}, ${u}>; + const workgroup_size = ${u}u; + ${b.declareVariables(...y)} + ${b.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 = ${Qs("workgroup_shared[0][0]",l)} / f32(hight * ${l}); + let squared_sum_final = ${Qs("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:M},getRunData:()=>({outputs:[{dims:_,dataType:1}],dispatchGroup:{x:d},programUniforms:k}),getShaderSource:w},{inputs:[r,t,s],outputs:[-1]})[0]},tf=(e,r,t)=>{let s=r[0].dims,o=s,n=2,i=s[0],a=s[1],l=be.sizeFromDimension(s,n),c=or(l),p=be.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"],M=k=>{let w=ke("x",r[0].dataType,u.length,c),b=ke("scale_shift",1,f.length,2),$=at("output",r[0].dataType,u.length,c),E=[w,b,$];return` + ${k.registerUniform("output_size","u32").declareVariables(...E)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${$.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${b.getByIndices("vec2(batch, channel)")}; + let value = ${w.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:M},{inputs:[r[0],d]})},rf=(e,r,t)=>{let s=r[0].dims,o=s,n=s[0],i=s[s.length-1],a=be.sizeFromDimension(s,1)/i,l=or(i),c=be.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 w=0;ws[f[b]])),M=Bl(e,_,r[1],r[2],n,a,i,t.epsilon),k=w=>{let b=Sr(r[0].dataType),$=l===1?"vec2f":`mat${l}x2f`,E=y=>{let P=y===0?"x":"y",O=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${b}(${O}(scale.${P}))`;case 2:return`vec2<${b}>(${O}(scale[0].${P}, scale[1].${P}))`;case 4:return`vec4<${b}>(${O}(scale[0].${P}, scale[1].${P}, scale[2].${P}, scale[3].${P}))`;default:throw new Error(`Not supported compoents ${l}`)}},v=ke("input",r[0].dataType,r[0].dims,l),x=at("output",r[0].dataType,o,l);return` + @group(0) @binding(0) var input : array<${v.type.storage}>; + @group(0) @binding(1) var scale_input : array<${$}>; + @group(0) @binding(2) var output : array<${x.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${w.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], ${E(0)}, ${E(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],M]})},sf=(e,r)=>{r.format==="NHWC"?rf(e,e.inputs,r):tf(e,e.inputs,r)}}),nf,of,af,Nx=Ne(()=>{gt(),Et(),Pt(),nf=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},of=(e,r,t)=>{let s=r.simplified,o=e[0].dims,n=e[1],i=!s&&e[2],a=o,l=be.normalizeAxis(r.axis,o.length),c=be.sizeToDimension(o,l),p=be.sizeFromDimension(o,l),d=be.size(n.dims),u=i?be.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 v=0;v1,b=t>2,$=v=>{let x=Sr(e[0].dataType),y=[ke("x",e[0].dataType,e[0].dims,_),ke("scale",n.dataType,n.dims,_)];i&&y.push(ke("bias",i.dataType,i.dims,_)),y.push(at("output",e[0].dataType,a,_)),w&&y.push(at("mean_data_output",1,f)),b&&y.push(at("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` + ${v.registerUniforms(P).declareVariables(...y)} + ${v.mainStart()} + ${v.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 = ${Wn(x,_,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Qs("mean_vector",_)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Qs("mean_square_vector",_)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Wn(x,_,"x[j + offset]")}; + let f32scale = ${Wn(x,_,"scale[j]")}; + output[j + offset] = ${y[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${Wn(x,_,"bias[j]")}`:""} + ); + } + + ${w?"mean_data_output[global_idx] = mean":""}; + ${b?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},E=[{dims:a,dataType:e[0].dataType}];return w&&E.push({dims:f,dataType:1}),b&&E.push({dims:f,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${t};${s}`,inputDependencies:M},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:k}),getShaderSource:$}},af=(e,r)=>{nf(e.inputs),e.compute(of(e.inputs,r,e.outputCount))}}),lf,cf,Vx=Ne(()=>{Et(),bl(),Tl(),lf=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.")},cf=e=>{lf(e.inputs);let r=Vn.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=be.size(e.inputs[0].dims.slice(0,-2)),i=be.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(di(p,{activation:""},r,c),{inputs:p})}else e.compute(di(e.inputs,{activation:""},r))}}}),uf,df,pf,mf,hf,Ux=Ne(()=>{gt(),Et(),cr(),Pt(),uf=(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(!be.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(be.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(be.size(l)!==c)throw new Error("zeroPoints input size error.")}},df=(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=be.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]),M=o>1&&i/f%2===0?2:1,k=be.size(_)/f/M,w=64,b=[],$=[l,o,n/d],E=be.convertShape(e[1].dims).slice();E.splice(-1,1,c/u),b.push(...ct($)),b.push(...ct(E)),b.push(...ct(e[2].dims)),e.length===4&&b.push(...ct(be.convertShape(e[3].dims)));let v=[l,o,i/f];b.push(...ct(v));let x=y=>{let P=$.length,O=ke("a",e[0].dataType,P,d),D=ke("b",12,E.length,u),K=ke("scales",e[2].dataType,e[2].dims.length),G=[O,D,K],N=e.length===4?ke("zero_points",12,e[3].dims.length):void 0;N&&G.push(N);let te=v.length,H=at("output",e[0].dataType,te,f),ee=Sr(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.`)}})(),oe=()=>{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},(W,se)=>`${ee}(b_value_lower[${se}]), ${ee}(b_value_upper[${se}])`).join(", ")}); + b_dequantized_values = ${d===1?`${Z}(${Array.from({length:8},(W,se)=>`(b_quantized_values[${se}] - ${N?`zero_point${F}`:"zero_point"}) * scale${F}`).join(", ")});`:`(b_quantized_values - ${Z}(${Array(8).fill(`${N?`zero_point${F}`:"zero_point"}`).join(",")})) * scale${F};`}; + workgroup_shared[local_id.x * ${M} + ${Math.floor(F/f)}]${f>1?`[${F%f}]`:""} += ${Array.from({length:8/d},(W,se)=>`${d===1?`a_data[${se}] * b_dequantized_values[${se}]`:`dot(a_data[${se}], b_dequantized_values[${se}])`}`).join(" + ")}; + `;return j},pe=()=>{let j=` + var col_index = col * ${f}; + ${N?` + 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 = ${N.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}, ${M*w}>; + ${y.declareVariables(...G,H)} + ${y.mainStart([w,1,1])} + let output_indices = ${H.offsetToIndices(`(global_idx / ${w}) * ${M}`)}; + 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 += ${w}) { + //process one block + var word_offset: u32 = block * ${r.blockSize/d}; + ${pe()} + for (var word: u32 = 0; word < ${c}; word += ${u}) { + ${ue()} + for (var i: u32 = 0; i < ${u}; i++) { + ${oe()} + word_offset += ${8/d}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${M}) { + var output_value: ${H.type.value} = ${H.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${w}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${M}; + } + ${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};${M};${w}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:k},programUniforms:b}),getShaderSource:x}},pf=(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=be.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,M=i%8===0?8:i%4===0?4:1,k=_/M,w=k*u*8,b=w/d,$=w/r.blockSize,E=be.size(f)/M,v=[],x=[l,o,n/d],y=be.convertShape(e[1].dims).slice();y.splice(-1,1,c/u),v.push(...ct(x)),v.push(...ct(y)),v.push(...ct(e[2].dims)),e.length===4&&v.push(...ct(be.convertShape(e[3].dims)));let P=[l,o,i];v.push(...ct(P));let O=D=>{let K=x.length,G=ke("a",e[0].dataType,K,d),N=ke("b",12,y.length,u),te=ke("scales",e[2].dataType,e[2].dims.length),H=[G,N,te],ee=e.length===4?ke("zero_points",12,e[3].dims.length):void 0;ee&&H.push(ee);let Z=P.length,oe=at("output",e[0].dataType,Z),pe=Sr(e[0].dataType),ue=()=>{switch(d){case 1:return` + let a_data0 = vec4<${pe}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${pe}>(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<${pe}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${pe}>(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<${G.type.value}, ${b}>; + var inter_results: array, ${M}>; + ${D.declareVariables(...H,oe)} + ${D.mainStart([k,M,1])} + let output_indices = ${oe.offsetToIndices(`workgroup_index * ${M}`)}; + 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 * ${b}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${b}; a_offset += ${_}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${G.getByIndices(`${G.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${G.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 = ${pe}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${pe}(8);`} + let scale = ${te.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${N.getByIndices(`${N.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<${pe}>(${Array.from({length:4},(j,F)=>`${pe}(b_value_lower[${F}]), ${pe}(b_value_upper[${F}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${pe}>(${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 < ${M}) { + var output_value: ${oe.type.value} = ${oe.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]) + { + ${oe.setByIndices(`${oe.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${d};${u};${k};${M}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:E},programUniforms:v}),getShaderSource:O}},mf=(e,r)=>{uf(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(pf(e.inputs,r)):e.compute(df(e.inputs,r))},hf=e=>Nt(e)}),_f,ff,gf,wf,Mf,bf,yf,vf,xf,Wx=Ne(()=>{gt(),Et(),Pt(),_f=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].")}},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) { + 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]; + } + `},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 = -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]; + `},wf=(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]; + `},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 += 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]; + `},bf=(e,r,t)=>{switch(t.mode){case 0:return ff(e,r,t.pads.length);case 1:return gf(e,r,t.pads.length);case 2:return wf(e,r,t.pads.length);case 3:return Mf(e,r,t.pads.length);default:throw new Error("Invalid mode")}},yf=(e,r)=>{let t=be.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,o=be.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=at("output",e[0].dataType,t.length),d=ke("x",e[0].dataType,s.length),u=d.type.value,f=bf(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(be.size(t)/64)},programUniforms:n}),getShaderSource:l}},vf=(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},xf=(e,r)=>{_f(e.inputs);let t=vf(e.inputs,r);e.compute(yf(e.inputs,t),{inputs:[0]})}}),yo,Rl,jl,Nl,Vl,Tf,Ef,Ul,Wl,Pf,Cf,Gl,Sf,$f,Kl,kf,If,Af,Ff,Gx=Ne(()=>{Ms(),gt(),Et(),Pt(),yo=e=>{if(Jt.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();si.adjustPoolAttributes(t,o,i,a,l,c);let p=si.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=be.size(e),o=be.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],M=r.pads[r.pads.length/2-2],k=r.pads[r.pads.length-2];u=!!(M+k),n.push({type:12,data:f},{type:12,data:_},{type:12,data:M},{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=be.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,_=at("output",r.type.tensor,s);if(o.kernelShape.length<=2){let M="",k="",w="",b=t-(u?2:1);if(p?M=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${b}] = indices[${b}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${b}] < 0 || xIndices[${b}] + >= uniforms.x_shape[${b}]) { + pad++; + continue; + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:M=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${b}] = indices[${b}] * 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; + `,w=` + } + `}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} + ${M} + ${w} + ${i} + + output[global_idx] = value; + }`}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let M=o.kernelShape.length,k=o.pads.length,w="";return c?w=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:w=` + } + 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 < ${M-1}u; j++) { + offsets[j] = offset / ${lt("uniforms.kernelStrides","j",M)}; + offset -= offsets[j] * ${lt("uniforms.kernelStrides","j",M)}; + } + offsets[${M-1}] = offset; + + isPad = false; + for (var j = ${t-M}u; j < ${t}u; j++) { + xIndices[j] = indices[j] * ${lt("uniforms.strides",`j - ${t-M}u`,M)} + + offsets[j - ${t-M}u] - ${lt("uniforms.pads","j - 2u",k)}; + ${w} + } + ${i} + + output[global_idx] = value; + }`}},Vl=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Tf=e=>`${Vl(e)};${e.countIncludePad}`,Ef=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=ke("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 M=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${u};${f};${_}`,inputDependencies:M},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(be.size(n)/64)},programUniforms:p}),getShaderSource:k=>Nl(k,i,r.dims.length,n.length,o,l,c,0,d,u,f,_)}},Pf=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:Tf(s)}},Cf=(e,r)=>{yo(e.inputs),e.compute(Wl("AveragePool",e.inputs[0],!1,r))},Gl={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Sf=e=>{let r=e.format;return{format:r,...Gl,cacheKey:r}},$f=(e,r)=>{yo(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=ke("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(be.size(n)/64)},programUniforms:p}),getShaderSource:M=>Nl(M,l,r.dims.length,n.length,o,i,a,r.dataType===10?-65504:-1e5,d,u,f,_)}},kf=(e,r)=>{yo(e.inputs),e.compute(Kl("MaxPool",e.inputs[0],!1,r))},If=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:Ef(o)}},Af=e=>{let r=e.format;return{format:r,...Gl,cacheKey:r}},Ff=(e,r)=>{yo(e.inputs),e.compute(Kl("GlobalMaxPool",e.inputs[0],!0,r))}}),Of,Df,Lf,zf,Kx=Ne(()=>{gt(),Et(),cr(),Pt(),Of=(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)].")}},Df=(e,r)=>{let t=be.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,o=s===3,n=e[0].dims,i=e[1].dataType,a=be.size(n),l=s===3||s===2,c=l?[Math.ceil(be.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(be.size(d.dims)/4)]:d.dims:void 0,f=p.length===0||p.length===1&&p[0]===1,_=f===!1&&p.length===1,M=or(a),k=f&&(!l||M===4),w=k?M:1,b=k&&!l?M:1,$=ke("input",l?12:s,c.length,b),E=ke("scale",i,p.length),v=d?ke("zero_point",l?12:s,u.length):void 0,x=at("output",i,n.length,w),y=[$,E];v&&y.push(v);let P=[c,p];d&&P.push(u);let O=[{type:12,data:a/w},{type:12,data:t},{type:12,data:r.blockSize},...ct(...P,n)],D=K=>{let G=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${K.registerUniforms(G).declareVariables(...y,x)} + ${K.mainStart()} + ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${x.offsetToIndices("global_idx")}; + + // Set input x + ${l?` + let input = ${$.getByOffset("global_idx / 4")}; + let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${w===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${$.getByOffset("global_idx")};`}; + + // Set scale input + ${f?`let scale_value= ${E.getByOffset("0")}`:_?` + let scale_index = ${x.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${E.getByOffset("scale_index")};`:` + var scale_indices: ${E.type.indices} = output_indices; + let index = ${E.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${E.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${E.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${v?f?l?` + let zero_point_input = ${v.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 = ${v.getByOffset("0")}`:_?l?` + let zero_point_index = ${x.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${v.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 = ${x.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${v.getByOffset("zero_point_index")};`:l?` + let zero_point_offset = ${E.indicesToOffset("scale_indices")}; + let zero_point_input = ${v.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 = ${v.getByIndices("scale_indices")};`:`let zero_point_value = ${l?o?"i32":"u32":$.type.value}(0);`}; + // Compute and write output + ${x.setByOffset("global_idx",`${x.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:v?["rank","rank","rank"]:["rank","rank"]},getShaderSource:D,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(a/w/64),y:1,z:1},programUniforms:O})}},Lf=(e,r)=>{Of(e.inputs,r),e.compute(Df(e.inputs,r))},zf=e=>Nt({axis:e.axis,blockSize:e.blockSize})}),Bf,Rf,jf,Hx=Ne(()=>{Ms(),gt(),Pt(),Bf=(e,r,t)=>{let s=e===r,o=er&&t>0;if(s||o||n)throw new Error("Range these inputs' contents are invalid.")},Rf=(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=at("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})}},jf=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]),Jt.webgpu.validateInputContent&&Bf(r,t,s),e.compute(Rf(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),Nf,Hl,ql,Vf,Uf,Wf,qx=Ne(()=>{gt(),Et(),cr(),Pt(),Nf=(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]; + ${Nf(e.reduction,"output[data_offset + i]","value",r)} + }`,Vf=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t,n=1,i=Math.ceil(be.size(s)/n),a=s[s.length-1],l=be.sizeFromDimension(t,a),c=be.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=ke("indices",e[1].dataType,e[1].dims.length),_=ke("updates",e[2].dataType,e[2].dims.length,n),M=r.reduction!=="none"&&r.reduction!==""?Qd("output",e[0].dataType,o.length):at("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,_,M)} + ${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,M.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,M.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}},Uf=e=>Nt({reduction:e.reduction}),Wf=(e,r)=>{e.compute(Vf(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Gf,Kf,Hf,Ql,qf,Qf,Xf,Jf,Yf,Zf,eg,tg,Xl,rg,sg,ng,og,ig,ag,lg,Qx=Ne(()=>{gt(),Et(),cr(),Pt(),Gf=(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")}},Kf=(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},Hf=(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");Gf(s,r),r.axes.length>0&&Kf(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; +`,qf=(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`)}})()+"}",Qf=(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`)}})()+"}",Xf=(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},Jf=(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},Yf=(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},Zf=(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; + }`,eg=(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; + }`,tg=(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")}; +`:"",rg=(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); + }`},sg=(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,_=M=>{let k=M===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",M)}; + var originalIdx: ${f} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[M]}, + ${s[M]}, ${t[M]}, ${n[M]}, ${n[M]} + ${t.length}); + var fractOriginalIdx: ${f} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${a} && (originalIdx < 0 || originalIdx > (${t[M]} - 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[M]}) { + ${c?`coefs[i + 1] = 0.0; + continue;`:a?`return ${l};`:`${k} = max(0, min(${k}, ${t[M]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",M,`u32(${k})`)}; + data[i + 1] = ${M===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); + } + `},ng=(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); + }`},og=(e,r,t,s,o,n)=>{let i=e.dims,a=Xf(n,r.axes,i.length),l=Jf(i,s,o,r.axes),c=s.slice();s.length===0&&(c=i.map((b,$)=>b===0?1:l[$]/b),r.keepAspectRatioPolicy!=="stretch"&&(l=Yf(i,c,r)));let p=at("output",e.dataType,l.length),d=ke("input",e.dataType,i.length),u=be.size(l),f=i.length===l.length&&i.every((b,$)=>b===l[$]),_=r.coordinateTransformMode==="tf_crop_and_resize",M=r.extrapolationValue,k=d.type.value,w=b=>` + ${f?"":` + ${qf(r.coordinateTransformMode,k)}; + ${(()=>{switch(r.mode){case"nearest":return` + ${tg(d,i)}; + ${Qf(r.nearestMode,t,k)}; + ${eg(d,p,i,l,c.length,a.length,_)}; + `;case"linear":return` + ${Zf(p,i,l,c.length,a.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${rg(d,p,i,_,M)}`;if(i.length===3||i.length===5)return`${ng(d,p,i,_,M)}`;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`${sg(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")}})()}; + `} + ${b.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",a.length).declareVariables(d,p)} + ${b.mainStart()} + ${b.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:w,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)]})}},ig=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},ag=(e,r)=>{let t=[],s=[],o=[],n=ig(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Hf(e.inputs,r,n,t,s,o),e.compute(og(e.inputs[0],r,n,t,s,o),{inputs:[0]})},lg=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})}}),cg,ug,dg,Xx=Ne(()=>{gt(),Et(),Pt(),cg=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")}},ug=(e,r,t,s)=>{let o=r.simplified,n=e[0].dims,i=be.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,M=t>3,k=64,w=or(c),b=[{type:12,data:l},{type:12,data:w},{type:12,data:c},{type:1,data:r.epsilon}],$=v=>{let x=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],y=[ke("x",e[0].dataType,e[0].dims,w),ke("skip",e[1].dataType,e[1].dims,w),ke("gamma",e[2].dataType,e[2].dims,w)];d&&y.push(ke("beta",e[3].dataType,e[3].dims,w)),u&&y.push(ke("bias",e[4].dataType,e[4].dims,w)),y.push(at("output",e[0].dataType,a,w)),f&&y.push(at("mean_output",1,p)),_&&y.push(at("inv_std_output",1,p)),M&&y.push(at("input_skip_bias_sum",e[0].dataType,a,w));let P=Sr(e[0].dataType),O=Sr(1,w);return` + + ${v.registerUniforms(x).declareVariables(...y)} + var sum_shared : array<${O}, ${k}>; + var sum_squared_shared : array<${O}, ${k}>; + + ${v.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; + ${M?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Wn(P,w,"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 = ${Qs("sum",w)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Qs("square_sum",w)} / 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]":""}; + } + }`},E=[{dims:a,dataType:e[0].dataType}];return t>1&&E.push({dims:p,dataType:1}),t>2&&E.push({dims:p,dataType:1}),t>3&&E.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${w};${f};${_};${M}`,inputDependencies:e.map((v,x)=>"type")},getShaderSource:$,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/c)},programUniforms:b})}},dg=(e,r)=>{cg(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(ug(e.inputs,r,e.outputCount,!1),{outputs:t})}}),pg,vo,mg,Jl,hg,_g,fg,gg,Jx=Ne(()=>{gt(),Et(),cr(),Pt(),pg=(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`)})},vo=(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},mg=(e,r)=>{if(e.length>1){let t=vo(e,1),s=vo(e,2),o=vo(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]]))},hg=(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; + }`,_g=(e,r)=>{let t=e[0].dims,s=be.size(t),o=r.axes.length>0?be.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=vo(e,4);n.forEach(w=>w!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(o.length).fill(1));let i=r.starts.map((w,b)=>Jl(w,b,t,o,n)),a=r.ends.map((w,b)=>Jl(w,b,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 w=0;wMath.sign(w));n.forEach((w,b,$)=>{if(w<0){let E=(a[b]-i[b])/w,v=i[b],x=v+E*n[b];i[b]=x,a[b]=v,$[b]=-w}});let c=t.slice(0);o.forEach((w,b)=>{c[w]=Math.ceil((a[w]-i[w])/n[w])});let p={dims:c,dataType:e[0].dataType},d=at("output",e[0].dataType,c.length),u=ke("input",e[0].dataType,e[0].dims.length),f=be.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}],M=[{type:12,data:f},{type:12,data:i},{type:6,data:l},{type:12,data:n},...ct(e[0].dims,c)],k=w=>` + ${w.registerUniforms(_).declareVariables(u,d)} + ${hg(u,d,t)} + ${w.mainStart()} + ${w.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:M})}},fg=(e,r)=>{pg(e.inputs,r);let t=mg(e.inputs,r);e.compute(_g(e.inputs,t),{inputs:[0]})},gg=e=>{let r=e.starts,t=e.ends,s=e.axes;return Nt({starts:r,ends:t,axes:s})}}),wg,Mg,bg,yg,Yx=Ne(()=>{gt(),Et(),cr(),Xs(),Pt(),wg=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Mg=(e,r)=>{let t=e.inputs[0],s=t.dims,o=be.size(s),n=s.length,i=be.normalizeAxis(r.axis,n),a=iP),c[i]=n-1,c[n-1]=i,l=e.compute(ts(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,M=64;u===1&&(M=256);let k=(y,P)=>P===4?`max(max(${y}.x, ${y}.y), max(${y}.z, ${y}.w))`:P===2?`max(${y}.x, ${y}.y)`:P===3?`max(max(${y}.x, ${y}.y), ${y}.z)`:y,w=ke("x",l.dataType,l.dims,f),b=at("result",l.dataType,l.dims,f),$=w.type.value,E=Sr(l.dataType)==="f32"?`var threadMax = ${$}(-3.402823e+38f);`:`var threadMax = ${$}(-65504.0h);`,v=y=>` + var rowMaxShared : ${$}; + var rowSumShared : ${$}; + var threadShared : array<${$}, ${M}>; + + 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; + } + ${y.registerUniform("packedCols","i32").declareVariables(w,b)} + ${y.mainStart(M)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${M}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${E} + 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 = ${$}(${Qs("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); + } + }`,x=e.compute({name:"Softmax",shaderCache:{hint:`${f};${M}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:_}]}),getShaderSource:v},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(ts(x,c),{inputs:[x]})},bg=(e,r)=>{wg(e.inputs),Mg(e,r)},yg=e=>Nt({axis:e.axis})}),Yl,vg,xg,Tg,Eg,Zx=Ne(()=>{gt(),Et(),Pt(),Yl=e=>Array.from(e.getBigInt64Array(),Number),vg=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")},xg=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Yl(e[1]),o=xg(t,s),n=be.size(o),i=e[0].dataType,a=ke("input",i,t.length),l=at("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}},Eg=e=>{vg(e.inputs),e.compute(Tg(e.inputs),{inputs:[0]})}}),Pg,Cg,Sg,eT=Ne(()=>{gt(),Et(),Pt(),Pg=(e,r,t,s,o)=>{let n=at("output_data",o,t.length,4),i=ke("a_data",r[1].dataType,r[1].dims.length,4),a=ke("b_data",r[2].dataType,r[2].dims.length,4),l=ke("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 M=`a_data[index_a${f}][component_a${f}]`,k=`b_data[index_b${f}][component_b${f}]`,w=`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(M,k,w)}); + `};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} + }`},Cg=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,o=e[1].dataType,n=!(be.areEqual(r,t)&&be.areEqual(t,s)),i=r,a=be.size(r);if(n){let c=Vn.calcShape(Vn.calcShape(r,t,!1),s,!1);if(!c)throw new Error("Can't perform where op on the given tensors");i=c,a=be.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>Pg(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)]})}},Sg=e=>{e.compute(Cg(e.inputs))}}),$g,tT=Ne(()=>{_x(),pl(),fx(),gx(),wx(),Mx(),bx(),Ex(),Cx(),Sx(),$x(),kx(),Ix(),Ax(),Fx(),Ox(),Dx(),Lx(),zx(),Bx(),Rx(),jx(),Nx(),Vx(),Ux(),j_(),Wx(),Gx(),Kx(),Hx(),qx(),cl(),Qx(),X_(),Xx(),Jx(),Yx(),H_(),Zx(),Xs(),fl(),eT(),$g=new Map([["Abs",[lm]],["Acos",[cm]],["Acosh",[um]],["Add",[Jm]],["ArgMax",[Hp,dl]],["ArgMin",[Kp,dl]],["Asin",[dm]],["Asinh",[pm]],["Atan",[mm]],["Atanh",[hm]],["Attention",[Zp]],["AveragePool",[Cf,Pf]],["BatchNormalization",[sm]],["BiasAdd",[im]],["BiasSplitGelu",[qm]],["Cast",[fm,_m]],["Ceil",[Mm]],["Clip",[wm]],["Concat",[dh,ph]],["Conv",[$l,Cl]],["ConvTranspose",[Rh,Lh]],["Cos",[bm]],["Cosh",[ym]],["CumSum",[Nh,Vh]],["DepthToSpace",[Kh,Hh]],["DequantizeLinear",[Lf,zf]],["Div",[Ym]],["Einsum",[Zh,e_]],["Elu",[vm,fo]],["Equal",[Zm]],["Erf",[xm]],["Exp",[Tm]],["Expand",[n_]],["FastGelu",[i_]],["Floor",[Em]],["FusedConv",[$l,Cl]],["Gather",[u_,c_]],["GatherElements",[y_,b_]],["GatherBlockQuantized",[f_,g_]],["GatherND",[p_,m_]],["Gelu",[Pm]],["Gemm",[E_,T_]],["GlobalAveragePool",[$f,Sf]],["GlobalMaxPool",[Ff,Af]],["Greater",[sh]],["GreaterOrEqual",[oh]],["GridSample",[O_,D_]],["GroupQueryAttention",[ef]],["HardSigmoid",[Om,Fm]],["InstanceNormalization",[sf]],["LayerNormalization",[af]],["LeakyRelu",[Cm,fo]],["Less",[nh]],["LessOrEqual",[ih]],["Log",[Vm]],["MatMul",[cf]],["MatMulNBits",[mf,hf]],["MaxPool",[kf,If]],["Mul",[eh]],["MultiHeadAttention",[R_,z_]],["Neg",[$m]],["Not",[Sm]],["Pad",[xf]],["Pow",[th]],["QuickGelu",[Gm,fo]],["Range",[jf]],["Reciprocal",[km]],["ReduceMin",[Np]],["ReduceMean",[Lp]],["ReduceMax",[jp]],["ReduceSum",[Up]],["ReduceProd",[Vp]],["ReduceL1",[zp]],["ReduceL2",[Bp]],["ReduceLogSum",[Gp]],["ReduceLogSumExp",[Rp]],["ReduceSumSquare",[Wp]],["Relu",[Im]],["Resize",[ag,lg]],["RotaryEmbedding",[Q_]],["ScatterND",[Wf,Uf]],["Sigmoid",[Am]],["Sin",[Dm]],["Sinh",[Lm]],["Slice",[fg,gg]],["SkipLayerNormalization",[dg]],["Split",[G_,K_]],["Sqrt",[zm]],["Softmax",[bg,yg]],["Sub",[rh]],["Tan",[Bm]],["Tanh",[Rm]],["ThresholdedRelu",[Nm,fo]],["Tile",[Eg]],["Transpose",[sp,np]],["Where",[Sg]]])}),kg,rT=Ne(()=>{Ms(),js(),Pt(),kg=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){ws(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(),ls(e.programInfo.name)}dispose(){}build(e,r){ws(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=Jd(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 ls(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]}}}),Ig={};jn(Ig,{WebGpuBackend:()=>Dg});var Ag,Fg,Og,Dg,sT=Ne(()=>{Ms(),gt(),js(),zd(),mx(),tT(),rT(),Ag=(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+`:${Ag(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},Og=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Dg=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 Og(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Hd(this),this.programManager=new kg(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;ws(),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 M=Number(f-this.queryTimeBase),k=Number(_-this.queryTimeBase);if(!Number.isSafeInteger(M)||!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(w=>({dims:w.dims,dataType:Rs(w.dataType)})),outputsMetadata:u.map(w=>({dims:w.dims,dataType:Rs(w.dataType)})),kernelId:i,kernelType:l,kernelName:c,programName:p,startTime:M,endTime:k});else{let w="";d.forEach(($,E)=>{w+=`input[${E}]: [${$.dims}] | ${Rs($.dataType)}, `});let b="";u.forEach(($,E)=>{b+=`output[${E}]: [${$.dims}] | ${Rs($.dataType)}, `}),console.log(`[profiling] kernel "${i}|${l}|${c}|${p}" ${w}${b}execution time: ${k-M} ns`)}uo("GPU",`${p}::${f}::${_}`)}e.unmap(),this.pendingQueries.delete(e)}),ls()}run(e,r,t,s,o,n){ws(e.name);let i=[];for(let b=0;b$):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let d=[],u=[];for(let b=0;b=n)throw new Error(`Invalid output index: ${p[b]}`);if(p[b]===-3)continue;let $=p[b]===-1,E=p[b]===-2,v=$||E?o(a[b].dataType,a[b].dims):s(p[b],a[b].dataType,a[b].dims);if(d.push(v),v.data===0)continue;let x=this.gpuDataManager.get(v.data);if(!x)throw new Error(`no GPU data for output: ${v.data}`);if($&&this.temporaryData.push(x),E){let y=this.kernelPersistentData.get(this.currentKernelId);y||(y=[],this.kernelPersistentData.set(this.currentKernelId,y)),y.push(x)}u.push(x)}if(i.length!==r.length||u.length!==d.length){if(u.length===0)return ls(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 b=0,$=[];c.forEach(y=>{let P=typeof y.data=="number"?[y.data]:y.data;if(P.length===0)return;let O=y.type===10?2:4,D,K;y.type===10?(K=P.length>4?16:P.length>2?8:P.length*O,D=P.length>4?16:O*P.length):(K=P.length<=2?P.length*O:16,D=16),b=Math.ceil(b/K)*K,$.push(b);let G=y.type===10?8:4;b+=P.length>4?Math.ceil(P.length/G)*D:P.length*O});let E=16;b=Math.ceil(b/E)*E;let v=new ArrayBuffer(b);c.forEach((y,P)=>{let O=$[P],D=typeof y.data=="number"?[y.data]:y.data;if(y.type===6)new Int32Array(v,O,D.length).set(D);else if(y.type===12)new Uint32Array(v,O,D.length).set(D);else if(y.type===10)new Uint16Array(v,O,D.length).set(D);else if(y.type===1)new Float32Array(v,O,D.length).set(D);else throw new Error(`Unsupported uniform type: ${Rs(y.type)}`)});let x=this.gpuDataManager.create(b,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(x.buffer,0,v,0,b),this.gpuDataManager.release(x.id),f={offset:0,size:b,buffer:x.buffer}}let _=this.programManager.normalizeDispatchGroupSize(l),M=_[1]===1&&_[2]===1,k=Fg(e,r,M),w=this.programManager.getArtifact(k);if(w||(w=this.programManager.build(e,_),this.programManager.setArtifact(k,w),Dt("info",()=>`[artifact] key: ${k}, programName: ${e.name}`)),c&&w.uniformVariablesInfo){if(c.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${c.length} in program "${w.programInfo.name}".`);for(let b=0;b`[ProgramManager] run "${e.name}" (key=${k}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let b={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:r,outputTensorViews:d};this.pendingKernels.push(b),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(b)}return this.programManager.run(w,i,u,_,f),ls(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=$g.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()}}}),Lg={};jn(Lg,{init:()=>Bg});var fi,zg,Bg,nT=Ne(()=>{gt(),js(),Et(),px(),fi=class Cv{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=be.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=be.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=be.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=be.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(be.size(r)!==be.size(this.dims))throw new Error("Invalid new shape");return new Cv(this.module,this.dataType,this.data,r)}},zg=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 fi(this.module,l,this.output(a,c),c),n=(a,l)=>{let c=dn(a,l);if(!c)throw new Error(`Unsupported data type: ${a}`);let p=c>0?this.backend.gpuDataManager.create(c).id:0;return new fi(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=(sT(),ao(Ig)).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 zg(r,i,Number(l));return i.computeKernel(Number(a),d,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let n=new Ud(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)])}}}),Rg,Zl,ec,Js,jg,tc,gi,rc,sc,nc,oc,ic,ac,Ng=Ne(()=>{cx(),ux(),gt(),un(),Na(),Cd(),Rg=(e,r)=>{Xt()._OrtInit(e,r)!==0&&Wt("Can't initialize onnxruntime.")},Zl=async e=>{Rg(e.wasm.numThreads,ri(e.logLevel))},ec=async(e,r)=>{var t,s;(s=(t=Xt()).asyncInit)==null||s.call(t);{let o=(nT(),ao(Lg)).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",Xt(),e,n)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await o("webnn",Xt(),e)}}},Js=new Map,jg=e=>{let r=Xt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,o,o+s)!==0&&Wt("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=Xt(),s=t.stackSave(),o=0;try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputMetadata(e,r,i,i+n)!==0&&Wt("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=Xt(),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=Xt();Array.isArray(e)?[t,s]=e:e.buffer===o.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=gi(e);let n=0,i=0,a=0,l=[],c=[],p=[];try{if([i,l]=await Pd(r),(r==null?void 0:r.externalData)&&o.mountExternalData){let P=[];for(let O of r.externalData){let D=typeof O=="string"?O:O.path;P.push(Ka(typeof O=="string"?O:O.data).then(K=>{o.mountExternalData(D,K)}))}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,D=O==null?void 0:O.context,K=O==null?void 0:O.gpuDevice,G=O==null?void 0:O.deviceType,N=O==null?void 0:O.powerPreference;D?o.currentContext=D:K?o.currentContext=await o.webnnCreateMLContext(K):o.currentContext=await o.webnnCreateMLContext({deviceType:G,powerPreference:N})}else o.currentContext=await o.webnnCreateMLContext();break}n=await o._OrtCreateSession(t,s,i),(d=o.webgpuOnCreateSession)==null||d.call(o,n),n===0&&Wt("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[M,k]=jg(n),w=!!(r!=null&&r.enableGraphCapture),b=[],$=[],E=[],v=[],x=[];for(let P=0;PP==="gpu-buffer"||P==="ml-tensor")&&(a=o._OrtCreateBinding(n),a===0&&Wt("Can't create IO binding."),y={handle:a,outputPreferredLocations:x,outputPreferredLocationsEncoded:x.map(P=>Ga(P))}),Js.set(n,[n,c,p,y,w,!1]),[n,b,$,E,v]}catch(M){throw c.forEach(k=>o._OrtFree(k)),p.forEach(k=>o._OrtFree(k)),a!==0&&o._OrtReleaseBinding(a)!==0&&Wt("Can't release IO binding."),n!==0&&o._OrtReleaseSession(n)!==0&&Wt("Can't release session."),M}finally{o._free(t),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&Wt("Can't release session options."),l.forEach(M=>o._free(M)),(_=o.unmountExternalData)==null||_.call(o)}},sc=e=>{var l,c,p;let r=Xt(),t=Js.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&&Wt("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&Wt("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&&Wt("Can't release session."),Js.delete(e)},nc=async(e,r,t,s,o,n,i=!1)=>{if(!e){r.push(0);return}let a=Xt(),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 w=e[2].gpuBuffer;_=dn(Nn(c),p);{let b=a.jsepRegisterBuffer;if(!b)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');f=b(s,n,w,_)}}else if(d==="ml-tensor"){let w=e[2].mlTensor;_=dn(Nn(c),p);let b=a.webnnRegisterMLTensor;if(!b)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');f=b(s,w,Nn(c),p)}else{let w=e[2];if(Array.isArray(w)){_=l*w.length,f=a._malloc(_),t.push(f);for(let b=0;ba.setValue(k+$*l,b,l===4?"i32":"i64"));let w=a._OrtCreateTensor(Nn(c),f,_,k,p.length,Ga(u));w===0&&Wt(`Can't create tensor for input/output. session=${s}, index=${n}.`),r.push(w)}finally{a.stackRestore(M)}},oc=async(e,r,t,s,o,n)=>{var K,G,N,te;let i=Xt(),a=i.PTR_SIZE,l=Js.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],M=r.length,k=s.length,w=0,b=[],$=[],E=[],v=[],x=i.stackSave(),y=i.stackAlloc(M*a),P=i.stackAlloc(M*a),O=i.stackAlloc(k*a),D=i.stackAlloc(k*a);try{[w,b]=yd(n);for(let Z=0;ZQ*B,1);F=Rs(_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 Q=[];for(let B=0;B0){let Q=i.jsepGetBuffer;if(!Q)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let B=Q(W),me=dn(_e,Ge);if(me===void 0||!Ua(F))throw new Error(`Unsupported data type: ${F}`);j=!0,ee.push([F,Le,{gpuBuffer:B,download:i.jsepCreateDownloader(B,me,F),dispose:()=>{i._OrtReleaseTensor(oe)!==0&&Wt("Can't release tensor.")}},"gpu-buffer"])}else if(Ie==="ml-tensor"&&Ge>0){let Q=i.webnnEnsureTensor,B=i.webnnIsInt64Supported;if(!Q||!B)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(dn(_e,Ge)===void 0||!Wa(F))throw new Error(`Unsupported data type: ${F}`);if(F==="int64"&&!B(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let me=await Q(e,W,_e,Le,!1);j=!0,ee.push([F,Le,{mlTensor:me,download:i.webnnCreateMLTensorDownloader(W,F),dispose:()=>{i.webnnReleaseTensorId(W),i._OrtReleaseTensor(oe)}},"ml-tensor"])}else{let Q=Va(F),B=new Q(Ge);new Uint8Array(B.buffer,B.byteOffset,B.byteLength).set(i.HEAPU8.subarray(W,W+B.byteLength)),ee.push([F,Le,B,"cpu"])}}finally{i.stackRestore(pe),F==="string"&&W&&i._free(W),j||i._OrtReleaseTensor(oe),(te=i.webnnOnRunEnd)==null||te.call(i,c)}}return u&&!f&&(i._OrtClearBoundOutputs(u.handle)!==0&&Wt("Can't clear bound outputs."),Js.set(e,[c,p,d,u,f,!1])),ee}finally{i.stackRestore(x),$.forEach(H=>i._OrtReleaseTensor(H)),E.forEach(H=>i._OrtReleaseTensor(H)),v.forEach(H=>i._free(H)),w!==0&&i._OrtReleaseRunOptions(w),b.forEach(H=>i._free(H))}},ic=e=>{let r=Xt(),t=Js.get(e);if(!t)throw new Error("invalid session id");let s=t[0],o=r._OrtEndProfiling(s);o===0&&Wt("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}}),Ys,Xr,Gn,xo,To,wi,lc,Mi,wn,Mn,Vg,Ug,Wg,Gg,Kg,Hg,qg,Qg,Xg=Ne(()=>{Ms(),Ng(),un(),za(),Ys=()=>!!Jt.wasm.proxy&&typeof document<"u",Gn=!1,xo=!1,To=!1,Mi=new Map,wn=(e,r)=>{let t=Mi.get(e);t?t.push(r):Mi.set(e,[r])},Mn=()=>{if(Gn||!xo||To||!Xr)throw new Error("worker not ready")},Vg=e=>{switch(e.data.type){case"init-wasm":Gn=!1,e.data.err?(To=!0,lc[1](e.data.err)):(xo=!0,lc[0]()),wi&&(URL.revokeObjectURL(wi),wi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=Mi.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},Ug=async()=>{if(!xo){if(Gn)throw new Error("multiple calls to 'initWasm()' detected.");if(To)throw new Error("previous call to 'initWasm()' failed.");if(Gn=!0,Ys())return new Promise((e,r)=>{Xr==null||Xr.terminate(),fd().then(([t,s])=>{try{Xr=s,Xr.onerror=n=>r(n),Xr.onmessage=Vg,lc=[e,r];let o={type:"init-wasm",in:Jt};!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}),Xr.postMessage(o),wi=t}catch(o){r(o)}},r)});try{await ja(Jt.wasm),await Zl(Jt),xo=!0}catch(e){throw To=!0,e}finally{Gn=!1}}},Wg=async e=>{if(Ys())return Mn(),new Promise((r,t)=>{wn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Jt}};Xr.postMessage(s)});await ec(Jt,e)},Gg=async e=>Ys()?(Mn(),new Promise((r,t)=>{wn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};Xr.postMessage(s,[e.buffer])})):gi(e),Kg=async(e,r)=>{if(Ys()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Mn(),new Promise((t,s)=>{wn("create",[t,s]);let o={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),Xr.postMessage(o,n)})}else return rc(e,r)},Hg=async e=>{if(Ys())return Mn(),new Promise((r,t)=>{wn("release",[r,t]);let s={type:"release",in:e};Xr.postMessage(s)});sc(e)},qg=async(e,r,t,s,o,n)=>{if(Ys()){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 Mn(),new Promise((i,a)=>{wn("run",[i,a]);let l=t,c={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};Xr.postMessage(c,ac(l))})}else return oc(e,r,t,s,o,n)},Qg=async e=>{if(Ys())return Mn(),new Promise((r,t)=>{wn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};Xr.postMessage(s)});ic(e)}}),cc,Jg,Yg,oT=Ne(()=>{Ms(),Xg(),gt(),Ca(),Cd(),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()}`)}},Jg=e=>{switch(e[3]){case"cpu":return new gs(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 gs.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 gs.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},Yg=class{async fetchModelAndCopyToWasmMemory(e){return Gg(await Ka(e))}async loadModel(e,r){ws();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Kg(t,r),ls()}async dispose(){return Hg(this.sessionId)}async run(e,r,t){ws();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 qg(this.sessionId,o,a,i,l,t),p={};for(let d=0;ddc,initializeFlags:()=>uc,wasmBackend:()=>ew});var uc,dc,ew,iT=Ne(()=>{Ms(),Xg(),oT(),uc=()=>{(typeof Jt.wasm.initTimeout!="number"||Jt.wasm.initTimeout<0)&&(Jt.wasm.initTimeout=0);let e=Jt.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.`),Jt.wasm.simd=!1),typeof Jt.wasm.proxy!="boolean"&&(Jt.wasm.proxy=!1),typeof Jt.wasm.trace!="boolean"&&(Jt.wasm.trace=!1),typeof Jt.wasm.numThreads!="number"||!Number.isInteger(Jt.wasm.numThreads)||Jt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Jt.wasm.numThreads=1;else{let r=typeof navigator>"u"?Kv("node:os").cpus().length:navigator.hardwareConcurrency;Jt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},dc=class{async init(e){uc(),await Ug(),await Wg(e)}async createInferenceSessionHandler(e,r){let t=new Yg;return await t.loadModel(e,r),t}},ew=new dc});Ms(),Ms(),Ms();var aT="1.22.0-dev.20250409-89f8206ba4",lT=od;{let e=(iT(),ao(Zg)).wasmBackend;ln("webgpu",e,5),ln("webnn",e,5),ln("cpu",e,10),ln("wasm",e,10)}Object.defineProperty(Jt.versions,"web",{value:aT,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 cT=Object.freeze({__proto__:null,get InferenceSession(){return Pa},get TRACE(){return uo},get TRACE_FUNC_BEGIN(){return ws},get TRACE_FUNC_END(){return ls},get Tensor(){return gs},default:lT,get env(){return Jt},get registerBackend(){return ln}}),Vs={},uT={"onnxruntime-common":(e=>{e.exports=Vv}),"onnxruntime-web":(e=>{e.exports=cT}),"?2ce3":(()=>{}),"?7992":(()=>{}),"?5af5":(()=>{}),"?2b25":(()=>{}),"?db59":(()=>{}),"?383f":(()=>{}),"?fa4b":(()=>{}),"./node_modules/@huggingface/jinja/dist/index.js":((e,r,t)=>{t.r(r),t.d(r,{Environment:()=>ze,Interpreter:()=>nt,Template:()=>Ht,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,X){this.value=S,this.type=X}};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,X={}){return S.endsWith(` +`)&&(S=S.slice(0,-1)),X.lstrip_blocks&&(S=S.replace(/^[ \t]*({[#%-])/gm,"$1")),X.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,X={}){var ot,ft;const R=[],q=c(S,X);let re=0,ge=0;const Ae=pt=>{let vt="";for(;pt(q[re]);){if(q[re]==="\\"){if(++re,re>=q.length)throw new SyntaxError("Unexpected end of input");const tt=q[re++],At=l.get(tt);if(At===void 0)throw new SyntaxError(`Unexpected escaped character: ${tt}`);vt+=At;continue}if(vt+=q[re++],re>=q.length)throw new SyntaxError("Unexpected end of input")}return vt};e:for(;re0){R.push(new o(tt,s.Text));continue}}if(q[re]==="{"&&q[re+1]==="#"){re+=2;let tt="";for(;q[re]!=="#"||q[re+1]!=="}";){if(re+2>=q.length)throw new SyntaxError("Missing end of comment tag");tt+=q[re++]}R.push(new o(tt,s.Comment)),re+=2;continue}Ae(tt=>/\s/.test(tt));const vt=q[re];if(vt==="-"||vt==="+"){const tt=(ft=R.at(-1))==null?void 0:ft.type;if(tt===s.Text||tt===void 0)throw new SyntaxError(`Unexpected character: ${vt}`);switch(tt){case s.Identifier:case s.NumericLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++re;const At=Ae(i);R.push(new o(`${vt}${At}`,At.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[tt,At]of a){if(tt==="}}"&&ge>0)continue;if(q.slice(re,re+tt.length)===tt){R.push(new o(tt,At)),At===s.OpenExpression?ge=0:At===s.OpenCurlyBracket?++ge:At===s.CloseCurlyBracket&&--ge,re+=tt.length;continue e}}if(vt==="'"||vt==='"'){++re;const tt=Ae(At=>At!==vt);R.push(new o(tt,s.StringLiteral)),++re;continue}if(i(vt)){let tt=Ae(i);if(q[re]==="."&&i(q[re+1])){++re;const At=Ae(i);tt=`${tt}.${At}`}R.push(new o(tt,s.NumericLiteral));continue}if(n(vt)){const tt=Ae(n);R.push(new o(tt,s.Identifier));continue}throw new SyntaxError(`Unexpected character: ${vt}`)}return R}var d=class{constructor(){J(this,"type","Statement")}},u=class extends d{constructor(X){super();J(this,"type","Program");this.body=X}},f=class extends d{constructor(X,R,q){super();J(this,"type","If");this.test=X,this.body=R,this.alternate=q}},_=class extends d{constructor(X,R,q,re){super();J(this,"type","For");this.loopvar=X,this.iterable=R,this.body=q,this.defaultBlock=re}},M=class extends d{constructor(){super(...arguments);J(this,"type","Break")}},k=class extends d{constructor(){super(...arguments);J(this,"type","Continue")}},w=class extends d{constructor(X,R,q){super();J(this,"type","Set");this.assignee=X,this.value=R,this.body=q}},b=class extends d{constructor(X,R,q){super();J(this,"type","Macro");this.name=X,this.args=R,this.body=q}},$=class extends d{constructor(X){super();J(this,"type","Comment");this.value=X}},E=class extends d{constructor(){super(...arguments);J(this,"type","Expression")}},v=class extends E{constructor(X,R,q){super();J(this,"type","MemberExpression");this.object=X,this.property=R,this.computed=q}},x=class extends E{constructor(X,R){super();J(this,"type","CallExpression");this.callee=X,this.args=R}},y=class extends E{constructor(X){super();J(this,"type","Identifier");this.value=X}},P=class extends E{constructor(X){super();J(this,"type","Literal");this.value=X}},O=class extends P{constructor(){super(...arguments);J(this,"type","IntegerLiteral")}},D=class extends P{constructor(){super(...arguments);J(this,"type","FloatLiteral")}},K=class extends P{constructor(){super(...arguments);J(this,"type","StringLiteral")}},G=class extends P{constructor(){super(...arguments);J(this,"type","ArrayLiteral")}},N=class extends P{constructor(){super(...arguments);J(this,"type","TupleLiteral")}},te=class extends P{constructor(){super(...arguments);J(this,"type","ObjectLiteral")}},H=class extends E{constructor(X,R,q){super();J(this,"type","BinaryExpression");this.operator=X,this.left=R,this.right=q}},ee=class extends E{constructor(X,R){super();J(this,"type","FilterExpression");this.operand=X,this.filter=R}},Z=class extends d{constructor(X,R){super();J(this,"type","FilterStatement");this.filter=X,this.body=R}},oe=class extends E{constructor(X,R){super();J(this,"type","SelectExpression");this.lhs=X,this.test=R}},pe=class extends E{constructor(X,R,q){super();J(this,"type","TestExpression");this.operand=X,this.negate=R,this.test=q}},ue=class extends E{constructor(X,R){super();J(this,"type","UnaryExpression");this.operator=X,this.argument=R}},j=class extends E{constructor(X=void 0,R=void 0,q=void 0){super();J(this,"type","SliceExpression");this.start=X,this.stop=R,this.step=q}},F=class extends E{constructor(X,R){super();J(this,"type","KeywordArgumentExpression");this.key=X,this.value=R}},W=class extends E{constructor(X){super();J(this,"type","SpreadExpression");this.argument=X}},se=class extends d{constructor(X,R,q){super();J(this,"type","CallStatement");this.call=X,this.callerArgs=R,this.body=q}},_e=class extends E{constructor(X,R,q){super();J(this,"type","Ternary");this.condition=X,this.trueExpr=R,this.falseExpr=q}};function ie(S){const X=new u([]);let R=0;function q(Re,je){const rt=S[R++];if(!rt||rt.type!==Re)throw new Error(`Parser Error: ${je}. ${rt.type} !== ${Re}.`);return rt}function re(Re){if(!ft(Re))throw new SyntaxError(`Expected ${Re}`);++R}function ge(){switch(S[R].type){case s.Comment:return new $(S[R++].value);case s.Text:return pt();case s.OpenStatement:return vt();case s.OpenExpression:return tt();default:throw new SyntaxError(`Unexpected token type: ${S[R].type}`)}}function Ae(...Re){return R+Re.length<=S.length&&Re.every((je,rt)=>je===S[R+rt].type)}function ot(...Re){var je,rt,Qt;return((je=S[R])==null?void 0:je.type)===s.OpenStatement&&((rt=S[R+1])==null?void 0:rt.type)===s.Identifier&&Re.includes((Qt=S[R+1])==null?void 0:Qt.value)}function ft(...Re){return R+Re.length<=S.length&&Re.every((je,rt)=>S[R+rt].type==="Identifier"&&je===S[R+rt].value)}function pt(){return new K(q(s.Text,"Expected text token").value)}function vt(){if(q(s.OpenStatement,"Expected opening statement token"),S[R].type!==s.Identifier)throw new SyntaxError(`Unknown statement, got ${S[R].type}`);const Re=S[R].value;let je;switch(Re){case"set":++R,je=At();break;case"if":++R,je=qt(),q(s.OpenStatement,"Expected {% token"),re("endif"),q(s.CloseStatement,"Expected %} token");break;case"macro":++R,je=Ur(),q(s.OpenStatement,"Expected {% token"),re("endmacro"),q(s.CloseStatement,"Expected %} token");break;case"for":++R,je=nr(),q(s.OpenStatement,"Expected {% token"),re("endfor"),q(s.CloseStatement,"Expected %} token");break;case"call":{++R;let rt=null;Ae(s.OpenParen)&&(rt=Jr());const Qt=Wr();if(Qt.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const Ws=Jr();q(s.CloseStatement,"Expected closing statement token");const Cs=[];for(;!ot("endcall");)Cs.push(ge());q(s.OpenStatement,"Expected '{%'"),re("endcall"),q(s.CloseStatement,"Expected closing statement token");const rs=new x(Qt,Ws);je=new se(rs,rt,Cs);break}case"break":++R,q(s.CloseStatement,"Expected closing statement token"),je=new M;break;case"continue":++R,q(s.CloseStatement,"Expected closing statement token"),je=new k;break;case"filter":{++R;let rt=Wr();rt instanceof y&&Ae(s.OpenParen)&&(rt=ps(rt)),q(s.CloseStatement,"Expected closing statement token");const Qt=[];for(;!ot("endfilter");)Qt.push(ge());q(s.OpenStatement,"Expected '{%'"),re("endfilter"),q(s.CloseStatement,"Expected '%}'"),je=new Z(rt,Qt);break}default:throw new SyntaxError(`Unknown statement type: ${Re}`)}return je}function tt(){q(s.OpenExpression,"Expected opening expression token");const Re=Ir();return q(s.CloseExpression,"Expected closing expression token"),Re}function At(){const Re=Hr();let je=null;const rt=[];if(Ae(s.Equals))++R,je=Hr();else{for(q(s.CloseStatement,"Expected %} token");!ot("endset");)rt.push(ge());q(s.OpenStatement,"Expected {% token"),re("endset")}return q(s.CloseStatement,"Expected closing statement token"),new w(Re,je,rt)}function qt(){const Re=Ir();q(s.CloseStatement,"Expected closing statement token");const je=[],rt=[];for(;!ot("elif","else","endif");)je.push(ge());if(ot("elif")){++R,++R;const Qt=qt();rt.push(Qt)}else if(ot("else"))for(++R,++R,q(s.CloseStatement,"Expected closing statement token");!ot("endif");)rt.push(ge());return new f(Re,je,rt)}function Ur(){const Re=Wr();if(Re.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const je=Jr();q(s.CloseStatement,"Expected closing statement token");const rt=[];for(;!ot("endmacro");)rt.push(ge());return new b(Re,je,rt)}function Hr(Re=!1){const je=Re?Wr:Ir,rt=[je()],Qt=Ae(s.Comma);for(;Qt&&(++R,rt.push(je()),!!Ae(s.Comma)););return Qt?new N(rt):rt[0]}function nr(){const Re=Hr(!0);if(!(Re instanceof y||Re instanceof N))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");++R;const je=Ir();q(s.CloseStatement,"Expected closing statement token");const rt=[];for(;!ot("endfor","else");)rt.push(ge());const Qt=[];if(ot("else"))for(++R,++R,q(s.CloseStatement,"Expected closing statement token");!ot("endfor");)Qt.push(ge());return new _(Re,je,rt,Qt)}function Ir(){return ur()}function ur(){const Re=us();if(ft("if")){++R;const je=us();if(ft("else")){++R;const rt=ur();return new _e(je,Re,rt)}else return new oe(Re,je)}return Re}function us(){let Re=ds();for(;ft("or");){const je=S[R];++R;const rt=ds();Re=new H(je,Re,rt)}return Re}function ds(){let Re=Ar();for(;ft("and");){const je=S[R];++R;const rt=Ar();Re=new H(je,Re,rt)}return Re}function Ar(){let Re;for(;ft("not");){const je=S[R];++R;const rt=Ar();Re=new ue(je,rt)}return Re??Ds()}function Ds(){let Re=Ls();for(;;){let je;if(ft("not","in"))je=new o("not in",s.Identifier),R+=2;else if(ft("in"))je=S[R++];else if(Ae(s.ComparisonBinaryOperator))je=S[R++];else break;const rt=Ls();Re=new H(je,Re,rt)}return Re}function Ls(){let Re=ir();for(;Ae(s.AdditiveBinaryOperator);){const je=S[R];++R;const rt=ir();Re=new H(je,Re,rt)}return Re}function vr(){const Re=hr(Wr());return Ae(s.OpenParen)?ps(Re):Re}function ps(Re){let je=new x(Re,Jr());return je=hr(je),Ae(s.OpenParen)&&(je=ps(je)),je}function Jr(){q(s.OpenParen,"Expected opening parenthesis for arguments list");const Re=Br();return q(s.CloseParen,"Expected closing parenthesis for arguments list"),Re}function Br(){const Re=[];for(;!Ae(s.CloseParen);){let je;if(S[R].type===s.MultiplicativeBinaryOperator&&S[R].value==="*"){++R;const rt=Ir();je=new W(rt)}else if(je=Ir(),Ae(s.Equals)){if(++R,!(je instanceof y))throw new SyntaxError("Expected identifier for keyword argument");const rt=Ir();je=new F(je,rt)}Re.push(je),Ae(s.Comma)&&++R}return Re}function Ps(){const Re=[];let je=!1;for(;!Ae(s.CloseSquareBracket);)Ae(s.Colon)?(Re.push(void 0),++R,je=!0):(Re.push(Ir()),Ae(s.Colon)&&(++R,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 hr(Re){for(;Ae(s.Dot)||Ae(s.OpenSquareBracket);){const je=S[R];++R;let rt;const Qt=je.type===s.OpenSquareBracket;if(Qt)rt=Ps(),q(s.CloseSquareBracket,"Expected closing square bracket");else if(rt=Wr(),rt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Re=new v(Re,rt,Qt)}return Re}function ir(){let Re=ms();for(;Ae(s.MultiplicativeBinaryOperator);){const je=S[R++],rt=ms();Re=new H(je,Re,rt)}return Re}function ms(){let Re=Us();for(;ft("is");){++R;const je=ft("not");je&&++R;const rt=Wr();if(!(rt instanceof y))throw new SyntaxError("Expected identifier for the test");Re=new pe(Re,je,rt)}return Re}function Us(){let Re=vr();for(;Ae(s.Pipe);){++R;let je=Wr();if(!(je instanceof y))throw new SyntaxError("Expected identifier for the filter");Ae(s.OpenParen)&&(je=ps(je)),Re=new ee(Re,je)}return Re}function Wr(){const Re=S[R++];switch(Re.type){case s.NumericLiteral:{const je=Re.value;return je.includes(".")?new D(Number(je)):new O(Number(je))}case s.StringLiteral:{let je=Re.value;for(;Ae(s.StringLiteral);)je+=S[R++].value;return new K(je)}case s.Identifier:return new y(Re.value);case s.OpenParen:{const je=Hr();return q(s.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),je}case s.OpenSquareBracket:{const je=[];for(;!Ae(s.CloseSquareBracket);)je.push(Ir()),Ae(s.Comma)&&++R;return++R,new G(je)}case s.OpenCurlyBracket:{const je=new Map;for(;!Ae(s.CloseCurlyBracket);){const rt=Ir();q(s.Colon,"Expected colon between key and value in object literal");const Qt=Ir();je.set(rt,Qt),Ae(s.Comma)&&++R}return++R,new te(je)}default:throw new SyntaxError(`Unexpected token: ${Re.type}`)}}for(;R=0?(X=(X??(X=0))<0?Math.max(S.length+X,0):Math.min(X,S.length),R=(R??(R=S.length))<0?Math.max(S.length+R,0):Math.min(R,S.length)):(X=(X??(X=S.length-1))<0?Math.max(S.length+X,-1):Math.min(X,S.length-1),R=(R??(R=-1))<-1?Math.max(S.length+R,-1):Math.min(R,S.length-1));const ge=[];for(let Ae=X;re*AeX.toUpperCase())}function Ie(S){return Q(new Date,S)}function Q(S,X){const R=new Intl.DateTimeFormat(void 0,{month:"long"}),q=new Intl.DateTimeFormat(void 0,{month:"short"}),re=ge=>ge<10?"0"+ge:ge.toString();return X.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 R.format(S);case"%H":return re(S.getHours());case"%M":return re(S.getMinutes());case"%%":return"%";default:return ge}})}function B(S){return S.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function me(S,X,R,q){if(q===0)return S;let re=q==null||q<0?1/0:q;const ge=X.length===0?new RegExp("(?=)","gu"):new RegExp(B(X),"gu");return S.replaceAll(ge,Ae=>re>0?(--re,R):Ae)}var Ce=class extends Error{},Pe=class extends Error{},Se=class{constructor(S=void 0){J(this,"type","RuntimeValue");J(this,"value");J(this,"builtins",new Map);this.value=S}__bool__(){return new Fe(!!this.value)}toString(){return String(this.value)}},Me=class extends Se{constructor(){super(...arguments);J(this,"type","IntegerValue")}},$e=class extends Se{constructor(){super(...arguments);J(this,"type","FloatValue")}toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},we=class extends Se{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(X=>{if(X.length===0)throw new Error("startswith() requires at least one argument");const R=X[0];if(R instanceof we)return new Fe(this.value.startsWith(R.value));if(R instanceof ye){for(const q of R.value){if(!(q instanceof we))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(q.value))return new Fe(!0)}return new Fe(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Ke(X=>{if(X.length===0)throw new Error("endswith() requires at least one argument");const R=X[0];if(R instanceof we)return new Fe(this.value.endsWith(R.value));if(R instanceof ye){for(const q of R.value){if(!(q instanceof we))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(q.value))return new Fe(!0)}return new Fe(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Ke(X=>{const R=X[0]??new st;if(!(R instanceof we||R instanceof st))throw new Error("sep argument must be a string or null");const q=X[1]??new Me(-1);if(!(q instanceof Me))throw new Error("maxsplit argument must be a number");let re=[];if(R instanceof st){const ge=this.value.trimStart();for(const{0:Ae,index:ot}of ge.matchAll(/\S+/g)){if(q.value!==-1&&re.length>=q.value&&ot!==void 0){re.push(Ae+ge.slice(ot+Ae.length));break}re.push(Ae)}}else{if(R.value==="")throw new Error("empty separator");re=this.value.split(R.value),q.value!==-1&&re.length>q.value&&re.push(re.splice(q.value).join(R.value))}return new ye(re.map(ge=>new we(ge)))})],["replace",new Ke(X=>{if(X.length<2)throw new Error("replace() requires at least two arguments");const R=X[0],q=X[1];if(!(R instanceof we&&q instanceof we))throw new Error("replace() arguments must be strings");let re;if(X.length>2?X[2].type==="KeywordArgumentsValue"?re=X[2].value.get("count")??new st:re=X[2]:re=new st,!(re instanceof Me||re instanceof st))throw new Error("replace() count argument must be a number or null");return new we(me(this.value,R.value,q.value,re.value))})]]))}},Fe=class extends Se{constructor(){super(...arguments);J(this,"type","BooleanValue")}},Oe=class extends Se{constructor(){super(...arguments);J(this,"type","ObjectValue");J(this,"builtins",new Map([["get",new Ke(([X,R])=>{if(!(X instanceof we))throw new Error(`Object key must be a string: got ${X.type}`);return this.value.get(X.value)??R??new st})],["items",new Ke(()=>this.items())],["keys",new Ke(()=>this.keys())],["values",new Ke(()=>this.values())]]))}__bool__(){return new Fe(this.value.size>0)}items(){return new ye(Array.from(this.value.entries()).map(([X,R])=>new ye([new we(X),R])))}keys(){return new ye(Array.from(this.value.keys()).map(X=>new we(X)))}values(){return new ye(Array.from(this.value.values()))}},Ye=class extends Oe{constructor(){super(...arguments);J(this,"type","KeywordArgumentsValue")}},ye=class extends Se{constructor(){super(...arguments);J(this,"type","ArrayValue");J(this,"builtins",new Map([["length",new Me(this.value.length)]]))}__bool__(){return new Fe(this.value.length>0)}},Ze=class extends ye{constructor(){super(...arguments);J(this,"type","TupleValue")}},Ke=class extends Se{constructor(){super(...arguments);J(this,"type","FunctionValue")}},st=class extends Se{constructor(){super(...arguments);J(this,"type","NullValue")}},Qe=class extends Se{constructor(){super(...arguments);J(this,"type","UndefinedValue")}},ze=class{constructor(S){J(this,"variables",new Map([["namespace",new Ke(S=>{if(S.length===0)return new Oe(new Map);if(S.length!==1||!(S[0]instanceof Oe))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 $e],["integer",S=>S instanceof Me],["iterable",S=>S.type==="ArrayValue"||S.type==="StringValue"],["mapping",S=>S.type==="ObjectValue"],["lower",S=>{const X=S.value;return S.type==="StringValue"&&X===X.toLowerCase()}],["upper",S=>{const X=S.value;return S.type==="StringValue"&&X===X.toUpperCase()}],["none",S=>S.type==="NullValue"],["defined",S=>S.type!=="UndefinedValue"],["undefined",S=>S.type==="UndefinedValue"],["equalto",(S,X)=>S.value===X.value],["eq",(S,X)=>S.value===X.value]]));this.parent=S}set(S,X){return this.declareVariable(S,It(X))}declareVariable(S,X){if(this.variables.has(S))throw new SyntaxError(`Variable already declared: ${S}`);return this.variables.set(S,X),X}setVariable(S,X){return this.variables.set(S,X),X}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 Qe}catch{return new Qe}}};function Je(S){S.set("false",!1),S.set("true",!0),S.set("none",null),S.set("raise_exception",X=>{throw new Error(X)}),S.set("range",ve),S.set("strftime_now",Ie),S.set("True",!0),S.set("False",!1),S.set("None",null)}var nt=class{constructor(S){J(this,"global");this.global=S??new ze}run(S){return this.evaluate(S,this.global)}evaluateBinaryExpression(S,X){const R=this.evaluate(S.left,X);switch(S.operator.value){case"and":return R.__bool__().value?this.evaluate(S.right,X):R;case"or":return R.__bool__().value?R:this.evaluate(S.right,X)}const q=this.evaluate(S.right,X);switch(S.operator.value){case"==":return new Fe(R.value==q.value);case"!=":return new Fe(R.value!=q.value)}if(R instanceof Qe||q instanceof Qe){if(q instanceof Qe&&["in","not in"].includes(S.operator.value))return new Fe(S.operator.value==="not in");throw new Error(`Cannot perform operation ${S.operator.value} on undefined values`)}else{if(R instanceof st||q instanceof st)throw new Error("Cannot perform operation on null values");if(S.operator.value==="~")return new we(R.value.toString()+q.value.toString());if((R instanceof Me||R instanceof $e)&&(q instanceof Me||q instanceof $e)){const re=R.value,ge=q.value;switch(S.operator.value){case"+":case"-":case"*":{const Ae=S.operator.value==="+"?re+ge:S.operator.value==="-"?re-ge:re*ge;return R instanceof $e||q instanceof $e?new $e(Ae):new Me(Ae)}case"/":return new $e(re/ge);case"%":{const Ae=re%ge;return R instanceof $e||q instanceof $e?new $e(Ae):new Me(Ae)}case"<":return new Fe(re":return new Fe(re>ge);case">=":return new Fe(re>=ge);case"<=":return new Fe(re<=ge)}}else if(R instanceof ye&&q instanceof ye)switch(S.operator.value){case"+":return new ye(R.value.concat(q.value))}else if(q instanceof ye){const re=q.value.find(ge=>ge.value===R.value)!==void 0;switch(S.operator.value){case"in":return new Fe(re);case"not in":return new Fe(!re)}}}if(R instanceof we||q instanceof we)switch(S.operator.value){case"+":return new we(R.value.toString()+q.value.toString())}if(R instanceof we&&q instanceof we)switch(S.operator.value){case"in":return new Fe(q.value.includes(R.value));case"not in":return new Fe(!q.value.includes(R.value))}if(R instanceof we&&q instanceof Oe)switch(S.operator.value){case"in":return new Fe(q.value.has(R.value));case"not in":return new Fe(!q.value.has(R.value))}throw new SyntaxError(`Unknown operator "${S.operator.value}" between ${R.type} and ${q.type}`)}evaluateArguments(S,X){const R=[],q=new Map;for(const re of S)if(re.type==="SpreadExpression"){const ge=re,Ae=this.evaluate(ge.argument,X);if(!(Ae instanceof ye))throw new Error(`Cannot unpack non-iterable type: ${Ae.type}`);for(const ot of Ae.value)R.push(ot)}else if(re.type==="KeywordArgumentExpression"){const ge=re;q.set(ge.key.value,this.evaluate(ge.value,X))}else{if(q.size>0)throw new Error("Positional arguments must come before keyword arguments");R.push(this.evaluate(re,X))}return[R,q]}applyFilter(S,X,R){if(X.type==="Identifier"){const q=X;if(q.value==="tojson")return new we(Ct(S));if(S instanceof ye)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 ye(S.value.reverse());case"sort":return new ye(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(Ct(S));case"unique":{const re=new Set,ge=[];for(const Ae of S.value)re.has(Ae.value)||(re.add(Ae.value),ge.push(Ae));return new ye(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([],R);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 $e(isNaN(re)?0:re)}default:throw new Error(`Unknown StringValue filter: ${q.value}`)}else if(S instanceof Me||S instanceof $e)switch(q.value){case"abs":return S instanceof Me?new Me(Math.abs(S.value)):new $e(Math.abs(S.value));case"int":return new Me(Math.floor(S.value));case"float":return new $e(S.value);default:throw new Error(`Unknown NumericValue filter: ${q.value}`)}else if(S instanceof Oe)switch(q.value){case"items":return new ye(Array.from(S.value.entries()).map(([re,ge])=>new ye([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 Fe)switch(q.value){case"bool":return new Fe(S.value);case"int":return new Me(S.value?1:0);case"float":return new $e(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(X.type==="CallExpression"){const q=X;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,R),Ae=ge.get("indent")??new st;if(!(Ae instanceof Me||Ae instanceof st))throw new Error("If set, indent must be a number");return new we(Ct(S,Ae.value))}else if(re==="join"){let ge;if(S instanceof we)ge=Array.from(S.value);else if(S instanceof ye)ge=S.value.map(pt=>pt.value);else throw new Error(`Cannot apply filter "${re}" to type: ${S.type}`);const[Ae,ot]=this.evaluateArguments(q.args,R),ft=Ae.at(0)??ot.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,Ae]=this.evaluateArguments(q.args,R),ot=ge.at(0)??Ae.get("default")??(re==="int"?new Me(0):new $e(0));if(S instanceof we){const ft=re==="int"?parseInt(S.value,10):parseFloat(S.value);return isNaN(ft)?ot:re==="int"?new Me(ft):new $e(ft)}else{if(S instanceof Me||S instanceof $e)return S;if(S instanceof Fe)return re==="int"?new Me(S.value?1:0):new $e(S.value?1:0);throw new Error(`Cannot apply filter "${re}" to type: ${S.type}`)}}else if(re==="default"){const[ge,Ae]=this.evaluateArguments(q.args,R),ot=ge[0]??new we(""),ft=ge[1]??Ae.get("boolean")??new Fe(!1);if(!(ft instanceof Fe))throw new Error("`default` filter flag must be a boolean");return S instanceof Qe||ft.value&&!S.__bool__().value?ot:S}if(S instanceof ye){switch(re){case"selectattr":case"rejectattr":{const ge=re==="selectattr";if(S.value.some(tt=>!(tt instanceof Oe)))throw new Error(`\`${re}\` can only be applied to array of objects`);if(q.args.some(tt=>tt.type!=="StringLiteral"))throw new Error(`arguments of \`${re}\` must be strings`);const[Ae,ot,ft]=q.args.map(tt=>this.evaluate(tt,R));let pt;if(ot){const tt=R.tests.get(ot.value);if(!tt)throw new Error(`Unknown test: ${ot.value}`);pt=tt}else pt=(...tt)=>tt[0].__bool__().value;const vt=S.value.filter(tt=>{const At=tt.value.get(Ae.value),qt=At?pt(At,ft):!1;return ge?qt:!qt});return new ye(vt)}case"map":{const[,ge]=this.evaluateArguments(q.args,R);if(ge.has("attribute")){const Ae=ge.get("attribute");if(!(Ae instanceof we))throw new Error("attribute must be a string");const ot=ge.get("default"),ft=S.value.map(pt=>{if(!(pt instanceof Oe))throw new Error("items in map must be an object");return pt.value.get(Ae.value)??ot??new Qe});return new ye(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,Ae]=this.evaluateArguments(q.args,R),ot=ge.at(0)??Ae.get("width")??new Me(4);if(!(ot instanceof Me))throw new Error("width must be a number");const ft=ge.at(1)??Ae.get("first")??new Fe(!1),pt=ge.at(2)??Ae.get("blank")??new Fe(!1),vt=S.value.split(` +`),tt=" ".repeat(ot.value),At=vt.map((qt,Ur)=>!ft.value&&Ur===0||!pt.value&&qt.length===0?qt:tt+qt);return new we(At.join(` +`))}case"replace":{const ge=S.builtins.get("replace");if(!(ge instanceof Ke))throw new Error("replace filter not available");const[Ae,ot]=this.evaluateArguments(q.args,R);return ge.value([...Ae,new Ye(ot)],R)}}throw new Error(`Unknown StringValue filter: ${re}`)}else throw new Error(`Cannot apply filter "${re}" to type: ${S.type}`)}throw new Error(`Unknown filter: ${X.type}`)}evaluateFilterExpression(S,X){const R=this.evaluate(S.operand,X);return this.applyFilter(R,S.filter,X)}evaluateTestExpression(S,X){const R=this.evaluate(S.operand,X),q=X.tests.get(S.test.value);if(!q)throw new Error(`Unknown test: ${S.test.value}`);const re=q(R);return new Fe(S.negate?!re:re)}evaluateSelectExpression(S,X){return this.evaluate(S.test,X).__bool__().value?this.evaluate(S.lhs,X):new Qe}evaluateUnaryExpression(S,X){const R=this.evaluate(S.argument,X);switch(S.operator.value){case"not":return new Fe(!R.value);default:throw new SyntaxError(`Unknown operator: ${S.operator.value}`)}}evaluateTernaryExpression(S,X){return this.evaluate(S.condition,X).__bool__().value?this.evaluate(S.trueExpr,X):this.evaluate(S.falseExpr,X)}evalProgram(S,X){return this.evaluateBlock(S.body,X)}evaluateBlock(S,X){let R="";for(const q of S){const re=this.evaluate(q,X);re.type!=="NullValue"&&re.type!=="UndefinedValue"&&(R+=re.toString())}return new we(R)}evaluateIdentifier(S,X){return X.lookupVariable(S.value)}evaluateCallExpression(S,X){const[R,q]=this.evaluateArguments(S.args,X);q.size>0&&R.push(new Ye(q));const re=this.evaluate(S.callee,X);if(re.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${re.type}`);return re.value(R,X)}evaluateSliceExpression(S,X,R){if(!(S instanceof ye||S instanceof we))throw new Error("Slice object must be an array or string");const q=this.evaluate(X.start,R),re=this.evaluate(X.stop,R),ge=this.evaluate(X.step,R);if(!(q instanceof Me||q instanceof Qe))throw new Error("Slice start must be numeric or undefined");if(!(re instanceof Me||re instanceof Qe))throw new Error("Slice stop must be numeric or undefined");if(!(ge instanceof Me||ge instanceof Qe))throw new Error("Slice step must be numeric or undefined");return S instanceof ye?new ye(Le(S.value,q.value,re.value,ge.value)):new we(Le(Array.from(S.value),q.value,re.value,ge.value).join(""))}evaluateMemberExpression(S,X){const R=this.evaluate(S.object,X);let q;if(S.computed){if(S.property.type==="SliceExpression")return this.evaluateSliceExpression(R,S.property,X);q=this.evaluate(S.property,X)}else q=new we(S.property.value);let re;if(R instanceof Oe){if(!(q instanceof we))throw new Error(`Cannot access property with non-string: got ${q.type}`);re=R.value.get(q.value)??R.builtins.get(q.value)}else if(R instanceof ye||R instanceof we)if(q instanceof Me)re=R.value.at(q.value),R instanceof we&&(re=new we(R.value.at(q.value)));else if(q instanceof we)re=R.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=R.builtins.get(q.value)}return re instanceof Se?re:new Qe}evaluateSet(S,X){const R=S.value?this.evaluate(S.value,X):this.evaluateBlock(S.body,X);if(S.assignee.type==="Identifier"){const q=S.assignee.value;X.setVariable(q,R)}else if(S.assignee.type==="TupleLiteral"){const q=S.assignee;if(!(R instanceof ye))throw new Error(`Cannot unpack non-iterable type in set: ${R.type}`);const re=R.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;geqt.setVariable(S.loopvar.value,tt);else if(S.loopvar.type==="TupleLiteral"){const qt=S.loopvar;if(tt.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${tt.type}`);const Ur=tt;if(qt.value.length!==Ur.value.length)throw new Error(`Too ${qt.value.length>Ur.value.length?"few":"many"} items to unpack`);At=Hr=>{for(let nr=0;nr0?ge[pt-1]:new Qe],["nextitem",pt{var Ae;const re=new ze(q);R=R.slice();let ge;((Ae=R.at(-1))==null?void 0:Ae.type)==="KeywordArgumentsValue"&&(ge=R.pop());for(let ot=0;ot{const pt=new ze(ft);if(S.callerArgs)for(let vt=0;vtthis.evaluate(R,X)));case"TupleLiteral":return new Ze(S.value.map(R=>this.evaluate(R,X)));case"ObjectLiteral":{const R=new Map;for(const[q,re]of S.value){const ge=this.evaluate(q,X);if(!(ge instanceof we))throw new Error(`Object keys must be strings: got ${ge.type}`);R.set(ge.value,this.evaluate(re,X))}return new Oe(R)}case"Identifier":return this.evaluateIdentifier(S,X);case"CallExpression":return this.evaluateCallExpression(S,X);case"MemberExpression":return this.evaluateMemberExpression(S,X);case"UnaryExpression":return this.evaluateUnaryExpression(S,X);case"BinaryExpression":return this.evaluateBinaryExpression(S,X);case"FilterExpression":return this.evaluateFilterExpression(S,X);case"FilterStatement":return this.evaluateFilterStatement(S,X);case"TestExpression":return this.evaluateTestExpression(S,X);case"SelectExpression":return this.evaluateSelectExpression(S,X);case"Ternary":return this.evaluateTernaryExpression(S,X);case"Comment":return new st;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 $e(S);case"string":return new we(S);case"boolean":return new Fe(S);case"undefined":return new Qe;case"object":return S===null?new st:Array.isArray(S)?new ye(S.map(It)):new Oe(new Map(Object.entries(S).map(([X,R])=>[X,It(R)])));case"function":return new Ke((X,R)=>{const q=S(...X.map(re=>re.value))??null;return It(q)});default:throw new Error(`Cannot convert to runtime value: ${S}`)}}function Ct(S,X,R){const q=R??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=X?" ".repeat(X):"",ge=` +`+re.repeat(q),Ae=ge+re;if(S.type==="ArrayValue"){const ot=S.value.map(ft=>Ct(ft,X,q+1));return X?`[${Ae}${ot.join(`,${Ae}`)}${ge}]`:`[${ot.join(", ")}]`}else{const ot=Array.from(S.value.entries()).map(([ft,pt])=>{const vt=`"${ft}": ${Ct(pt,X,q+1)}`;return X?`${Ae}${vt}`:vt});return X?`{${ot.join(",")}${ge}}`:`{${ot.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${S.type}`)}}var Mt=` +`,yr="{%- ",$r=" -%}";function Nr(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 Vr(S,X=" "){const R=typeof X=="number"?" ".repeat(X):X;return kr(S.body,0,R).replace(/\n$/,"")}function sr(...S){return yr+S.join(" ")+$r}function kr(S,X,R){return S.map(q=>Zs(q,X,R)).join(Mt)}function Zs(S,X,R){const q=R.repeat(X);switch(S.type){case"Program":return kr(S.body,X,R);case"If":return en(S,X,R);case"For":return tn(S,X,R);case"Set":return cs(S,X,R);case"Macro":return ht(S,X,R);case"Break":return q+sr("break");case"Continue":return q+sr("continue");case"CallStatement":return Fs(S,X,R);case"FilterStatement":return Os(S,X,R);case"Comment":return q+"{# "+S.value+" #}";default:return q+"{{- "+St(S)+" -}}"}}function en(S,X,R){const q=R.repeat(X),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 Ae=q+sr("if",St(re[0].test))+Mt+kr(re[0].body,X+1,R);for(let ot=1;ot0&&(Ae+=Mt+q+sr("else")+Mt+kr(ge.alternate,X+1,R)),Ae+=Mt+q+sr("endif"),Ae}function tn(S,X,R){const q=R.repeat(X);let re="";if(S.iterable.type==="SelectExpression"){const Ae=S.iterable;re=`${St(Ae.lhs)} if ${St(Ae.test)}`}else re=St(S.iterable);let ge=q+sr("for",St(S.loopvar),"in",re)+Mt+kr(S.body,X+1,R);return S.defaultBlock.length>0&&(ge+=Mt+q+sr("else")+Mt+kr(S.defaultBlock,X+1,R)),ge+=Mt+q+sr("endfor"),ge}function cs(S,X,R){const q=R.repeat(X),re=St(S.assignee),ge=S.value?St(S.value):"",Ae=q+sr("set",`${re}${S.value?" = "+ge:""}`);return S.body.length===0?Ae:Ae+Mt+kr(S.body,X+1,R)+Mt+q+sr("endset")}function ht(S,X,R){const q=R.repeat(X),re=S.args.map(St).join(", ");return q+sr("macro",`${S.name.value}(${re})`)+Mt+kr(S.body,X+1,R)+Mt+q+sr("endmacro")}function Fs(S,X,R){const q=R.repeat(X),re=S.callerArgs&&S.callerArgs.length>0?`(${S.callerArgs.map(St).join(", ")})`:"",ge=St(S.call);let Ae=q+sr(`call${re}`,ge)+Mt;return Ae+=kr(S.body,X+1,R)+Mt,Ae+=q+sr("endcall"),Ae}function Os(S,X,R){const q=R.repeat(X),re=S.filter.type==="Identifier"?S.filter.value:St(S.filter);let ge=q+sr("filter",re)+Mt;return ge+=kr(S.body,X+1,R)+Mt,ge+=q+sr("endfilter"),ge}function St(S,X=-1){switch(S.type){case"SpreadExpression":return`*${St(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 R=S,q=Nr(R),re=St(R.left,q),ge=St(R.right,q+1),Ae=`${re} ${R.operator.value} ${ge}`;return q`${St(q)}: ${St(re)}`).join(", ")}}`;case"SliceExpression":{const R=S,q=R.start?St(R.start):"",re=R.stop?St(R.stop):"",ge=R.step?`:${St(R.step)}`:"";return`${q}:${re}${ge}`}case"KeywordArgumentExpression":{const R=S;return`${R.key.value}=${St(R.value)}`}case"Ternary":{const R=S,q=`${St(R.trueExpr)} if ${St(R.condition,0)} else ${St(R.falseExpr)}`;return X>-1?`(${q})`:q}default:throw new Error(`Unknown expression type: ${S.type}`)}}var Ht=class{constructor(S){J(this,"parsed");const X=p(S,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=ie(X)}render(S){const X=new ze;if(Je(X),S)for(const[re,ge]of Object.entries(S))X.set(re,ge);return new nt(X).run(this.parsed).value}format(S){return Vr(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:()=>x,isONNXTensor:()=>E,runInferenceSession:()=>$});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 _(y=null){if(!y)return p;switch(y){case"auto":return c;case"gpu":return c.filter(P=>["webgpu","cuda","dml","webnn-gpu"].includes(P))}if(c.includes(y))return[l[y]??y];throw new Error(`Unsupported device: "${y}". Should be one of: ${c.join(", ")}.`)}let M=null;async function k(y,P,O){M&&await M;const D=f.create(y,P);M??(M=D);const K=await D;return K.config=O,K}let w=Promise.resolve();const b=o.apis.IS_BROWSER_ENV||o.apis.IS_WEBWORKER_ENV;async function $(y,P){const O=()=>y.run(P);return await(b?w=w.then(O):O())}function E(y){return y instanceof d.Tensor}const v=d==null?void 0:d.env;v!=null&&v.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!v.wasm.wasmPaths&&(v.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`),v.wasm.proxy=!1),v!=null&&v.webgpu&&(v.webgpu.powerPreference="high-performance");function x(){var y;return(y=v==null?void 0:v.wasm)==null?void 0:y.proxy}o.env.backends.onnx=v}),"./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:()=>E,center_to_corners_format:()=>d,post_process_instance_segmentation:()=>$,post_process_object_detection:()=>u,post_process_panoptic_segmentation:()=>b,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(v,x,y=0,P=null){const O=v/x;let D=(0,n.bankers_round)(O)*x;return P!==null&&D>P&&(D=Math.floor(O)*x),Dx&&F.push(se)}else{let se=(0,n.max)(j.data)[1];if(se===N-1||(W=(0,n.softmax)(j.data),W[se]ie*ee[(ve+1)%2])),Z.boxes.push(_e),Z.classes.push(se),Z.scores.push(W[se])}}te.push(Z)}return te}function f(v,x=null){const y=v.logits,P=y.dims[0];if(x!==null&&x.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 D=0;Dee[F]&&(ee[F]=j[F],Z[F]=ue)}const oe=new Array(G.dims[0]);for(let ue=0;ueue!==void 0);O.push({segmentation:H,labels:pe})}return O}function _(v,x,y,P){const O=[],D=[],K=[];for(let G=0;Gy&&(O.push(te),D.push(Z),K.push(H))}return[O,D,K]}function M(v,x,y,P=.5,O=.8){const D=[];let K=0,G=0;const N=x[y].data;for(let H=0;H=P&&++G;let te=K>0&&G>0;return te&&(te=K/G>O),[te,D]}function k(v,x,y,P,O,D=null,K=null){const[G,N]=K??v[0].dims,te=new o.Tensor("int32",new Int32Array(G*N),[G,N]),H=[];if(K!==null)for(let ue=0;ueZ[W]&&(ee[W]=ue,Z[W]=F[W])}let oe=0;const pe=te.data;for(let ue=0;ue200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(v,x)/Math.min(v,x)}`);let D=Math.round(v/y)*y,K=Math.round(x/y)*y;if(D*K>O){const G=Math.sqrt(v*x/O);D=Math.floor(v/G/y)*y,K=Math.floor(x/G/y)*y}else if(D*KD?te=Math.floor(D*N/O):D>O&&(N=Math.floor(O*te/D)),await x.resize(te,N,{resample:P}))}async crop_margin(x,y=200){const P=x.clone().grayscale(),O=(0,n.min)(P.data)[0],K=(0,n.max)(P.data)[0]-O;if(K===0)return x;const G=y/255;let N=P.width,te=P.height,H=0,ee=0;const Z=P.data;for(let oe=0;oethis.preprocess(D)));return{pixel_values:(0,o.stack)(P.map(D=>D.pixel_values),0),original_sizes:P.map(D=>D.original_size),reshaped_input_sizes:P.map(D=>D.reshaped_input_size)}}static async from_pretrained(x,y={}){const P=await(0,a.getModelJSON)(x,l.IMAGE_PROCESSOR_NAME,!0,y);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"llama4_text":case"arcee":case"lfm2":case"smollm3":case"olmo":case"olmo2":case"mobilellm":case"granite":case"granitemoehybrid":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"vaultgemma":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 M=i(d.decoder),k="num_decoder_layers"in M,w=(0,s.pick)(d,["model_type","is_encoder_decoder"]);return k?(w.num_decoder_layers=M.num_decoder_layers,w.num_decoder_heads=M.num_decoder_heads,w.decoder_hidden_size=M.decoder_hidden_size,w.num_encoder_layers=M.num_encoder_layers,w.num_encoder_heads=M.num_encoder_heads,w.encoder_hidden_size=M.encoder_hidden_size):(w.num_layers=M.num_layers,w.num_heads=M.num_heads,w.hidden_size=M.hidden_size),w}const _={...f,...(0,s.pick)(d,["model_type","multi_query","is_encoder_decoder"])};for(const M in u)_[M]=d[u[M]];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",M={},{layer_types:k,num_attention_heads:w,num_key_value_heads:b,hidden_size:$,conv_L_cache:E}=d,v=$/w,x=(u==null?void 0:u.batch_size)??1;for(let y=0;y{var O,D;t.r(r),t.d(r,{apis:()=>w,env:()=>y});var s=t("?db59"),o=t("?383f"),n=t("?fa4b");const i="3.7.5",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&&((D=process==null?void 0:process.release)==null?void 0:D.name)==="node",_=!P(s),M=!P(o),k=typeof globalThis.Deno<"u",w=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:M}),b=_&&M;let $="./";if(b){const K=Object({url:self.location.href}).url;K?$=o.dirname(o.dirname(n.fileURLToPath(K))):typeof __dirname<"u"&&($=o.dirname(__dirname))}const E=b?o.join($,"/.cache/"):null,v="/models/",x=b?o.join($,v):v,y={version:i,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:x,useFS:_,useBrowserCache:c&&!k,useFSCache:_,cacheDir:E,useCustomCache:!1,customCache:null};function P(K){return Object.keys(K).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:()=>w,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>c,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>_,MinNewTokensLengthLogitsProcessor:()=>M,NoBadWordsLogitsProcessor:()=>k,NoRepeatNGramLogitsProcessor:()=>u,RepetitionPenaltyLogitsProcessor:()=>f,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>b,TopKLogitsWarper:()=>E,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(x,y){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(x,y){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(x){this.processors.push(x)}extend(x){this.processors.push(...x)}_call(x,y){let P=y;for(const O of this.processors)P=O(x,P);return P}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(x){super(),this.bos_token_id=x}_call(x,y){for(let P=0;P=1&&D[D.length-1]>=this.timestamp_begin,G=D.length<2||D[D.length-2]>=this.timestamp_begin;if(K&&(G?O.subarray(this.timestamp_begin).fill(-1/0):O.subarray(0,this.eos_token_id).fill(-1/0)),x[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 N=(0,o.log_softmax)(O),te=Math.log(N.subarray(this.timestamp_begin).map(Math.exp).reduce((ee,Z)=>ee+Z)),H=(0,o.max)(N.subarray(0,this.timestamp_begin))[0];te>H&&O.subarray(0,this.timestamp_begin).fill(-1/0)}return y}}class u extends n{constructor(x){super(),this.no_repeat_ngram_size=x}getNgrams(x){const y=x.length,P=[];for(let D=0;D1 to use the classifier free guidance processor, got guidance scale ${x}.`);this.guidance_scale=x}_call(x,y){if(y.dims[0]!==2*x.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 ${y.dims[0]} for the logits and ${x.length} for the input ids.`);const P=x.length,O=y.slice([0,P],null),D=y.slice([P,y.dims[0]],null);for(let K=0;K1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${x}`);if(!Number.isInteger(P)||P<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${P}`);this.top_p=x,this.filter_value=y,this.min_tokens_to_keep=P}}class E extends i{constructor(x,{filter_value:y=-1/0,min_tokens_to_keep:P=1}={}){if(super(),!Number.isInteger(x)||x<0)throw new Error(`\`top_k\` must be a positive integer, but is ${x}`);this.top_k=Math.max(x,P),this.filter_value=y}}}),"./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 M=u*f;_=_.slice(M,M+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),M=(0,n.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},()=>{const k=this.randomSelect(M);return[_.data[k],Math.log(M[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),M=(0,n.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},(k,w)=>[_.data[w],Math.log(M[w])])}}}),"./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 M=0;Md.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:M=!0,decode_kwargs:k={},...w}={}){super(),this.tokenizer=d,this.skip_prompt=u,this.callback_function=f??a,this.token_callback_function=_,this.decode_kwargs={skip_special_tokens:M,...k,...w},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 M;u||_.endsWith(` +`)?(M=_.slice(this.print_len),this.token_cache=[],this.print_len=0):_.length>0&&(0,o.is_chinese_char)(_.charCodeAt(_.length-1))?(M=_.slice(this.print_len),this.print_len+=M.length):(M=_.slice(this.print_len,_.lastIndexOf(" ")+1),this.print_len+=M.length),this.on_finalized_text(M,!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:M=null,on_chunk_end:k=null,on_finalize:w=null,time_precision:b=.02,skip_special_tokens:$=!0,decode_kwargs:E={}}={}){super(d,{skip_prompt:u,skip_special_tokens:$,callback_function:f,token_callback_function:_,decode_kwargs:E}),this.timestamp_begin=d.timestamp_begin,this.on_chunk_start=M,this.on_chunk_end=k,this.on_finalize=w,this.time_precision=b,this.waiting_for_timestamp=!1}put(d){var f,_,M;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 w=k*this.time_precision;this.waiting_for_timestamp?(f=this.on_chunk_end)==null||f.call(this,w):(_=this.on_chunk_start)==null||_.call(this,w),this.waiting_for_timestamp=!this.waiting_for_timestamp,(M=this.token_callback_function)==null||M.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:()=>Oi,ASTModel:()=>Fi,ASTPreTrainedModel:()=>Kn,AlbertForMaskedLM:()=>et,AlbertForQuestionAnswering:()=>We,AlbertForSequenceClassification:()=>He,AlbertModel:()=>Ve,AlbertPreTrainedModel:()=>xe,ArceeForCausalLM:()=>zt,ArceeModel:()=>xt,ArceePreTrainedModel:()=>it,AutoModel:()=>ku,AutoModelForAudioClassification:()=>cv,AutoModelForAudioFrameClassification:()=>dv,AutoModelForAudioTextToText:()=>bv,AutoModelForCTC:()=>lv,AutoModelForCausalLM:()=>J0,AutoModelForDepthEstimation:()=>_v,AutoModelForDocumentQuestionAnswering:()=>pv,AutoModelForImageClassification:()=>tv,AutoModelForImageFeatureExtraction:()=>wv,AutoModelForImageMatting:()=>mv,AutoModelForImageSegmentation:()=>rv,AutoModelForImageTextToText:()=>Mv,AutoModelForImageToImage:()=>hv,AutoModelForMaskGeneration:()=>av,AutoModelForMaskedLM:()=>Y0,AutoModelForNormalEstimation:()=>fv,AutoModelForObjectDetection:()=>ov,AutoModelForPoseEstimation:()=>gv,AutoModelForQuestionAnswering:()=>Z0,AutoModelForSemanticSegmentation:()=>sv,AutoModelForSeq2SeqLM:()=>H0,AutoModelForSequenceClassification:()=>G0,AutoModelForSpeechSeq2Seq:()=>q0,AutoModelForTextToSpectrogram:()=>Q0,AutoModelForTextToWaveform:()=>X0,AutoModelForTokenClassification:()=>K0,AutoModelForUniversalSegmentation:()=>nv,AutoModelForVision2Seq:()=>ev,AutoModelForXVector:()=>uv,AutoModelForZeroShotObjectDetection:()=>iv,BartForConditionalGeneration:()=>Yt,BartForSequenceClassification:()=>Mr,BartModel:()=>ss,BartPretrainedModel:()=>xr,BaseModelOutput:()=>Ce,BeitForImageClassification:()=>yM,BeitModel:()=>bM,BeitPreTrainedModel:()=>Gc,BertForMaskedLM:()=>Me,BertForQuestionAnswering:()=>Fe,BertForSequenceClassification:()=>$e,BertForTokenClassification:()=>we,BertModel:()=>Se,BertPreTrainedModel:()=>Pe,BlenderbotForConditionalGeneration:()=>_r,BlenderbotModel:()=>pr,BlenderbotPreTrainedModel:()=>ar,BlenderbotSmallForConditionalGeneration:()=>Gs,BlenderbotSmallModel:()=>qr,BlenderbotSmallPreTrainedModel:()=>er,BloomForCausalLM:()=>Uw,BloomModel:()=>Vw,BloomPreTrainedModel:()=>Fc,CLIPModel:()=>Xn,CLIPPreTrainedModel:()=>$s,CLIPSegForImageSegmentation:()=>Sn,CLIPSegModel:()=>ns,CLIPSegPreTrainedModel:()=>nn,CLIPTextModel:()=>Ki,CLIPTextModelWithProjection:()=>Ao,CLIPVisionModel:()=>Hi,CLIPVisionModelWithProjection:()=>Fo,CamembertForMaskedLM:()=>ft,CamembertForQuestionAnswering:()=>tt,CamembertForSequenceClassification:()=>pt,CamembertForTokenClassification:()=>vt,CamembertModel:()=>ot,CamembertPreTrainedModel:()=>Ae,CausalLMOutput:()=>An,CausalLMOutputWithPast:()=>AT,ChineseCLIPModel:()=>Cn,ChineseCLIPPreTrainedModel:()=>Lo,ClapAudioModelWithProjection:()=>Cy,ClapModel:()=>Ey,ClapPreTrainedModel:()=>ra,ClapTextModelWithProjection:()=>Py,CodeGenForCausalLM:()=>z,CodeGenModel:()=>A,CodeGenPreTrainedModel:()=>T,CohereForCausalLM:()=>yw,CohereModel:()=>bw,CoherePreTrainedModel:()=>xc,ConvBertForMaskedLM:()=>Fs,ConvBertForQuestionAnswering:()=>Ht,ConvBertForSequenceClassification:()=>Os,ConvBertForTokenClassification:()=>St,ConvBertModel:()=>ht,ConvBertPreTrainedModel:()=>cs,ConvNextForImageClassification:()=>_b,ConvNextModel:()=>hb,ConvNextPreTrainedModel:()=>iu,ConvNextV2ForImageClassification:()=>gb,ConvNextV2Model:()=>fb,ConvNextV2PreTrainedModel:()=>au,DFineForObjectDetection:()=>OM,DFineModel:()=>FM,DFinePreTrainedModel:()=>Jc,DINOv3ConvNextModel:()=>Eb,DINOv3ConvNextPreTrainedModel:()=>Tb,DINOv3ViTModel:()=>xb,DINOv3ViTPreTrainedModel:()=>vb,DPTForDepthEstimation:()=>XM,DPTModel:()=>QM,DPTPreTrainedModel:()=>su,DacDecoderModel:()=>_0,DacDecoderOutput:()=>p0,DacEncoderModel:()=>h0,DacEncoderOutput:()=>d0,DacModel:()=>m0,DacPreTrainedModel:()=>ca,DebertaForMaskedLM:()=>Ur,DebertaForQuestionAnswering:()=>Ir,DebertaForSequenceClassification:()=>Hr,DebertaForTokenClassification:()=>nr,DebertaModel:()=>qt,DebertaPreTrainedModel:()=>At,DebertaV2ForMaskedLM:()=>ds,DebertaV2ForQuestionAnswering:()=>Ls,DebertaV2ForSequenceClassification:()=>Ar,DebertaV2ForTokenClassification:()=>Ds,DebertaV2Model:()=>us,DebertaV2PreTrainedModel:()=>ur,DecisionTransformerModel:()=>qy,DecisionTransformerPreTrainedModel:()=>Hy,DeiTForImageClassification:()=>RM,DeiTModel:()=>BM,DeiTPreTrainedModel:()=>Zc,DepthAnythingForDepthEstimation:()=>YM,DepthAnythingPreTrainedModel:()=>JM,DepthProForDepthEstimation:()=>sb,DepthProPreTrainedModel:()=>rb,DetrForObjectDetection:()=>xM,DetrForSegmentation:()=>Kc,DetrModel:()=>vM,DetrObjectDetectionOutput:()=>Hc,DetrPreTrainedModel:()=>Xi,DetrSegmentationOutput:()=>TM,Dinov2ForImageClassification:()=>Mb,Dinov2Model:()=>wb,Dinov2PreTrainedModel:()=>lu,Dinov2WithRegistersForImageClassification:()=>yb,Dinov2WithRegistersModel:()=>bb,Dinov2WithRegistersPreTrainedModel:()=>cu,DistilBertForMaskedLM:()=>hr,DistilBertForQuestionAnswering:()=>Ps,DistilBertForSequenceClassification:()=>Jr,DistilBertForTokenClassification:()=>Br,DistilBertModel:()=>ps,DistilBertPreTrainedModel:()=>vr,DonutSwinModel:()=>mb,DonutSwinPreTrainedModel:()=>pb,EfficientNetForImageClassification:()=>Oy,EfficientNetModel:()=>Fy,EfficientNetPreTrainedModel:()=>bu,ElectraForMaskedLM:()=>R,ElectraForQuestionAnswering:()=>ge,ElectraForSequenceClassification:()=>q,ElectraForTokenClassification:()=>re,ElectraModel:()=>X,ElectraPreTrainedModel:()=>S,Ernie4_5_ForCausalLM:()=>by,Ernie4_5_Model:()=>My,Ernie4_5_PretrainedModel:()=>_u,EsmForMaskedLM:()=>Us,EsmForSequenceClassification:()=>Wr,EsmForTokenClassification:()=>Re,EsmModel:()=>ms,EsmPreTrainedModel:()=>ir,ExaoneForCausalLM:()=>cw,ExaoneModel:()=>lw,ExaonePreTrainedModel:()=>gc,FalconForCausalLM:()=>Ty,FalconModel:()=>xy,FalconPreTrainedModel:()=>gu,FastViTForImageClassification:()=>cM,FastViTModel:()=>lM,FastViTPreTrainedModel:()=>jc,Florence2ForConditionalGeneration:()=>ji,Florence2PreTrainedModel:()=>Ri,GLPNForDepthEstimation:()=>db,GLPNModel:()=>ub,GLPNPreTrainedModel:()=>ou,GPT2LMHeadModel:()=>jo,GPT2Model:()=>Ro,GPT2PreTrainedModel:()=>$n,GPTBigCodeForCausalLM:()=>m,GPTBigCodeModel:()=>Ko,GPTBigCodePreTrainedModel:()=>so,GPTJForCausalLM:()=>Go,GPTJModel:()=>Wo,GPTJPreTrainedModel:()=>ro,GPTNeoForCausalLM:()=>kn,GPTNeoModel:()=>Vo,GPTNeoPreTrainedModel:()=>eo,GPTNeoXForCausalLM:()=>Uo,GPTNeoXModel:()=>to,GPTNeoXPreTrainedModel:()=>In,Gemma2ForCausalLM:()=>Ew,Gemma2Model:()=>Tw,Gemma2PreTrainedModel:()=>Ec,Gemma3ForCausalLM:()=>$w,Gemma3Model:()=>Sw,Gemma3PreTrainedModel:()=>Cc,Gemma3nForConditionalGeneration:()=>ko,Gemma3nPreTrainedModel:()=>Wi,GemmaForCausalLM:()=>xw,GemmaModel:()=>vw,GemmaPreTrainedModel:()=>Tc,GlmForCausalLM:()=>aw,GlmModel:()=>iw,GlmPreTrainedModel:()=>fc,GraniteForCausalLM:()=>gw,GraniteModel:()=>fw,GraniteMoeHybridForCausalLM:()=>Mw,GraniteMoeHybridModel:()=>ww,GraniteMoeHybridPreTrainedModel:()=>vc,GranitePreTrainedModel:()=>yc,GroundingDinoForObjectDetection:()=>Cb,GroundingDinoPreTrainedModel:()=>Pb,GroupViTModel:()=>aM,GroupViTPreTrainedModel:()=>iM,HeliumForCausalLM:()=>ow,HeliumModel:()=>nw,HeliumPreTrainedModel:()=>_c,HieraForImageClassification:()=>NM,HieraModel:()=>jM,HieraPreTrainedModel:()=>eu,HubertForCTC:()=>sy,HubertForSequenceClassification:()=>ny,HubertModel:()=>ry,HubertPreTrainedModel:()=>wT,IJepaForImageClassification:()=>Jw,IJepaModel:()=>Xw,IJepaPreTrainedModel:()=>zc,Idefics3ForConditionalGeneration:()=>Bs,Idefics3PreTrainedModel:()=>Pn,ImageMattingOutput:()=>vv,JAISLMHeadModel:()=>No,JAISModel:()=>Zn,JAISPreTrainedModel:()=>Yn,JinaCLIPModel:()=>Qi,JinaCLIPPreTrainedModel:()=>ut,JinaCLIPTextModel:()=>zo,JinaCLIPVisionModel:()=>Bo,Lfm2ForCausalLM:()=>Hs,Lfm2Model:()=>Tr,Lfm2PreTrainedModel:()=>Ut,LiteWhisperForConditionalGeneration:()=>Di,Llama4ForCausalLM:()=>qe,Llama4PreTrainedModel:()=>De,LlamaForCausalLM:()=>Te,LlamaModel:()=>le,LlamaPreTrainedModel:()=>U,LlavaForConditionalGeneration:()=>En,LlavaOnevisionForConditionalGeneration:()=>zi,LlavaPreTrainedModel:()=>Tn,LlavaQwen2ForCausalLM:()=>Ui,LongT5ForConditionalGeneration:()=>fr,LongT5Model:()=>Gt,LongT5PreTrainedModel:()=>Zt,M2M100ForConditionalGeneration:()=>zb,M2M100Model:()=>Lb,M2M100PreTrainedModel:()=>pu,MBartForCausalLM:()=>hs,MBartForConditionalGeneration:()=>Ss,MBartForSequenceClassification:()=>Or,MBartModel:()=>Yr,MBartPreTrainedModel:()=>Fr,MPNetForMaskedLM:()=>yn,MPNetForQuestionAnswering:()=>de,MPNetForSequenceClassification:()=>vn,MPNetForTokenClassification:()=>xn,MPNetModel:()=>bn,MPNetPreTrainedModel:()=>rs,MT5ForConditionalGeneration:()=>wr,MT5Model:()=>dr,MT5PreTrainedModel:()=>gr,MarianMTModel:()=>Db,MarianModel:()=>Ob,MarianPreTrainedModel:()=>du,MaskFormerForInstanceSegmentation:()=>cb,MaskFormerModel:()=>lb,MaskFormerPreTrainedModel:()=>nu,MaskedLMOutput:()=>Dr,Metric3DForDepthEstimation:()=>ob,Metric3DPreTrainedModel:()=>nb,Metric3Dv2ForDepthEstimation:()=>ab,Metric3Dv2PreTrainedModel:()=>ib,MgpstrForSceneTextRecognition:()=>Zy,MgpstrModelOutput:()=>Jy,MgpstrPreTrainedModel:()=>Yy,MimiDecoderModel:()=>u0,MimiDecoderOutput:()=>a0,MimiEncoderModel:()=>c0,MimiEncoderOutput:()=>i0,MimiModel:()=>l0,MimiPreTrainedModel:()=>la,MistralForCausalLM:()=>wy,MistralModel:()=>gy,MistralPreTrainedModel:()=>hu,MobileBertForMaskedLM:()=>Qt,MobileBertForQuestionAnswering:()=>Cs,MobileBertForSequenceClassification:()=>Ws,MobileBertModel:()=>rt,MobileBertPreTrainedModel:()=>je,MobileLLMForCausalLM:()=>dw,MobileLLMModel:()=>uw,MobileLLMPreTrainedModel:()=>wc,MobileNetV1ForImageClassification:()=>Ly,MobileNetV1ForSemanticSegmentation:()=>zy,MobileNetV1Model:()=>Dy,MobileNetV1PreTrainedModel:()=>na,MobileNetV2ForImageClassification:()=>Ry,MobileNetV2ForSemanticSegmentation:()=>jy,MobileNetV2Model:()=>By,MobileNetV2PreTrainedModel:()=>oa,MobileNetV3ForImageClassification:()=>Vy,MobileNetV3ForSemanticSegmentation:()=>Uy,MobileNetV3Model:()=>Ny,MobileNetV3PreTrainedModel:()=>ia,MobileNetV4ForImageClassification:()=>Gy,MobileNetV4ForSemanticSegmentation:()=>Ky,MobileNetV4Model:()=>Wy,MobileNetV4PreTrainedModel:()=>aa,MobileViTForImageClassification:()=>mM,MobileViTModel:()=>pM,MobileViTPreTrainedModel:()=>Nc,MobileViTV2ForImageClassification:()=>_M,MobileViTV2Model:()=>hM,MobileViTV2PreTrainedModel:()=>Vc,ModelOutput:()=>me,ModernBertDecoderForCausalLM:()=>yr,ModernBertDecoderModel:()=>Mt,ModernBertDecoderPreTrainedModel:()=>Ct,ModernBertForMaskedLM:()=>Je,ModernBertForSequenceClassification:()=>nt,ModernBertForTokenClassification:()=>It,ModernBertModel:()=>ze,ModernBertPreTrainedModel:()=>Qe,Moondream1ForConditionalGeneration:()=>Bi,MoonshineForConditionalGeneration:()=>Li,MoonshineModel:()=>hc,MoonshinePreTrainedModel:()=>qn,MptForCausalLM:()=>Gw,MptModel:()=>Ww,MptPreTrainedModel:()=>Oc,MultiModalityCausalLM:()=>Xy,MultiModalityPreTrainedModel:()=>Qy,MusicgenForCausalLM:()=>vT,MusicgenForConditionalGeneration:()=>vu,MusicgenModel:()=>yT,MusicgenPreTrainedModel:()=>yu,NeoBertForMaskedLM:()=>ye,NeoBertForQuestionAnswering:()=>st,NeoBertForSequenceClassification:()=>Ze,NeoBertForTokenClassification:()=>Ke,NeoBertModel:()=>Ye,NeoBertPreTrainedModel:()=>Oe,NomicBertModel:()=>Nr,NomicBertPreTrainedModel:()=>$r,OPTForCausalLM:()=>Hw,OPTModel:()=>Kw,OPTPreTrainedModel:()=>Dc,Olmo2ForCausalLM:()=>_w,Olmo2Model:()=>hw,Olmo2PreTrainedModel:()=>bc,OlmoForCausalLM:()=>mw,OlmoModel:()=>pw,OlmoPreTrainedModel:()=>Mc,OpenELMForCausalLM:()=>Iw,OpenELMModel:()=>kw,OpenELMPreTrainedModel:()=>Sc,OwlViTForObjectDetection:()=>gM,OwlViTModel:()=>fM,OwlViTPreTrainedModel:()=>Uc,Owlv2ForObjectDetection:()=>MM,Owlv2Model:()=>wM,Owlv2PreTrainedModel:()=>Wc,PaliGemmaForConditionalGeneration:()=>Vi,PaliGemmaPreTrainedModel:()=>Ni,PatchTSMixerForPrediction:()=>s0,PatchTSMixerModel:()=>r0,PatchTSMixerPreTrainedModel:()=>Tu,PatchTSTForPrediction:()=>t0,PatchTSTModel:()=>e0,PatchTSTPreTrainedModel:()=>xu,Phi3ForCausalLM:()=>Nw,Phi3Model:()=>jw,Phi3PreTrainedModel:()=>Ac,Phi3VForCausalLM:()=>Io,Phi3VPreTrainedModel:()=>Gi,PhiForCausalLM:()=>Rw,PhiModel:()=>Bw,PhiPreTrainedModel:()=>Ic,PreTrainedModel:()=>B,PretrainedMixin:()=>jt,PvtForImageClassification:()=>tM,PvtModel:()=>eM,PvtPreTrainedModel:()=>Bc,PyAnnoteForAudioFrameClassification:()=>Ub,PyAnnoteModel:()=>Vb,PyAnnotePreTrainedModel:()=>mu,QuestionAnsweringModelOutput:()=>Rr,Qwen2ForCausalLM:()=>Fw,Qwen2Model:()=>Aw,Qwen2PreTrainedModel:()=>$c,Qwen2VLForConditionalGeneration:()=>zw,Qwen2VLPreTrainedModel:()=>Lw,Qwen3ForCausalLM:()=>Dw,Qwen3Model:()=>Ow,Qwen3PreTrainedModel:()=>kc,RFDetrForObjectDetection:()=>IM,RFDetrModel:()=>kM,RFDetrObjectDetectionOutput:()=>AM,RFDetrPreTrainedModel:()=>Xc,RTDetrForObjectDetection:()=>PM,RTDetrModel:()=>EM,RTDetrObjectDetectionOutput:()=>qo,RTDetrPreTrainedModel:()=>qc,RTDetrV2ForObjectDetection:()=>SM,RTDetrV2Model:()=>CM,RTDetrV2ObjectDetectionOutput:()=>$M,RTDetrV2PreTrainedModel:()=>Qc,ResNetForImageClassification:()=>UM,ResNetModel:()=>VM,ResNetPreTrainedModel:()=>tu,RoFormerForMaskedLM:()=>kr,RoFormerForQuestionAnswering:()=>tn,RoFormerForSequenceClassification:()=>Zs,RoFormerForTokenClassification:()=>en,RoFormerModel:()=>sr,RoFormerPreTrainedModel:()=>Vr,RobertaForMaskedLM:()=>vi,RobertaForQuestionAnswering:()=>Ti,RobertaForSequenceClassification:()=>Eo,RobertaForTokenClassification:()=>xi,RobertaModel:()=>yi,RobertaPreTrainedModel:()=>zs,SamImageSegmentationOutput:()=>Fb,SamModel:()=>Ab,SamPreTrainedModel:()=>Ib,SapiensForDepthEstimation:()=>eb,SapiensForNormalEstimation:()=>tb,SapiensForSemanticSegmentation:()=>ZM,SapiensPreTrainedModel:()=>Yi,SegformerForImageClassification:()=>$y,SegformerForSemanticSegmentation:()=>ky,SegformerModel:()=>bT,SegformerPreTrainedModel:()=>sa,Seq2SeqLMOutput:()=>IT,SequenceClassifierOutput:()=>Tt,SiglipModel:()=>Oo,SiglipPreTrainedModel:()=>Jn,SiglipTextModel:()=>qi,SiglipVisionModel:()=>Do,SmolLM3ForCausalLM:()=>sw,SmolLM3Model:()=>rw,SmolLM3PreTrainedModel:()=>Ho,SmolVLMForConditionalGeneration:()=>Qn,SnacDecoderModel:()=>w0,SnacEncoderModel:()=>g0,SnacModel:()=>f0,SnacPreTrainedModel:()=>ua,SpeechT5ForSpeechToText:()=>py,SpeechT5ForTextToSpeech:()=>my,SpeechT5HifiGan:()=>hy,SpeechT5Model:()=>MT,SpeechT5PreTrainedModel:()=>ta,SqueezeBertForMaskedLM:()=>Y,SqueezeBertForQuestionAnswering:()=>ce,SqueezeBertForSequenceClassification:()=>ae,SqueezeBertModel:()=>V,SqueezeBertPreTrainedModel:()=>I,StableLmForCausalLM:()=>Ay,StableLmModel:()=>Iy,StableLmPreTrainedModel:()=>Mu,Starcoder2ForCausalLM:()=>vy,Starcoder2Model:()=>yy,Starcoder2PreTrainedModel:()=>fu,StyleTextToSpeech2Model:()=>dy,StyleTextToSpeech2PreTrainedModel:()=>uy,Swin2SRForImageSuperResolution:()=>qM,Swin2SRModel:()=>HM,Swin2SRPreTrainedModel:()=>ru,SwinForImageClassification:()=>GM,SwinForSemanticSegmentation:()=>KM,SwinModel:()=>WM,SwinPreTrainedModel:()=>Ji,T5ForConditionalGeneration:()=>Lt,T5Model:()=>Bt,T5PreTrainedModel:()=>wt,TableTransformerForObjectDetection:()=>LM,TableTransformerModel:()=>DM,TableTransformerObjectDetectionOutput:()=>zM,TableTransformerPreTrainedModel:()=>Yc,TokenClassifierOutput:()=>Er,TrOCRForCausalLM:()=>fy,TrOCRPreTrainedModel:()=>_y,UltravoxModel:()=>Eu,UltravoxPreTrainedModel:()=>n0,UniSpeechForCTC:()=>Hb,UniSpeechForSequenceClassification:()=>qb,UniSpeechModel:()=>Kb,UniSpeechPreTrainedModel:()=>Zi,UniSpeechSatForAudioFrameClassification:()=>Yb,UniSpeechSatForCTC:()=>Xb,UniSpeechSatForSequenceClassification:()=>Jb,UniSpeechSatModel:()=>Qb,UniSpeechSatPreTrainedModel:()=>Qo,VaultGemmaForCausalLM:()=>Cw,VaultGemmaModel:()=>Pw,VaultGemmaPreTrainedModel:()=>Pc,ViTForImageClassification:()=>Qw,ViTMAEModel:()=>sM,ViTMAEPreTrainedModel:()=>rM,ViTMSNForImageClassification:()=>oM,ViTMSNModel:()=>nM,ViTMSNPreTrainedModel:()=>Rc,ViTModel:()=>qw,ViTPreTrainedModel:()=>Lc,VisionEncoderDecoderModel:()=>$o,VitMatteForImageMatting:()=>dM,VitMattePreTrainedModel:()=>uM,VitPoseForPoseEstimation:()=>Zw,VitPosePreTrainedModel:()=>Yw,VitsModel:()=>wu,VitsModelOutput:()=>xv,VitsPreTrainedModel:()=>Sy,VoxtralForConditionalGeneration:()=>o0,Wav2Vec2BertForCTC:()=>ey,Wav2Vec2BertForSequenceClassification:()=>ty,Wav2Vec2BertModel:()=>Zb,Wav2Vec2BertPreTrainedModel:()=>ea,Wav2Vec2ForAudioFrameClassification:()=>Nb,Wav2Vec2ForCTC:()=>Rb,Wav2Vec2ForSequenceClassification:()=>jb,Wav2Vec2Model:()=>Bb,Wav2Vec2PreTrainedModel:()=>on,WavLMForAudioFrameClassification:()=>cy,WavLMForCTC:()=>iy,WavLMForSequenceClassification:()=>ay,WavLMForXVector:()=>ly,WavLMModel:()=>oy,WavLMPreTrainedModel:()=>no,WeSpeakerResNetModel:()=>Gb,WeSpeakerResNetPreTrainedModel:()=>Wb,WhisperForConditionalGeneration:()=>Ks,WhisperModel:()=>So,WhisperPreTrainedModel:()=>Hn,XLMForQuestionAnswering:()=>$i,XLMForSequenceClassification:()=>Ci,XLMForTokenClassification:()=>Si,XLMModel:()=>Ei,XLMPreTrainedModel:()=>rn,XLMRobertaForMaskedLM:()=>Ii,XLMRobertaForQuestionAnswering:()=>Co,XLMRobertaForSequenceClassification:()=>Ai,XLMRobertaForTokenClassification:()=>Po,XLMRobertaModel:()=>ki,XLMRobertaPreTrainedModel:()=>sn,XLMWithLMHeadModel:()=>Pi,XVectorOutput:()=>yv,YolosForObjectDetection:()=>$b,YolosModel:()=>Sb,YolosObjectDetectionOutput:()=>kb,YolosPreTrainedModel:()=>uu});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"),M=t("./src/generation/stopping_criteria.js"),k=t("./src/generation/logits_sampler.js"),w=t("./src/env.js"),b=t("./src/models/whisper/generation_whisper.js"),$=t("./src/models/whisper/common_whisper.js");const E={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},v=new Map,x=new Map,y=new Map;async function P(g,C,L){var Lr;let ne=((Lr=L.config)==null?void 0:Lr["transformers.js_config"])??{},fe=L.device??ne.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??(w.apis.IS_NODE_ENV?"cpu":"wasm"),Ee=(0,o.deviceToExecutionProviders)(he),Be=ne.device_config??{};Be.hasOwnProperty(he)&&(ne={...ne,...Be[he]});let Ue=L.dtype??ne.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=ne.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=ne.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},Ot=n.DEFAULT_DTYPE_SUFFIX_MAPPING[Xe],_t=`${C}${Ot}.onnx`,$t=`${L.subfolder??""}/${_t}`,dt={...L.session_options};dt.executionProviders??(dt.executionProviders=Ee);const Ft=ne.free_dimension_overrides;Ft?dt.freeDimensionOverrides??(dt.freeDimensionOverrides=Ft):he.startsWith("webnn")&&!dt.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 Kt=w.apis.IS_NODE_ENV&&w.env.useFSCache,tr=(0,l.getModelFile)(g,$t,!0,L,Kt),mr=L.use_external_data_format??ne.use_external_data_format;let lr=[];if(mr){let kt;typeof mr=="object"?mr.hasOwnProperty(_t)?kt=mr[_t]:mr.hasOwnProperty(C)?kt=mr[C]:kt=!1:kt=mr;const Pr=+kt;if(Pr>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${Pr}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let os=0;os{const On=await(0,l.getModelFile)(g,Qr,!0,L,Kt);_s(On instanceof Uint8Array?{path:Fn,data:On}:Fn)}))}}else dt.externalData!==void 0&&(lr=dt.externalData.map(async kt=>{if(typeof kt.data=="string"){const Pr=await(0,l.getModelFile)(g,kt.data,!0,L);return{...kt,data:Pr}}return kt}));if(lr.length>0){const kt=await Promise.all(lr);w.apis.IS_NODE_ENV||(dt.externalData=kt)}if(he==="webgpu"){const kt=(0,s.getCacheShapes)(L.config,{prefix:"present"});if(Object.keys(kt).length>0&&!(0,o.isONNXProxy)()){const Pr={};for(const os in kt)Pr[os]="gpu-buffer";dt.preferredOutputLocation=Pr}}return{buffer_or_path:await tr,session_options:dt,session_config:yt}}async function O(g,C,L){return Object.fromEntries(await Promise.all(Object.keys(C).map(async ne=>{const{buffer_or_path:fe,session_options:he,session_config:Ee}=await P(g,C[ne],L),Be=await(0,o.createInferenceSession)(fe,he,Ee);return[ne,Be]})))}async function D(g,C,L){return Object.fromEntries(await Promise.all(Object.keys(C).map(async ne=>{const fe=await(0,l.getModelJSON)(g,C[ne],!1,L);return[ne,fe]})))}function K(g,C){const L=Object.create(null),ne=[];for(const Ee of g.inputNames){const Be=C[Ee];if(!(Be instanceof u.Tensor)){ne.push(Ee);continue}L[Ee]=(0,o.isONNXProxy)()?Be.clone():Be}if(ne.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ne.join(", ")}.`);const fe=Object.keys(C).length,he=g.inputNames.length;if(fe>he){let Ee=Object.keys(C).filter(Be=>!g.inputNames.includes(Be));console.warn(`WARNING: Too many inputs were provided (${fe} > ${he}). The following inputs will be ignored: "${Ee.join(", ")}".`)}return L}async function G(g,C){const L=K(g,C);try{const ne=Object.fromEntries(Object.entries(L).map(([he,Ee])=>[he,Ee.ort_tensor])),fe=await(0,o.runInferenceSession)(g,ne);return N(fe)}catch(ne){const fe=Object.fromEntries(Object.entries(L).map(([he,Ee])=>{const Be={type:Ee.type,dims:Ee.dims,location:Ee.location};return Be.location!=="gpu-buffer"&&(Be.data=Ee.data),[he,Be]}));throw console.error(`An error occurred during model execution: "${ne}".`),console.error("Inputs given to model:",fe),ne}}function N(g){for(let C in g)(0,o.isONNXTensor)(g[C])?g[C]=new u.Tensor(g[C]):typeof g[C]=="object"&&N(g[C]);return g}function te(g){if(g instanceof u.Tensor)return g;if(g.length===0)throw Error("items must be non-empty");if(Array.isArray(g[0])){if(g.some(C=>C.length!==g[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(g.flat().map(C=>BigInt(C))),[g.length,g[0].length])}else return new u.Tensor("int64",BigInt64Array.from(g.map(C=>BigInt(C))),[1,g.length])}function H(g){return new u.Tensor("bool",[g],[1])}async function ee(g,C){let{encoder_outputs:L,input_ids:ne,decoder_input_ids:fe,...he}=C;if(!L){const Be=(0,a.pick)(C,g.sessions.model.inputNames);L=(await Z(g,Be)).last_hidden_state}return he.input_ids=fe,he.encoder_hidden_states=L,g.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(he.encoder_attention_mask=C.attention_mask),await pe(g,he,!0)}async function Z(g,C){const L=g.sessions.model,ne=(0,a.pick)(C,L.inputNames);if(L.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds){if(!C.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ne.inputs_embeds=await g.encode_text({input_ids:C.input_ids})}if(L.inputNames.includes("token_type_ids")&&!ne.token_type_ids){if(!ne.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");ne.token_type_ids=(0,u.zeros_like)(ne.input_ids)}if(L.inputNames.includes("pixel_mask")&&!ne.pixel_mask){if(!ne.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const fe=ne.pixel_values.dims;ne.pixel_mask=(0,u.ones)([fe[0],fe[2],fe[3]])}return await G(L,ne)}async function oe(g,C){const L=await g.encode(C);return await g.decode(L)}async function pe(g,C,L=!1){const ne=g.sessions[L?"decoder_model_merged":"model"],{past_key_values:fe,...he}=C;if(ne.inputNames.includes("use_cache_branch")&&(he.use_cache_branch=H(!!fe)),ne.inputNames.includes("position_ids")&&he.attention_mask&&!he.position_ids){const Be=["paligemma","gemma3_text","gemma3"].includes(g.config.model_type)?1:0;he.position_ids=ve(he,fe,Be)}g.addPastKeyValues(he,fe);const Ee=(0,a.pick)(he,ne.inputNames);return await G(ne,Ee)}function ue({modality_token_id:g,inputs_embeds:C,modality_features:L,input_ids:ne,attention_mask:fe}){const he=ne.tolist().map(Xe=>Xe.reduce((mt,bt,yt)=>(bt==g&&mt.push(yt),mt),[])),Ee=he.reduce((Xe,mt)=>Xe+mt.length,0),Be=L.dims[0];if(Ee!==Be)throw new Error(`Number of tokens and features do not match: tokens: ${Ee}, features ${Be}`);let Ue=0;for(let Xe=0;Xehe.dims[1]||fe[fe.at(-1)])),{...L,decoder_input_ids:te(C)}}function Ie(g,...C){return g.config.is_encoder_decoder?Ge(g,...C):Le(g,...C)}function Q(g,C,L,ne){const fe=!!L.past_key_values;return ne.guidance_scale!==null&&ne.guidance_scale>1&&(fe?L.input_ids=(0,u.cat)([L.input_ids,L.input_ids],0):(L.input_ids=(0,u.cat)([L.input_ids,(0,u.full_like)(L.input_ids,BigInt(ne.pad_token_id))],0),L.attention_mask=(0,u.cat)([L.attention_mask,(0,u.full_like)(L.attention_mask,0n)],0))),(fe||!L.pixel_values)&&(L.pixel_values=(0,u.full)([0,0,3,384,384],1)),fe&&(L.images_seq_mask=new u.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),L.images_emb_mask=new u.Tensor("bool",new Array(0).fill(!1),[1,1,0])),L}class B extends i.Callable{constructor(L,ne,fe){super();J(this,"main_input_name","input_ids");J(this,"forward_params",["input_ids","attention_mask"]);this.config=L,this.sessions=ne,this.configs=fe;const he=y.get(this.constructor),Ee=v.get(he);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ee){case E.DecoderOnly:this.can_generate=!0,this._forward=pe,this._prepare_inputs_for_generation=Le;break;case E.Seq2Seq:case E.Vision2Seq:case E.Musicgen:this.can_generate=!0,this._forward=ee,this._prepare_inputs_for_generation=Ge;break;case E.EncoderDecoder:this._forward=ee;break;case E.ImageTextToText:this.can_generate=!0,this._forward=_e,this._prepare_inputs_for_generation=Ie;break;case E.AudioTextToText:this.can_generate=!0,this._forward=se,this._prepare_inputs_for_generation=Ie;break;case E.Phi3V:case E.ImageAudioTextToText:this.can_generate=!0,this._prepare_inputs_for_generation=Ie;break;case E.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Q;break;case E.AutoEncoder:this._forward=oe;break;default:this._forward=Z;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ne;const L=[];for(const fe of Object.values(this.sessions))(ne=fe==null?void 0:fe.handler)!=null&&ne.dispose&&L.push(fe.handler.dispose());return await Promise.all(L)}static async from_pretrained(L,{progress_callback:ne=null,config:fe=null,cache_dir:he=null,local_files_only:Ee=!1,revision:Be="main",model_file_name:Ue=null,subfolder:Xe="onnx",device:mt=null,dtype:bt=null,use_external_data_format:yt=null,session_options:Ot={}}={}){let _t={progress_callback:ne,config:fe,cache_dir:he,local_files_only:Ee,revision:Be,model_file_name:Ue,subfolder:Xe,device:mt,dtype:bt,use_external_data_format:yt,session_options:Ot};const $t=y.get(this),dt=v.get($t);fe=_t.config=await s.AutoConfig.from_pretrained(L,_t);let Ft;if(dt===E.DecoderOnly)Ft=await Promise.all([O(L,{model:_t.model_file_name??"model"},_t),D(L,{generation_config:"generation_config.json"},_t)]);else if(dt===E.Seq2Seq||dt===E.Vision2Seq)Ft=await Promise.all([O(L,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},_t),D(L,{generation_config:"generation_config.json"},_t)]);else if(dt===E.MaskGeneration)Ft=await Promise.all([O(L,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},_t)]);else if(dt===E.EncoderDecoder)Ft=await Promise.all([O(L,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},_t)]);else if(dt===E.ImageTextToText){const Kt={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};fe.is_encoder_decoder&&(Kt.model="encoder_model"),Ft=await Promise.all([O(L,Kt,_t),D(L,{generation_config:"generation_config.json"},_t)])}else if(dt===E.AudioTextToText){const Kt={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};Ft=await Promise.all([O(L,Kt,_t),D(L,{generation_config:"generation_config.json"},_t)])}else if(dt===E.ImageAudioTextToText){const Kt={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};Ft=await Promise.all([O(L,Kt,_t),D(L,{generation_config:"generation_config.json"},_t)])}else if(dt===E.Musicgen)Ft=await Promise.all([O(L,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},_t),D(L,{generation_config:"generation_config.json"},_t)]);else if(dt===E.MultiModality)Ft=await Promise.all([O(L,{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),D(L,{generation_config:"generation_config.json"},_t)]);else if(dt===E.Phi3V)Ft=await Promise.all([O(L,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},_t),D(L,{generation_config:"generation_config.json"},_t)]);else if(dt===E.AutoEncoder)Ft=await Promise.all([O(L,{encoder_model:"encoder_model",decoder_model:"decoder_model"},_t)]);else{if(dt!==E.EncoderOnly){const Kt=$t??(fe==null?void 0:fe.model_type);Kt!=="custom"&&console.warn(`Model type for '${Kt}' not found, assuming encoder-only architecture. Please report this at ${c.GITHUB_ISSUE_URL}.`)}Ft=await Promise.all([O(L,{model:_t.model_file_name??"model"},_t)])}return new this(fe,...Ft)}async _call(L){return await this.forward(L)}async forward(L){return await this._forward(this,L)}get generation_config(){var L;return((L=this.configs)==null?void 0:L.generation_config)??null}_get_logits_processor(L,ne,fe=null){const he=new p.LogitsProcessorList;if(L.repetition_penalty!==null&&L.repetition_penalty!==1&&he.push(new p.RepetitionPenaltyLogitsProcessor(L.repetition_penalty)),L.no_repeat_ngram_size!==null&&L.no_repeat_ngram_size>0&&he.push(new p.NoRepeatNGramLogitsProcessor(L.no_repeat_ngram_size)),L.bad_words_ids!==null&&he.push(new p.NoBadWordsLogitsProcessor(L.bad_words_ids,L.eos_token_id)),L.min_length!==null&&L.eos_token_id!==null&&L.min_length>0&&he.push(new p.MinLengthLogitsProcessor(L.min_length,L.eos_token_id)),L.min_new_tokens!==null&&L.eos_token_id!==null&&L.min_new_tokens>0&&he.push(new p.MinNewTokensLengthLogitsProcessor(ne,L.min_new_tokens,L.eos_token_id)),L.forced_bos_token_id!==null&&he.push(new p.ForcedBOSTokenLogitsProcessor(L.forced_bos_token_id)),L.forced_eos_token_id!==null&&he.push(new p.ForcedEOSTokenLogitsProcessor(L.max_length,L.forced_eos_token_id)),L.begin_suppress_tokens!==null){const Ee=ne>1||L.forced_bos_token_id===null?ne:ne+1;he.push(new p.SuppressTokensAtBeginLogitsProcessor(L.begin_suppress_tokens,Ee))}return L.guidance_scale!==null&&L.guidance_scale>1&&he.push(new p.ClassifierFreeGuidanceLogitsProcessor(L.guidance_scale)),L.do_sample&&L.temperature!==null&&L.temperature!==1&&he.push(new p.TemperatureLogitsWarper(L.temperature)),fe!==null&&he.extend(fe),he}_prepare_generation_config(L,ne,fe=d.GenerationConfig){const he={...this.config};for(const Be of["decoder","generator","text_config"])Be in he&&Object.assign(he,he[Be]);const Ee=new fe(he);return Object.assign(Ee,this.generation_config??{}),L&&Object.assign(Ee,L),ne&&Object.assign(Ee,(0,a.pick)(ne,Object.getOwnPropertyNames(Ee))),Ee}_get_stopping_criteria(L,ne=null){const fe=new M.StoppingCriteriaList;return L.max_length!==null&&fe.push(new M.MaxLengthCriteria(L.max_length,this.config.max_position_embeddings??null)),L.eos_token_id!==null&&fe.push(new M.EosTokenCriteria(L.eos_token_id)),ne&&fe.extend(ne),fe}_validate_model_class(){if(!this.can_generate){const L=[Su,$u,Cu,Pu],ne=y.get(this.constructor),fe=new Set,he=this.config.model_type;for(const Be of L){const Ue=Be.get(he);Ue&&fe.add(Ue[0])}let Ee=`The current model class (${ne}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw fe.size>0&&(Ee+=` Please use the following class instead: ${[...fe].join(", ")}`),Error(Ee)}}prepare_inputs_for_generation(...L){return this._prepare_inputs_for_generation(this,...L)}_update_model_kwargs_for_generation({generated_input_ids:L,outputs:ne,model_inputs:fe,is_encoder_decoder:he}){return fe.past_key_values=this.getPastKeyValues(ne,fe.past_key_values),fe.input_ids=new u.Tensor("int64",L.flat(),[L.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:L,bos_token_id:ne,model_kwargs:fe}){const he=(0,a.pick)(fe,this.forward_params),Ee=this.main_input_name;if(Ee in he){if(L)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[Ee]=L;return{inputs_tensor:he[Ee],model_inputs:he,model_input_name:Ee}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:L,model_inputs:ne,model_input_name:fe,generation_config:he}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Be,pixel_values:Ue,attention_mask:Xe,...mt}=ne,bt=await this._prepare_inputs_embeds(ne);ne={...mt,...(0,a.pick)(bt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ee}=await Z(this,ne);if(he.guidance_scale!==null&&he.guidance_scale>1)Ee=(0,u.cat)([Ee,(0,u.full_like)(Ee,0)],0),"attention_mask"in ne&&(ne.attention_mask=(0,u.cat)([ne.attention_mask,(0,u.zeros_like)(ne.attention_mask)],0));else if(ne.decoder_input_ids){const Be=te(ne.decoder_input_ids).dims[0];if(Be!==Ee.dims[0]){if(Ee.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ee.dims[0]}) than the decoder inputs (${Be}).`);Ee=(0,u.cat)(Array.from({length:Be},()=>Ee),0)}}return ne.encoder_outputs=Ee,ne}_prepare_decoder_input_ids_for_generation({batch_size:L,model_input_name:ne,model_kwargs:fe,decoder_start_token_id:he,bos_token_id:Ee,generation_config:Be}){let{decoder_input_ids:Ue,...Xe}=fe;if(!(Ue instanceof u.Tensor)){if(Ue)Array.isArray(Ue[0])||(Ue=Array.from({length:L},()=>Ue));else if(he??(he=Ee),this.config.model_type==="musicgen")Ue=Array.from({length:L*this.config.decoder.num_codebooks},()=>[he]);else if(Array.isArray(he)){if(he.length!==L)throw new Error(`\`decoder_start_token_id\` expcted to have length ${L} but got ${he.length}`);Ue=he}else Ue=Array.from({length:L},()=>[he]);Ue=te(Ue)}return fe.decoder_attention_mask=(0,u.ones_like)(Ue),{input_ids:Ue,model_inputs:Xe}}async generate({inputs:L=null,generation_config:ne=null,logits_processor:fe=null,stopping_criteria:he=null,streamer:Ee=null,...Be}){this._validate_model_class(),ne=this._prepare_generation_config(ne,Be);let{inputs_tensor:Ue,model_inputs:Xe,model_input_name:mt}=this._prepare_model_inputs({inputs:L,model_kwargs:Be});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:ne})));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:ne.decoder_start_token_id,bos_token_id:ne.bos_token_id,generation_config:ne}):yt=Xe[mt];let Ot=yt.dims.at(-1);ne.max_new_tokens!==null&&(ne.max_length=Ot+ne.max_new_tokens);const _t=this._get_logits_processor(ne,Ot,fe),$t=this._get_stopping_criteria(ne,he),dt=Xe[mt].dims.at(0),Ft=k.LogitsSampler.getSampler(ne),Kt=new Array(dt).fill(0),tr=yt.tolist();Ee&&Ee.put(tr);let mr,lr={};for(;;){if(Xe=this.prepare_inputs_for_generation(tr,Xe,ne),mr=await this.forward(Xe),ne.output_attentions&&ne.return_dict_in_generate){const Qr=this.getAttentions(mr);for(const _s in Qr)_s in lr||(lr[_s]=[]),lr[_s].push(Qr[_s])}const kt=mr.logits.slice(null,-1,null),Pr=_t(tr,kt),os=[];for(let Qr=0;QrQr))break;Xe=this._update_model_kwargs_for_generation({generated_input_ids:os,outputs:mr,model_inputs:Xe,is_encoder_decoder:bt})}Ee&&Ee.end();const br=this.getPastKeyValues(mr,Xe.past_key_values,!0),Lr=new u.Tensor("int64",tr.flat(),[tr.length,tr[0].length]);if(ne.return_dict_in_generate)return{sequences:Lr,past_key_values:br,...lr};for(const kt of Object.values(mr))kt.location==="gpu-buffer"&&kt.dispose();return Lr}getPastKeyValues(L,ne,fe=!1){const he=Object.create(null);for(const Ee in L)if(Ee.startsWith("present")){const Be=Ee.replace("present_conv","past_conv").replace("present","past_key_values"),Ue=Ee.includes("encoder");if(Ue&&ne?he[Be]=ne[Be]:he[Be]=L[Ee],ne&&(!Ue||fe)){const Xe=ne[Be];Xe.location==="gpu-buffer"&&Xe.dispose()}}return he}getAttentions(L){const ne={};for(const fe of["cross_attentions","encoder_attentions","decoder_attentions"])for(const he in L)he.startsWith(fe)&&(fe in ne||(ne[fe]=[]),ne[fe].push(L[he]));return ne}addPastKeyValues(L,ne){var fe,he,Ee;if(ne)Object.assign(L,ne);else{const Be=this.sessions.decoder_model_merged??this.sessions.model,Ue=((he=(fe=L[this.main_input_name]??L.attention_mask)==null?void 0:fe.dims)==null?void 0:he[0])??1,Xe=((Ee=Be==null?void 0:Be.config)==null?void 0:Ee.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 Ot=bt[yt].reduce((_t,$t)=>_t*$t,1);L[yt]=new u.Tensor(Xe,new mt(Ot),bt[yt])}}}async encode_image({pixel_values:L}){return(await G(this.sessions.vision_encoder,{pixel_values:L})).image_features}async encode_text({input_ids:L}){return(await G(this.sessions.embed_tokens,{input_ids:L})).inputs_embeds}async encode_audio({audio_values:L}){return(await G(this.sessions.audio_encoder,{audio_values:L})).audio_features}}class me{}class Ce extends me{constructor({last_hidden_state:C,hidden_states:L=null,attentions:ne=null}){super(),this.last_hidden_state=C,this.hidden_states=L,this.attentions=ne}}class Pe extends B{}class Se extends Pe{}class Me extends Pe{async _call(C){return new Dr(await super._call(C))}}class $e extends Pe{async _call(C){return new Tt(await super._call(C))}}class we extends Pe{async _call(C){return new Er(await super._call(C))}}class Fe extends Pe{async _call(C){return new Rr(await super._call(C))}}class Oe extends B{}class Ye extends Oe{}class ye extends Oe{async _call(C){return new Dr(await super._call(C))}}class Ze extends Oe{async _call(C){return new Tt(await super._call(C))}}class Ke extends Oe{async _call(C){return new Er(await super._call(C))}}class st extends Oe{async _call(C){return new Rr(await super._call(C))}}class Qe extends B{}class ze extends Qe{}class Je extends Qe{async _call(C){return new Dr(await super._call(C))}}class nt extends Qe{async _call(C){return new Tt(await super._call(C))}}class It extends Qe{async _call(C){return new Er(await super._call(C))}}class Ct extends B{}class Mt extends Ct{}class yr extends Ct{}class $r extends B{}class Nr extends $r{}class Vr extends B{}class sr extends Vr{}class kr extends Vr{async _call(C){return new Dr(await super._call(C))}}class Zs extends Vr{async _call(C){return new Tt(await super._call(C))}}class en extends Vr{async _call(C){return new Er(await super._call(C))}}class tn extends Vr{async _call(C){return new Rr(await super._call(C))}}class cs extends B{}class ht extends cs{}class Fs extends cs{async _call(C){return new Dr(await super._call(C))}}class Os extends cs{async _call(C){return new Tt(await super._call(C))}}class St extends cs{async _call(C){return new Er(await super._call(C))}}class Ht extends cs{async _call(C){return new Rr(await super._call(C))}}class S extends B{}class X extends S{}class R extends S{async _call(C){return new Dr(await super._call(C))}}class q extends S{async _call(C){return new Tt(await super._call(C))}}class re extends S{async _call(C){return new Er(await super._call(C))}}class ge extends S{async _call(C){return new Rr(await super._call(C))}}class Ae extends B{}class ot extends Ae{}class ft extends Ae{async _call(C){return new Dr(await super._call(C))}}class pt extends Ae{async _call(C){return new Tt(await super._call(C))}}class vt extends Ae{async _call(C){return new Er(await super._call(C))}}class tt extends Ae{async _call(C){return new Rr(await super._call(C))}}class At extends B{}class qt extends At{}class Ur extends At{async _call(C){return new Dr(await super._call(C))}}class Hr extends At{async _call(C){return new Tt(await super._call(C))}}class nr extends At{async _call(C){return new Er(await super._call(C))}}class Ir extends At{async _call(C){return new Rr(await super._call(C))}}class ur extends B{}class us extends ur{}class ds extends ur{async _call(C){return new Dr(await super._call(C))}}class Ar extends ur{async _call(C){return new Tt(await super._call(C))}}class Ds extends ur{async _call(C){return new Er(await super._call(C))}}class Ls extends ur{async _call(C){return new Rr(await super._call(C))}}class vr extends B{}class ps extends vr{}class Jr extends vr{async _call(C){return new Tt(await super._call(C))}}class Br extends vr{async _call(C){return new Er(await super._call(C))}}class Ps extends vr{async _call(C){return new Rr(await super._call(C))}}class hr extends vr{async _call(C){return new Dr(await super._call(C))}}class ir extends B{}class ms extends ir{}class Us extends ir{async _call(C){return new Dr(await super._call(C))}}class Wr extends ir{async _call(C){return new Tt(await super._call(C))}}class Re extends ir{async _call(C){return new Er(await super._call(C))}}class je extends B{}class rt extends je{}class Qt extends je{async _call(C){return new Dr(await super._call(C))}}class Ws extends je{async _call(C){return new Tt(await super._call(C))}}class Cs extends je{async _call(C){return new Rr(await super._call(C))}}class rs extends B{}class bn extends rs{}class yn extends rs{async _call(C){return new Dr(await super._call(C))}}class vn extends rs{async _call(C){return new Tt(await super._call(C))}}class xn extends rs{async _call(C){return new Er(await super._call(C))}}class de extends rs{async _call(C){return new Rr(await super._call(C))}}class I extends B{}class V extends I{}class Y extends I{async _call(C){return new Dr(await super._call(C))}}class ae extends I{async _call(C){return new Tt(await super._call(C))}}class ce extends I{async _call(C){return new Rr(await super._call(C))}}class xe extends B{}class Ve extends xe{}class He extends xe{async _call(C){return new Tt(await super._call(C))}}class We extends xe{async _call(C){return new Rr(await super._call(C))}}class et extends xe{async _call(C){return new Dr(await super._call(C))}}class wt extends B{constructor(){super(...arguments);J(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Bt extends wt{}class Lt extends wt{}class Zt extends B{}class Gt extends Zt{}class fr extends Zt{}class gr extends B{}class dr extends gr{}class wr extends gr{}class xr extends B{}class ss extends xr{}class Yt extends xr{}class Mr extends xr{async _call(C){return new Tt(await super._call(C))}}class Fr extends B{}class Yr extends Fr{}class Ss extends Fr{}class Or extends Fr{async _call(C){return new Tt(await super._call(C))}}class hs extends Fr{}class ar extends B{}class pr extends ar{}class _r extends ar{}class er extends B{}class qr extends er{}class Gs extends er{}class zs extends B{}class yi extends zs{}class vi extends zs{async _call(C){return new Dr(await super._call(C))}}class Eo extends zs{async _call(C){return new Tt(await super._call(C))}}class xi extends zs{async _call(C){return new Er(await super._call(C))}}class Ti extends zs{async _call(C){return new Rr(await super._call(C))}}class rn extends B{}class Ei extends rn{}class Pi extends rn{async _call(C){return new Dr(await super._call(C))}}class Ci extends rn{async _call(C){return new Tt(await super._call(C))}}class Si extends rn{async _call(C){return new Er(await super._call(C))}}class $i extends rn{async _call(C){return new Rr(await super._call(C))}}class sn extends B{}class ki extends sn{}class Ii extends sn{async _call(C){return new Dr(await super._call(C))}}class Ai extends sn{async _call(C){return new Tt(await super._call(C))}}class Po extends sn{async _call(C){return new Er(await super._call(C))}}class Co extends sn{async _call(C){return new Rr(await super._call(C))}}class Kn extends B{}class Fi extends Kn{}class Oi extends Kn{}class Hn extends B{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 So extends Hn{}class Ks extends Hn{_prepare_generation_config(C,L){return super._prepare_generation_config(C,L,b.WhisperGenerationConfig)}_retrieve_init_tokens(C){const L=[C.decoder_start_token_id];let ne=C.language;const fe=C.task;if(C.is_multilingual){ne||(console.warn("No language specified - defaulting to English (en)."),ne="en");const Ee=`<|${(0,$.whisper_language_to_code)(ne)}|>`;L.push(C.lang_to_id[Ee]),L.push(C.task_to_id[fe??"transcribe"])}else if(ne||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&&L.at(-1)!==C.no_timestamps_token_id?L.push(C.no_timestamps_token_id):C.return_timestamps&&L.at(-1)===C.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),L.pop()),L.filter(he=>he!=null)}async generate({inputs:C=null,generation_config:L=null,logits_processor:ne=null,stopping_criteria:fe=null,...he}){L=this._prepare_generation_config(L,he);const Ee=he.decoder_input_ids??this._retrieve_init_tokens(L);if(L.return_timestamps&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.WhisperTimeStampLogitsProcessor(L,Ee))),L.begin_suppress_tokens&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.SuppressTokensAtBeginLogitsProcessor(L.begin_suppress_tokens,Ee.length))),L.return_token_timestamps){if(!L.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.");L.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),L.output_attentions=!0,L.return_dict_in_generate=!0}const Be=await super.generate({inputs:C,generation_config:L,logits_processor:ne,decoder_input_ids:Ee,...he});return L.return_token_timestamps&&(Be.token_timestamps=this._extract_token_timestamps(Be,L.alignment_heads,L.num_frames)),Be}_extract_token_timestamps(C,L,ne=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`.");ne==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 Ee=C.cross_attentions,Be=Array.from({length:this.config.decoder_layers},($t,dt)=>(0,u.cat)(Ee.map(Ft=>Ft[dt]),2)),Ue=(0,u.stack)(L.map(([$t,dt])=>{if($t>=Be.length)throw new Error(`Layer index ${$t} is out of bounds for cross attentions (length ${Be.length}).`);return ne?Be[$t].slice(null,dt,null,[0,ne]):Be[$t].slice(null,dt)})).transpose(1,0,2,3),[Xe,mt]=(0,u.std_mean)(Ue,-2,0,!0),bt=Ue.clone();for(let $t=0;$tFt[Lr+1]-Ft[Lr]),mr=(0,a.mergeArrays)([1],tr).map(br=>!!br),lr=[];for(let br=0;brArray.from({length:C.dims[0]},tr=>Array.from({length:C.dims[1]},mr=>1))),_t=L?L.tolist():[],$t=ne?ne.tolist():[];let dt=0,Ft=0;for(let Kt=0;Ktyt[Kt][Cr]==1),lr=tr.reduce((rr,Cr,an)=>(Cr==Ue&&rr.push(an),rr),[]).map(rr=>tr[rr+1]),br=lr.filter(rr=>rr==Ee).length,Lr=lr.filter(rr=>rr==Be).length;let kt=[],Pr=0,os=br,Fn=Lr;for(let rr=0;rrks>Pr&&Ln==Ee),an=tr.findIndex((Ln,ks)=>ks>Pr&&Ln==Be),Dn=os>0&&Cr!==-1?Cr:tr.length+1,io=Fn>0&&an!==-1?an:tr.length+1;let ha,Iu,Au,Fu;Dn0?(0,_.max)(kt.at(-1))[0]+1:0;kt.push(Array.from({length:3*Du},(Ln,ks)=>Tv+ks%Du));const Lu=Du+Tv,fa=FT*Ou*_a,OT=Array.from({length:fa},(Ln,ks)=>Lu+Math.floor(ks/(Ou*_a))),DT=Array.from({length:fa},(Ln,ks)=>Lu+Math.floor(ks/_a)%Ou),LT=Array.from({length:fa},(Ln,ks)=>Lu+ks%_a);kt.push([OT,DT,LT].flat()),Pr=ha+fa}if(Pr0?(0,_.max)(kt.at(-1))[0]+1:0,Cr=tr.length-Pr;kt.push(Array.from({length:3*Cr},(an,Dn)=>rr+Dn%Cr))}const Qr=kt.reduce((rr,Cr)=>rr+Cr.length,0),_s=new Array(Qr);let da=0;for(let rr=0;rr<3;++rr)for(let Cr=0;Crbt[dt%bt.length]),_t=Array.from({length:yt[0]},($t,dt)=>(0,_.max)(bt.subarray(yt[1]*dt,yt[1]*(dt+1)))[0]+1n+BigInt(yt[1]));return[new u.Tensor("int64",Ot,[3,...yt]),new u.Tensor("int64",_t,[_t.length,1])]}else{const[bt,yt]=C.dims,Ot=BigInt64Array.from({length:3*bt*yt},(_t,$t)=>BigInt(Math.floor($t%yt/bt)));return[new u.Tensor("int64",Ot,[3,...C.dims]),(0,u.zeros)([bt,1])]}}async encode_image({pixel_values:C,image_grid_thw:L}){return(await G(this.sessions.vision_encoder,{pixel_values:C,grid_thw:L})).image_features}_merge_input_ids_with_image_features(C){return j({image_token_id:this.config.image_token_id,...C})}prepare_inputs_for_generation(C,L,ne){if(L.attention_mask&&!L.position_ids)if(!L.past_key_values)[L.position_ids,L.rope_deltas]=this.get_rope_index(L.input_ids,L.image_grid_thw,L.video_grid_thw,L.attention_mask);else{L.pixel_values=null;const fe=BigInt(Object.values(L.past_key_values)[0].dims.at(-2)),he=L.rope_deltas.map(Ee=>fe+Ee);L.position_ids=(0,u.stack)([he,he,he],0)}return L}}class Ic extends B{}class Bw extends Ic{}class Rw extends Ic{}class Ac extends B{}class jw extends Ac{}class Nw extends Ac{}class Fc extends B{}class Vw extends Fc{}class Uw extends Fc{}class Oc extends B{}class Ww extends Oc{}class Gw extends Oc{}class Dc extends B{}class Kw extends Dc{}class Hw extends Dc{}class Lc extends B{}class qw extends Lc{}class Qw extends Lc{async _call(C){return new Tt(await super._call(C))}}class zc extends B{}class Xw extends zc{}class Jw extends zc{async _call(C){return new Tt(await super._call(C))}}class Yw extends B{}class Zw extends Yw{}class Bc extends B{}class eM extends Bc{}class tM extends Bc{async _call(C){return new Tt(await super._call(C))}}class rM extends B{}class sM extends rM{}class Rc extends B{}class nM extends Rc{}class oM extends Rc{async _call(C){return new Tt(await super._call(C))}}class iM extends B{}class aM extends iM{}class jc extends B{}class lM extends jc{}class cM extends jc{async _call(C){return new Tt(await super._call(C))}}class uM extends B{}class dM extends uM{async _call(C){return new vv(await super._call(C))}}class Nc extends B{}class pM extends Nc{}class mM extends Nc{async _call(C){return new Tt(await super._call(C))}}class Vc extends B{}class hM extends Vc{}class _M extends Vc{async _call(C){return new Tt(await super._call(C))}}class Uc extends B{}class fM extends Uc{}class gM extends Uc{}class Wc extends B{}class wM extends Wc{}class MM extends Wc{}class Gc extends B{}class bM extends Gc{}class yM extends Gc{async _call(C){return new Tt(await super._call(C))}}class Xi extends B{}class vM extends Xi{}class xM extends Xi{async _call(C){return new Hc(await super._call(C))}}class Kc extends Xi{async _call(C){return new TM(await super._call(C))}}class Hc extends me{constructor({logits:C,pred_boxes:L}){super(),this.logits=C,this.pred_boxes=L}}class TM extends me{constructor({logits:C,pred_boxes:L,pred_masks:ne}){super(),this.logits=C,this.pred_boxes=L,this.pred_masks=ne}}class qc extends B{}class EM extends qc{}class PM extends qc{async _call(C){return new qo(await super._call(C))}}class qo extends me{constructor({logits:C,pred_boxes:L}){super(),this.logits=C,this.pred_boxes=L}}class Qc extends B{}class CM extends Qc{}class SM extends Qc{async _call(C){return new $M(await super._call(C))}}class $M extends qo{}class Xc extends B{}class kM extends Xc{}class IM extends Xc{async _call(C){return new AM(await super._call(C))}}class AM extends qo{}class Jc extends B{}class FM extends Jc{}class OM extends Jc{async _call(C){return new qo(await super._call(C))}}class Yc extends B{}class DM extends Yc{}class LM extends Yc{async _call(C){return new zM(await super._call(C))}}class zM extends Hc{}class Zc extends B{}class BM extends Zc{}class RM extends Zc{async _call(C){return new Tt(await super._call(C))}}class eu extends B{}class jM extends eu{}class NM extends eu{async _call(C){return new Tt(await super._call(C))}}class tu extends B{}class VM extends tu{}class UM extends tu{async _call(C){return new Tt(await super._call(C))}}class Ji extends B{}class WM extends Ji{}class GM extends Ji{async _call(C){return new Tt(await super._call(C))}}class KM extends Ji{}class ru extends B{}class HM extends ru{}class qM extends ru{}class su extends B{}class QM extends su{}class XM extends su{}class JM extends B{}class YM extends JM{}class Yi extends B{}class ZM extends Yi{}class eb extends Yi{}class tb extends Yi{}class rb extends B{}class sb extends rb{}class nb extends B{}class ob extends nb{}class ib extends B{}class ab extends ib{}class nu extends B{}class lb extends nu{}class cb extends nu{}class ou extends B{}class ub extends ou{}class db extends ou{}class pb extends B{}class mb extends pb{}class iu extends B{}class hb extends iu{}class _b extends iu{async _call(C){return new Tt(await super._call(C))}}class au extends B{}class fb extends au{}class gb extends au{async _call(C){return new Tt(await super._call(C))}}class lu extends B{}class wb extends lu{}class Mb extends lu{async _call(C){return new Tt(await super._call(C))}}class cu extends B{}class bb extends cu{}class yb extends cu{async _call(C){return new Tt(await super._call(C))}}class vb extends B{}class xb extends vb{}class Tb extends B{}class Eb extends Tb{}class Pb extends B{}class Cb extends Pb{}class uu extends B{}class Sb extends uu{}class $b extends uu{async _call(C){return new kb(await super._call(C))}}class kb extends me{constructor({logits:C,pred_boxes:L}){super(),this.logits=C,this.pred_boxes=L}}class Ib extends B{}class Ab extends Ib{async get_image_embeddings({pixel_values:C}){return await Z(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 ne=C.input_points.dims.slice(0,-1),fe=ne.reduce((he,Ee)=>he*Ee,1);C.input_labels=new u.Tensor("int64",new BigInt64Array(fe).fill(1n),ne)}const L={image_embeddings:C.image_embeddings,image_positional_embeddings:C.image_positional_embeddings};return C.input_points&&(L.input_points=C.input_points),C.input_labels&&(L.input_labels=C.input_labels),C.input_boxes&&(L.input_boxes=C.input_boxes),await G(this.sessions.prompt_encoder_mask_decoder,L)}async _call(C){return new Fb(await super._call(C))}}class Fb extends me{constructor({iou_scores:C,pred_masks:L}){super(),this.iou_scores=C,this.pred_masks=L}}class du extends B{}class Ob extends du{}class Db extends du{}class pu extends B{}class Lb extends pu{}class zb extends pu{}class on extends B{}class Bb extends on{}class Rb extends on{async _call(C){return new An(await super._call(C))}}class jb extends on{async _call(C){return new Tt(await super._call(C))}}class Nb extends on{async _call(C){return new Er(await super._call(C))}}class mu extends B{}class Vb extends mu{}class Ub extends mu{async _call(C){return new Er(await super._call(C))}}class Wb extends B{}class Gb extends Wb{}class Zi extends B{}class Kb extends Zi{}class Hb extends Zi{async _call(C){return new An(await super._call(C))}}class qb extends Zi{async _call(C){return new Tt(await super._call(C))}}class Qo extends B{}class Qb extends Qo{}class Xb extends Qo{async _call(C){return new An(await super._call(C))}}class Jb extends Qo{async _call(C){return new Tt(await super._call(C))}}class Yb extends Qo{async _call(C){return new Er(await super._call(C))}}class ea extends B{}class Zb extends ea{}class ey extends ea{async _call(C){return new An(await super._call(C))}}class ty extends ea{async _call(C){return new Tt(await super._call(C))}}class wT extends B{}class ry extends on{}class sy extends on{async _call(C){return new An(await super._call(C))}}class ny extends on{async _call(C){return new Tt(await super._call(C))}}class no extends B{}class oy extends no{}class iy extends no{async _call(C){return new An(await super._call(C))}}class ay extends no{async _call(C){return new Tt(await super._call(C))}}class ly extends no{async _call(C){return new yv(await super._call(C))}}class cy extends no{async _call(C){return new Er(await super._call(C))}}class uy extends B{}class dy extends uy{}class ta extends B{}class MT extends ta{}class py extends ta{}class my extends ta{async generate_speech(C,L,{threshold:ne=.5,minlenratio:fe=0,maxlenratio:he=20,vocoder:Ee=null}={}){const Be={input_ids:C},{encoder_outputs:Ue,encoder_attention_mask:Xe}=await Z(this,Be),mt=Ue.dims[1]/this.config.reduction_factor,bt=Math.floor(mt*he),yt=Math.floor(mt*fe),Ot=this.config.num_mel_bins;let _t=[],$t=null,dt=null,Ft=0;for(;;){++Ft;const mr=H(!!dt);let lr;dt?lr=dt.output_sequence_out:lr=new u.Tensor("float32",new Float32Array(Ot),[1,1,Ot]);let br={use_cache_branch:mr,output_sequence:lr,encoder_attention_mask:Xe,speaker_embeddings:L,encoder_hidden_states:Ue};this.addPastKeyValues(br,$t),dt=await G(this.sessions.decoder_model_merged,br),$t=this.getPastKeyValues(dt,$t);const{prob:Lr,spectrum:kt}=dt;if(_t.push(kt),Ft>=yt&&(Array.from(Lr.data).filter(Pr=>Pr>=ne).length>0||Ft>=bt))break}const Kt=(0,u.cat)(_t),{waveform:tr}=await G(Ee.sessions.model,{spectrogram:Kt});return{spectrogram:Kt,waveform:tr}}}class hy extends B{constructor(){super(...arguments);J(this,"main_input_name","spectrogram")}}class _y extends B{}class fy extends _y{}class hu extends B{}class gy extends hu{}class wy extends hu{}class _u extends B{}class My extends _u{}class by extends _u{}class fu extends B{}class yy extends fu{}class vy extends fu{}class gu extends B{}class xy extends gu{}class Ty extends gu{}class ra extends B{}class Ey extends ra{}class Py extends ra{static async from_pretrained(C,L={}){return super.from_pretrained(C,{...L,model_file_name:L.model_file_name??"text_model"})}}class Cy extends ra{static async from_pretrained(C,L={}){return super.from_pretrained(C,{...L,model_file_name:L.model_file_name??"audio_model"})}}class Sy extends B{}class wu extends Sy{async _call(C){return new xv(await super._call(C))}}class sa extends B{}class bT extends sa{}class $y extends sa{}class ky extends sa{}class Mu extends B{}class Iy extends Mu{}class Ay extends Mu{}class bu extends B{}class Fy extends bu{}class Oy extends bu{async _call(C){return new Tt(await super._call(C))}}class yu extends B{}class yT extends yu{}class vT extends yu{}class vu extends B{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(L){const[ne,fe]=L.dims,he=this.config.decoder.num_codebooks,Ee=fe-he;let Be=0;for(let mt=0;mt0&&Ot<=Ee&&(L.data[Be++]=L.data[mt])}const Ue=Math.floor(ne/he),Xe=Be/(Ue*he);return new u.Tensor(L.type,L.data.slice(0,Be),[Ue,he,Xe])}prepare_inputs_for_generation(L,ne,fe){let he=structuredClone(L);for(let Be=0;Be=Ue&&(he[Be][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,ne,fe)}async generate(L){const ne=await super.generate(L),fe=this._apply_and_filter_by_delay_pattern_mask(ne).unsqueeze_(0),{audio_values:he}=await G(this.sessions.encodec_decode,{audio_codes:fe});return he}}class na extends B{}class Dy extends na{}class Ly extends na{async _call(C){return new Tt(await super._call(C))}}class zy extends na{}class oa extends B{}class By extends oa{}class Ry extends oa{async _call(C){return new Tt(await super._call(C))}}class jy extends oa{}class ia extends B{}class Ny extends ia{}class Vy extends ia{async _call(C){return new Tt(await super._call(C))}}class Uy extends ia{}class aa extends B{}class Wy extends aa{}class Gy extends aa{async _call(C){return new Tt(await super._call(C))}}class Ky extends aa{}class Hy extends B{}class qy extends Hy{}class Qy extends B{}class Xy extends Qy{constructor(...L){super(...L);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(L){const ne=this._generation_mode??"text";let fe;if(ne==="text"||!L.past_key_values){const Xe=this.sessions.prepare_inputs_embeds,mt=(0,a.pick)(L,Xe.inputNames);fe=await G(Xe,mt)}else{const Xe=this.sessions.gen_img_embeds,mt=(0,a.pick)({image_ids:L.input_ids},Xe.inputNames);fe=await G(Xe,mt)}const he={...L,...fe},Ee=await pe(this,he),Be=this.sessions[ne==="text"?"lm_head":"gen_head"];if(!Be)throw new Error(`Unable to find "${Be}" generation head`);const Ue=await G(Be,(0,a.pick)(Ee,Be.inputNames));return{...fe,...Ee,...Ue}}async generate(L){return this._generation_mode="text",super.generate(L)}async generate_images(L){this._generation_mode="image";const ne=(L.inputs??L[this.main_input_name]).dims[1],he=(await super.generate(L)).slice(null,[ne,null]),Ee=this.sessions.image_decode,{decoded_image:Be}=await G(Ee,{generated_tokens:he}),Ue=Be.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 me{constructor({char_logits:C,bpe_logits:L,wp_logits:ne}){super(),this.char_logits=C,this.bpe_logits=L,this.wp_logits=ne}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Yy extends B{}class Zy extends Yy{async _call(C){return new Jy(await super._call(C))}}class xu extends B{}class e0 extends xu{}class t0 extends xu{}class Tu extends B{}class r0 extends Tu{}class s0 extends Tu{}class n0 extends B{constructor(){super(...arguments);J(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class Eu extends n0{_merge_input_ids_with_audio_features(C){const L=C.audio_features.dims.at(-1),ne=C.audio_features.view(-1,L);return F({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...C,audio_features:ne})}}class o0 extends Eu{}class la extends B{constructor(){super(...arguments);J(this,"main_input_name","input_values");J(this,"forward_params",["input_values"])}}class i0 extends me{constructor({audio_codes:C}){super(),this.audio_codes=C}}class a0 extends me{constructor({audio_values:C}){super(),this.audio_values=C}}class l0 extends la{async encode(C){return new i0(await G(this.sessions.encoder_model,C))}async decode(C){return new a0(await G(this.sessions.decoder_model,C))}}class c0 extends la{static async from_pretrained(C,L={}){return super.from_pretrained(C,{...L,model_file_name:L.model_file_name??"encoder_model"})}}class u0 extends la{static async from_pretrained(C,L={}){return super.from_pretrained(C,{...L,model_file_name:L.model_file_name??"decoder_model"})}}class ca extends B{constructor(){super(...arguments);J(this,"main_input_name","input_values");J(this,"forward_params",["input_values"])}}class d0 extends me{constructor({audio_codes:C}){super(),this.audio_codes=C}}class p0 extends me{constructor({audio_values:C}){super(),this.audio_values=C}}class m0 extends ca{async encode(C){return new d0(await G(this.sessions.encoder_model,C))}async decode(C){return new p0(await G(this.sessions.decoder_model,C))}}class h0 extends ca{static async from_pretrained(C,L={}){return super.from_pretrained(C,{...L,model_file_name:L.model_file_name??"encoder_model"})}}class _0 extends ca{static async from_pretrained(C,L={}){return super.from_pretrained(C,{...L,model_file_name:L.model_file_name??"decoder_model"})}}class ua extends B{constructor(){super(...arguments);J(this,"main_input_name","input_values");J(this,"forward_params",["input_values"])}}class f0 extends ua{async encode(C){return await G(this.sessions.encoder_model,C)}async decode(C){return await G(this.sessions.decoder_model,C)}}class g0 extends ua{static async from_pretrained(C,L={}){return super.from_pretrained(C,{...L,model_file_name:L.model_file_name??"encoder_model"})}}class w0 extends ua{static async from_pretrained(C,L={}){return super.from_pretrained(C,{...L,model_file_name:L.model_file_name??"decoder_model"})}}class jt{static async from_pretrained(C,{progress_callback:L=null,config:ne=null,cache_dir:fe=null,local_files_only:he=!1,revision:Ee="main",model_file_name:Be=null,subfolder:Ue="onnx",device:Xe=null,dtype:mt=null,use_external_data_format:bt=null,session_options:yt={}}={}){const Ot={progress_callback:L,config:ne,cache_dir:fe,local_files_only:he,revision:Ee,model_file_name:Be,subfolder:Ue,device:Xe,dtype:mt,use_external_data_format:bt,session_options:yt};if(Ot.config=await s.AutoConfig.from_pretrained(C,Ot),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const _t=Ot.config.model_type;for(const $t of this.MODEL_CLASS_MAPPINGS){let dt=$t.get(_t);if(!dt){for(const Ft of $t.values())if(Ft[0]===_t){dt=Ft;break}if(!dt)continue}return await dt[1].from_pretrained(C,Ot)}if(this.BASE_IF_FAIL)return W0.has(_t)||console.warn(`Unknown model class "${_t}", attempting to construct from base class.`),await B.from_pretrained(C,Ot);throw Error(`Unsupported model type: ${_t}`)}}J(jt,"MODEL_CLASS_MAPPINGS",null),J(jt,"BASE_IF_FAIL",!1);const xT=new Map([["bert",["BertModel",Se]],["neobert",["NeoBertModel",Ye]],["modernbert",["ModernBertModel",ze]],["nomic_bert",["NomicBertModel",Nr]],["roformer",["RoFormerModel",sr]],["electra",["ElectraModel",X]],["esm",["EsmModel",ms]],["convbert",["ConvBertModel",ht]],["camembert",["CamembertModel",ot]],["deberta",["DebertaModel",qt]],["deberta-v2",["DebertaV2Model",us]],["mpnet",["MPNetModel",bn]],["albert",["AlbertModel",Ve]],["distilbert",["DistilBertModel",ps]],["roberta",["RobertaModel",yi]],["xlm",["XLMModel",Ei]],["xlm-roberta",["XLMRobertaModel",ki]],["clap",["ClapModel",Ey]],["clip",["CLIPModel",Xn]],["clipseg",["CLIPSegModel",ns]],["chinese_clip",["ChineseCLIPModel",Cn]],["siglip",["SiglipModel",Oo]],["jina_clip",["JinaCLIPModel",Qi]],["mobilebert",["MobileBertModel",rt]],["squeezebert",["SqueezeBertModel",V]],["wav2vec2",["Wav2Vec2Model",Bb]],["wav2vec2-bert",["Wav2Vec2BertModel",Zb]],["unispeech",["UniSpeechModel",Kb]],["unispeech-sat",["UniSpeechSatModel",Qb]],["hubert",["HubertModel",ry]],["wavlm",["WavLMModel",oy]],["audio-spectrogram-transformer",["ASTModel",Fi]],["vits",["VitsModel",wu]],["pyannote",["PyAnnoteModel",Vb]],["wespeaker-resnet",["WeSpeakerResNetModel",Gb]],["detr",["DetrModel",vM]],["rt_detr",["RTDetrModel",EM]],["rt_detr_v2",["RTDetrV2Model",CM]],["rf_detr",["RFDetrModel",kM]],["d_fine",["DFineModel",FM]],["table-transformer",["TableTransformerModel",DM]],["vit",["ViTModel",qw]],["ijepa",["IJepaModel",Xw]],["pvt",["PvtModel",eM]],["vit_msn",["ViTMSNModel",nM]],["vit_mae",["ViTMAEModel",sM]],["groupvit",["GroupViTModel",aM]],["fastvit",["FastViTModel",lM]],["mobilevit",["MobileViTModel",pM]],["mobilevitv2",["MobileViTV2Model",hM]],["owlvit",["OwlViTModel",fM]],["owlv2",["Owlv2Model",wM]],["beit",["BeitModel",bM]],["deit",["DeiTModel",BM]],["hiera",["HieraModel",jM]],["convnext",["ConvNextModel",hb]],["convnextv2",["ConvNextV2Model",fb]],["dinov2",["Dinov2Model",wb]],["dinov2_with_registers",["Dinov2WithRegistersModel",bb]],["dinov3_vit",["DINOv3ViTModel",xb]],["dinov3_convnext",["DINOv3ConvNextModel",Eb]],["resnet",["ResNetModel",VM]],["swin",["SwinModel",WM]],["swin2sr",["Swin2SRModel",HM]],["donut-swin",["DonutSwinModel",mb]],["yolos",["YolosModel",Sb]],["dpt",["DPTModel",QM]],["glpn",["GLPNModel",ub]],["hifigan",["SpeechT5HifiGan",hy]],["efficientnet",["EfficientNetModel",Fy]],["decision_transformer",["DecisionTransformerModel",qy]],["patchtst",["PatchTSTForPrediction",e0]],["patchtsmixer",["PatchTSMixerForPrediction",r0]],["mobilenet_v1",["MobileNetV1Model",Dy]],["mobilenet_v2",["MobileNetV2Model",By]],["mobilenet_v3",["MobileNetV3Model",Ny]],["mobilenet_v4",["MobileNetV4Model",Wy]],["maskformer",["MaskFormerModel",lb]],["mgp-str",["MgpstrForSceneTextRecognition",Zy]],["style_text_to_speech_2",["StyleTextToSpeech2Model",dy]]]),TT=new Map([["t5",["T5Model",Bt]],["longt5",["LongT5Model",Gt]],["mt5",["MT5Model",dr]],["bart",["BartModel",ss]],["mbart",["MBartModel",Yr]],["marian",["MarianModel",Ob]],["whisper",["WhisperModel",So]],["m2m_100",["M2M100Model",Lb]],["blenderbot",["BlenderbotModel",pr]],["blenderbot-small",["BlenderbotSmallModel",qr]]]),ET=new Map([["mimi",["MimiModel",l0]],["dac",["DacModel",m0]],["snac",["SnacModel",f0]]]),PT=new Map([["bloom",["BloomModel",Vw]],["jais",["JAISModel",Zn]],["gpt2",["GPT2Model",Ro]],["gptj",["GPTJModel",Wo]],["gpt_bigcode",["GPTBigCodeModel",Ko]],["gpt_neo",["GPTNeoModel",Vo]],["gpt_neox",["GPTNeoXModel",to]],["codegen",["CodeGenModel",A]],["llama",["LlamaModel",le]],["arcee",["ArceeModel",xt]],["lfm2",["Lfm2Model",Tr]],["smollm3",["SmolLM3Model",rw]],["exaone",["ExaoneModel",lw]],["olmo",["OlmoModel",pw]],["olmo2",["Olmo2Model",hw]],["mobilellm",["MobileLLMModel",uw]],["granite",["GraniteModel",fw]],["granitemoehybrid",["GraniteMoeHybridModel",ww]],["cohere",["CohereModel",bw]],["gemma",["GemmaModel",vw]],["gemma2",["Gemma2Model",Tw]],["vaultgemma",["VaultGemmaModel",Pw]],["gemma3_text",["Gemma3Model",Sw]],["helium",["HeliumModel",nw]],["glm",["GlmModel",iw]],["openelm",["OpenELMModel",kw]],["qwen2",["Qwen2Model",Aw]],["qwen3",["Qwen3Model",Ow]],["phi",["PhiModel",Bw]],["phi3",["Phi3Model",jw]],["mpt",["MptModel",Ww]],["opt",["OPTModel",Kw]],["mistral",["MistralModel",gy]],["ernie4_5",["Ernie4_5_Model",My]],["starcoder2",["Starcoder2Model",yy]],["falcon",["FalconModel",xy]],["stablelm",["StableLmModel",Iy]],["modernbert-decoder",["ModernBertDecoderModel",Mt]]]),Pu=new Map([["speecht5",["SpeechT5ForSpeechToText",py]],["whisper",["WhisperForConditionalGeneration",Ks]],["lite-whisper",["LiteWhisperForConditionalGeneration",Di]],["moonshine",["MoonshineForConditionalGeneration",Li]]]),M0=new Map([["speecht5",["SpeechT5ForTextToSpeech",my]]]),b0=new Map([["vits",["VitsModel",wu]],["musicgen",["MusicgenForConditionalGeneration",vu]]]),y0=new Map([["bert",["BertForSequenceClassification",$e]],["neobert",["NeoBertForSequenceClassification",Ze]],["modernbert",["ModernBertForSequenceClassification",nt]],["roformer",["RoFormerForSequenceClassification",Zs]],["electra",["ElectraForSequenceClassification",q]],["esm",["EsmForSequenceClassification",Wr]],["convbert",["ConvBertForSequenceClassification",Os]],["camembert",["CamembertForSequenceClassification",pt]],["deberta",["DebertaForSequenceClassification",Hr]],["deberta-v2",["DebertaV2ForSequenceClassification",Ar]],["mpnet",["MPNetForSequenceClassification",vn]],["albert",["AlbertForSequenceClassification",He]],["distilbert",["DistilBertForSequenceClassification",Jr]],["roberta",["RobertaForSequenceClassification",Eo]],["xlm",["XLMForSequenceClassification",Ci]],["xlm-roberta",["XLMRobertaForSequenceClassification",Ai]],["bart",["BartForSequenceClassification",Mr]],["mbart",["MBartForSequenceClassification",Or]],["mobilebert",["MobileBertForSequenceClassification",Ws]],["squeezebert",["SqueezeBertForSequenceClassification",ae]]]),v0=new Map([["bert",["BertForTokenClassification",we]],["neobert",["NeoBertForTokenClassification",Ke]],["modernbert",["ModernBertForTokenClassification",It]],["roformer",["RoFormerForTokenClassification",en]],["electra",["ElectraForTokenClassification",re]],["esm",["EsmForTokenClassification",Re]],["convbert",["ConvBertForTokenClassification",St]],["camembert",["CamembertForTokenClassification",vt]],["deberta",["DebertaForTokenClassification",nr]],["deberta-v2",["DebertaV2ForTokenClassification",Ds]],["mpnet",["MPNetForTokenClassification",xn]],["distilbert",["DistilBertForTokenClassification",Br]],["roberta",["RobertaForTokenClassification",xi]],["xlm",["XLMForTokenClassification",Si]],["xlm-roberta",["XLMRobertaForTokenClassification",Po]]]),Cu=new Map([["t5",["T5ForConditionalGeneration",Lt]],["longt5",["LongT5ForConditionalGeneration",fr]],["mt5",["MT5ForConditionalGeneration",wr]],["bart",["BartForConditionalGeneration",Yt]],["mbart",["MBartForConditionalGeneration",Ss]],["marian",["MarianMTModel",Db]],["m2m_100",["M2M100ForConditionalGeneration",zb]],["blenderbot",["BlenderbotForConditionalGeneration",_r]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Gs]]]),Su=new Map([["bloom",["BloomForCausalLM",Uw]],["gpt2",["GPT2LMHeadModel",jo]],["jais",["JAISLMHeadModel",No]],["gptj",["GPTJForCausalLM",Go]],["gpt_bigcode",["GPTBigCodeForCausalLM",m]],["gpt_neo",["GPTNeoForCausalLM",kn]],["gpt_neox",["GPTNeoXForCausalLM",Uo]],["codegen",["CodeGenForCausalLM",z]],["llama",["LlamaForCausalLM",Te]],["llama4_text",["Llama4ForCausalLM",qe]],["arcee",["ArceeForCausalLM",zt]],["lfm2",["Lfm2ForCausalLM",Hs]],["smollm3",["SmolLM3ForCausalLM",sw]],["exaone",["ExaoneForCausalLM",cw]],["olmo",["OlmoForCausalLM",mw]],["olmo2",["Olmo2ForCausalLM",_w]],["mobilellm",["MobileLLMForCausalLM",dw]],["granite",["GraniteForCausalLM",gw]],["granitemoehybrid",["GraniteMoeHybridForCausalLM",Mw]],["cohere",["CohereForCausalLM",yw]],["gemma",["GemmaForCausalLM",xw]],["gemma2",["Gemma2ForCausalLM",Ew]],["vaultgemma",["VaultGemmaForCausalLM",Cw]],["gemma3_text",["Gemma3ForCausalLM",$w]],["helium",["HeliumForCausalLM",ow]],["glm",["GlmForCausalLM",aw]],["openelm",["OpenELMForCausalLM",Iw]],["qwen2",["Qwen2ForCausalLM",Fw]],["qwen3",["Qwen3ForCausalLM",Dw]],["phi",["PhiForCausalLM",Rw]],["phi3",["Phi3ForCausalLM",Nw]],["mpt",["MptForCausalLM",Gw]],["opt",["OPTForCausalLM",Hw]],["mbart",["MBartForCausalLM",hs]],["mistral",["MistralForCausalLM",wy]],["ernie4_5",["Ernie4_5_ForCausalLM",by]],["starcoder2",["Starcoder2ForCausalLM",vy]],["falcon",["FalconForCausalLM",Ty]],["trocr",["TrOCRForCausalLM",fy]],["stablelm",["StableLmForCausalLM",Ay]],["modernbert-decoder",["ModernBertDecoderForCausalLM",yr]],["phi3_v",["Phi3VForCausalLM",Io]]]),CT=new Map([["multi_modality",["MultiModalityCausalLM",Xy]]]),x0=new Map([["bert",["BertForMaskedLM",Me]],["neobert",["NeoBertForMaskedLM",ye]],["modernbert",["ModernBertForMaskedLM",Je]],["roformer",["RoFormerForMaskedLM",kr]],["electra",["ElectraForMaskedLM",R]],["esm",["EsmForMaskedLM",Us]],["convbert",["ConvBertForMaskedLM",Fs]],["camembert",["CamembertForMaskedLM",ft]],["deberta",["DebertaForMaskedLM",Ur]],["deberta-v2",["DebertaV2ForMaskedLM",ds]],["mpnet",["MPNetForMaskedLM",yn]],["albert",["AlbertForMaskedLM",et]],["distilbert",["DistilBertForMaskedLM",hr]],["roberta",["RobertaForMaskedLM",vi]],["xlm",["XLMWithLMHeadModel",Pi]],["xlm-roberta",["XLMRobertaForMaskedLM",Ii]],["mobilebert",["MobileBertForMaskedLM",Qt]],["squeezebert",["SqueezeBertForMaskedLM",Y]]]),T0=new Map([["bert",["BertForQuestionAnswering",Fe]],["neobert",["NeoBertForQuestionAnswering",st]],["roformer",["RoFormerForQuestionAnswering",tn]],["electra",["ElectraForQuestionAnswering",ge]],["convbert",["ConvBertForQuestionAnswering",Ht]],["camembert",["CamembertForQuestionAnswering",tt]],["deberta",["DebertaForQuestionAnswering",Ir]],["deberta-v2",["DebertaV2ForQuestionAnswering",Ls]],["mpnet",["MPNetForQuestionAnswering",de]],["albert",["AlbertForQuestionAnswering",We]],["distilbert",["DistilBertForQuestionAnswering",Ps]],["roberta",["RobertaForQuestionAnswering",Ti]],["xlm",["XLMForQuestionAnswering",$i]],["xlm-roberta",["XLMRobertaForQuestionAnswering",Co]],["mobilebert",["MobileBertForQuestionAnswering",Cs]],["squeezebert",["SqueezeBertForQuestionAnswering",ce]]]),$u=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",$o]],["idefics3",["Idefics3ForConditionalGeneration",Bs]],["smolvlm",["SmolVLMForConditionalGeneration",Qn]]]),E0=new Map([["llava",["LlavaForConditionalGeneration",En]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",zi]],["moondream1",["Moondream1ForConditionalGeneration",Bi]],["florence2",["Florence2ForConditionalGeneration",ji]],["qwen2-vl",["Qwen2VLForConditionalGeneration",zw]],["idefics3",["Idefics3ForConditionalGeneration",Bs]],["smolvlm",["SmolVLMForConditionalGeneration",Qn]],["paligemma",["PaliGemmaForConditionalGeneration",Vi]],["llava_qwen2",["LlavaQwen2ForCausalLM",Ui]],["gemma3n",["Gemma3nForConditionalGeneration",ko]]]),P0=new Map([["ultravox",["UltravoxModel",Eu]],["voxtral",["VoxtralForConditionalGeneration",o0]]]),ST=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",$o]]]),C0=new Map([["vit",["ViTForImageClassification",Qw]],["ijepa",["IJepaForImageClassification",Jw]],["pvt",["PvtForImageClassification",tM]],["vit_msn",["ViTMSNForImageClassification",oM]],["fastvit",["FastViTForImageClassification",cM]],["mobilevit",["MobileViTForImageClassification",mM]],["mobilevitv2",["MobileViTV2ForImageClassification",_M]],["beit",["BeitForImageClassification",yM]],["deit",["DeiTForImageClassification",RM]],["hiera",["HieraForImageClassification",NM]],["convnext",["ConvNextForImageClassification",_b]],["convnextv2",["ConvNextV2ForImageClassification",gb]],["dinov2",["Dinov2ForImageClassification",Mb]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",yb]],["resnet",["ResNetForImageClassification",UM]],["swin",["SwinForImageClassification",GM]],["segformer",["SegformerForImageClassification",$y]],["efficientnet",["EfficientNetForImageClassification",Oy]],["mobilenet_v1",["MobileNetV1ForImageClassification",Ly]],["mobilenet_v2",["MobileNetV2ForImageClassification",Ry]],["mobilenet_v3",["MobileNetV3ForImageClassification",Vy]],["mobilenet_v4",["MobileNetV4ForImageClassification",Gy]]]),S0=new Map([["detr",["DetrForObjectDetection",xM]],["rt_detr",["RTDetrForObjectDetection",PM]],["rt_detr_v2",["RTDetrV2ForObjectDetection",SM]],["rf_detr",["RFDetrForObjectDetection",IM]],["d_fine",["DFineForObjectDetection",OM]],["table-transformer",["TableTransformerForObjectDetection",LM]],["yolos",["YolosForObjectDetection",$b]]]),$0=new Map([["owlvit",["OwlViTForObjectDetection",gM]],["owlv2",["Owlv2ForObjectDetection",MM]],["grounding-dino",["GroundingDinoForObjectDetection",Cb]]]),oo=new Map([["detr",["DetrForSegmentation",Kc]],["clipseg",["CLIPSegForImageSegmentation",Sn]]]),k0=new Map([["segformer",["SegformerForSemanticSegmentation",ky]],["sapiens",["SapiensForSemanticSegmentation",ZM]],["swin",["SwinForSemanticSegmentation",KM]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",zy]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",jy]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Uy]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Ky]]]),I0=new Map([["detr",["DetrForSegmentation",Kc]],["maskformer",["MaskFormerForInstanceSegmentation",cb]]]),A0=new Map([["sam",["SamModel",Ab]]]),F0=new Map([["wav2vec2",["Wav2Vec2ForCTC",Rb]],["wav2vec2-bert",["Wav2Vec2BertForCTC",ey]],["unispeech",["UniSpeechForCTC",Hb]],["unispeech-sat",["UniSpeechSatForCTC",Xb]],["wavlm",["WavLMForCTC",iy]],["hubert",["HubertForCTC",sy]]]),O0=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",jb]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",ty]],["unispeech",["UniSpeechForSequenceClassification",qb]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Jb]],["wavlm",["WavLMForSequenceClassification",ay]],["hubert",["HubertForSequenceClassification",ny]],["audio-spectrogram-transformer",["ASTForAudioClassification",Oi]]]),D0=new Map([["wavlm",["WavLMForXVector",ly]]]),L0=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Yb]],["wavlm",["WavLMForAudioFrameClassification",cy]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Nb]],["pyannote",["PyAnnoteForAudioFrameClassification",Ub]]]),z0=new Map([["vitmatte",["VitMatteForImageMatting",dM]]]),$T=new Map([["patchtst",["PatchTSTForPrediction",t0]],["patchtsmixer",["PatchTSMixerForPrediction",s0]]]),B0=new Map([["swin2sr",["Swin2SRForImageSuperResolution",qM]]]),R0=new Map([["dpt",["DPTForDepthEstimation",XM]],["depth_anything",["DepthAnythingForDepthEstimation",YM]],["glpn",["GLPNForDepthEstimation",db]],["sapiens",["SapiensForDepthEstimation",eb]],["depth_pro",["DepthProForDepthEstimation",sb]],["metric3d",["Metric3DForDepthEstimation",ob]],["metric3dv2",["Metric3Dv2ForDepthEstimation",ab]]]),j0=new Map([["sapiens",["SapiensForNormalEstimation",tb]]]),N0=new Map([["vitpose",["VitPoseForPoseEstimation",Zw]]]),V0=new Map([["clip",["CLIPVisionModelWithProjection",Fo]],["siglip",["SiglipVisionModel",Do]],["jina_clip",["JinaCLIPVisionModel",Bo]]]),U0=[[xT,E.EncoderOnly],[TT,E.EncoderDecoder],[PT,E.DecoderOnly],[ET,E.AutoEncoder],[y0,E.EncoderOnly],[v0,E.EncoderOnly],[Cu,E.Seq2Seq],[Pu,E.Seq2Seq],[Su,E.DecoderOnly],[CT,E.MultiModality],[x0,E.EncoderOnly],[T0,E.EncoderOnly],[$u,E.Vision2Seq],[E0,E.ImageTextToText],[P0,E.AudioTextToText],[C0,E.EncoderOnly],[oo,E.EncoderOnly],[I0,E.EncoderOnly],[k0,E.EncoderOnly],[z0,E.EncoderOnly],[$T,E.EncoderOnly],[B0,E.EncoderOnly],[R0,E.EncoderOnly],[j0,E.EncoderOnly],[N0,E.EncoderOnly],[S0,E.EncoderOnly],[$0,E.EncoderOnly],[A0,E.MaskGeneration],[F0,E.EncoderOnly],[O0,E.EncoderOnly],[M0,E.Seq2Seq],[b0,E.EncoderOnly],[D0,E.EncoderOnly],[L0,E.EncoderOnly],[V0,E.EncoderOnly]];for(const[g,C]of U0)for(const[L,ne]of g.values())v.set(L,C),y.set(ne,L),x.set(L,ne);const kT=[["MusicgenForConditionalGeneration",vu,E.Musicgen],["Phi3VForCausalLM",Io,E.Phi3V],["CLIPTextModelWithProjection",Ao,E.EncoderOnly],["SiglipTextModel",qi,E.EncoderOnly],["JinaCLIPTextModel",zo,E.EncoderOnly],["ClapTextModelWithProjection",Py,E.EncoderOnly],["ClapAudioModelWithProjection",Cy,E.EncoderOnly],["DacEncoderModel",h0,E.EncoderOnly],["DacDecoderModel",_0,E.EncoderOnly],["MimiEncoderModel",c0,E.EncoderOnly],["MimiDecoderModel",u0,E.EncoderOnly],["SnacEncoderModel",g0,E.EncoderOnly],["SnacDecoderModel",w0,E.EncoderOnly],["Gemma3nForConditionalGeneration",ko,E.ImageAudioTextToText]];for(const[g,C,L]of kT)v.set(g,L),y.set(C,g),x.set(g,C);const W0=new Map([["modnet",oo],["birefnet",oo],["isnet",oo],["ben",oo]]);for(const[g,C]of W0.entries())C.set(g,["PreTrainedModel",B]),v.set(g,E.EncoderOnly),y.set(B,g),x.set(g,B);class ku extends jt{}J(ku,"MODEL_CLASS_MAPPINGS",U0.map(C=>C[0])),J(ku,"BASE_IF_FAIL",!0);class G0 extends jt{}J(G0,"MODEL_CLASS_MAPPINGS",[y0]);class K0 extends jt{}J(K0,"MODEL_CLASS_MAPPINGS",[v0]);class H0 extends jt{}J(H0,"MODEL_CLASS_MAPPINGS",[Cu]);class q0 extends jt{}J(q0,"MODEL_CLASS_MAPPINGS",[Pu]);class Q0 extends jt{}J(Q0,"MODEL_CLASS_MAPPINGS",[M0]);class X0 extends jt{}J(X0,"MODEL_CLASS_MAPPINGS",[b0]);class J0 extends jt{}J(J0,"MODEL_CLASS_MAPPINGS",[Su]);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",[$u]);class tv extends jt{}J(tv,"MODEL_CLASS_MAPPINGS",[C0]);class rv extends jt{}J(rv,"MODEL_CLASS_MAPPINGS",[oo]);class sv extends jt{}J(sv,"MODEL_CLASS_MAPPINGS",[k0]);class nv extends jt{}J(nv,"MODEL_CLASS_MAPPINGS",[I0]);class ov extends jt{}J(ov,"MODEL_CLASS_MAPPINGS",[S0]);class iv extends jt{}J(iv,"MODEL_CLASS_MAPPINGS",[$0]);class av extends jt{}J(av,"MODEL_CLASS_MAPPINGS",[A0]);class lv extends jt{}J(lv,"MODEL_CLASS_MAPPINGS",[F0]);class cv extends jt{}J(cv,"MODEL_CLASS_MAPPINGS",[O0]);class uv extends jt{}J(uv,"MODEL_CLASS_MAPPINGS",[D0]);class dv extends jt{}J(dv,"MODEL_CLASS_MAPPINGS",[L0]);class pv extends jt{}J(pv,"MODEL_CLASS_MAPPINGS",[ST]);class mv extends jt{}J(mv,"MODEL_CLASS_MAPPINGS",[z0]);class hv extends jt{}J(hv,"MODEL_CLASS_MAPPINGS",[B0]);class _v extends jt{}J(_v,"MODEL_CLASS_MAPPINGS",[R0]);class fv extends jt{}J(fv,"MODEL_CLASS_MAPPINGS",[j0]);class gv extends jt{}J(gv,"MODEL_CLASS_MAPPINGS",[N0]);class wv extends jt{}J(wv,"MODEL_CLASS_MAPPINGS",[V0]);class Mv extends jt{}J(Mv,"MODEL_CLASS_MAPPINGS",[E0]);class bv extends jt{}J(bv,"MODEL_CLASS_MAPPINGS",[P0]);class IT extends me{constructor({logits:C,past_key_values:L,encoder_outputs:ne,decoder_attentions:fe=null,cross_attentions:he=null}){super(),this.logits=C,this.past_key_values=L,this.encoder_outputs=ne,this.decoder_attentions=fe,this.cross_attentions=he}}class Tt extends me{constructor({logits:C,...L}){super(),this.logits=C;const ne=Object.values(L);ne.length>0&&(this.attentions=ne)}}class yv extends me{constructor({logits:C,embeddings:L}){super(),this.logits=C,this.embeddings=L}}class Er extends me{constructor({logits:C}){super(),this.logits=C}}class Dr extends me{constructor({logits:C}){super(),this.logits=C}}class Rr extends me{constructor({start_logits:C,end_logits:L}){super(),this.start_logits=C,this.end_logits=L}}class An extends me{constructor({logits:C}){super(),this.logits=C}}class AT extends me{constructor({logits:C,past_key_values:L}){super(),this.logits=C,this.past_key_values=L}}class vv extends me{constructor({alphas:C}){super(),this.alphas=C}}class xv extends me{constructor({waveform:C,spectrogram:L}){super(),this.waveform=C,this.spectrogram=L}}}),"./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:M,processor_class:k}=f;if(k&&i[k])return i[k].from_pretrained(d,u);if(!_&&!M)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const w={};if(_){const $=a[_.replace(/Fast$/,"")];if(!$)throw new Error(`Unknown image_processor_type: '${_}'.`);w.image_processor=new $(f)}if(M){const $=a[M];if($)w.image_processor=new $(f);else{const E=l[M];if(!E)throw new Error(`Unknown feature_extractor_type: '${M}'.`);w.feature_extractor=new E(f)}}const b={};return new n.Processor(b,w,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/dinov3_vit/image_processing_dinov3_vit.js":((e,r,t)=>{t.r(r),t.d(r,{DINOv3ViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}}),"./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 M=this.image_std;Array.isArray(M)||(M=new Array(f).fill(_));const k=_.map((w,b)=>-w/M[b]);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:()=>M.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"),M=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]),M=[],k=[];for(const[w,b,...$]of _)M.push(b?b.trim():M.at(-1)??""),k.push($.map((E,v)=>(Number(E)+.5)/this.size_per_bin*p[v%2]));u={labels:M,[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,M=(0,n.mel_filter_bank)(Math.floor(1+c/2),p,d,u,f,null,"htk",!1);this.mel_filters=M,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 M=u-l.length%u,k=new Float64Array(l.length+M);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:M,image_token_id:k,boi_token:w,image_token:b,eoi_token:$}=this.tokenizer.config;this.audio_token_id=u,this.boa_token=f,this.audio_token=_;const E=_.repeat(this.audio_seq_length);this.full_audio_sequence=` + +${f}${E}${M} + +`,this.image_token_id=k,this.boi_token=w,this.image_token=b;const v=b.repeat(this.image_seq_length);this.full_image_sequence=` + +${w}${v}${$} + +`}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((M,k)=>M?k:null).filter(M=>M!==null).map(M=>_[M])}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:M,pred_boxes:k}=p,w=M.dims[0];if(_!==null&&_.length!==w)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const b=M.dims.at(1),$=M.sigmoid(),E=$.max(-1).tolist(),v=k.tolist().map(y=>y.map(P=>(0,i.center_to_corners_format)(P))),x=[];for(let y=0;yN.map((te,H)=>te*P[(H+1)%2])));const O=E[y],D=[],K=[],G=[];for(let N=0;N{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 _=[],M=[];for(const y of p){let P=await Promise.all(y.map(K=>this.preprocess(K)));_.push(...P.map(K=>K.original_size)),M.push(...P.map(K=>K.reshaped_input_size)),P.forEach(K=>K.pixel_values.unsqueeze_(0));const{longest_edge:O}=this.max_image_size;let D;if(l??this.do_image_splitting){let K=new Array(P.length),G=new Array(P.length);D=await Promise.all(P.map(async(N,te)=>{const H=this.get_resize_for_vision_encoder(N.pixel_values,O),ee=await(0,o.interpolate_4d)(N.pixel_values,{size:[H.height,H.width]}),{frames:Z,num_splits_h:oe,num_splits_w:pe}=await this.split_image(ee,this.max_image_size);return K[te]=oe,G[te]=pe,(0,o.cat)(Z,0)})),u.push(K),f.push(G)}else{const K=[O,O];D=await Promise.all(P.map(G=>(0,o.interpolate_4d)(G.pixel_values,{size:K}))),u.push(new Array(P.length).fill(0)),f.push(new Array(P.length).fill(0))}d.push((0,o.cat)(D,0))}const k=d.length,[w,b,$,E]=d[0].dims;let v,x;if(k===1)v=d[0].unsqueeze_(0),x=(0,o.full)([k,w,$,E],!0);else{const y=Math.max(...d.map(D=>D.dims.at(0)));x=(0,o.full)([k,y,$,E],!0);const P=x.data,O=y*$*E;for(let D=0;Dc||f>p){_=Math.ceil(u/c),M=Math.ceil(f/p);const k=Math.ceil(u/_),w=Math.ceil(f/M);for(let E=0;E<_;++E)for(let v=0;v{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,_,M,k){let w="";for(let b=0;b`+M.repeat(d);w+=` +`}return w+=` +${_}${k}`+M.repeat(d)+`${_}`,w}function l(d,u,f,_){return`${u}${_}`+f.repeat(d)+`${u}`}function c(d,u,f,_,M,k){return d===0&&u===0?l(f,_,M,k):a(f,d,u,_,M,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,M={}){M.return_row_col_info??(M.return_row_col_info=!0);let k;_&&(k=await this.image_processor(_,M)),Array.isArray(f)||(f=[f]);const w=k.rows??[new Array(f.length).fill(0)],b=k.cols??[new Array(f.length).fill(0)],$=this.config.image_seq_len,E=[],v=[];for(let y=0;yc(te,D[H],$,this.fake_image_token,this.image_token,this.global_img_token)),G=P.split(this.image_token);if(G.length===0)throw new Error("The image token should be present in the text.");let N=G[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,DINOv3ViTImageProcessor:()=>p.DINOv3ViTImageProcessor,DPTFeatureExtractor:()=>u.DPTFeatureExtractor,DPTImageProcessor:()=>u.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>c.DetrFeatureExtractor,DetrImageProcessor:()=>c.DetrImageProcessor,DonutFeatureExtractor:()=>d.DonutFeatureExtractor,DonutImageProcessor:()=>d.DonutImageProcessor,EfficientNetImageProcessor:()=>f.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>M.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>k.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>b.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>$.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>E.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>v.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>v.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>x.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>x.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>y.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>y.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>P.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>P.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>O.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>O.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>D.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>D.MobileViTImageProcessor,NougatImageProcessor:()=>K.NougatImageProcessor,OwlViTFeatureExtractor:()=>N.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>N.OwlViTImageProcessor,Owlv2ImageProcessor:()=>G.Owlv2ImageProcessor,Phi3VImageProcessor:()=>te.Phi3VImageProcessor,PvtImageProcessor:()=>H.PvtImageProcessor,Qwen2VLImageProcessor:()=>ee.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Z.RTDetrImageProcessor,SamImageProcessor:()=>oe.SamImageProcessor,SegformerFeatureExtractor:()=>pe.SegformerFeatureExtractor,SegformerImageProcessor:()=>pe.SegformerImageProcessor,SiglipImageProcessor:()=>ue.SiglipImageProcessor,SmolVLMImageProcessor:()=>j.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>F.Swin2SRImageProcessor,VLMImageProcessor:()=>w.VLMImageProcessor,ViTFeatureExtractor:()=>W.ViTFeatureExtractor,ViTImageProcessor:()=>W.ViTImageProcessor,VitMatteImageProcessor:()=>se.VitMatteImageProcessor,VitPoseImageProcessor:()=>_e.VitPoseImageProcessor,YolosFeatureExtractor:()=>ie.YolosFeatureExtractor,YolosImageProcessor:()=>ie.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/dinov3_vit/image_processing_dinov3_vit.js"),d=t("./src/models/donut/image_processing_donut.js"),u=t("./src/models/dpt/image_processing_dpt.js"),f=t("./src/models/efficientnet/image_processing_efficientnet.js"),_=t("./src/models/glpn/image_processing_glpn.js"),M=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),k=t("./src/models/idefics3/image_processing_idefics3.js"),w=t("./src/models/janus/image_processing_janus.js"),b=t("./src/models/jina_clip/image_processing_jina_clip.js"),$=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),E=t("./src/models/mask2former/image_processing_mask2former.js"),v=t("./src/models/maskformer/image_processing_maskformer.js"),x=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),y=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),P=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),O=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),D=t("./src/models/mobilevit/image_processing_mobilevit.js"),K=t("./src/models/nougat/image_processing_nougat.js"),G=t("./src/models/owlv2/image_processing_owlv2.js"),N=t("./src/models/owlvit/image_processing_owlvit.js"),te=t("./src/models/phi3_v/image_processing_phi3_v.js"),H=t("./src/models/pvt/image_processing_pvt.js"),ee=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Z=t("./src/models/rt_detr/image_processing_rt_detr.js"),oe=t("./src/models/sam/image_processing_sam.js"),pe=t("./src/models/segformer/image_processing_segformer.js"),ue=t("./src/models/siglip/image_processing_siglip.js"),j=t("./src/models/smolvlm/image_processing_smolvlm.js"),F=t("./src/models/swin2sr/image_processing_swin2sr.js"),W=t("./src/models/vit/image_processing_vit.js"),se=t("./src/models/vitmatte/image_processing_vitmatte.js"),_e=t("./src/models/vitpose/image_processing_vitpose.js"),ie=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(D=>D.images).flatMap(D=>D.images).map(D=>l.RawImage.read(D)));const _=this.tokenizer,M=_.apply_chat_template(d,{tokenize:!1,add_generation_prompt:!0,chat_template:f}),k=D=>_.encode(D,{add_special_tokens:!1}),w=M.split(this.image_tag),b=w.length-1;if(u.length!==b)throw new Error(`Number of images provided (${u.length}) does not match number of "${this.image_tag}" image tags (${b})`);const[$,E,v]=_.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let x=k(w[0]),y=new Array(x.length).fill(!1);for(let D=1;D0){const D=await this.image_processor(u);return D.pixel_values.unsqueeze_(0),{...O,...D}}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:M,patch_size:k,num_additional_image_tokens:w}=this.config,b=Math.floor(f/k)*Math.floor(_/k)+w;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),[M,k]=p.dims,w=[],b=[],$=p.tolist();for(let v=0;v0?P.reduce((D,K)=>D*K,1):0;b.push(y),w.push(O)}return[_(b),w]}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"),[M,k]=this._decode_helper(d,"bpe"),[w,b]=this._decode_helper(u,"wp"),$=[],E=[];for(let v=0;v{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 M;d.some(b=>b.includes(i))?M=d.map(b=>{const $=b.replaceAll(i,i.repeat(_)),E=$.lastIndexOf(i),v=E===-1?0:E+i.length;return $.slice(0,v)+f+$.slice(v)+` +`}):(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."),M=d.map(b=>a(b,f,_,i,p.length)));const k=this.tokenizer(M,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,[M,k]=u.size;let w=M/k,b=1;for(;b*Math.ceil(b/w)<=_;)b+=1;b-=1;const $=Math.floor(b*336),E=Math.floor($/w);return[$,E]}pad_image(u,f,_,M={}){const[k,w]=f,b=n*a(k/n),$=n*a(w/n),E=[1,1,1].map((v,x)=>(v-this.image_mean[x])/this.image_std[x]);return super.pad_image(u,f,{width:$,height:b},{center:!0,constant_values:E,...M})}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,M=await Promise.all(u.map(y=>this.preprocess(y))),k=M.map(y=>y.original_size),w=M.map(y=>y.reshaped_input_size),b=[];for(const{pixel_values:y}of M){y.unsqueeze_(0);const[P,O]=y.dims.slice(-2),D=await(0,o.interpolate_4d)(y,{size:[n,n],mode:"bicubic"});if(f>0){const K=[],G=c(f),N=l(O/G),te=l(P/G);for(let ee=0;eey.map(P=>n*a(P/n))),v=new o.Tensor("int64",E.flat(),[_,2]),x=E.map(([y,P])=>this.calc_num_image_tokens_from_image_size(P,y));return{pixel_values:$,original_sizes:k,reshaped_input_sizes:w,image_sizes:v,num_img_tokens:x}}}}),"./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 M,k;if(d){k=await this.image_processor(d,{num_crops:_});const{num_img_tokens:w}=k,b=p.map((E,v)=>E.split(a).join(i.repeat(w[v])));M=this.tokenizer(b,{padding:u,truncation:f});const $=this.tokenizer.model.convert_tokens_to_ids([i])[0];M.input_ids.map_(E=>E==$?-E:E)}else M=this.tokenizer(p);return{...M,...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:()=>M.PyAnnoteProcessor,Qwen2VLProcessor:()=>k.Qwen2VLProcessor,SamProcessor:()=>w.SamProcessor,SmolVLMProcessor:()=>b.SmolVLMProcessor,SpeechT5Processor:()=>$.SpeechT5Processor,UltravoxProcessor:()=>E.UltravoxProcessor,VLChatProcessor:()=>a.VLChatProcessor,VoxtralProcessor:()=>v.VoxtralProcessor,Wav2Vec2Processor:()=>x.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>y.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"),M=t("./src/models/pyannote/processing_pyannote.js"),k=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),w=t("./src/models/sam/processing_sam.js"),b=t("./src/models/smolvlm/processing_smolvlm.js"),$=t("./src/models/speecht5/processing_speecht5.js"),E=t("./src/models/ultravox/processing_ultravox.js"),v=t("./src/models/voxtral/processing_voxtral.js"),x=t("./src/models/wav2vec2/processing_wav2vec2.js"),y=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 M=0;M({id:M,start:k*p,end:w*p,confidence:b/(w-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:M}=this.config;u.dims[0]===1&&(u=(0,o.cat)(Array.from({length:f},()=>u),0));const k=u.dims[0]/f,w=u.dims[1],b=Math.floor(u.dims[2]/M),$=Math.floor(u.dims[3]/M),E=u.view(k,f,w,Math.floor(b/_),_,M,Math.floor($/_),_,M).permute(0,3,6,4,7,2,1,5,8).view(k*b*$,w*f*M*M),v=new o.Tensor("int64",[k,b,$],[1,3]);return{pixel_values:E,image_grid_thw:v,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,M=0;const k=u.tolist();l=l.map(w=>{for(;w.includes("<|image_pad|>");){const b=Number(k[M++].reduce(($,E)=>$*E,1n));w=w.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(b/_)))}return w.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 M=[f.height,f.width];for(let k=0;kd&&(v[x]=1);$=new n.Tensor("bool",v,$.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[v,x]=f.dims,y=f.data;for(let P=0;P0){const O=new Float32Array(x*(v+P));O.set(y),O.fill(this.config.padding_value,y.length);const D=v+P;f=new o.Tensor(f.type,O,[D,x]),u&&(_=new o.Tensor("int64",new BigInt64Array(D),[1,D]),_.data.fill(1n,0,v))}}const[M,k]=f.dims,w=this.config.stride;if(M%w!==0)throw new Error(`The number of frames (${M}) must be a multiple of the stride (${w}).`);const $=f.view(1,Math.floor(M/w),k*w),E={input_features:$};if(u){const v=$.dims[1],x=new BigInt64Array(v);if(_){const y=_.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}),M=Math.round(f/this.config.encoder_ds_factor+1e-4),k=1+Math.ceil(M/this.config.stack_factor);d.audio_token_len=[k],d.audio_values=_;const w=this.config.audio_placeholder;if(!l.includes(w))throw new Error(`The input text does not contain the image token ${w}.`);l=l.replaceAll(w,w.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 M=0;M{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 M=0;Mp(D,E)),x=v.map(D=>D.length),y=v.flat(),P=(await Promise.all(y.map(D=>this.feature_extractor(D,M)))).map(D=>D.input_features);k.audio_values=P.length>1?(0,i.cat)(P,0):P[0];let O=b[0];for(let D=0;D{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:()=>i});var s=t("./src/backends/onnx.js"),o=t("./src/utils/tensor.js");const n=async(a,l,c)=>{const p=await(0,s.createInferenceSession)(new Uint8Array(a),l);return(async d=>{const u=(0,s.isONNXProxy)(),f=Object.fromEntries(Object.entries(d).map(([M,k])=>[M,(u?k.clone():k).ort_tensor])),_=await(0,s.runInferenceSession)(p,f);return Array.isArray(c)?c.map(M=>new o.Tensor(_[M])):new o.Tensor(_[c])})};class i{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=n([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=n([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=n([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=n([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=n([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=n([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=n([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=n([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(i,"session_options",{})}),"./src/pipelines.js":((e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>G,AutomaticSpeechRecognitionPipeline:()=>te,BackgroundRemovalPipeline:()=>oe,DepthEstimationPipeline:()=>_e,DocumentQuestionAnsweringPipeline:()=>F,FeatureExtractionPipeline:()=>D,FillMaskPipeline:()=>$,ImageClassificationPipeline:()=>ee,ImageFeatureExtractionPipeline:()=>K,ImageSegmentationPipeline:()=>Z,ImageToImagePipeline:()=>se,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>ue,Pipeline:()=>M,QuestionAnsweringPipeline:()=>b,SummarizationPipeline:()=>v,Text2TextGenerationPipeline:()=>E,TextClassificationPipeline:()=>k,TextGenerationPipeline:()=>P,TextToAudioPipeline:()=>W,TokenClassificationPipeline:()=>w,TranslationPipeline:()=>x,ZeroShotAudioClassificationPipeline:()=>N,ZeroShotClassificationPipeline:()=>O,ZeroShotImageClassificationPipeline:()=>pe,ZeroShotObjectDetectionPipeline:()=>j,pipeline:()=>Le});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(Q=>d.RawImage.read(Q)))}async function f(Ie,Q){return Array.isArray(Ie)||(Ie=[Ie]),await Promise.all(Ie.map(B=>typeof B=="string"||B instanceof URL?(0,c.read_audio)(B,Q):B instanceof Float64Array?new Float32Array(B):B))}function _(Ie,Q){Q&&(Ie=Ie.map(Se=>Se|0));const[B,me,Ce,Pe]=Ie;return{xmin:B,ymin:me,xmax:Ce,ymax:Pe}}class M extends i.Callable{constructor({task:Q,model:B,tokenizer:me=null,processor:Ce=null}){super(),this.task=Q,this.model=B,this.tokenizer=me,this.processor=Ce}async dispose(){await this.model.dispose()}}class k extends M{constructor(Q){super(Q)}async _call(Q,{top_k:B=1}={}){const me=this.tokenizer(Q,{padding:!0,truncation:!0}),Ce=await this.model(me),Pe=this.model.config.problem_type==="multi_label_classification"?$e=>$e.sigmoid():$e=>new p.Tensor("float32",(0,l.softmax)($e.data),$e.dims),Se=this.model.config.id2label,Me=[];for(const $e of Ce.logits){const we=Pe($e),Fe=await(0,p.topk)(we,B),Oe=Fe[0].tolist(),ye=Fe[1].tolist().map((Ze,Ke)=>({label:Se?Se[Ze]:`LABEL_${Ze}`,score:Oe[Ke]}));B===1?Me.push(...ye):Me.push(ye)}return Array.isArray(Q)||B===1?Me:Me[0]}}class w extends M{constructor(Q){super(Q)}async _call(Q,{ignore_labels:B=["O"]}={}){const me=Array.isArray(Q),Ce=this.tokenizer(me?Q:[Q],{padding:!0,truncation:!0}),Se=(await this.model(Ce)).logits,Me=this.model.config.id2label,$e=[];for(let we=0;weJe==this.tokenizer.sep_token_id);$e[Oe].map((Je,nt)=>Je==1&&(nt===0||nt>ye&&we.findIndex(It=>It==Ye[nt])===-1));const Ze=Pe[Oe].tolist(),Ke=Se[Oe].tolist();for(let Je=1;Jent==Ye[Je])!==-1)&&(Ze[Je]=-1/0,Ke[Je]=-1/0);const st=(0,l.softmax)(Ze).map((Je,nt)=>[Je,nt]),Qe=(0,l.softmax)(Ke).map((Je,nt)=>[Je,nt]);st[0][0]=0,Qe[0][0]=0;const ze=(0,a.product)(st,Qe).filter(Je=>Je[0][1]<=Je[1][1]).map(Je=>[Je[0][1],Je[1][1],Je[0][0]*Je[1][0]]).sort((Je,nt)=>nt[2]-Je[2]);for(let Je=0;JeZe==this.tokenizer.mask_token_id);if(we===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Fe=Ce[Me][we],Oe=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Fe.data),Fe.dims),B),Ye=Oe[0].tolist(),ye=Oe[1].tolist();Pe.push(ye.map((Ze,Ke)=>{const st=$e.slice();return st[we]=Ze,{score:Ye[Ke],token:Number(Ze),token_str:this.tokenizer.decode([Ze]),sequence:this.tokenizer.decode(st,{skip_special_tokens:!0})}}))}return Array.isArray(Q)?Pe:Pe[0]}}class E extends M{constructor(B){super(B);J(this,"_key","generated_text")}async _call(B,me={}){Array.isArray(B)||(B=[B]),this.model.config.prefix&&(B=B.map(we=>this.model.config.prefix+we));const Ce=this.model.config.task_specific_params;Ce&&Ce[this.task]&&Ce[this.task].prefix&&(B=B.map(we=>Ce[this.task].prefix+we));const Pe=this.tokenizer,Se={padding:!0,truncation:!0};let Me;this instanceof x&&"_build_translation_inputs"in Pe?Me=Pe._build_translation_inputs(B,Se,me):Me=Pe(B,Se);const $e=await this.model.generate({...Me,...me});return Pe.batch_decode($e,{skip_special_tokens:!0}).map(we=>({[this._key]:we}))}}class v extends E{constructor(B){super(B);J(this,"_key","summary_text")}}class x extends E{constructor(B){super(B);J(this,"_key","translation_text")}}function y(Ie){return Array.isArray(Ie)&&Ie.every(Q=>"role"in Q&&"content"in Q)}class P extends M{constructor(Q){super(Q)}async _call(Q,B={}){let me=!1,Ce=!1,Pe=B.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,Se;if(typeof Q=="string")Se=Q=[Q];else if(Array.isArray(Q)&&Q.every(ye=>typeof ye=="string"))me=!0,Se=Q;else{if(y(Q))Q=[Q];else if(Array.isArray(Q)&&Q.every(y))me=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Ce=!0,Se=Q.map(ye=>this.tokenizer.apply_chat_template(ye,{tokenize:!1,add_generation_prompt:!0})),Pe=!1}const Me=Ce?!1:B.return_full_text??!0;this.tokenizer.padding_side="left";const $e=this.tokenizer(Se,{add_special_tokens:Pe,padding:!0,truncation:!0}),we=await this.model.generate({...$e,...B}),Fe=this.tokenizer.batch_decode(we,{skip_special_tokens:!0});let Oe;!Me&&$e.input_ids.dims.at(-1)>0&&(Oe=this.tokenizer.batch_decode($e.input_ids,{skip_special_tokens:!0}).map(ye=>ye.length));const Ye=Array.from({length:Q.length},ye=>[]);for(let ye=0;ye[B.toLowerCase(),me])),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(Q,B,{hypothesis_template:me="This example is {}.",multi_label:Ce=!1}={}){const Pe=Array.isArray(Q);Pe||(Q=[Q]),Array.isArray(B)||(B=[B]);const Se=B.map(we=>me.replace("{}",we)),Me=Ce||B.length===1,$e=[];for(const we of Q){const Fe=[];for(const ye of Se){const Ze=this.tokenizer(we,{text_pair:ye,padding:!0,truncation:!0}),Ke=await this.model(Ze);Me?Fe.push([Ke.logits.data[this.contradiction_id],Ke.logits.data[this.entailment_id]]):Fe.push(Ke.logits.data[this.entailment_id])}const Ye=(Me?Fe.map(ye=>(0,l.softmax)(ye)[1]):(0,l.softmax)(Fe)).map((ye,Ze)=>[ye,Ze]).sort((ye,Ze)=>Ze[0]-ye[0]);$e.push({sequence:we,labels:Ye.map(ye=>B[ye[1]]),scores:Ye.map(ye=>ye[0])})}return Pe?$e:$e[0]}}class D extends M{constructor(Q){super(Q)}async _call(Q,{pooling:B="none",normalize:me=!1,quantize:Ce=!1,precision:Pe="binary"}={}){const Se=this.tokenizer(Q,{padding:!0,truncation:!0}),Me=await this.model(Se);let $e=Me.last_hidden_state??Me.logits??Me.token_embeddings;switch(B){case"none":break;case"mean":$e=(0,p.mean_pooling)($e,Se.attention_mask);break;case"first_token":case"cls":$e=$e.slice(null,0);break;case"last_token":case"eos":$e=$e.slice(null,-1);break;default:throw Error(`Pooling method '${B}' not supported.`)}return me&&($e=$e.normalize(2,-1)),Ce&&($e=(0,p.quantize_embeddings)($e,Pe)),$e}}class K extends M{constructor(Q){super(Q)}async _call(Q,{pool:B=null}={}){const me=await u(Q),{pixel_values:Ce}=await this.processor(me),Pe=await this.model({pixel_values:Ce});let Se;if(B){if(!("pooler_output"in Pe))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Se=Pe.pooler_output}else Se=Pe.last_hidden_state??Pe.logits??Pe.image_embeds;return Se}}class G extends M{constructor(Q){super(Q)}async _call(Q,{top_k:B=5}={}){const me=this.processor.feature_extractor.config.sampling_rate,Ce=await f(Q,me),Pe=this.model.config.id2label,Se=[];for(const Me of Ce){const $e=await this.processor(Me),Fe=(await this.model($e)).logits[0],Oe=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Fe.data),Fe.dims),B),Ye=Oe[0].tolist(),Ze=Oe[1].tolist().map((Ke,st)=>({label:Pe?Pe[Ke]:`LABEL_${Ke}`,score:Ye[st]}));Se.push(Ze)}return Array.isArray(Q)?Se:Se[0]}}class N extends M{constructor(Q){super(Q)}async _call(Q,B,{hypothesis_template:me="This is a sound of {}."}={}){const Ce=!Array.isArray(Q);Ce&&(Q=[Q]);const Pe=B.map(Fe=>me.replace("{}",Fe)),Se=this.tokenizer(Pe,{padding:!0,truncation:!0}),Me=this.processor.feature_extractor.config.sampling_rate,$e=await f(Q,Me),we=[];for(const Fe of $e){const Oe=await this.processor(Fe),Ye=await this.model({...Se,...Oe}),ye=(0,l.softmax)(Ye.logits_per_audio.data);we.push([...ye].map((Ze,Ke)=>({score:Ze,label:B[Ke]})))}return Ce?we[0]:we}}class te extends M{constructor(Q){super(Q)}async _call(Q,B={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(Q,B);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(Q,B);case"moonshine":return this._call_moonshine(Q,B);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(Q,B){B.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),B.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const me=!Array.isArray(Q);me&&(Q=[Q]);const Ce=this.processor.feature_extractor.config.sampling_rate,Pe=await f(Q,Ce),Se=[];for(const Me of Pe){const $e=await this.processor(Me),Fe=(await this.model($e)).logits[0],Oe=[];for(const ye of Fe)Oe.push((0,l.max)(ye.data)[1]);const Ye=this.tokenizer.decode(Oe);Se.push({text:Ye})}return me?Se[0]:Se}async _call_whisper(Q,B){const me=B.return_timestamps??!1,Ce=B.chunk_length_s??0,Pe=B.force_full_sequences??!1;let Se=B.stride_length_s??null;const Me={...B};me==="word"&&(Me.return_token_timestamps=!0,Me.return_timestamps=!1);const $e=!Array.isArray(Q);$e&&(Q=[Q]);const we=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Fe=this.processor.feature_extractor.config.hop_length,Oe=this.processor.feature_extractor.config.sampling_rate,Ye=await f(Q,Oe),ye=[];for(const Ze of Ye){let Ke=[];if(Ce>0){if(Se===null)Se=Ce/6;else if(Ce<=Se)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const ze=Oe*Ce,Je=Oe*Se,nt=ze-2*Je;let It=0;for(;;){const Ct=It+ze,Mt=Ze.subarray(It,Ct),yr=await this.processor(Mt),$r=It===0,Nr=Ct>=Ze.length;if(Ke.push({stride:[Mt.length,$r?0:Je,Nr?0:Je],input_features:yr.input_features,is_last:Nr}),Nr)break;It+=nt}}else Ke=[{stride:[Ze.length,0,0],input_features:(await this.processor(Ze)).input_features,is_last:!0}];for(const ze of Ke){Me.num_frames=Math.floor(ze.stride[0]/Fe);const Je=await this.model.generate({inputs:ze.input_features,...Me});me==="word"?(ze.tokens=Je.sequences.tolist()[0],ze.token_timestamps=Je.token_timestamps.tolist()[0].map(nt=>(0,l.round)(nt,2))):ze.tokens=Je[0].tolist(),ze.stride=ze.stride.map(nt=>nt/Oe)}const[st,Qe]=this.tokenizer._decode_asr(Ke,{time_precision:we,return_timestamps:me,force_full_sequences:Pe});ye.push({text:st,...Qe})}return $e?ye[0]:ye}async _call_moonshine(Q,B){const me=!Array.isArray(Q);me&&(Q=[Q]);const Ce=this.processor.feature_extractor.config.sampling_rate,Pe=await f(Q,Ce),Se=[];for(const Me of Pe){const $e=await this.processor(Me),we=Math.floor(Me.length/Ce)*6,Fe=await this.model.generate({max_new_tokens:we,...B,...$e}),Oe=this.processor.batch_decode(Fe,{skip_special_tokens:!0})[0];Se.push({text:Oe})}return me?Se[0]:Se}}class H extends M{constructor(Q){super(Q)}async _call(Q,B={}){const me=Array.isArray(Q),Ce=await u(Q),{pixel_values:Pe}=await this.processor(Ce),Se=[];for(const Me of Pe){Me.dims=[1,...Me.dims];const $e=await this.model.generate({inputs:Me,...B}),we=this.tokenizer.batch_decode($e,{skip_special_tokens:!0}).map(Fe=>({generated_text:Fe.trim()}));Se.push(we)}return me?Se:Se[0]}}class ee extends M{constructor(Q){super(Q)}async _call(Q,{top_k:B=5}={}){const me=await u(Q),{pixel_values:Ce}=await this.processor(me),Pe=await this.model({pixel_values:Ce}),Se=this.model.config.id2label,Me=[];for(const $e of Pe.logits){const we=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)($e.data),$e.dims),B),Fe=we[0].tolist(),Ye=we[1].tolist().map((ye,Ze)=>({label:Se?Se[ye]:`LABEL_${ye}`,score:Fe[Ze]}));Me.push(Ye)}return Array.isArray(Q)?Me:Me[0]}}class Z extends M{constructor(Q){super(Q),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(Q,{threshold:B=.5,mask_threshold:me=.5,overlap_mask_area_threshold:Ce=.8,label_ids_to_fuse:Pe=null,target_sizes:Se=null,subtask:Me=null}={}){if(Array.isArray(Q)&&Q.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const we=await u(Q),Fe=we.map(ze=>[ze.height,ze.width]),Oe=await this.processor(we),{inputNames:Ye,outputNames:ye}=this.model.sessions.model;if(!Ye.includes("pixel_values")){if(Ye.length!==1)throw Error(`Expected a single input name, but got ${Ye.length} inputs: ${Ye}.`);const ze=Ye[0];if(ze in Oe)throw Error(`Input name ${ze} already exists in the inputs.`);Oe[ze]=Oe.pixel_values}const Ze=await this.model(Oe);let Ke=null;if(Me!==null)Ke=this.subtasks_mapping[Me];else if(this.processor.image_processor){for(const[ze,Je]of Object.entries(this.subtasks_mapping))if(Je in this.processor.image_processor){Ke=this.processor.image_processor[Je].bind(this.processor.image_processor),Me=ze;break}}const st=this.model.config.id2label,Qe=[];if(Me)if(Me==="panoptic"||Me==="instance"){const ze=Ke(Ze,B,me,Ce,Pe,Se??Fe)[0],Je=ze.segmentation;for(const nt of ze.segments_info){const It=new Uint8ClampedArray(Je.data.length);for(let Mt=0;Mtyr<-1e-5||yr>1+1e-5)&&Ct.sigmoid_();const Mt=await d.RawImage.fromTensor(Ct.mul_(255).to("uint8")).resize(It[1],It[0]);Qe.push({label:null,score:null,mask:Mt})}}return Qe}}class oe extends Z{constructor(Q){super(Q)}async _call(Q,B={}){if(Array.isArray(Q)&&Q.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const Ce=await u(Q),Pe=await super._call(Q,B);return Ce.map((Me,$e)=>{const we=Me.clone();return we.putAlpha(Pe[$e].mask),we})}}class pe extends M{constructor(Q){super(Q)}async _call(Q,B,{hypothesis_template:me="This is a photo of {}"}={}){const Ce=Array.isArray(Q),Pe=await u(Q),Se=B.map(Ye=>me.replace("{}",Ye)),Me=this.tokenizer(Se,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:$e}=await this.processor(Pe),we=await this.model({...Me,pixel_values:$e}),Fe=this.model.config.model_type==="siglip"?Ye=>Ye.sigmoid().data:Ye=>(0,l.softmax)(Ye.data),Oe=[];for(const Ye of we.logits_per_image){const Ze=[...Fe(Ye)].map((Ke,st)=>({score:Ke,label:B[st]}));Ze.sort((Ke,st)=>st.score-Ke.score),Oe.push(Ze)}return Ce?Oe:Oe[0]}}class ue extends M{constructor(Q){super(Q)}async _call(Q,{threshold:B=.9,percentage:me=!1}={}){const Ce=Array.isArray(Q);if(Ce&&Q.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Pe=await u(Q),Se=me?null:Pe.map(ye=>[ye.height,ye.width]),{pixel_values:Me,pixel_mask:$e}=await this.processor(Pe),we=await this.model({pixel_values:Me,pixel_mask:$e}),Fe=this.processor.image_processor.post_process_object_detection(we,B,Se),Oe=this.model.config.id2label,Ye=Fe.map(ye=>ye.boxes.map((Ze,Ke)=>({score:ye.scores[Ke],label:Oe[ye.classes[Ke]],box:_(Ze,!me)})));return Ce?Ye:Ye[0]}}class j extends M{constructor(Q){super(Q)}async _call(Q,B,{threshold:me=.1,top_k:Ce=null,percentage:Pe=!1}={}){const Se=Array.isArray(Q),Me=await u(Q),$e=this.tokenizer(B,{padding:!0,truncation:!0}),we=await this.processor(Me),Fe=[];for(let Oe=0;Oe({score:Qe.scores[Je],label:Qe.labels[Je],box:_(ze,!Pe)}))}else{const Qe=this.processor.image_processor.post_process_object_detection(Ke,me,ye,!0)[0];st=Qe.boxes.map((ze,Je)=>({score:Qe.scores[Je],label:B[Qe.classes[Je]],box:_(ze,!Pe)}))}st.sort((Qe,ze)=>ze.score-Qe.score),Ce!==null&&(st=st.slice(0,Ce)),Fe.push(st)}return Se?Fe:Fe[0]}}class F extends M{constructor(Q){super(Q)}async _call(Q,B,me={}){const Ce=(await u(Q))[0],{pixel_values:Pe}=await this.processor(Ce),Se=`${B}`,Me=this.tokenizer(Se,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,$e=await this.model.generate({inputs:Pe,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Me,...me}),Fe=this.tokenizer.batch_decode($e)[0].match(/(.*?)<\/s_answer>/);let Oe=null;return Fe&&Fe.length>=2&&(Oe=Fe[1].trim()),[{answer:Oe}]}}class W extends M{constructor(B){super(B);J(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=B.vocoder??null}async _call(B,{speaker_embeddings:me=null}={}){return this.processor?this._call_text_to_spectrogram(B,{speaker_embeddings:me}):this._call_text_to_waveform(B)}async _call_text_to_waveform(B){const me=this.tokenizer(B,{padding:!0,truncation:!0}),{waveform:Ce}=await this.model(me),Pe=this.model.config.sampling_rate;return new c.RawAudio(Ce.data,Pe)}async _call_text_to_spectrogram(B,{speaker_embeddings:me}){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 me=="string"||me instanceof URL)&&(me=new Float32Array(await(await fetch(me)).arrayBuffer())),me instanceof Float32Array)me=new p.Tensor("float32",me,[1,me.length]);else if(!(me instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Ce}=this.tokenizer(B,{padding:!0,truncation:!0}),{waveform:Pe}=await this.model.generate_speech(Ce,me,{vocoder:this.vocoder}),Se=this.processor.feature_extractor.config.sampling_rate;return new c.RawAudio(Pe.data,Se)}}class se extends M{constructor(Q){super(Q)}async _call(Q){const B=await u(Q),me=await this.processor(B),Ce=await this.model(me),Pe=[];for(const Se of Ce.reconstruction){const Me=Se.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Pe.push(d.RawImage.fromTensor(Me))}return Pe.length>1?Pe:Pe[0]}}class _e extends M{constructor(Q){super(Q)}async _call(Q){const B=await u(Q),me=await this.processor(B),{predicted_depth:Ce}=await this.model(me),Pe=[];for(let Se=0;Se1?Pe:Pe[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:w,model:o.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:b,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:v,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:x,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:E,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:G,model:o.AutoModelForAudioClassification,processor:n.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:N,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:W,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:oe,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:pe,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:D,model:o.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:n.AutoProcessor,pipeline:K,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 Le(Ie,Q=null,{progress_callback:B=null,config:me=null,cache_dir:Ce=null,local_files_only:Pe=!1,revision:Se="main",device:Me=null,dtype:$e=null,subfolder:we="onnx",use_external_data_format:Fe=null,model_file_name:Oe=null,session_options:Ye={}}={}){Ie=ve[Ie]??Ie;const ye=ie[Ie.split("_",1)[0]];if(!ye)throw Error(`Unsupported pipeline: ${Ie}. Must be one of [${Object.keys(ie)}]`);Q||(Q=ye.default.model,console.log(`No model specified. Using default model: "${Q}".`));const Ze={progress_callback:B,config:me,cache_dir:Ce,local_files_only:Pe,revision:Se,device:Me,dtype:$e,subfolder:we,use_external_data_format:Fe,model_file_name:Oe,session_options:Ye},Ke=new Map([["tokenizer",ye.tokenizer],["model",ye.model],["processor",ye.processor]]),st=await Ge(Ke,Q,Ze);st.task=Ie,(0,a.dispatchCallback)(B,{status:"ready",task:Ie,model:Q});const Qe=ye.pipeline;return new Qe(st)}async function Ge(Ie,Q,B){const me=Object.create(null),Ce=[];for(const[Pe,Se]of Ie.entries()){if(!Se)continue;let Me;Array.isArray(Se)?Me=new Promise(async($e,we)=>{var Oe,Ye;let Fe;for(const ye of Se){if(ye===null){$e(null);return}try{$e(await ye.from_pretrained(Q,B));return}catch(Ze){if((Oe=Ze.message)!=null&&Oe.includes("Unsupported model type"))Fe=Ze;else if((Ye=Ze.message)!=null&&Ye.includes("Could not locate file"))Fe=Ze;else{we(Ze);return}}}we(Fe)}):Me=Se.from_pretrained(Q,B),me[Pe]=Me,Ce.push(Me)}await Promise.all(Ce);for(const[Pe,Se]of Object.entries(me))me[Pe]=await Se;return me}}),"./src/tokenizers.js":((e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Os,AutoTokenizer:()=>xn,BartTokenizer:()=>tt,BertTokenizer:()=>Fs,BlenderbotSmallTokenizer:()=>Qt,BlenderbotTokenizer:()=>rt,BloomTokenizer:()=>Hr,CLIPTokenizer:()=>Us,CamembertTokenizer:()=>Ae,CodeGenTokenizer:()=>ms,CodeLlamaTokenizer:()=>ur,CohereTokenizer:()=>bn,ConvBertTokenizer:()=>q,DebertaTokenizer:()=>S,DebertaV2Tokenizer:()=>X,DistilBertTokenizer:()=>ge,ElectraTokenizer:()=>ft,Ernie4_5_Tokenizer:()=>vn,EsmTokenizer:()=>Ls,FalconTokenizer:()=>Ar,GPT2Tokenizer:()=>vt,GPTNeoXTokenizer:()=>Ds,GemmaTokenizer:()=>ps,Grok1Tokenizer:()=>Jr,HerbertTokenizer:()=>R,LlamaTokenizer:()=>Ir,M2M100Tokenizer:()=>hr,MBart50Tokenizer:()=>qt,MBartTokenizer:()=>At,MPNetTokenizer:()=>ds,MarianTokenizer:()=>Re,MgpstrTokenizer:()=>yn,MobileBertTokenizer:()=>St,NllbTokenizer:()=>Ps,NougatTokenizer:()=>Cs,PreTrainedTokenizer:()=>ht,Qwen2Tokenizer:()=>vr,RoFormerTokenizer:()=>re,RobertaTokenizer:()=>Ur,SiglipTokenizer:()=>Wr,SpeechT5Tokenizer:()=>Ws,SqueezeBertTokenizer:()=>Ht,T5Tokenizer:()=>pt,TokenizerModel:()=>K,VitsTokenizer:()=>rs,Wav2Vec2CTCTokenizer:()=>je,WhisperTokenizer:()=>ir,XLMRobertaTokenizer:()=>us,XLMTokenizer:()=>ot,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(de,I){const V=await Promise.all([(0,n.getModelJSON)(de,"tokenizer.json",!0,I),(0,n.getModelJSON)(de,"tokenizer_config.json",!0,I)]);return I.legacy!==null&&(V[1].legacy=I.legacy),V}function u(de,I){const V=[];let Y=0;for(const ae of de.matchAll(I)){const ce=ae[0];Y0&&V.push(ce),Y=ae.index+ce.length}return Y=19968&&de<=40959||de>=13312&&de<=19903||de>=131072&&de<=173791||de>=173824&&de<=177983||de>=177984&&de<=178207||de>=178208&&de<=183983||de>=63744&&de<=64255||de>=194560&&de<=195103}function E(de,I,V){const Y=[];let ae=0;for(;aethis.tokens_to_ids.get(V)??this.unk_token_id)}convert_ids_to_tokens(I){return I.map(V=>this.vocab[V]??this.unk_token)}}class G extends K{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[V,Y]of this.tokens_to_ids)this.vocab[Y]=V}encode(I){const V=[];for(const Y of I){const ae=[...Y];if(ae.length>this.max_input_chars_per_word){V.push(this.unk_token);continue}let ce=!1,xe=0;const Ve=[];for(;xe0&&(et=this.config.continuing_subword_prefix+et),this.tokens_to_ids.has(et)){We=et;break}--He}if(We===null){ce=!0;break}Ve.push(We),xe=He}ce?V.push(this.unk_token):V.push(...Ve)}return V}}class N extends K{constructor(I,V){super(I);const Y=I.vocab.length;this.vocab=new Array(Y),this.scores=new Array(Y);for(let ae=0;ae[ae,ce])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=V.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 V=I.chars,Y=1;let ae=0;for(;ae{const de=[...Array.from({length:94},(ae,ce)=>ce+33),...Array.from({length:12},(ae,ce)=>ce+161),...Array.from({length:82},(ae,ce)=>ce+174)],I=de.slice();let V=0;for(let ae=0;ae<256;++ae)de.includes(ae)||(de.push(ae),I.push(256+V),V+=1);const Y=I.map(ae=>String.fromCharCode(ae));return Object.fromEntries(de.map((ae,ce)=>[ae,Y[ce]]))})(),H=(0,o.reverseDictionary)(te);class ee extends K{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,ae]of this.tokens_to_ids)this.vocab[ae]=Y;const V=Array.isArray(I.merges[0]);this.merges=V?I.merges:I.merges.map(Y=>Y.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((Y,ae)=>[JSON.stringify(Y),ae])),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 V=this.cache.get(I);if(V!==void 0)return V;const Y=Array.from(I);this.end_of_word_suffix&&(Y[Y.length-1]+=this.end_of_word_suffix);let ae=[];if(Y.length>1){const ce=new l.PriorityQueue((He,We)=>He.score`<0x${Ve.toString(16).toUpperCase().padStart(2,"0")}>`);xe.every(Ve=>this.tokens_to_ids.has(Ve))?V.push(...xe):V.push(this.unk_token)}else V.push(this.unk_token)}return V}}class Z extends K{constructor(I,V){super(I),this.tokens_to_ids=_(V.target_lang?I.vocab[V.target_lang]:I.vocab),this.bos_token=V.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=V.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=V.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=V.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,ae]of this.tokens_to_ids)this.vocab[ae]=Y}encode(I){return I}}class oe 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 Nr(I);case"Sequence":return new Ge(I);case"Replace":return new pe(I);case"NFC":return new j(I);case"NFD":return new F(I);case"NFKC":return new W(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 Le(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 pe extends oe{normalize(I){const V=f(this.config.pattern);return V===null?I:I.replaceAll(V,this.config.content)}}class ue extends oe{constructor(){super(...arguments);J(this,"form")}normalize(V){return V=V.normalize(this.form),V}}class j extends ue{constructor(){super(...arguments);J(this,"form","NFC")}}class F extends ue{constructor(){super(...arguments);J(this,"form","NFD")}}class W extends ue{constructor(){super(...arguments);J(this,"form","NFKC")}}class se extends ue{constructor(){super(...arguments);J(this,"form","NFKD")}}class _e extends oe{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 oe{normalize(I){return I=w(I),I}}class ve extends oe{normalize(I){return I=I.toLowerCase(),I}}class Le extends oe{normalize(I){return I=this.config.prepend+I,I}}class Ge extends oe{constructor(I){super(I),this.normalizers=I.normalizers.map(V=>oe.fromConfig(V))}normalize(I){return this.normalizers.reduce((V,Y)=>Y.normalize(V),I)}}class Ie extends oe{_tokenize_chinese_chars(I){const V=[];for(let Y=0;Ythis.pre_tokenize_text(Y,V)):this.pre_tokenize_text(I,V)).flat()}_call(I,V){return this.pre_tokenize(I,V)}}class B extends Q{constructor(I){super(),this.pattern=new RegExp(`[^\\s${x}]+|[${x}]`,"gu")}pre_tokenize_text(I,V){return I.trim().match(this.pattern)||[]}}class me extends Q{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,V){return this.add_prefix_space&&!I.startsWith(" ")&&(I=" "+I),(this.use_regex?I.match(this.pattern)||[]:[I]).map(ae=>Array.from(this.text_encoder.encode(ae),ce=>this.byte_encoder[ce]).join(""))}}class Ce extends Q{constructor(I){super(),this.config=I,this.pattern=f(this.config.pattern,this.config.invert)}pre_tokenize_text(I,V){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(ae=>ae):u(I,this.pattern)}}class Pe extends Q{constructor(I){super(),this.config=I,this.pattern=new RegExp(`[^${x}]+|[${x}]+`,"gu")}pre_tokenize_text(I,V){return I.match(this.pattern)||[]}}class Se extends Q{constructor(I){super(),this.config=I;const V=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(V,"gu")}pre_tokenize_text(I,V){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 Fe(I);case"ByteLevel":return new Oe(I);case"RobertaProcessing":return new we(I);case"BertProcessing":return new $e(I);case"Sequence":return new Ye(I);default:throw new Error(`Unknown PostProcessor type: ${I.type}`)}}post_process(I,...V){throw Error("post_process should be implemented in subclass.")}_call(I,...V){return this.post_process(I,...V)}}class $e extends Me{constructor(I){super(I),this.cls=I.cls[0],this.sep=I.sep[0]}post_process(I,V=null,{add_special_tokens:Y=!0}={}){Y&&(I=(0,o.mergeArrays)([this.cls],I,[this.sep]));let ae=new Array(I.length).fill(0);if(V!==null){const ce=Y&&this instanceof we?[this.sep]:[],xe=Y?[this.sep]:[];I=(0,o.mergeArrays)(I,ce,V,xe),ae=(0,o.mergeArrays)(ae,new Array(V.length+ce.length+xe.length).fill(1))}return{tokens:I,token_type_ids:ae}}}class we extends $e{}class Fe extends Me{constructor(I){super(I),this.single=I.single,this.pair=I.pair}post_process(I,V=null,{add_special_tokens:Y=!0}={}){const ae=V===null?this.single:this.pair;let ce=[],xe=[];for(const Ve of ae)"SpecialToken"in Ve?Y&&(ce.push(Ve.SpecialToken.id),xe.push(Ve.SpecialToken.type_id)):"Sequence"in Ve&&(Ve.Sequence.id==="A"?(ce=(0,o.mergeArrays)(ce,I),xe=(0,o.mergeArrays)(xe,new Array(I.length).fill(Ve.Sequence.type_id))):Ve.Sequence.id==="B"&&(ce=(0,o.mergeArrays)(ce,V),xe=(0,o.mergeArrays)(xe,new Array(V.length).fill(Ve.Sequence.type_id))));return{tokens:ce,token_type_ids:xe}}}class Oe extends Me{post_process(I,V=null){return V&&(I=(0,o.mergeArrays)(I,V)),{tokens:I}}}class Ye extends Me{constructor(I){super(I),this.processors=I.processors.map(V=>Me.fromConfig(V))}post_process(I,V=null,Y={}){let ae;for(const ce of this.processors)if(ce instanceof Oe)I=ce.post_process(I).tokens,V&&(V=ce.post_process(V).tokens);else{const xe=ce.post_process(I,V,Y);I=xe.tokens,ae=xe.token_type_ids}return{tokens:I,token_type_ids:ae}}}class ye 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 ze(I);case"Metaspace":return new $r(I);case"ByteLevel":return new Je(I);case"Replace":return new Ze(I);case"ByteFallback":return new Ke(I);case"Fuse":return new st(I);case"Strip":return new Qe(I);case"Sequence":return new It(I);case"CTC":return new nt(I);case"BPEDecoder":return new Ct(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 ye{decode_chain(I){const V=f(this.config.pattern);return V===null?I:I.map(Y=>Y.replaceAll(V,this.config.content))}}class Ke extends ye{constructor(I){super(I),this.text_decoder=new TextDecoder}decode_chain(I){const V=[];let Y=[];for(const ae of I){let ce=null;if(ae.length===6&&ae.startsWith("<0x")&&ae.endsWith(">")){const xe=parseInt(ae.slice(3,5),16);isNaN(xe)||(ce=xe)}if(ce!==null)Y.push(ce);else{if(Y.length>0){const xe=this.text_decoder.decode(Uint8Array.from(Y));V.push(xe),Y=[]}V.push(ae)}}if(Y.length>0){const ae=this.text_decoder.decode(Uint8Array.from(Y));V.push(ae),Y=[]}return V}}class st extends ye{decode_chain(I){return[I.join("")]}}class Qe extends ye{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(V=>{let Y=0;for(let ce=0;ce(Y!==0&&(V.startsWith(this.config.prefix)?V=V.replace(this.config.prefix,""):V=" "+V),this.cleanup&&(V=k(V)),V))}}class Je extends ye{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 V=I.join(""),Y=new Uint8Array([...V].map(ce=>this.byte_decoder[ce]));return this.text_decoder.decode(Y)}decode_chain(I){const V=[];let Y=[];for(const ae of I)this.added_tokens.find(ce=>ce.content===ae)!==void 0?(Y.length>0&&(V.push(this.convert_tokens_to_string(Y)),Y=[]),V.push(ae)):Y.push(ae);return Y.length>0&&V.push(this.convert_tokens_to_string(Y)),V}}class nt extends ye{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 V=[I[0]];for(let ce=1;cece!==this.pad_token).join("");return this.cleanup&&(ae=k(ae).replaceAll(this.word_delimiter_token," ").trim()),ae}decode_chain(I){return[this.convert_tokens_to_string(I)]}}class It extends ye{constructor(I){super(I),this.decoders=I.decoders.map(V=>ye.fromConfig(V))}decode_chain(I){return this.decoders.reduce((V,Y)=>Y.decode_chain(V),I)}}class Ct extends ye{constructor(I){super(I),this.suffix=this.config.suffix}decode_chain(I){return I.map((V,Y)=>V.replaceAll(this.suffix,Y===I.length-1?"":" "))}}class Mt extends ye{decode_chain(I){let V="";for(let Y=1;YY.normalize("NFKC")).join("~"):I=I.normalize("NFKC"),I}}class Vr extends Q{constructor(I){super(),this.tokenizers=I.pretokenizers.map(V=>Q.fromConfig(V))}pre_tokenize_text(I,V){return this.tokenizers.reduce((Y,ae)=>ae.pre_tokenize(Y,V),[I])}}class sr extends Q{constructor(I){super()}pre_tokenize_text(I,V){return I.match(/\w+|[^\w\s]+/g)||[]}}class kr extends Q{constructor(I){super()}pre_tokenize_text(I,V){return v(I)}}class Zs extends Q{constructor(I){super(),this.config=I,this.pattern=f(this.config.pattern),this.content=this.config.content}pre_tokenize_text(I,V){return this.pattern===null?[I]:[I.replaceAll(this.pattern,this.config.content)]}}const en=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function tn(de,I,V,Y){for(const ae of Object.keys(de)){const ce=I-de[ae].length,xe=V(ae),Ve=new Array(ce).fill(xe);de[ae]=Y==="right"?(0,o.mergeArrays)(de[ae],Ve):(0,o.mergeArrays)(Ve,de[ae])}}function cs(de,I){for(const V of Object.keys(de))de[V].length=I}class ht extends s.Callable{constructor(V,Y){super();J(this,"return_token_type_ids",!1);J(this,"padding_side","right");this.config=Y,this.normalizer=oe.fromConfig(V.normalizer),this.pre_tokenizer=Q.fromConfig(V.pre_tokenizer),this.model=K.fromConfig(V.model,Y),this.post_processor=Me.fromConfig(V.post_processor),this.decoder=ye.fromConfig(V.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ae of V.added_tokens){const ce=new D(ae);this.added_tokens.push(ce),this.model.tokens_to_ids.set(ce.content,ce.id),this.model.vocab[ce.id]=ce.content,ce.special&&(this.special_tokens.push(ce.content),this.all_special_ids.push(ce.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(ae=>ae.content)),this.added_tokens_map=new Map(this.added_tokens.map(ae=>[ae.content,ae])),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 ae=Object.create(null);for(const{name:ce,template:xe}of this.chat_template){if(typeof ce!="string"||typeof xe!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ae[ce]=xe}this.chat_template=ae}this._compiled_template_cache=new Map}getToken(...V){for(const Y of V){const ae=this.config[Y];if(ae)if(typeof ae=="object"){if(ae.__type==="AddedToken")return ae.content;throw Error(`Unknown token: ${ae}`)}else return ae}return null}static async from_pretrained(V,{progress_callback:Y=null,config:ae=null,cache_dir:ce=null,local_files_only:xe=!1,revision:Ve="main",legacy:He=null}={}){const We=await d(V,{progress_callback:Y,config:ae,cache_dir:ce,local_files_only:xe,revision:Ve,legacy:He});return new this(...We)}_call(V,{text_pair:Y=null,add_special_tokens:ae=!0,padding:ce=!1,truncation:xe=null,max_length:Ve=null,return_tensor:He=!0,return_token_type_ids:We=null}={}){const et=Array.isArray(V);let wt;if(et){if(V.length===0)throw Error("text array must be non-empty");if(Y!==null){if(Array.isArray(Y)){if(V.length!==Y.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");wt=V.map((Lt,Zt)=>this._encode_plus(Lt,{text_pair:Y[Zt],add_special_tokens:ae,return_token_type_ids:We}))}else wt=V.map(Lt=>this._encode_plus(Lt,{add_special_tokens:ae,return_token_type_ids:We}))}else{if(V==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).");wt=[this._encode_plus(V,{text_pair:Y,add_special_tokens:ae,return_token_type_ids:We})]}if(Ve===null?Ve=this.model_max_length:xe===null&&(ce===!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'`."),Ve=this.model_max_length):ce===!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."),xe=!0)),ce===!0&&(Ve=Math.min((0,i.max)(wt.map(Lt=>Lt.input_ids.length))[0],Ve??1/0)),Ve=Math.min(Ve,this.model_max_length??1/0),ce||xe)for(let Lt=0;LtVe?xe&&cs(wt[Lt],Ve):ce&&tn(wt[Lt],Ve,Zt=>Zt==="input_ids"?this.pad_token_id:0,this.padding_side));const Bt={};if(He){if(!(ce&&xe)&&wt.some(Zt=>{var Gt;for(const fr of Object.keys(Zt))if(Zt[fr].length!==((Gt=wt[0][fr])==null?void 0:Gt.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=[wt.length,wt[0].input_ids.length];for(const Zt of Object.keys(wt[0]))Bt[Zt]=new a.Tensor("int64",BigInt64Array.from(wt.flatMap(Gt=>Gt[Zt]).map(BigInt)),Lt)}else{for(const Lt of Object.keys(wt[0]))Bt[Lt]=wt.map(Zt=>Zt[Lt]);if(!et)for(const Lt of Object.keys(Bt))Bt[Lt]=Bt[Lt][0]}return Bt}_encode_text(V){if(V===null)return null;const Y=this.added_tokens_splitter.split(V);for(let ce=0;ce0&&(Y[ce-1]=Y[ce-1].trimEnd()),xe.rstrip&&ce{if(ce.length===0)return[];if(this.added_tokens_map.has(ce))return[ce];if(this.remove_space===!0&&(ce=ce.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(ce=b(ce)),this.normalizer!==null&&(ce=this.normalizer(ce)),ce.length===0)return[];const Ve=this.pre_tokenizer!==null?this.pre_tokenizer(ce,{section_index:xe}):[ce];return this.model(Ve)})}_encode_plus(V,{text_pair:Y=null,add_special_tokens:ae=!0,return_token_type_ids:ce=null}={}){const{tokens:xe,token_type_ids:Ve}=this._tokenize_helper(V,{pair:Y,add_special_tokens:ae}),He=this.model.convert_tokens_to_ids(xe),We={input_ids:He,attention_mask:new Array(He.length).fill(1)};return(ce??this.return_token_type_ids)&&Ve&&(We.token_type_ids=Ve),We}_tokenize_helper(V,{pair:Y=null,add_special_tokens:ae=!1}={}){const ce=this._encode_text(V),xe=this._encode_text(Y);return this.post_processor?this.post_processor(ce,xe,{add_special_tokens:ae}):{tokens:(0,o.mergeArrays)(ce??[],xe??[])}}tokenize(V,{pair:Y=null,add_special_tokens:ae=!1}={}){return this._tokenize_helper(V,{pair:Y,add_special_tokens:ae}).tokens}encode(V,{text_pair:Y=null,add_special_tokens:ae=!0,return_token_type_ids:ce=null}={}){return this._encode_plus(V,{text_pair:Y,add_special_tokens:ae,return_token_type_ids:ce}).input_ids}batch_decode(V,Y={}){return V instanceof a.Tensor&&(V=V.tolist()),V.map(ae=>this.decode(ae,Y))}decode(V,Y={}){if(V instanceof a.Tensor&&(V=M(V)),!Array.isArray(V)||V.length===0||!(0,o.isIntegralNumber)(V[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(V,Y)}decode_single(V,{skip_special_tokens:Y=!1,clean_up_tokenization_spaces:ae=null}){let ce=this.model.convert_ids_to_tokens(V);Y&&(ce=ce.filter(Ve=>!this.special_tokens.includes(Ve)));let xe=this.decoder?this.decoder(ce):ce.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(xe=xe.replaceAll(this.decoder.end_of_word_suffix," "),Y&&(xe=xe.trim())),(ae??this.clean_up_tokenization_spaces)&&(xe=k(xe)),xe}get_chat_template({chat_template:V=null,tools:Y=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ae=this.chat_template;if(V!==null&&Object.hasOwn(ae,V))V=ae[V];else if(V===null)if(Y!==null&&"tool_use"in ae)V=ae.tool_use;else if("default"in ae)V=ae.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(ae).sort()}.`)}else if(V===null)if(this.chat_template)V=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 V}apply_chat_template(V,{tools:Y=null,documents:ae=null,chat_template:ce=null,add_generation_prompt:xe=!1,tokenize:Ve=!0,padding:He=!1,truncation:We=!1,max_length:et=null,return_tensor:wt=!0,return_dict:Bt=!1,tokenizer_kwargs:Lt={},...Zt}={}){if(ce=this.get_chat_template({chat_template:ce,tools:Y}),typeof ce!="string")throw Error(`chat_template must be a string, but got ${typeof ce}`);let Gt=this._compiled_template_cache.get(ce);Gt===void 0&&(Gt=new c.Template(ce),this._compiled_template_cache.set(ce,Gt));const fr=Object.create(null);for(const dr of en){const wr=this.getToken(dr);wr&&(fr[dr]=wr)}const gr=Gt.render({messages:V,add_generation_prompt:xe,tools:Y,documents:ae,...fr,...Zt});if(Ve){const dr=this._call(gr,{add_special_tokens:!1,padding:He,truncation:We,max_length:et,return_tensor:wt,...Lt});return Bt?dr:dr.input_ids}return gr}}class Fs extends ht{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class Os extends ht{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class St extends ht{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class Ht extends ht{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class S extends ht{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class X extends ht{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class R extends ht{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class q extends ht{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class re extends ht{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class ge extends ht{}class Ae extends ht{}class ot extends ht{constructor(V,Y){super(V,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 ht{constructor(){super(...arguments);J(this,"return_token_type_ids",!0)}}class pt extends ht{}class vt extends ht{}class tt extends ht{}class At extends ht{constructor(I,V){super(I,V),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,V,Y){return Br(this,I,V,Y)}}class qt extends At{}class Ur extends ht{}class Hr extends ht{}const nr="▁";class Ir extends ht{constructor(V,Y){super(V,Y);J(this,"padding_side","left");this.legacy=Y.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new yr({replacement:nr,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(V){if(V===null)return null;if(this.legacy||V.length===0)return super._encode_text(V);let Y=super._encode_text(nr+V.replaceAll(nr," "));return Y.length>1&&Y[0]===nr&&this.special_tokens.includes(Y[1])&&(Y=Y.slice(1)),Y}}class ur extends ht{}class us extends ht{}class ds extends ht{}class Ar extends ht{}class Ds extends ht{}class Ls extends ht{}class vr extends ht{}class ps extends ht{}class Jr extends ht{}function Br(de,I,V,Y){if(!("language_codes"in de)||!Array.isArray(de.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in de)||!(de.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in de)||typeof de.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ae=Y.src_lang,ce=Y.tgt_lang;if(!de.language_codes.includes(ce))throw new Error(`Target language code "${ce}" is not valid. Must be one of: {${de.language_codes.join(", ")}}`);if(ae!==void 0){if(!de.language_codes.includes(ae))throw new Error(`Source language code "${ae}" is not valid. Must be one of: {${de.language_codes.join(", ")}}`);for(const xe of de.post_processor.config.single)if("SpecialToken"in xe&&de.languageRegex.test(xe.SpecialToken.id)){xe.SpecialToken.id=de.lang_to_token(ae);break}}return Y.forced_bos_token_id=de.model.convert_tokens_to_ids([de.lang_to_token(ce)])[0],de._call(I,V)}class Ps extends ht{constructor(I,V){super(I,V),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,V,Y){return Br(this,I,V,Y)}}class hr extends ht{constructor(I,V){super(I,V),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,V,Y){return Br(this,I,V,Y)}}class ir extends ht{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(I,{return_timestamps:V=!1,return_language:Y=!1,time_precision:ae=null,force_full_sequences:ce=!0}={}){if(ae===null)throw Error("Must specify time_precision");let xe=null;const Ve=V==="word";function He(){return{language:xe,timestamp:[null,null],text:""}}const We=[];let et=He(),wt=0;const Bt=this.timestamp_begin,Zt=Bt+1500;let Gt=[],fr=[],gr=!1,dr=null;const wr=new Set(this.all_special_ids);for(const Yt of I){const Mr=Yt.tokens,Fr=Ve?Yt.token_timestamps:null;let Yr=null,Ss=Bt;if("stride"in Yt){const[ar,pr,_r]=Yt.stride;if(wt-=pr,dr=ar-_r,pr&&(Ss=pr/ae+Bt),_r)for(let er=Mr.length-1;er>=0;--er){const qr=Number(Mr[er]);if(qr>=Bt){if(Yr!==null&&(qr-Bt)*ae=Bt&&pr<=Zt){const _r=(pr-Bt)*ae+wt,er=(0,i.round)(_r,2);if(Yr!==null&&pr>=Yr)gr=!0;else if(gr||Gt.length>0&&pr0?(Gt.push(Or),Ve&&fr.push(hs)):Gt.every(ar=>ar.length===0)&&(et=He(),Gt=[],Or=[],fr=[],hs=[])}if(Gt.length>0){if(ce&&V)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[Yt,Mr]=this.findLongestCommonSequence(Gt,fr),Fr=this.decode(Yt);et.text=Fr,Ve&&(et.words=this.collateWordTimestamps(Yt,Mr,xe)),We.push(et)}let xr=Object.create(null);const ss=We.map(Yt=>Yt.text).join("");if(V||Y){for(let Yt=0;Yt0;let Ve=xe?[]:null,He=xe?V[0]:null;for(let We=1;Wepr===Ss[_r]&&He[ss+_r]<=V[We][Fr+_r]).length:Or=Mr.filter((pr,_r)=>pr===Ss[_r]).length;const hs=xr/1e4,ar=Or/xr+hs;Or>1&&ar>wt&&(wt=ar,Bt=[ss,Yt,Fr,Yr])}const[Zt,Gt,fr,gr]=Bt,dr=Math.floor((Gt+Zt)/2),wr=Math.floor((gr+fr)/2);ce.push(...Y.slice(0,dr)),Y=et.slice(wr),ae=Y.length,xe&&(Ve.push(...He.slice(0,dr)),He=V[We].slice(wr))}return ce.push(...Y),xe?(Ve.push(...He),[ce,Ve]):[ce,[]]}collateWordTimestamps(I,V,Y){const[ae,ce,xe]=this.combineTokensIntoWords(I,Y),Ve=[];for(let He=0;He=ae){const Ve=((xe-ae)*Y).toFixed(2);ce.push(`<|${Ve}|>`),ce.push([])}else ce[ce.length-1].push(xe);return ce=ce.map(xe=>typeof xe=="string"?xe:super.decode(xe,V)),ce.join("")}splitTokensOnUnicode(I){const V=this.decode(I,{decode_with_timestamps:!0}),Y="�",ae=[],ce=[],xe=[];let Ve=[],He=[],We=0;for(let et=0;et=this.model.tokens_to_ids.get("<|endoftext|>"),Zt=et.startsWith(" "),Gt=et.trim(),fr=He.test(Gt);if(Lt||Zt||fr||ce.length===0)ce.push(et),xe.push(wt),Ve.push(Bt);else{const gr=ce.length-1;ce[gr]+=et,xe[gr].push(...wt),Ve[gr].push(...Bt)}}return[ce,xe,Ve]}mergePunctuations(I,V,Y,ae,ce){const xe=structuredClone(I),Ve=structuredClone(V),He=structuredClone(Y);let We=xe.length-2,et=xe.length-1;for(;We>=0;)xe[We].startsWith(" ")&&ae.includes(xe[We].trim())?(xe[et]=xe[We]+xe[et],Ve[et]=(0,o.mergeArrays)(Ve[We],Ve[et]),He[et]=(0,o.mergeArrays)(He[We],He[et]),xe[We]="",Ve[We]=[],He[We]=[]):et=We,--We;for(We=0,et=1;etwt),Ve.filter(wt=>wt.length>0),He.filter(wt=>wt.length>0)]}}class ms extends ht{}class Us extends ht{}class Wr extends ht{}class Re extends ht{constructor(I,V){super(I,V),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[V,...Y]=I.trim().split(this.languageRegex);if(Y.length===0)return super._encode_text(V);if(Y.length===2){const[ae,ce]=Y;return this.supported_language_codes.includes(ae)||console.warn(`Unsupported language code "${ae}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,o.mergeArrays)([ae],super._encode_text(ce))}}}class je extends ht{}class rt extends ht{}class Qt extends ht{}class Ws extends ht{}class Cs extends ht{}class rs extends ht{constructor(I,V){super(I,V),this.decoder=new Mt({})}}class bn extends ht{}class yn extends ht{}class vn extends ht{}class xn{static async from_pretrained(I,{progress_callback:V=null,config:Y=null,cache_dir:ae=null,local_files_only:ce=!1,revision:xe="main",legacy:Ve=null}={}){var Bt;const[He,We]=await d(I,{progress_callback:V,config:Y,cache_dir:ae,local_files_only:ce,revision:xe,legacy:Ve}),et=((Bt=We.tokenizer_class)==null?void 0:Bt.replace(/Fast$/,""))??"PreTrainedTokenizer";let wt=this.TOKENIZER_CLASS_MAPPING[et];return wt||(console.warn(`Unknown tokenizer class "${et}", attempting to construct from base class.`),wt=ht),new wt(He,We)}}J(xn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:pt,DistilBertTokenizer:ge,CamembertTokenizer:Ae,DebertaTokenizer:S,DebertaV2Tokenizer:X,BertTokenizer:Fs,HerbertTokenizer:R,ConvBertTokenizer:q,RoFormerTokenizer:re,XLMTokenizer:ot,ElectraTokenizer:ft,MobileBertTokenizer:St,SqueezeBertTokenizer:Ht,AlbertTokenizer:Os,GPT2Tokenizer:vt,BartTokenizer:tt,MBartTokenizer:At,MBart50Tokenizer:qt,RobertaTokenizer:Ur,WhisperTokenizer:ir,CodeGenTokenizer:ms,CLIPTokenizer:Us,SiglipTokenizer:Wr,MarianTokenizer:Re,BloomTokenizer:Hr,NllbTokenizer:Ps,M2M100Tokenizer:hr,LlamaTokenizer:Ir,CodeLlamaTokenizer:ur,XLMRobertaTokenizer:us,MPNetTokenizer:ds,FalconTokenizer:Ar,GPTNeoXTokenizer:Ds,EsmTokenizer:Ls,Wav2Vec2CTCTokenizer:je,BlenderbotTokenizer:rt,BlenderbotSmallTokenizer:Qt,SpeechT5Tokenizer:Ws,NougatTokenizer:Cs,VitsTokenizer:rs,Qwen2Tokenizer:vr,GemmaTokenizer:ps,Grok1Tokenizer:Jr,CohereTokenizer:bn,MgpstrTokenizer:yn,Ernie4_5_Tokenizer:vn,PreTrainedTokenizer:ht})}),"./src/utils/audio.js":((e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>G,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(N,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)(N)).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 oe;if(Z.numberOfChannels===2){const pe=Math.sqrt(2),ue=Z.getChannelData(0),j=Z.getChannelData(1);oe=new Float32Array(ue.length);for(let F=0;F2595*Math.log10(1+N/700),kaldi:N=>1127*Math.log(1+N/700),slaney:(N,te=1e3,H=15,ee=27/Math.log(6.4))=>N>=te?H+Math.log(N/te)*ee:3*N/200};function _(N,te="htk"){const H=f[te];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof N=="number"?H(N):N.map(ee=>H(ee))}const M={htk:N=>700*(10**(N/2595)-1),kaldi:N=>700*(Math.exp(N/1127)-1),slaney:(N,te=1e3,H=15,ee=Math.log(6.4)/27)=>N>=H?te*Math.exp(ee*(N-H)):200*N/3};function k(N,te="htk"){const H=M[te];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof N=="number"?H(N):N.map(ee=>H(ee))}function w(N,te){const H=Float64Array.from({length:te.length-1},(pe,ue)=>te[ue+1]-te[ue]),ee=Array.from({length:N.length},()=>new Array(te.length));for(let pe=0;penew Array(N.length));for(let pe=0;peN+ee*oe)}function $(N,te,H,ee,Z,oe=null,pe="htk",ue=!1){if(oe!==null&&oe!=="slaney")throw new Error('norm must be one of null or "slaney"');if(N<2)throw new Error(`Require num_frequency_bins: ${N} >= 2`);if(H>ee)throw new Error(`Require min_frequency: ${H} <= max_frequency: ${ee}`);const j=_(H,pe),F=_(ee,pe),W=b(j,F,te+2);let se=k(W,pe),_e;if(ue){const ve=Z/((N-1)*2);_e=_(Float64Array.from({length:N},(Le,Ge)=>Ge*ve),pe),se=W}else _e=b(0,Math.floor(Z/2),N);const ie=w(_e,se);if(oe!==null&&oe==="slaney")for(let ve=0;veZ)throw Error(`frame_length (${H}) may not be larger than fft_length (${Z})`);if(Pe!==H)throw new Error(`Length of the window (${Pe}) must equal frame_length (${H})`);if(ee<=0)throw new Error("hop_length must be greater than zero");if(oe===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(!W)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(pe){if(ue!=="reflect")throw new Error(`pad_mode="${ue}" not implemented yet.`);const Qe=Math.floor((Z-1)/2)+1;N=E(N,Qe,Qe)}let Se=Math.floor(1+Math.floor((N.length-H)/ee));Q!==null&&SeSe?me&&(we=B):we=$e=B);const Fe=new o.FFT(Z),Oe=new Float64Array(Z),Ye=new Float64Array(Fe.outputBufferSize),ye=new Float32Array(Me*we);for(let Qe=0;Qe<$e;++Qe){const ze=Qe*ee,Je=Math.min(N.length-ze,H);Je!==H&&Oe.fill(0,0,H);for(let nt=0;nt=1;--nt)Oe[nt]-=F*Oe[nt-1];Oe[0]*=1-F}for(let nt=0;ntMath.pow(ue,.85));break;default:throw new Error(`Unknown window type ${te}.`)}if(H&&(pe=pe.subarray(0,N)),ee===null)return pe;if(N>ee)throw new Error(`Length of the window (${N}) may not be larger than frame_length (${ee})`);return pe}function D(N,te){let H=44;const ee=new ArrayBuffer(H+N.length*4),Z=new DataView(ee);K(Z,0,"RIFF"),Z.setUint32(4,36+N.length*4,!0),K(Z,8,"WAVE"),K(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),K(Z,36,"data"),Z.setUint32(40,N.length*4,!0);for(let oe=0;oe{let oe=await Z.arrayBuffer();l.writeFileSync(ee,Buffer.from(oe))};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:()=>w,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>k,mergeArrays:()=>d,pick:()=>M,pop:()=>p,product:()=>u,reverseDictionary:()=>o,saveBlob:()=>_});function s(b,$){b&&b($)}function o(b){return Object.fromEntries(Object.entries(b).map(([$,E])=>[E,$]))}function n(b){return b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(b){var $,E,v;return((v=(E=($=b==null?void 0:b.prototype)==null?void 0:$.__proto__)==null?void 0:E.constructor)==null?void 0:v.name)==="TypedArray"}function a(b){return Number.isInteger(b)||typeof b=="bigint"}function l(b){return b==null||b===-1}function c(b){const $=[];let E=b;for(;Array.isArray(E);)$.push(E.length),E=E[0];return $}function p(b,$,E=void 0){const v=b[$];if(v!==void 0)return delete b[$],v;if(E===void 0)throw Error(`Key ${$} does not exist in object.`);return E}function d(...b){return Array.prototype.concat.apply([],b)}function u(...b){return b.reduce(($,E)=>$.flatMap(v=>E.map(x=>[v,x])))}function f(b,$){return Math.abs((b+$)%(2*$)-$)}function _(b,$){const E=URL.createObjectURL($),v=document.createElement("a");v.href=E,v.download=b,v.click(),v.remove(),URL.revokeObjectURL(E)}function M(b,$){return Object.assign({},...$.map(E=>{if(b[E]!==void 0)return{[E]:b[E]}}))}function k(b){let $=0;for(const E of b)++$;return $}function w(b,$){let E=0;for(const v of b)v===$&&++E;return E}}),"./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),M=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(_.clone()),this.nodes.push(M.clone()),this.beginNodes[this.len].push(M),this.endNodes[0].push(_)}insert(d,u,f,_){const M=this.nodes.length,k=new a(_,M,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 w of this.beginNodes[u]){w.prev=null;let b=0,$=null;for(let E of this.endNodes[u]){const v=E.backtraceScore+w.score;($===null||v>b)&&($=E.clone(),b=v)}if($!==null)w.prev=$,w.backtraceScore=b;else return[]}++u}const f=[],M=this.beginNodes[d][0].prev;if(M===null)return[];let k=M.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,_,M){this.tokenId=d,this.nodeId=u,this.pos=f,this.length=_,this.score=M,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 M=u;for(let k=0;k<_.length;++k)M=M[f=_[k]]??(M[f]=Object.create(null));M.end=_}return u}split(d){const u=[],f=d.length;let _=0,M=0;for(;M_&&u.push(d.slice(_,M)),u.push(w),M+=w.length,_=M):++M}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:()=>b,getModelJSON:()=>E,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 D=s.createReadStream(P);this.body=new ReadableStream({start(K){D.on("data",G=>K.enqueue(G)),D.on("end",()=>K.close()),D.on("error",G=>K.error(G))},cancel(){D.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(y,P=null,O=null){let D;try{D=new URL(y)}catch{return!1}return!(P&&!P.includes(D.protocol)||O&&!O.includes(D.hostname))}const d=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function u(y){return!(!d.test(y)||y.includes("..")||y.includes("--")||y.endsWith(".git")||y.endsWith(".ipynb"))}async function f(y){var P;if(n.env.useFS&&!p(y,["http:","https:","blob:"]))return new c(y instanceof URL?y.protocol==="file:"?y.pathname:y.toString():y);if(typeof process<"u"&&((P=process==null?void 0:process.release)==null?void 0:P.name)==="node"){const O=!!(Vs!=null&&Vs.TESTING_REMOTELY),D=n.env.version,K=new Headers;if(K.set("User-Agent",`transformers.js/${D}; is_ci/${O};`),p(y,["http:","https:"],["huggingface.co","hf.co"])){const N=(Vs==null?void 0:Vs.HF_TOKEN)??(Vs==null?void 0:Vs.HF_ACCESS_TOKEN);N&&K.set("Authorization",`Bearer ${N}`)}return fetch(y,{headers:K})}else return fetch(y)}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 M(y,P,O){if(!O)return null;const D=_[y]??`Error (${y}) occurred while trying to load file`;throw Error(`${D}: "${P}".`)}class k{constructor(P){this.path=P}async match(P){let O=o.join(this.path,P),D=new c(O);if(D.exists)return D}async put(P,O,D=void 0){let K=o.join(this.path,P);try{const G=O.headers.get("Content-Length"),N=parseInt(G??"0");let te=0;await s.promises.mkdir(o.dirname(K),{recursive:!0});const H=s.createWriteStream(K),ee=O.body.getReader();for(;;){const{done:Z,value:oe}=await ee.read();if(Z)break;await new Promise((ue,j)=>{H.write(oe,F=>{if(F){j(F);return}ue()})}),te+=oe.length;const pe=N?te/N*100:0;D==null||D({progress:pe,loaded:te,total:N})}H.close()}catch(G){try{await s.promises.unlink(K)}catch{}throw G}}}async function w(y,...P){for(let O of P)try{let D=await y.match(O);if(D)return D}catch{continue}}async function b(y,P,O=!0,D={},K=!1){if(!n.env.allowLocalModels){if(D.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)(D.progress_callback,{status:"initiate",name:y,file:P});let G;if(!G&&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");G=n.env.customCache}if(!G&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{G=await caches.open("transformers-cache")}catch(_e){console.warn("An error occurred while opening the browser cache:",_e)}}if(!G&&n.env.useFSCache){if(!n.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");G=new k(D.cache_dir??n.env.cacheDir)}const N=D.revision??"main",te=x(y,P),H=u(y),ee=H?x(n.env.localModelPath,te):te,Z=x(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",y).replaceAll("{revision}",encodeURIComponent(N)),P);let oe;const pe=G instanceof k?N==="main"?te:x(y,N,P):Z;let ue=!1,j;G&&(j=await w(G,ee,pe));const F=j!==void 0;if(j===void 0){if(n.env.allowLocalModels)if(p(te,["http:","https:"])){if(D.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),oe=ee}catch(ie){console.warn(`Unable to load from local path "${ee}": "${ie}"`)}if(j===void 0||j.status===404){if(D.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 "${y}".`);if(j=await f(Z),j.status!==200)return M(j.status,Z,O);oe=pe}ue=G&&typeof Response<"u"&&j instanceof Response&&j.status===200}(0,i.dispatchCallback)(D.progress_callback,{status:"download",name:y,file:P});let W;if(!(n.apis.IS_NODE_ENV&&K)){let _e;D.progress_callback?F&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(_e=new Uint8Array(await j.arrayBuffer()),(0,i.dispatchCallback)(D.progress_callback,{status:"progress",name:y,file:P,progress:100,loaded:_e.length,total:_e.length})):_e=await v(j,ie=>{(0,i.dispatchCallback)(D.progress_callback,{status:"progress",name:y,file:P,...ie})}):_e=new Uint8Array(await j.arrayBuffer()),W=_e}if(ue&&oe&&await G.match(oe)===void 0)if(W)await G.put(oe,new Response(W,{headers:j.headers})).catch(_e=>{console.warn(`Unable to add response to browser cache: ${_e}.`)});else{const _e=D.progress_callback?ie=>(0,i.dispatchCallback)(D.progress_callback,{status:"progress",name:y,file:P,...ie}):void 0;await G.put(oe,j,_e)}if((0,i.dispatchCallback)(D.progress_callback,{status:"done",name:y,file:P}),W){if(!n.apis.IS_NODE_ENV&&K)throw new Error("Cannot return path in a browser environment.");return W}if(j instanceof c)return j.filePath;const se=await(G==null?void 0:G.match(oe));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 $(y,P,O=!0,D={}){const K=await b(y,P,O,D,!1);return K===null?null:new TextDecoder("utf-8").decode(K)}async function E(y,P,O=!0,D={}){const K=await $(y,P,O,D);return K===null?{}:JSON.parse(K)}async function v(y,P){const O=y.headers.get("Content-Length");O===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let D=parseInt(O??"0"),K=new Uint8Array(D),G=0;const N=y.body.getReader();async function te(){const{done:H,value:ee}=await N.read();if(H)return;const Z=G+ee.length;if(Z>D){D=Z;const pe=new Uint8Array(D);pe.set(K),K=pe}K.set(ee,G),G=Z;const oe=G/D*100;return P({progress:oe,loaded:G,total:D}),te()}return await te(),K}function x(...y){return y=y.map((P,O)=>(O&&(P=P.replace(new RegExp("^/"),"")),O!==y.length-1&&(P=P.replace(new RegExp("/$"),"")),P)),y.join("/")}}),"./src/utils/image.js":((e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>_,load_image:()=>M});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,w)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(k,w)},p=self.createImageBitmap,c=self.ImageData;else if(a)p=async k=>{const b=(await k.metadata()).channels,{data:$,info:E}=await k.rotate().raw().toBuffer({resolveWithObject:!0}),v=new _(new Uint8ClampedArray($),E.width,E.height,E.channels);return b!==void 0&&b!==E.channels&&v.convert(b),v};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(w,b,$,E){this.data=w,this.width=b,this.height=$,this.channels=E}get size(){return[this.width,this.height]}static async read(w){if(w instanceof _)return w;if(typeof w=="string"||w instanceof URL)return await this.fromURL(w);if(w instanceof Blob)return await this.fromBlob(w);if(typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&w instanceof OffscreenCanvas)return this.fromCanvas(w);throw new Error(`Unsupported input type: ${typeof w}`)}static fromCanvas(w){if(!d)throw new Error("fromCanvas() is only supported in browser environments.");const $=w.getContext("2d").getImageData(0,0,w.width,w.height).data;return new _($,w.width,w.height,4)}static async fromURL(w){const b=await(0,o.getFile)(w);if(b.status!==200)throw new Error(`Unable to read image from "${w}" (${b.status} ${b.statusText})`);const $=await b.blob();return this.fromBlob($)}static async fromBlob(w){if(d){const b=await p(w),$=l(b.width,b.height).getContext("2d");return $.drawImage(b,0,0),new this($.getImageData(0,0,b.width,b.height).data,b.width,b.height,4)}else{const b=a(await w.arrayBuffer());return await p(b)}}static fromTensor(w,b="CHW"){if(w.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${w.dims.length} dimensions.`);if(b==="CHW")w=w.transpose(1,2,0);else if(b!=="HWC")throw new Error(`Unsupported channel format: ${b}`);if(!(w.data instanceof Uint8ClampedArray||w.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${w.type}`);switch(w.dims[2]){case 1:case 2:case 3:case 4:return new _(w.data,w.dims[1],w.dims[0],w.dims[2]);default:throw new Error(`Unsupported number of channels: ${w.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const w=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let b=0,$=0;b=0?P=$:D=-$,E>=0?O=E:K=-E,y.drawImage(x,P,O,w,b,D,K,w,b),new _(y.getImageData(0,0,w,b).data,w,b,4).convert(v)}else{let v=this.toSharp();if($>=0&&E>=0)v=v.extract({left:Math.floor($),top:Math.floor(E),width:w,height:b});else if($<=0&&E<=0){const x=Math.floor(-E),y=Math.floor(-$);v=v.extend({top:x,left:y,right:w-this.width-y,bottom:b-this.height-x})}else{let x=[0,0],y=0;E<0?(x[0]=Math.floor(-E),x[1]=b-this.height-x[0]):y=Math.floor(E);let P=[0,0],O=0;$<0?(P[0]=Math.floor(-$),P[1]=w-this.width-P[0]):O=Math.floor($),v=v.extend({top:x[0],bottom:x[1],left:P[0],right:P[1]}).extract({left:O,top:y,width:w,height:b})}return await p(v)}}async toBlob(w="image/png",b=1){if(!d)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:w,quality:b})}toTensor(w="CHW"){let b=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(w!=="HWC")if(w==="CHW")b=b.permute(2,0,1);else throw new Error(`Unsupported channel format: ${w}`);return b}toCanvas(){if(!d)throw new Error("toCanvas() is only supported in browser environments.");const w=this.clone().rgba(),b=l(w.width,w.height),$=new c(w.data,w.width,w.height);return b.getContext("2d").putImageData($,0,0),b}split(){const{data:w,width:b,height:$,channels:E}=this,v=w.constructor,x=w.length/E,y=Array.from({length:E},()=>new v(x));for(let P=0;Pnew _(P,b,$,1))}_update(w,b,$,E=null){return this.data=w,this.width=b,this.height=$,E!==null&&(this.channels=E),this}clone(){return new _(this.data.slice(),this.width,this.height,this.channels)}convert(w){if(this.channels===w)return this;switch(w){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(w){if(d){if(n.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const b=w.split(".").pop().toLowerCase(),$=f.get(b)??"image/png",E=await this.toBlob($);(0,s.saveBlob)(w,E)}else{if(n.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(w);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 M=_.read.bind(_)}),"./src/utils/maths.js":((e,r,t)=>{t.r(r),t.d(r,{FFT:()=>M,bankers_round:()=>b,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:()=>w,softmax:()=>n});function s(E,[v,x,y],[P,O],D="bilinear",K=!1){const G=O/y,N=P/x,te=new E.constructor(P*O*v),H=x*y,ee=P*O;for(let Z=0;Z=0;--K)P[K]=G,y[K]=v[x[K]],G*=y[K];const O=x.map((K,G)=>P[x.indexOf(G)]),D=new E.constructor(E.length);for(let K=0;K=0;--N)G+=te%v[N]*O[N],te=Math.floor(te/v[N]);D[G]=E[K]}return[D,y]}function n(E){const v=d(E)[0],x=E.map(O=>Math.exp(O-v)),y=x.reduce((O,D)=>O+D,0);return x.map(O=>O/y)}function i(E){const v=d(E)[0];let x=0;for(let O=0;OO-v-y)}function a(E,v){let x=0;for(let y=0;yv+x*x,0))}function p(E){if(E.length===0)throw Error("Array must not be empty");let v=E[0],x=0;for(let y=1;yv&&(v=E[y],x=y);return[v,x]}function u(E){return E>0&&(E&E-1)===0}class f{constructor(v){if(this.size=v|0,this.size<=1||!u(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=v<<1,this.table=new Float64Array(this.size*2);for(let y=0;yy;y<<=1)++x;this._width=x%2===0?x-1:x,this._bitrev=new Int32Array(1<>>P&3)<>>1);for(let P=0;P>>1]=v[P];return y}toComplexArray(v,x){const y=x||this.createComplexArray();for(let P=0;P>>1],y[P+1]=0;return y}transform(v,x){if(v===x)throw new Error("Input and output buffers must be different");this._transform4(v,x,1)}realTransform(v,x){if(v===x)throw new Error("Input and output buffers must be different");this._realTransform4(v,x,1)}inverseTransform(v,x){if(v===x)throw new Error("Input and output buffers must be different");this._transform4(v,x,-1);for(let y=0;y>=2;D>=2;D>>=2){K=P/D<<1;const ee=K>>>2;for(G=0;G>>1,D>>>1)}else for(G=0,N=0;G>>1,D>>>1,y)}const H=this.table;for(D>>=2;D>=2;D>>=2){K=P/D<<1;const Z=K>>>1,oe=Z>>>1,pe=oe>>>1;for(G=0;G>>1;for(let Z=2;Z>1;++te){const H=(te+1-v)**2/2,ee=Math.sqrt(G**2+N**2)**H,Z=H*Math.atan2(N,G),oe=2*te;O[oe]=ee*Math.cos(Z),O[oe+1]=ee*Math.sin(Z),D[oe]=O[oe],D[oe+1]=-O[oe+1]}this._slicedChirpBuffer=O.subarray(x,y),this._f=new f(P>>1),this._f.transform(this._chirpBuffer,D)}_transform(v,x,y){const P=this._buffer1,O=this._buffer2,D=this._outBuffer1,K=this._outBuffer2,G=this._chirpBuffer,N=this._slicedChirpBuffer,te=this._a;if(y)for(let H=0;H>1,oe=x[Z];P[H]=oe*N[H],P[ee]=oe*N[ee]}else for(let H=0;H=E.length&&(G=2*(E.length-1)-G),y[D++]=E[G]}y.sort(),x[O]=y[P]}return x}function w(E,v){const x=Math.pow(10,v);return Math.round(E*x)/x}function b(E){const v=Math.round(E);return Math.abs(E)%1===.5?v%2===0?v:v-1:v}function $(E){const v=E.length,x=E[0].length,y=[v+1,x+1],P=Array.from({length:y[0]},()=>Array(y[1]).fill(1/0));P[0][0]=0;const O=Array.from({length:y[0]},()=>Array(y[1]).fill(-1));for(let te=1;te0||K>0;)switch(G.push(D-1),N.push(K-1),O[D][K]){case 0:--D,--K;break;case 1:--D;break;case 2:--K;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${D}, ${K}]. Please file a bug report.`)}return G.reverse(),N.reverse(),[G,N]}}),"./src/utils/tensor.js":((e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>x,full:()=>N,full_like:()=>te,interpolate:()=>p,interpolate_4d:()=>d,layer_norm:()=>b,matmul:()=>u,mean:()=>D,mean_pooling:()=>w,ones:()=>H,ones_like:()=>ee,permute:()=>c,quantize_embeddings:()=>ue,rand:()=>pe,rfft:()=>f,slice:()=>k,stack:()=>y,std_mean:()=>O,topk:()=>_,zeros:()=>Z,zeros_like:()=>oe});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:(W,se)=>{if(typeof se=="string"){let _e=Number(se);if(Number.isInteger(_e))return W._getitem(_e)}return W[se]},set:(W,se,_e)=>W[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,...W]=this.dims;if(W.length>0){const se=W.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 W=this.data;for(let se=0;seCe)throw new Error(`Invalid slice: ${B}`);const Pe=[Math.max(me,0),Math.min(Ce,this.dims[Q])];se.push(Pe),W.push(Pe[1]-Pe[0])}else throw new Error(`Invalid slice: ${B}`)}const _e=se.map(([Q,B])=>B-Q),ie=_e.reduce((Q,B)=>Q*B),ve=this.data,Le=new ve.constructor(ie),Ge=this.stride();let Ie=!0;for(let Q=1;Q<_e.length;++Q)if(se[Q][0]!==0||se[Q][1]!==this.dims[Q]){Ie=!1;break}if(Ie){const Q=se[0][0]*Ge[0],B=se[0][1]*Ge[0];if(ArrayBuffer.isView(ve))Le.set(ve.subarray(Q,B));else if(Array.isArray(ve)){const me=ve.slice(Q,B);for(let Ce=0;Ce=0;--me){const Pe=_e[me];B+=(Ce%Pe+se[me][0])*Ge[me],Ce=Math.floor(Ce/Pe)}Le[Q]=ve[B]}return new a(this.type,Le,W)}permute(...F){return c(this,F)}transpose(...F){return this.permute(...F)}sum(F=null,W=!1){return this.norm(1,F,W)}norm(F="fro",W=null,se=!1){if(F==="fro")F=2;else if(typeof F=="string")throw Error(`Unsupported norm: ${F}`);const _e=this.data,ie=(Ie,Q)=>Ie+Q**F;if(W===null){const Ie=_e.reduce(ie,0)**(1/F);return new a(this.type,[Ie],[])}const[ve,Le,Ge]=P(ie,this,W,se);if(F!==1)for(let Ie=0;Ie=0;--Ge){const B=this.dims[Ge];if(Ge!==W){const me=Ie%B;Le+=me*Q,Q*=this.dims[Ge]}Ie=Math.floor(Ie/B)}_e[ve]/=ie[Le]}return this}normalize(F=2,W=1){return this.clone().normalize_(F,W)}stride(){return K(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,E(this.dims,F))}unsqueeze_(F=null){return this.dims=E(this.dims,F),this}flatten_(F=0,W=-1){W=(W+this.dims.length)%this.dims.length;let se=this.dims.slice(0,F),_e=this.dims.slice(F,W+1),ie=this.dims.slice(W+1);return this.dims=[...se,_e.reduce((ve,Le)=>ve*Le,1),...ie],this}flatten(F=0,W=-1){return this.clone().flatten_(F,W)}view(...F){let W=-1;for(let _e=0;_eLe!==W?ie*ve:ie,1);F[W]=se.length/_e}return new a(this.type,se,F)}neg_(){const F=this.data;for(let W=0;WF?1:0;return new a("bool",W,this.dims)}lt(F){const W=new Uint8Array(this.data.length),se=this.data;for(let _e=0;_eMath.min(ve,Le),this,F,W,1/0);return new a(se,_e,ie)}max(F=null,W=!1){if(F===null){const ve=(0,s.max)(this.data)[0];return new a(this.type,[ve],[])}const[se,_e,ie]=P((ve,Le)=>Math.max(ve,Le),this,F,W,-1/0);return new a(se,_e,ie)}argmin(F=null,W=!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,W=!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 W;const se=["int64","uint64"].includes(this.type),_e=["int64","uint64"].includes(F);return se&&!_e?W=Number:!se&&_e&&(W=BigInt),new a(F,i[F].from(this.data,W),this.dims)}}function l(j,F){const W=j.length,se=F.reduce((ie,ve)=>ie*ve);if(W!==se)throw Error(`cannot reshape array of size ${W} into shape (${F})`);let _e=j;for(let ie=F.length-1;ie>=0;ie--)_e=_e.reduce((ve,Le)=>{let Ge=ve[ve.length-1];return Ge.lengthnew a("int64",j,[j.length]);async function k(j,F,W,se,_e){return await(await n.TensorOpRegistry.slice)({x:j,s:M(F),e:M(W),a:M(se),t:M(_e??new Array(se.length).fill(1))})}function w(j,F){const W=j.data,se=F.data,_e=[j.dims[0],j.dims[2]],ie=new W.constructor(_e[0]*_e[1]),[ve,Le,Ge]=j.dims;let Ie=0;for(let Q=0;QW!==1):typeof F=="number"?j[F]===1&&j.splice(F,1):Array.isArray(F)&&(j=j.filter((W,se)=>W!==1||!F.includes(se))),j}function E(j,F){return F=v(F,j.length+1),j=j.slice(),j.splice(F,0,1),j}function v(j,F,W=null,se=!0){if(j<-F||j>=F){if(se)throw new Error(`IndexError: index ${j} is out of bounds for dimension${W===null?"":" "+W} with size ${F}`);return j<-F?0:F}return j<0&&(j=(j%F+F)%F),j}function x(j,F=0){F=v(F,j[0].dims.length);const W=j[0].dims.slice();W[F]=j.reduce((ve,Le)=>ve+Le.dims[F],0);const se=W.reduce((ve,Le)=>ve*Le,1),_e=new j[0].data.constructor(se),ie=j[0].type;if(F===0){let ve=0;for(const Le of j){const Ge=Le.data;_e.set(Ge,ve),ve+=Ge.length}}else{let ve=0;for(let Le=0;Le=0;--me){const Se=Ie[me];let Me=Ce%Se;me===F&&(Me+=ve),B+=Me*Pe,Pe*=W[me],Ce=Math.floor(Ce/Se)}_e[B]=Ge[Q]}ve+=Ie[F]}}return new a(ie,_e,W)}function y(j,F=0){return x(j.map(W=>W.unsqueeze(F)),F)}function P(j,F,W=null,se=!1,_e=null){const ie=F.data,ve=F.dims;W=v(W,ve.length);const Le=ve.slice();Le[W]=1;const Ge=new ie.constructor(ie.length/ve[W]);_e!==null&&Ge.fill(_e);for(let Ie=0;Ie=0;--B){const Pe=ve[B];if(B!==W){const Se=me%Pe;Q+=Se*Ce,Ce*=Le[B]}me=Math.floor(me/Pe)}Ge[Q]=j(Ge[Q],ie[Ie],Ie,Q)}return se||Le.splice(W,1),[F.type,Ge,Le]}function O(j,F=null,W=1,se=!1){const _e=j.data,ie=j.dims;if(F===null){const Ce=_e.reduce(($e,we)=>$e+we,0)/_e.length,Pe=Math.sqrt(_e.reduce(($e,we)=>$e+(we-Ce)**2,0)/(_e.length-W)),Se=new a(j.type,[Ce],[]);return[new a(j.type,[Pe],[]),Se]}F=v(F,ie.length);const ve=D(j,F,se),Le=ve.data,[Ge,Ie,Q]=P((me,Ce,Pe,Se)=>me+(Ce-Le[Se])**2,j,F,se);for(let me=0;meIe+Q,0);return new a(j.type,[Ge/_e.length],[])}F=v(F,se.length);const[ie,ve,Le]=P((Ge,Ie)=>Ge+Ie,j,F,W);if(se[F]!==1)for(let Ge=0;Ge=0;--W)F[W]=se,se*=j[W];return F}function G(j,F,W,se){const _e=j.reduce((ie,ve)=>ie*ve,1);return new a(W,new se(_e).fill(F),j)}function N(j,F){let W,se;if(typeof F=="number")W="float32",se=Float32Array;else if(typeof F=="bigint")W="int64",se=BigInt64Array;else if(typeof F=="boolean")W="bool",se=Uint8Array;else throw new Error(`Unsupported data type: ${typeof F}`);return G(j,F,W,se)}function te(j,F){return N(j.dims,F)}function H(j){return G(j,1n,"int64",BigInt64Array)}function ee(j){return H(j.dims)}function Z(j){return G(j,0n,"int64",BigInt64Array)}function oe(j){return Z(j.dims)}function pe(j){const F=j.reduce((W,se)=>W*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 W=F==="binary",se=W?"int8":"uint8",_e=W?Int8Array:Uint8Array,ie=j.data,ve=new _e(ie.length/8);for(let Le=0;Le0?1:0,Ie=Math.floor(Le/8),Q=Le%8;ve[Ie]|=Ge<<7-Q,W&&Q===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 E=await(await fetch(u.src)).blob();u.src=URL.createObjectURL(E),await new Promise(v=>u.onloadedmetadata=v)}const f=u.duration;let _,M;c!=null?(_=c,M=c===1?0:f/(c-1)):(M=1/p,_=Math.floor(f/M));let k=[];for(let $=0;$<_;++$)k.push(c===1?f/2:$*M);const w=document.createElement("canvas");w.width=u.videoWidth,w.height=u.videoHeight;const b=w.getContext("2d",{willReadFrequently:!0});for(const $ of k){u.currentTime=$,await new Promise(y=>{u.onseeked=y}),b.drawImage(u,0,0,w.width,w.height);const E=b.getImageData(0,0,w.width,w.height),v=new s.RawImage(E.data,w.width,w.height,4),x=new n(v,$);d.push(x)}return u.remove(),new i(d,f)}})},tw={};function Vt(e){var r=tw[e];if(r!==void 0)return r.exports;var t=tw[e]={exports:{}};return uT[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 h={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/Vt.r(h),Vt.d(h,{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:()=>M.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:()=>b.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:()=>v.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,DINOv3ConvNextModel:()=>t.DINOv3ConvNextModel,DINOv3ConvNextPreTrainedModel:()=>t.DINOv3ConvNextPreTrainedModel,DINOv3ViTImageProcessor:()=>_.DINOv3ViTImageProcessor,DINOv3ViTModel:()=>t.DINOv3ViTModel,DINOv3ViTPreTrainedModel:()=>t.DINOv3ViTPreTrainedModel,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:()=>E.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:()=>w.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>v.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>v.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:()=>w.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,GraniteMoeHybridForCausalLM:()=>t.GraniteMoeHybridForCausalLM,GraniteMoeHybridModel:()=>t.GraniteMoeHybridModel,GraniteMoeHybridPreTrainedModel:()=>t.GraniteMoeHybridPreTrainedModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>w.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:()=>w.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:()=>E.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>_.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>w.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,Lfm2ForCausalLM:()=>t.Lfm2ForCausalLM,Lfm2Model:()=>t.Lfm2Model,Lfm2PreTrainedModel:()=>t.Lfm2PreTrainedModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,Llama4ForCausalLM:()=>t.Llama4ForCausalLM,Llama4PreTrainedModel:()=>t.Llama4PreTrainedModel,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>_.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LlavaProcessor:()=>w.LlavaProcessor,LlavaQwen2ForCausalLM:()=>t.LlavaQwen2ForCausalLM,LogitsProcessor:()=>v.LogitsProcessor,LogitsProcessorList:()=>v.LogitsProcessorList,LogitsWarper:()=>v.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:()=>E.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>w.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>v.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>v.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:()=>w.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:()=>v.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>v.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:()=>w.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>_.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>w.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:()=>w.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:()=>w.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:()=>w.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:()=>v.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:()=>w.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:()=>w.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:()=>w.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:()=>E.StoppingCriteria,StoppingCriteriaList:()=>E.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>v.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:()=>v.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:()=>v.TopKLogitsWarper,TopPLogitsWarper:()=>v.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>w.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:()=>w.VLChatProcessor,VLMImageProcessor:()=>_.VLMImageProcessor,VaultGemmaForCausalLM:()=>t.VaultGemmaForCausalLM,VaultGemmaModel:()=>t.VaultGemmaModel,VaultGemmaPreTrainedModel:()=>t.VaultGemmaPreTrainedModel,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:()=>w.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:()=>w.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>w.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:()=>w.WhisperProcessor,WhisperTextStreamer:()=>$.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>v.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"),M=Vt("./src/models/auto/image_processing_auto.js"),k=Vt("./src/base/processing_utils.js"),w=Vt("./src/models/processors.js"),b=Vt("./src/models/auto/processing_auto.js"),$=Vt("./src/generation/streamers.js"),E=Vt("./src/generation/stopping_criteria.js"),v=Vt("./src/generation/logits_process.js")})(),h.ASTFeatureExtractor,h.ASTForAudioClassification,h.ASTModel,h.ASTPreTrainedModel,h.AlbertForMaskedLM,h.AlbertForQuestionAnswering,h.AlbertForSequenceClassification,h.AlbertModel,h.AlbertPreTrainedModel,h.AlbertTokenizer,h.ArceeForCausalLM,h.ArceeModel,h.ArceePreTrainedModel,h.AudioClassificationPipeline,h.AutoConfig,h.AutoFeatureExtractor,h.AutoImageProcessor,h.AutoModel,h.AutoModelForAudioClassification,h.AutoModelForAudioFrameClassification,h.AutoModelForAudioTextToText,h.AutoModelForCTC;var dT=h.AutoModelForCausalLM;h.AutoModelForDepthEstimation,h.AutoModelForDocumentQuestionAnswering,h.AutoModelForImageClassification,h.AutoModelForImageFeatureExtraction,h.AutoModelForImageMatting,h.AutoModelForImageSegmentation,h.AutoModelForImageTextToText,h.AutoModelForImageToImage,h.AutoModelForMaskGeneration,h.AutoModelForMaskedLM,h.AutoModelForNormalEstimation,h.AutoModelForObjectDetection,h.AutoModelForPoseEstimation,h.AutoModelForQuestionAnswering,h.AutoModelForSemanticSegmentation,h.AutoModelForSeq2SeqLM,h.AutoModelForSequenceClassification,h.AutoModelForSpeechSeq2Seq,h.AutoModelForTextToSpectrogram,h.AutoModelForTextToWaveform,h.AutoModelForTokenClassification,h.AutoModelForUniversalSegmentation,h.AutoModelForVision2Seq,h.AutoModelForXVector,h.AutoModelForZeroShotObjectDetection,h.AutoProcessor;var pT=h.AutoTokenizer;h.AutomaticSpeechRecognitionPipeline,h.BackgroundRemovalPipeline,h.BartForConditionalGeneration,h.BartForSequenceClassification,h.BartModel,h.BartPretrainedModel,h.BartTokenizer,h.BaseModelOutput,h.BaseStreamer,h.BeitFeatureExtractor,h.BeitForImageClassification,h.BeitModel,h.BeitPreTrainedModel,h.BertForMaskedLM,h.BertForQuestionAnswering,h.BertForSequenceClassification,h.BertForTokenClassification,h.BertModel,h.BertPreTrainedModel,h.BertTokenizer,h.BitImageProcessor,h.BlenderbotForConditionalGeneration,h.BlenderbotModel,h.BlenderbotPreTrainedModel,h.BlenderbotSmallForConditionalGeneration,h.BlenderbotSmallModel,h.BlenderbotSmallPreTrainedModel,h.BlenderbotSmallTokenizer,h.BlenderbotTokenizer,h.BloomForCausalLM,h.BloomModel,h.BloomPreTrainedModel,h.BloomTokenizer,h.CLIPFeatureExtractor,h.CLIPImageProcessor,h.CLIPModel,h.CLIPPreTrainedModel,h.CLIPSegForImageSegmentation,h.CLIPSegModel,h.CLIPSegPreTrainedModel,h.CLIPTextModel,h.CLIPTextModelWithProjection,h.CLIPTokenizer,h.CLIPVisionModel,h.CLIPVisionModelWithProjection,h.CamembertForMaskedLM,h.CamembertForQuestionAnswering,h.CamembertForSequenceClassification,h.CamembertForTokenClassification,h.CamembertModel,h.CamembertPreTrainedModel,h.CamembertTokenizer,h.CausalLMOutput,h.CausalLMOutputWithPast,h.ChineseCLIPFeatureExtractor,h.ChineseCLIPModel,h.ChineseCLIPPreTrainedModel,h.ClapAudioModelWithProjection,h.ClapFeatureExtractor,h.ClapModel,h.ClapPreTrainedModel,h.ClapTextModelWithProjection,h.ClassifierFreeGuidanceLogitsProcessor,h.CodeGenForCausalLM,h.CodeGenModel,h.CodeGenPreTrainedModel,h.CodeGenTokenizer,h.CodeLlamaTokenizer,h.CohereForCausalLM,h.CohereModel,h.CoherePreTrainedModel,h.CohereTokenizer,h.ConvBertForMaskedLM,h.ConvBertForQuestionAnswering,h.ConvBertForSequenceClassification,h.ConvBertForTokenClassification,h.ConvBertModel,h.ConvBertPreTrainedModel,h.ConvBertTokenizer,h.ConvNextFeatureExtractor,h.ConvNextForImageClassification,h.ConvNextImageProcessor,h.ConvNextModel,h.ConvNextPreTrainedModel,h.ConvNextV2ForImageClassification,h.ConvNextV2Model,h.ConvNextV2PreTrainedModel,h.DFineForObjectDetection,h.DFineModel,h.DFinePreTrainedModel,h.DINOv3ConvNextModel,h.DINOv3ConvNextPreTrainedModel,h.DINOv3ViTImageProcessor,h.DINOv3ViTModel,h.DINOv3ViTPreTrainedModel,h.DPTFeatureExtractor,h.DPTForDepthEstimation,h.DPTImageProcessor,h.DPTModel,h.DPTPreTrainedModel,h.DacDecoderModel,h.DacDecoderOutput,h.DacEncoderModel,h.DacEncoderOutput,h.DacFeatureExtractor,h.DacModel,h.DacPreTrainedModel,h.DataTypeMap,h.DebertaForMaskedLM,h.DebertaForQuestionAnswering,h.DebertaForSequenceClassification,h.DebertaForTokenClassification,h.DebertaModel,h.DebertaPreTrainedModel,h.DebertaTokenizer,h.DebertaV2ForMaskedLM,h.DebertaV2ForQuestionAnswering,h.DebertaV2ForSequenceClassification,h.DebertaV2ForTokenClassification,h.DebertaV2Model,h.DebertaV2PreTrainedModel,h.DebertaV2Tokenizer,h.DecisionTransformerModel,h.DecisionTransformerPreTrainedModel,h.DeiTFeatureExtractor,h.DeiTForImageClassification,h.DeiTImageProcessor,h.DeiTModel,h.DeiTPreTrainedModel,h.DepthAnythingForDepthEstimation,h.DepthAnythingPreTrainedModel,h.DepthEstimationPipeline,h.DepthProForDepthEstimation,h.DepthProPreTrainedModel,h.DetrFeatureExtractor,h.DetrForObjectDetection,h.DetrForSegmentation,h.DetrImageProcessor,h.DetrModel,h.DetrObjectDetectionOutput,h.DetrPreTrainedModel,h.DetrSegmentationOutput,h.Dinov2ForImageClassification,h.Dinov2Model,h.Dinov2PreTrainedModel,h.Dinov2WithRegistersForImageClassification,h.Dinov2WithRegistersModel,h.Dinov2WithRegistersPreTrainedModel,h.DistilBertForMaskedLM,h.DistilBertForQuestionAnswering,h.DistilBertForSequenceClassification,h.DistilBertForTokenClassification,h.DistilBertModel,h.DistilBertPreTrainedModel,h.DistilBertTokenizer,h.DocumentQuestionAnsweringPipeline,h.DonutFeatureExtractor,h.DonutImageProcessor,h.DonutSwinModel,h.DonutSwinPreTrainedModel,h.EfficientNetForImageClassification,h.EfficientNetImageProcessor,h.EfficientNetModel,h.EfficientNetPreTrainedModel,h.ElectraForMaskedLM,h.ElectraForQuestionAnswering,h.ElectraForSequenceClassification,h.ElectraForTokenClassification,h.ElectraModel,h.ElectraPreTrainedModel,h.ElectraTokenizer,h.EncodecFeatureExtractor,h.EosTokenCriteria,h.Ernie4_5_ForCausalLM,h.Ernie4_5_Model,h.Ernie4_5_PretrainedModel,h.Ernie4_5_Tokenizer,h.EsmForMaskedLM,h.EsmForSequenceClassification,h.EsmForTokenClassification,h.EsmModel,h.EsmPreTrainedModel,h.EsmTokenizer,h.ExaoneForCausalLM,h.ExaoneModel,h.ExaonePreTrainedModel,h.FFT,h.FalconForCausalLM,h.FalconModel,h.FalconPreTrainedModel,h.FalconTokenizer,h.FastViTForImageClassification,h.FastViTModel,h.FastViTPreTrainedModel,h.FeatureExtractionPipeline,h.FeatureExtractor,h.FillMaskPipeline,h.Florence2ForConditionalGeneration,h.Florence2PreTrainedModel,h.Florence2Processor,h.ForcedBOSTokenLogitsProcessor,h.ForcedEOSTokenLogitsProcessor,h.GLPNFeatureExtractor,h.GLPNForDepthEstimation,h.GLPNModel,h.GLPNPreTrainedModel,h.GPT2LMHeadModel,h.GPT2Model,h.GPT2PreTrainedModel,h.GPT2Tokenizer,h.GPTBigCodeForCausalLM,h.GPTBigCodeModel,h.GPTBigCodePreTrainedModel,h.GPTJForCausalLM,h.GPTJModel,h.GPTJPreTrainedModel,h.GPTNeoForCausalLM,h.GPTNeoModel,h.GPTNeoPreTrainedModel,h.GPTNeoXForCausalLM,h.GPTNeoXModel,h.GPTNeoXPreTrainedModel,h.GPTNeoXTokenizer,h.Gemma2ForCausalLM,h.Gemma2Model,h.Gemma2PreTrainedModel,h.Gemma3ForCausalLM,h.Gemma3Model,h.Gemma3PreTrainedModel,h.Gemma3nAudioFeatureExtractor,h.Gemma3nForConditionalGeneration,h.Gemma3nPreTrainedModel,h.Gemma3nProcessor,h.GemmaForCausalLM,h.GemmaModel,h.GemmaPreTrainedModel,h.GemmaTokenizer,h.GlmForCausalLM,h.GlmModel,h.GlmPreTrainedModel,h.GraniteForCausalLM,h.GraniteModel,h.GraniteMoeHybridForCausalLM,h.GraniteMoeHybridModel,h.GraniteMoeHybridPreTrainedModel,h.GranitePreTrainedModel,h.Grok1Tokenizer,h.GroundingDinoForObjectDetection,h.GroundingDinoImageProcessor,h.GroundingDinoPreTrainedModel,h.GroundingDinoProcessor,h.GroupViTModel,h.GroupViTPreTrainedModel,h.HeliumForCausalLM,h.HeliumModel,h.HeliumPreTrainedModel,h.HerbertTokenizer,h.HieraForImageClassification,h.HieraModel,h.HieraPreTrainedModel,h.HubertForCTC,h.HubertForSequenceClassification,h.HubertModel,h.HubertPreTrainedModel,h.IJepaForImageClassification,h.IJepaModel,h.IJepaPreTrainedModel,h.Idefics3ForConditionalGeneration,h.Idefics3ImageProcessor,h.Idefics3PreTrainedModel,h.Idefics3Processor,h.ImageClassificationPipeline,h.ImageFeatureExtractionPipeline,h.ImageFeatureExtractor,h.ImageMattingOutput,h.ImageProcessor,h.ImageSegmentationPipeline,h.ImageToImagePipeline,h.ImageToTextPipeline;var mT=h.InterruptableStoppingCriteria;h.JAISLMHeadModel,h.JAISModel,h.JAISPreTrainedModel,h.JinaCLIPImageProcessor,h.JinaCLIPModel,h.JinaCLIPPreTrainedModel,h.JinaCLIPProcessor,h.JinaCLIPTextModel,h.JinaCLIPVisionModel,h.Lfm2ForCausalLM,h.Lfm2Model,h.Lfm2PreTrainedModel,h.LiteWhisperForConditionalGeneration,h.Llama4ForCausalLM,h.Llama4PreTrainedModel,h.LlamaForCausalLM,h.LlamaModel,h.LlamaPreTrainedModel,h.LlamaTokenizer,h.LlavaForConditionalGeneration,h.LlavaOnevisionForConditionalGeneration,h.LlavaOnevisionImageProcessor,h.LlavaPreTrainedModel,h.LlavaProcessor,h.LlavaQwen2ForCausalLM,h.LogitsProcessor,h.LogitsProcessorList,h.LogitsWarper,h.LongT5ForConditionalGeneration,h.LongT5Model,h.LongT5PreTrainedModel,h.M2M100ForConditionalGeneration,h.M2M100Model,h.M2M100PreTrainedModel,h.M2M100Tokenizer,h.MBart50Tokenizer,h.MBartForCausalLM,h.MBartForConditionalGeneration,h.MBartForSequenceClassification,h.MBartModel,h.MBartPreTrainedModel,h.MBartTokenizer,h.MPNetForMaskedLM,h.MPNetForQuestionAnswering,h.MPNetForSequenceClassification,h.MPNetForTokenClassification,h.MPNetModel,h.MPNetPreTrainedModel,h.MPNetTokenizer,h.MT5ForConditionalGeneration,h.MT5Model,h.MT5PreTrainedModel,h.MarianMTModel,h.MarianModel,h.MarianPreTrainedModel,h.MarianTokenizer,h.Mask2FormerImageProcessor,h.MaskFormerFeatureExtractor,h.MaskFormerForInstanceSegmentation,h.MaskFormerImageProcessor,h.MaskFormerModel,h.MaskFormerPreTrainedModel,h.MaskedLMOutput,h.MaxLengthCriteria,h.Metric3DForDepthEstimation,h.Metric3DPreTrainedModel,h.Metric3Dv2ForDepthEstimation,h.Metric3Dv2PreTrainedModel,h.MgpstrForSceneTextRecognition,h.MgpstrModelOutput,h.MgpstrPreTrainedModel,h.MgpstrProcessor,h.MgpstrTokenizer,h.MimiDecoderModel,h.MimiDecoderOutput,h.MimiEncoderModel,h.MimiEncoderOutput,h.MimiModel,h.MimiPreTrainedModel,h.MinLengthLogitsProcessor,h.MinNewTokensLengthLogitsProcessor,h.MistralForCausalLM,h.MistralModel,h.MistralPreTrainedModel,h.MobileBertForMaskedLM,h.MobileBertForQuestionAnswering,h.MobileBertForSequenceClassification,h.MobileBertModel,h.MobileBertPreTrainedModel,h.MobileBertTokenizer,h.MobileLLMForCausalLM,h.MobileLLMModel,h.MobileLLMPreTrainedModel,h.MobileNetV1FeatureExtractor,h.MobileNetV1ForImageClassification,h.MobileNetV1ForSemanticSegmentation,h.MobileNetV1ImageProcessor,h.MobileNetV1Model,h.MobileNetV1PreTrainedModel,h.MobileNetV2FeatureExtractor,h.MobileNetV2ForImageClassification,h.MobileNetV2ForSemanticSegmentation,h.MobileNetV2ImageProcessor,h.MobileNetV2Model,h.MobileNetV2PreTrainedModel,h.MobileNetV3FeatureExtractor,h.MobileNetV3ForImageClassification,h.MobileNetV3ForSemanticSegmentation,h.MobileNetV3ImageProcessor,h.MobileNetV3Model,h.MobileNetV3PreTrainedModel,h.MobileNetV4FeatureExtractor,h.MobileNetV4ForImageClassification,h.MobileNetV4ForSemanticSegmentation,h.MobileNetV4ImageProcessor,h.MobileNetV4Model,h.MobileNetV4PreTrainedModel,h.MobileViTFeatureExtractor,h.MobileViTForImageClassification,h.MobileViTImageProcessor,h.MobileViTModel,h.MobileViTPreTrainedModel,h.MobileViTV2ForImageClassification,h.MobileViTV2Model,h.MobileViTV2PreTrainedModel,h.ModelOutput,h.ModernBertDecoderForCausalLM,h.ModernBertDecoderModel,h.ModernBertDecoderPreTrainedModel,h.ModernBertForMaskedLM,h.ModernBertForSequenceClassification,h.ModernBertForTokenClassification,h.ModernBertModel,h.ModernBertPreTrainedModel,h.Moondream1ForConditionalGeneration,h.MoonshineFeatureExtractor,h.MoonshineForConditionalGeneration,h.MoonshineModel,h.MoonshinePreTrainedModel,h.MoonshineProcessor,h.MptForCausalLM,h.MptModel,h.MptPreTrainedModel,h.MultiModalityCausalLM,h.MultiModalityPreTrainedModel,h.MusicgenForCausalLM,h.MusicgenForConditionalGeneration,h.MusicgenModel,h.MusicgenPreTrainedModel,h.NeoBertForMaskedLM,h.NeoBertForQuestionAnswering,h.NeoBertForSequenceClassification,h.NeoBertForTokenClassification,h.NeoBertModel,h.NeoBertPreTrainedModel,h.NllbTokenizer,h.NoBadWordsLogitsProcessor,h.NoRepeatNGramLogitsProcessor,h.NomicBertModel,h.NomicBertPreTrainedModel,h.NougatImageProcessor,h.NougatTokenizer,h.OPTForCausalLM,h.OPTModel,h.OPTPreTrainedModel,h.ObjectDetectionPipeline,h.Olmo2ForCausalLM,h.Olmo2Model,h.Olmo2PreTrainedModel,h.OlmoForCausalLM,h.OlmoModel,h.OlmoPreTrainedModel,h.OpenELMForCausalLM,h.OpenELMModel,h.OpenELMPreTrainedModel,h.OwlViTFeatureExtractor,h.OwlViTForObjectDetection,h.OwlViTImageProcessor,h.OwlViTModel,h.OwlViTPreTrainedModel,h.OwlViTProcessor,h.Owlv2ForObjectDetection,h.Owlv2ImageProcessor,h.Owlv2Model,h.Owlv2PreTrainedModel,h.PaliGemmaForConditionalGeneration,h.PaliGemmaPreTrainedModel,h.PaliGemmaProcessor,h.PatchTSMixerForPrediction,h.PatchTSMixerModel,h.PatchTSMixerPreTrainedModel,h.PatchTSTForPrediction,h.PatchTSTModel,h.PatchTSTPreTrainedModel,h.Phi3ForCausalLM,h.Phi3Model,h.Phi3PreTrainedModel,h.Phi3VForCausalLM,h.Phi3VImageProcessor,h.Phi3VPreTrainedModel,h.Phi3VProcessor,h.PhiForCausalLM,h.PhiModel,h.PhiPreTrainedModel,h.Pipeline,h.PreTrainedModel,h.PreTrainedTokenizer,h.PretrainedConfig,h.PretrainedMixin,h.Processor,h.PvtForImageClassification,h.PvtImageProcessor,h.PvtModel,h.PvtPreTrainedModel,h.PyAnnoteFeatureExtractor,h.PyAnnoteForAudioFrameClassification,h.PyAnnoteModel,h.PyAnnotePreTrainedModel,h.PyAnnoteProcessor,h.QuestionAnsweringModelOutput,h.QuestionAnsweringPipeline,h.Qwen2ForCausalLM,h.Qwen2Model,h.Qwen2PreTrainedModel,h.Qwen2Tokenizer,h.Qwen2VLForConditionalGeneration,h.Qwen2VLImageProcessor,h.Qwen2VLPreTrainedModel,h.Qwen2VLProcessor,h.Qwen3ForCausalLM,h.Qwen3Model,h.Qwen3PreTrainedModel,h.RFDetrForObjectDetection,h.RFDetrModel,h.RFDetrObjectDetectionOutput,h.RFDetrPreTrainedModel,h.RTDetrForObjectDetection,h.RTDetrImageProcessor,h.RTDetrModel,h.RTDetrObjectDetectionOutput,h.RTDetrPreTrainedModel,h.RTDetrV2ForObjectDetection,h.RTDetrV2Model,h.RTDetrV2ObjectDetectionOutput,h.RTDetrV2PreTrainedModel,h.RawAudio,h.RawImage,h.RawVideo,h.RawVideoFrame,h.RepetitionPenaltyLogitsProcessor,h.ResNetForImageClassification,h.ResNetModel,h.ResNetPreTrainedModel,h.RoFormerForMaskedLM,h.RoFormerForQuestionAnswering,h.RoFormerForSequenceClassification,h.RoFormerForTokenClassification,h.RoFormerModel,h.RoFormerPreTrainedModel,h.RoFormerTokenizer,h.RobertaForMaskedLM,h.RobertaForQuestionAnswering,h.RobertaForSequenceClassification,h.RobertaForTokenClassification,h.RobertaModel,h.RobertaPreTrainedModel,h.RobertaTokenizer,h.SamImageProcessor,h.SamImageSegmentationOutput,h.SamModel,h.SamPreTrainedModel,h.SamProcessor,h.SapiensForDepthEstimation,h.SapiensForNormalEstimation,h.SapiensForSemanticSegmentation,h.SapiensPreTrainedModel,h.SeamlessM4TFeatureExtractor,h.SegformerFeatureExtractor,h.SegformerForImageClassification,h.SegformerForSemanticSegmentation,h.SegformerImageProcessor,h.SegformerModel,h.SegformerPreTrainedModel,h.Seq2SeqLMOutput,h.SequenceClassifierOutput,h.SiglipImageProcessor,h.SiglipModel,h.SiglipPreTrainedModel,h.SiglipTextModel,h.SiglipTokenizer,h.SiglipVisionModel,h.SmolLM3ForCausalLM,h.SmolLM3Model,h.SmolLM3PreTrainedModel,h.SmolVLMForConditionalGeneration,h.SmolVLMImageProcessor,h.SmolVLMProcessor,h.SnacDecoderModel,h.SnacEncoderModel,h.SnacFeatureExtractor,h.SnacModel,h.SnacPreTrainedModel,h.SpeechT5FeatureExtractor,h.SpeechT5ForSpeechToText,h.SpeechT5ForTextToSpeech,h.SpeechT5HifiGan,h.SpeechT5Model,h.SpeechT5PreTrainedModel,h.SpeechT5Processor,h.SpeechT5Tokenizer,h.SqueezeBertForMaskedLM,h.SqueezeBertForQuestionAnswering,h.SqueezeBertForSequenceClassification,h.SqueezeBertModel,h.SqueezeBertPreTrainedModel,h.SqueezeBertTokenizer,h.StableLmForCausalLM,h.StableLmModel,h.StableLmPreTrainedModel,h.Starcoder2ForCausalLM,h.Starcoder2Model,h.Starcoder2PreTrainedModel,h.StoppingCriteria,h.StoppingCriteriaList,h.StyleTextToSpeech2Model,h.StyleTextToSpeech2PreTrainedModel,h.SummarizationPipeline,h.SuppressTokensAtBeginLogitsProcessor,h.Swin2SRForImageSuperResolution,h.Swin2SRImageProcessor,h.Swin2SRModel,h.Swin2SRPreTrainedModel,h.SwinForImageClassification,h.SwinForSemanticSegmentation,h.SwinModel,h.SwinPreTrainedModel,h.T5ForConditionalGeneration,h.T5Model,h.T5PreTrainedModel,h.T5Tokenizer,h.TableTransformerForObjectDetection,h.TableTransformerModel,h.TableTransformerObjectDetectionOutput,h.TableTransformerPreTrainedModel,h.TemperatureLogitsWarper,h.Tensor,h.Text2TextGenerationPipeline,h.TextClassificationPipeline,h.TextGenerationPipeline;var hT=h.TextStreamer;h.TextToAudioPipeline,h.TokenClassificationPipeline,h.TokenClassifierOutput,h.TokenizerModel,h.TopKLogitsWarper,h.TopPLogitsWarper,h.TrOCRForCausalLM,h.TrOCRPreTrainedModel,h.TranslationPipeline,h.UltravoxModel,h.UltravoxPreTrainedModel,h.UltravoxProcessor,h.UniSpeechForCTC,h.UniSpeechForSequenceClassification,h.UniSpeechModel,h.UniSpeechPreTrainedModel,h.UniSpeechSatForAudioFrameClassification,h.UniSpeechSatForCTC,h.UniSpeechSatForSequenceClassification,h.UniSpeechSatModel,h.UniSpeechSatPreTrainedModel,h.VLChatProcessor,h.VLMImageProcessor,h.VaultGemmaForCausalLM,h.VaultGemmaModel,h.VaultGemmaPreTrainedModel,h.ViTFeatureExtractor,h.ViTForImageClassification,h.ViTImageProcessor,h.ViTMAEModel,h.ViTMAEPreTrainedModel,h.ViTMSNForImageClassification,h.ViTMSNModel,h.ViTMSNPreTrainedModel,h.ViTModel,h.ViTPreTrainedModel,h.VisionEncoderDecoderModel,h.VitMatteForImageMatting,h.VitMatteImageProcessor,h.VitMattePreTrainedModel,h.VitPoseForPoseEstimation,h.VitPoseImageProcessor,h.VitPosePreTrainedModel,h.VitsModel,h.VitsModelOutput,h.VitsPreTrainedModel,h.VitsTokenizer,h.VoxtralForConditionalGeneration,h.VoxtralProcessor,h.Wav2Vec2BertForCTC,h.Wav2Vec2BertForSequenceClassification,h.Wav2Vec2BertModel,h.Wav2Vec2BertPreTrainedModel,h.Wav2Vec2CTCTokenizer,h.Wav2Vec2FeatureExtractor,h.Wav2Vec2ForAudioFrameClassification,h.Wav2Vec2ForCTC,h.Wav2Vec2ForSequenceClassification,h.Wav2Vec2Model,h.Wav2Vec2PreTrainedModel,h.Wav2Vec2Processor,h.Wav2Vec2ProcessorWithLM,h.WavLMForAudioFrameClassification,h.WavLMForCTC,h.WavLMForSequenceClassification,h.WavLMForXVector,h.WavLMModel,h.WavLMPreTrainedModel,h.WeSpeakerFeatureExtractor,h.WeSpeakerResNetModel,h.WeSpeakerResNetPreTrainedModel,h.WhisperFeatureExtractor,h.WhisperForConditionalGeneration,h.WhisperModel,h.WhisperPreTrainedModel,h.WhisperProcessor,h.WhisperTextStreamer,h.WhisperTimeStampLogitsProcessor,h.WhisperTokenizer,h.XLMForQuestionAnswering,h.XLMForSequenceClassification,h.XLMForTokenClassification,h.XLMModel,h.XLMPreTrainedModel,h.XLMRobertaForMaskedLM,h.XLMRobertaForQuestionAnswering,h.XLMRobertaForSequenceClassification,h.XLMRobertaForTokenClassification,h.XLMRobertaModel,h.XLMRobertaPreTrainedModel,h.XLMRobertaTokenizer,h.XLMTokenizer,h.XLMWithLMHeadModel,h.XVectorOutput,h.YolosFeatureExtractor,h.YolosForObjectDetection,h.YolosImageProcessor,h.YolosModel,h.YolosObjectDetectionOutput,h.YolosPreTrainedModel,h.ZeroShotAudioClassificationPipeline,h.ZeroShotClassificationPipeline,h.ZeroShotImageClassificationPipeline,h.ZeroShotObjectDetectionPipeline,h.bankers_round,h.cat,h.cos_sim,h.dot,h.dynamic_time_warping,h.env,h.full,h.full_like,h.getCacheShapes,h.hamming,h.hanning,h.interpolate,h.interpolate_4d,h.interpolate_data,h.is_chinese_char,h.layer_norm,h.load_image,h.load_video,h.log_softmax,h.magnitude,h.matmul,h.max,h.mean,h.mean_pooling,h.medianFilter,h.mel_filter_bank,h.min,h.ones,h.ones_like,h.permute,h.permute_data,h.pipeline,h.quantize_embeddings,h.rand,h.read_audio,h.rfft,h.round,h.slice,h.softmax,h.spectrogram,h.stack,h.std_mean,h.topk,h.window_function,h.zeros,h.zeros_like;async function _T(){try{const e=await navigator.gpu.requestAdapter();if(!e)throw new Error("WebGPU is not supported (no adapter found)");if(!e.features.has("shader-f16"))throw new Error("WebGPU adapter does not support shader-f16")}catch(e){self.postMessage({status:"error",data:e.toString()})}}class pc{static async getInstance(r=null){return this.tokenizer??(this.tokenizer=pT.from_pretrained(this.model_id,{progress_callback:r})),this.model??(this.model=dT.from_pretrained(this.model_id,{dtype:"q4f16",device:"webgpu",progress_callback:r})),Promise.all([this.tokenizer,this.model])}}J(pc,"model_id","onnx-community/granite-4.0-micro-ONNX-web");const bi=new mT;let mc=null;async function fT(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 hT(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:mc,max_new_tokens:1024,streamer:c,stopping_criteria:bi,return_dict_in_generate:!0});mc=p;const u=r.batch_decode(d,{skip_special_tokens:!0});self.postMessage({status:"complete",output:u})}async function gT(){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":_T();break;case"load":gT();break;case"generate":bi.reset(),fT(t);break;case"interrupt":bi.interrupt();break;case"reset":mc=null,bi.reset();break}})})();