diff --git "a/assets/background-remove-LpZafIyn.js" "b/assets/background-remove-LpZafIyn.js" new file mode 100644--- /dev/null +++ "b/assets/background-remove-LpZafIyn.js" @@ -0,0 +1,2887 @@ +var uv=Object.defineProperty;var dv=(e,r,t)=>r in e?uv(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var te=(e,r,t)=>dv(e,typeof r!="symbol"?r+"":r,t);import"./Select.vue_vue_type_style_index_0_lang-qnD8bFjG.js";import{_ as cv}from"./InputFile.vue_vue_type_script_setup_true_lang-Y8JV72FD.js";import{d as pv,r as ks,h as hv,H as mv,c as Tn,o as En,e as Sr,i as fv,t as wf,F as bf,l as Mf,j as yf,z as _v,b as gv}from"./index-Bmr1P2PH.js";import"./floating-ui.core-CgBsuaUc.js";const la=new Map,kn=[],wv=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=la.get(e);if(s===void 0)la.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=kn.indexOf(e);o!==-1&&kn.splice(o,1);for(let n=0;n{const r=la.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}}},Mv=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?kn:t;let o;const n=[],i=new Set;for(const l of s){const u=await bv(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&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:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);const a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]},yv="1.21.1";let vf="warning";const ms={wasm:{},webgl:{},webgpu:{},versions:{common:yv},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}`);vf=e}},get logLevel(){return vf}};Object.defineProperty(ms,"logLevel",{enumerable:!0});const vv=ms,xv=(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,u;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?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));const p=n*o;let d=0,c=p,_=p*2,f=-1;i==="RGBA"?(d=0,c=p,_=p*2,f=p*3):i==="RGB"?(d=0,c=p,_=p*2):i==="RBG"&&(d=0,_=p,c=p*2);for(let v=0;v{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 u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[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 c=4;let _=0,f=1,v=2,$=3,w=0,g=d,C=d*2,E=-1;a==="RGBA"?(w=0,g=d,C=d*2,E=d*3):a==="RGB"?(w=0,g=d,C=d*2):a==="RBG"&&(w=0,C=d,g=d*2),s=t.createImageData(o,n);for(let y=0;y{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:t,width:s}=r,o=r.norm??{mean:255,bias:0};let n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let d=4,c=0,_=1,f=2,v=3,$=0,w=u,g=u*2,C=-1;a==="RGB"&&(d=3,c=0,_=1,f=2,v=-1),l==="RGBA"?C=u*3:l==="RBG"?($=0,g=u,w=u*2):l==="BGR"&&(g=0,w=u,$=u*2);for(let y=0;y{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string";let i,a=r??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=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=u(p);if(d!=null){let c=e.height,_=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(c=r.resizedHeight,_=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=c,a.width=_}else a.tensorFormat="RGBA",a.height=c,a.width=_;d.drawImage(e,0,0),i=d.getImageData(0,0,_,c).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 c=l();c.width=d,c.height=p;const _=u(c);if(_!=null)_.putImageData(e,0,0),i=_.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=u(p);if(d!=null){const c=e.height,_=e.width;return d.drawImage(e,0,0,_,c),i=d.getImageData(0,0,_,c).data,a.height=c,a.width=_,kl(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,d)=>{const c=l(),_=u(c);if(!e||!_)return d();const f=new Image;f.crossOrigin="Anonymous",f.src=e,f.onload=()=>{c.width=f.width,c.height=f.height,_.drawImage(f,0,0,c.width,c.height);const v=_.getImageData(0,0,c.width,c.height);a.height=c.height,a.width=c.width,p(kl(v.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return kl(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Pv=(e,r)=>{const{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Qr({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},Cv=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new Qr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},Sv=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new Qr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},$v=(e,r,t)=>new Qr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),so=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ua=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let xf=!1;const kv=()=>{if(!xf){xf=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(so.set("int64",BigInt64Array),ua.set(BigInt64Array,"int64")),r&&(so.set("uint64",BigUint64Array),ua.set(BigUint64Array,"uint64")),s?(so.set("float16",t),ua.set(t,"float16")):so.set("float16",Uint16Array)}},Iv=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Qr(e.type,e.data,r);case"cpu-pinned":return new Qr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Qr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Qr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Qr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Qr=class{constructor(r,t,s){kv();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=so.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 u=so.get(r);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&u===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${u.name} as data.`);r==="uint64"||r==="int64"?a=u.from(t,BigInt):a=u.from(t)}else if(t instanceof u)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&&u!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${o} tensor's data must be type of ${u}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const u=typeof r[0];if(u==="string")o="string",a=r;else if(u==="boolean")o="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else if(r instanceof Uint8ClampedArray)o="uint8",a=Uint8Array.from(r);else{const u=ua.get(r.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);o=u,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=Iv(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 Ev(r,t)}static fromTexture(r,t){return Pv(r,t)}static fromGpuBuffer(r,t){return Cv(r,t)}static fromMLTensor(r,t){return Sv(r,t)}static fromPinnedBuffer(r,t,s){return $v(r,t,s)}toDataURL(r){return xv(this,r)}toImageData(r){return Tv(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 Av(this,r)}};const to=Qr,nb=(e,r)=>{(typeof ms.trace>"u"?!ms.wasm.trace:!ms.trace)||console.timeStamp(`${e}::ORT::${r}`)},ob=(e,r)=>{var o;const t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[];let s=!1;for(let n=0;n{(typeof ms.trace>"u"?!ms.wasm.trace:!ms.trace)||ob("BEGIN",e)},Iu=e=>{(typeof ms.trace>"u"?!ms.wasm.trace:!ms.trace)||ob("END",e)};let Fv=class ib{constructor(r){this.handler=r}async run(r,t,s){ku();const o={};let n={};if(typeof r!="object"||r===null||r instanceof to||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 to)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 u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1;const p=Object.getOwnPropertyNames(t);for(const d of this.outputNames)if(p.indexOf(d)!==-1){const c=t[d];(c===null||c instanceof to)&&(u=!0,i=!1,o[d]=c)}if(u){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 u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(const u of this.outputNames)o[u]=null;const a=await this.handler.run(r,o,n),l={};for(const u in a)if(Object.hasOwnProperty.call(a,u)){const p=a[u];p instanceof to?l[u]=p:l[u]=new to(p.type,p.data,p.dims)}return Iu(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){ku();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,c=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(c=r.byteLength-d,typeof s=="number"){if(c=s,!Number.isSafeInteger(c))throw new RangeError("'byteLength' must be an integer.");if(c<=0||d+c>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,c)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await Mv(i),u=await a.createInferenceSessionHandler(n,l);return Iu(),new ib(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const Ov=Fv,Dv=Object.freeze(Object.defineProperty({__proto__:null,InferenceSession:Ov,TRACE:nb,TRACE_FUNC_BEGIN:ku,TRACE_FUNC_END:Iu,Tensor:to,env:vv,registerBackend:wv},Symbol.toStringTag,{value:"Module"}));/*! + * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var qu=Object.defineProperty,Lv=Object.getOwnPropertyDescriptor,zv=Object.getOwnPropertyNames,Bv=Object.prototype.hasOwnProperty,Rv=(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')}),Re=(e,r)=>()=>(e&&(r=e(e=0)),r),ao=(e,r)=>{for(var t in r)qu(e,t,{get:r[t],enumerable:!0})},jv=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of zv(r))!Bv.call(e,o)&&o!==t&&qu(e,o,{get:()=>r[o],enumerable:!(s=Lv(r,o))||s.enumerable});return e},Jo=e=>jv(qu({},"__esModule",{value:!0}),e),Lo,Hs,Fn,Tf,ab,lb=Re(()=>{Lo=new Map,Hs=[],Fn=(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=Hs.indexOf(e);o!==-1&&Hs.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}}},ab=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Hs:t,o,n=[],i=new Set;for(let l of s){let u=await Tf(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&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:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]}}),Nv=Re(()=>{lb()}),ub,Vv=Re(()=>{ub="1.22.0-dev.20250409-89f8206ba4"}),Il,Xr,db=Re(()=>{Vv(),Il="warning",Xr={wasm:{},webgl:{},webgpu:{},versions:{common:ub},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}`);Il=e}},get logLevel(){return Il}},Object.defineProperty(Xr,"logLevel",{enumerable:!0})}),jt,Uv=Re(()=>{db(),jt=Xr}),cb,pb,Wv=Re(()=>{cb=(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,u;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?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));let p=n*o,d=0,c=p,_=p*2,f=-1;i==="RGBA"?(d=0,c=p,_=p*2,f=p*3):i==="RGB"?(d=0,c=p,_=p*2):i==="RBG"&&(d=0,_=p,c=p*2);for(let v=0;v{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,u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[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 c=4,_=0,f=1,v=2,$=3,w=0,g=d,C=d*2,E=-1;a==="RGBA"?(w=0,g=d,C=d*2,E=d*3):a==="RGB"?(w=0,g=d,C=d*2):a==="RBG"&&(w=0,C=d,g=d*2),s=t.createImageData(o,n);for(let y=0;y{Xu(),qi=(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",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),d=4,c=0,_=1,f=2,v=3,$=0,w=u,g=u*2,C=-1;a==="RGB"&&(d=3,c=0,_=1,f=2,v=-1),l==="RGBA"?C=u*3:l==="RBG"?($=0,g=u,w=u*2):l==="BGR"&&(g=0,w=u,$=u*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")},u=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=u(p);if(d!=null){let c=e.height,_=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(c=r.resizedHeight,_=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=c,a.width=_}else a.tensorFormat="RGBA",a.height=c,a.width=_;d.drawImage(e,0,0),i=d.getImageData(0,0,_,c).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 c=l();c.width=d,c.height=p;let _=u(c);if(_!=null)_.putImageData(e,0,0),i=_.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=u(p);if(d!=null){let c=e.height,_=e.width;return d.drawImage(e,0,0,_,c),i=d.getImageData(0,0,_,c).data,a.height=c,a.width=_,qi(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,d)=>{let c=l(),_=u(c);if(!e||!_)return d();let f=new Image;f.crossOrigin="Anonymous",f.src=e,f.onload=()=>{c.width=f.width,c.height=f.height,_.drawImage(f,0,0,c.width,c.height);let v=_.getImageData(0,0,c.width,c.height);a.height=c.height,a.width=c.width,p(qi(v.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return qi(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},mb=(e,r)=>{let{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Nr({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},fb=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Nr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},_b=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Nr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},gb=(e,r,t)=>new Nr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),In,Ko,Al,wb,Kv=Re(()=>{In=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Ko=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Al=!1,wb=()=>{if(!Al){Al=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(In.set("int64",BigInt64Array),Ko.set(BigInt64Array,"int64")),r&&(In.set("uint64",BigUint64Array),Ko.set(BigUint64Array,"uint64")),s?(In.set("float16",t),Ko.set(t,"float16")):In.set("float16",Uint16Array)}}}),bb,Mb,Hv=Re(()=>{Xu(),bb=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Nr(e.type,e.data,r);case"cpu-pinned":return new Nr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Nr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Nr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Nr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Nr,Xu=Re(()=>{Wv(),Gv(),Kv(),Hv(),Nr=class{constructor(e,r,t){wb();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=In.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=In.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=Ko.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=bb(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 hb(e,r)}static fromTexture(e,r){return mb(e,r)}static fromGpuBuffer(e,r){return fb(e,r)}static fromMLTensor(e,r){return _b(e,r)}static fromPinnedBuffer(e,r,t){return gb(e,r,t)}toDataURL(e){return cb(this,e)}toImageData(e){return pb(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 Mb(this,e)}}}),hs,yb=Re(()=>{Xu(),hs=Nr}),Yo,Fl,fs,Jr,vb=Re(()=>{db(),Yo=(e,r)=>{(typeof Xr.trace>"u"?!Xr.wasm.trace:!Xr.trace)||console.timeStamp(`${e}::ORT::${r}`)},Fl=(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 Xr.trace>"u"?!Xr.wasm.trace:!Xr.trace)||Fl("BEGIN",e)},Jr=e=>{(typeof Xr.trace>"u"?!Xr.wasm.trace:!Xr.trace)||Fl("END",e)}}),xb,qv=Re(()=>{lb(),yb(),vb(),xb=class Tb{constructor(r){this.handler=r}async run(r,t,s){fs();let o={},n={};if(typeof r!="object"||r===null||r instanceof hs||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 hs)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 u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,p=Object.getOwnPropertyNames(t);for(let d of this.outputNames)if(p.indexOf(d)!==-1){let c=t[d];(c===null||c instanceof hs)&&(u=!0,i=!1,o[d]=c)}if(u){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 u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(let u of this.outputNames)o[u]=null;let a=await this.handler.run(r,o,n),l={};for(let u in a)if(Object.hasOwnProperty.call(a,u)){let p=a[u];p instanceof hs?l[u]=p:l[u]=new hs(p.type,p.data,p.dims)}return Jr(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){fs();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){let p=r,d=0,c=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(c=r.byteLength-d,typeof s=="number"){if(c=s,!Number.isSafeInteger(c))throw new RangeError("'byteLength' must be an integer.");if(c<=0||d+c>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,c)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await ab(i),u=await a.createInferenceSessionHandler(n,l);return Jr(),new Tb(u)}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}}}),Qu,Xv=Re(()=>{qv(),Qu=xb}),Qv=Re(()=>{}),Jv=Re(()=>{}),Yv=Re(()=>{}),Zv=Re(()=>{}),Eb={};ao(Eb,{InferenceSession:()=>Qu,TRACE:()=>Yo,TRACE_FUNC_BEGIN:()=>fs,TRACE_FUNC_END:()=>Jr,Tensor:()=>hs,env:()=>jt,registerBackend:()=>Fn});var _s=Re(()=>{Nv(),Uv(),Xv(),yb(),Qv(),Jv(),vb(),Yv(),Zv()}),Ju=Re(()=>{}),Pb={};ao(Pb,{default:()=>Cb});var Ol,Dl,Cb,ex=Re(()=>{var e;A0(),zn(),Yu(),Ol="ort-wasm-proxy-worker",Dl=((e=globalThis.self)==null?void 0:e.name)===Ol,Dl&&(self.onmessage=r=>{let{type:t,in:s}=r.data;try{switch(t){case"init-wasm":Zu(s.wasm).then(()=>{gd(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;wd(n,o).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:o}=s,n=wa(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=s;bd(o,n).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":Md(s),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:i,outputIndices:a,options:l}=s;yd(o,n,i,a,new Array(a.length).fill(null),l).then(u=>{u.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:u},xd([...i,...u]))},u=>{postMessage({type:t,err:u})});break}case"end-profiling":vd(s),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}}),Cb=Dl?null:r=>new Worker(r??jr,{type:"module",name:Ol})}),Sb={};ao(Sb,{default:()=>$b});var Ll,zl,$b,Ef,tx=Re(()=>{var e,r;zl=(Ll=import.meta.url,async function(t={}){var Oo;var s,o,n=t,i=new Promise((h,T)=>{s=h,o=T}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",u=l&&((Oo=self.name)==null?void 0:Oo.startsWith("em-pthread"));n.mountExternalData=(h,T)=>{h.startsWith("./")&&(h=h.substring(2)),(n.Eb||(n.Eb=new Map)).set(h,T)},n.unmountExternalData=()=>{delete n.Eb};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let d=h=>async(...T)=>{var I;try{if(n.Fb)throw Error("Session already started");let L=n.Fb={dc:T[0],errors:[]},U=await h(...T);if(n.Fb!==L)throw Error("Session mismatch");(I=n.Jb)==null||I.flush();let ue=L.errors;if(0Oe),0{if(h==="webgpu"){[n.Jb,n.Ub,n.Yb,n.Kb,n.Xb,n.jb,n.Zb,n.ac,n.Vb,n.Wb,n.$b]=T;let I=n.Jb;n.jsepRegisterBuffer=(L,U,ue,Te)=>I.registerBuffer(L,U,ue,Te),n.jsepGetBuffer=L=>I.getBuffer(L),n.jsepCreateDownloader=(L,U,ue)=>I.createDownloader(L,U,ue),n.jsepOnCreateSession=L=>{I.onCreateSession(L)},n.jsepOnReleaseSession=L=>{I.onReleaseSession(L)},n.jsepOnRunStart=L=>I.onRunStart(L),n.bc=(L,U)=>{I.upload(L,U)}}else if(h==="webnn"){let I=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=L=>I.onRunStart(L),n.webnnOnRunEnd=I.onRunEnd.bind(I),n.webnnRegisterMLContext=(L,U)=>{I.registerMLContext(L,U)},n.webnnOnReleaseSession=L=>{I.onReleaseSession(L)},n.webnnCreateMLTensorDownloader=(L,U)=>I.createMLTensorDownloader(L,U),n.webnnRegisterMLTensor=(L,U,ue,Te)=>I.registerMLTensor(L,U,ue,Te),n.webnnCreateMLContext=L=>I.createMLContext(L),n.webnnRegisterMLConstant=(L,U,ue,Te,Oe,Ke)=>I.registerMLConstant(L,U,ue,Te,Oe,n.Eb,Ke),n.webnnRegisterGraphInput=I.registerGraphInput.bind(I),n.webnnIsGraphInput=I.isGraphInput.bind(I),n.webnnCreateTemporaryTensor=I.createTemporaryTensor.bind(I),n.webnnIsInt64Supported=I.isInt64Supported.bind(I)}};let c=()=>{let h=(T,I,L)=>(...U)=>{let ue=Nt,Te=I==null?void 0:I();U=T(...U);let Oe=I==null?void 0:I();return Te!==Oe&&(T=Oe,L(Te),I=L=null),Nt!=ue?new Promise((Ke,Ye)=>{Lr={resolve:Ke,reject:Ye}}):U};(()=>{for(let T of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])n[T]=h(n[T],()=>n[T],I=>n[T]=I)})(),d!==void 0&&(n._OrtRun=d(n._OrtRun),n._OrtRunWithBinding=d(n._OrtRunWithBinding)),c=void 0};n.asyncInit=()=>{c==null||c()};var _,f,v=Object.assign({},n),$=(h,T)=>{throw T},w="";(a||l)&&(l?w=self.location.href:typeof document<"u"&&document.currentScript&&(w=document.currentScript.src),Ll&&(w=Ll),w=w.startsWith("blob:")?"":w.slice(0,w.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(f=h=>{var T=new XMLHttpRequest;return T.open("GET",h,!1),T.responseType="arraybuffer",T.send(null),new Uint8Array(T.response)}),_=async h=>{if(V(h))return new Promise((I,L)=>{var U=new XMLHttpRequest;U.open("GET",h,!0),U.responseType="arraybuffer",U.onload=()=>{U.status==200||U.status==0&&U.response?I(U.response):L(U.status)},U.onerror=L,U.send(null)});var T=await fetch(h,{credentials:"same-origin"});if(T.ok)return T.arrayBuffer();throw Error(T.status+" : "+T.url)});var g=console.log.bind(console),C=console.error.bind(console),E=g,y=C;Object.assign(n,v),v=null;var b,x,S,A,B,K,G,j,ee,H,Z,X,oe,me=n.wasmBinary,ae=!1,V=h=>h.startsWith("file://");function F(){return b.buffer!=A.buffer&&R(),A}function W(){return b.buffer!=A.buffer&&R(),B}function re(){return b.buffer!=A.buffer&&R(),K}function fe(){return b.buffer!=A.buffer&&R(),G}function se(){return b.buffer!=A.buffer&&R(),j}function ce(){return b.buffer!=A.buffer&&R(),ee}function $e(){return b.buffer!=A.buffer&&R(),H}function Ue(){return b.buffer!=A.buffer&&R(),oe}if(u){let h=function(T){try{var I=T.data,L=I.Bb;if(L==="load"){let U=[];self.onmessage=ue=>U.push(ue),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let ue of U)h(ue);self.onmessage=h};for(let ue of I.Rb)n[ue]&&!n[ue].proxy||(n[ue]=(...Te)=>{postMessage({Bb:"callHandler",Qb:ue,args:Te})},ue=="print"&&(E=n[ue]),ue=="printErr"&&(y=n[ue]));b=I.kc,R(),we(I.lc)}else if(L==="run"){kr(I.Ab),_n(I.Ab,0,0,1,0,0),lr(),ve(I.Ab),q||(Po(),q=!0);try{Ds(I.fc,I.Hb)}catch(U){if(U!="unwind")throw U}}else I.target!=="setimmediate"&&(L==="checkMailbox"?q&&je():L&&(y(`worker: received unknown command ${L}`),y(I)))}catch(U){throw Co(),U}};var we,q=!1;y=function(...T){T=T.join(" "),console.error(T)},self.alert=function(...T){postMessage({Bb:"alert",text:T.join(" "),ic:Ws()})},self.onunhandledrejection=T=>{throw T.reason||T},self.onmessage=h}function R(){var h=b.buffer;n.HEAP8=A=new Int8Array(h),n.HEAP16=K=new Int16Array(h),n.HEAPU8=B=new Uint8Array(h),n.HEAPU16=G=new Uint16Array(h),n.HEAP32=j=new Int32Array(h),n.HEAPU32=ee=new Uint32Array(h),n.HEAPF32=H=new Float32Array(h),n.HEAPF64=oe=new Float64Array(h),n.HEAP64=Z=new BigInt64Array(h),n.HEAPU64=X=new BigUint64Array(h)}function pe(){u?startWorker(n):nt.Ca()}u||(b=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),R());var xe,Me=0,Se=null;function Ae(){if(--Me==0&&Se){var h=Se;Se=null,h()}}function Fe(h){throw y(h="Aborted("+h+")"),ae=!0,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),o(h),h}function ze(){return{a:{L:Y,Aa:O,b:Ls,$:Zr,A:es,pa:ts,X:De,Z:Qe,qa:et,na:Bt,ga:Or,ma:Pr,J:rs,Y:ss,V:Ur,oa:ns,W:os,va:Ys,E:Zs,Q:en,O:rn,D:nn,u:on,r:Ms,P:an,z:N,R:Q,ja:ie,T:He,aa:Je,M:dt,F:vt,ia:ve,sa:Et,t:Kt,Ba:Mr,w:or,o:Zt,l:Rs,c:Ps,n:ei,j:si,v:ni,p:oi,f:ii,s:ai,m:lo,e:li,k:ui,i:uo,g:di,d:co,da:ci,ea:ho,fa:hi,ba:pn,ca:mo,N:fo,xa:fi,ua:gi,h:wi,C:_o,G:Ss,ta:_i,x:bi,ra:ba,U:Mi,q:mi,y:Ma,K:yi,S:go,za:vi,ya:xi,ka:Mo,la:Vn,_:Xe,B:yo,I:vo,ha:Un,H:xo,a:b,wa:Ie}}}var Ve={829644:(h,T,I,L,U)=>{if(n===void 0||!n.Eb)return 1;if((h=Ft(Number(h>>>0))).startsWith("./")&&(h=h.substring(2)),!(h=n.Eb.get(h)))return 2;if(T=Number(T>>>0),I=Number(I>>>0),L=Number(L>>>0),T+I>h.byteLength)return 3;try{let ue=h.subarray(T,T+I);switch(U){case 0:W().set(ue,L>>>0);break;case 1:n.mc?n.mc(L,ue):n.bc(L,ue);break;default:return 4}return 0}catch{return 4}},830468:(h,T,I)=>{n.Ob(h,W().subarray(T>>>0,T+I>>>0))},830532:()=>n.nc(),830574:h=>{n.Nb(h)},830611:()=>{n.Vb()},830642:()=>{n.Wb()},830671:()=>{n.$b()},830696:h=>n.Ub(h),830729:h=>n.Yb(h),830761:(h,T,I)=>{n.Kb(Number(h),Number(T),Number(I),!0)},830824:(h,T,I)=>{n.Kb(Number(h),Number(T),Number(I))},830881:()=>typeof wasmOffsetConverter<"u",830938:h=>{n.jb("Abs",h,void 0)},830989:h=>{n.jb("Neg",h,void 0)},831040:h=>{n.jb("Floor",h,void 0)},831093:h=>{n.jb("Ceil",h,void 0)},831145:h=>{n.jb("Reciprocal",h,void 0)},831203:h=>{n.jb("Sqrt",h,void 0)},831255:h=>{n.jb("Exp",h,void 0)},831306:h=>{n.jb("Erf",h,void 0)},831357:h=>{n.jb("Sigmoid",h,void 0)},831412:(h,T,I)=>{n.jb("HardSigmoid",h,{alpha:T,beta:I})},831491:h=>{n.jb("Log",h,void 0)},831542:h=>{n.jb("Sin",h,void 0)},831593:h=>{n.jb("Cos",h,void 0)},831644:h=>{n.jb("Tan",h,void 0)},831695:h=>{n.jb("Asin",h,void 0)},831747:h=>{n.jb("Acos",h,void 0)},831799:h=>{n.jb("Atan",h,void 0)},831851:h=>{n.jb("Sinh",h,void 0)},831903:h=>{n.jb("Cosh",h,void 0)},831955:h=>{n.jb("Asinh",h,void 0)},832008:h=>{n.jb("Acosh",h,void 0)},832061:h=>{n.jb("Atanh",h,void 0)},832114:h=>{n.jb("Tanh",h,void 0)},832166:h=>{n.jb("Not",h,void 0)},832217:(h,T,I)=>{n.jb("Clip",h,{min:T,max:I})},832286:h=>{n.jb("Clip",h,void 0)},832338:(h,T)=>{n.jb("Elu",h,{alpha:T})},832396:h=>{n.jb("Gelu",h,void 0)},832448:h=>{n.jb("Relu",h,void 0)},832500:(h,T)=>{n.jb("LeakyRelu",h,{alpha:T})},832564:(h,T)=>{n.jb("ThresholdedRelu",h,{alpha:T})},832634:(h,T)=>{n.jb("Cast",h,{to:T})},832692:h=>{n.jb("Add",h,void 0)},832743:h=>{n.jb("Sub",h,void 0)},832794:h=>{n.jb("Mul",h,void 0)},832845:h=>{n.jb("Div",h,void 0)},832896:h=>{n.jb("Pow",h,void 0)},832947:h=>{n.jb("Equal",h,void 0)},833e3:h=>{n.jb("Greater",h,void 0)},833055:h=>{n.jb("GreaterOrEqual",h,void 0)},833117:h=>{n.jb("Less",h,void 0)},833169:h=>{n.jb("LessOrEqual",h,void 0)},833228:(h,T,I,L,U)=>{n.jb("ReduceMean",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833403:(h,T,I,L,U)=>{n.jb("ReduceMax",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833577:(h,T,I,L,U)=>{n.jb("ReduceMin",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833751:(h,T,I,L,U)=>{n.jb("ReduceProd",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833926:(h,T,I,L,U)=>{n.jb("ReduceSum",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834100:(h,T,I,L,U)=>{n.jb("ReduceL1",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834273:(h,T,I,L,U)=>{n.jb("ReduceL2",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834446:(h,T,I,L,U)=>{n.jb("ReduceLogSum",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834623:(h,T,I,L,U)=>{n.jb("ReduceSumSquare",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834803:(h,T,I,L,U)=>{n.jb("ReduceLogSumExp",h,{keepDims:!!T,noopWithEmptyAxes:!!I,axes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834983:h=>{n.jb("Where",h,void 0)},835036:(h,T,I)=>{n.jb("Transpose",h,{perm:T?Array.from(se().subarray(Number(T)>>>0,Number(I)>>>0)):[]})},835160:(h,T,I,L)=>{n.jb("DepthToSpace",h,{blocksize:T,mode:Ft(I),format:L?"NHWC":"NCHW"})},835293:(h,T,I,L)=>{n.jb("DepthToSpace",h,{blocksize:T,mode:Ft(I),format:L?"NHWC":"NCHW"})},835426:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr,$s)=>{n.jb("ConvTranspose",h,{format:Ke?"NHWC":"NCHW",autoPad:T,dilations:[I],group:L,kernelShape:[U],pads:[ue,Te],strides:[Oe],wIsConst:()=>!!F()[Ye>>>0],outputPadding:ht?Array.from(se().subarray(Number(ht)>>>0,Number(xt)>>>0)):[],outputShape:It?Array.from(se().subarray(Number(It)>>>0,Number(sr)>>>0)):[],activation:Ft($s)})},835859:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr)=>{n.jb("ConvTranspose",h,{format:Oe?"NHWC":"NCHW",autoPad:T,dilations:Array.from(se().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(se().subarray(Number(U)>>>0,2+(Number(U)>>>0)>>>0)),pads:Array.from(se().subarray(Number(ue)>>>0,4+(Number(ue)>>>0)>>>0)),strides:Array.from(se().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!F()[Ke>>>0],outputPadding:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],outputShape:xt?Array.from(se().subarray(Number(xt)>>>0,Number(It)>>>0)):[],activation:Ft(sr)})},836520:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr,$s)=>{n.jb("ConvTranspose",h,{format:Ke?"NHWC":"NCHW",autoPad:T,dilations:[I],group:L,kernelShape:[U],pads:[ue,Te],strides:[Oe],wIsConst:()=>!!F()[Ye>>>0],outputPadding:ht?Array.from(se().subarray(Number(ht)>>>0,Number(xt)>>>0)):[],outputShape:It?Array.from(se().subarray(Number(It)>>>0,Number(sr)>>>0)):[],activation:Ft($s)})},836953:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr)=>{n.jb("ConvTranspose",h,{format:Oe?"NHWC":"NCHW",autoPad:T,dilations:Array.from(se().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(se().subarray(Number(U)>>>0,2+(Number(U)>>>0)>>>0)),pads:Array.from(se().subarray(Number(ue)>>>0,4+(Number(ue)>>>0)>>>0)),strides:Array.from(se().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!F()[Ke>>>0],outputPadding:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],outputShape:xt?Array.from(se().subarray(Number(xt)>>>0,Number(It)>>>0)):[],activation:Ft(sr)})},837614:(h,T)=>{n.jb("GlobalAveragePool",h,{format:T?"NHWC":"NCHW"})},837705:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr)=>{n.jb("AveragePool",h,{format:sr?"NHWC":"NCHW",auto_pad:T,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],strides:xt?Array.from(se().subarray(Number(xt)>>>0,Number(It)>>>0)):[]})},838184:(h,T)=>{n.jb("GlobalAveragePool",h,{format:T?"NHWC":"NCHW"})},838275:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr)=>{n.jb("AveragePool",h,{format:sr?"NHWC":"NCHW",auto_pad:T,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],strides:xt?Array.from(se().subarray(Number(xt)>>>0,Number(It)>>>0)):[]})},838754:(h,T)=>{n.jb("GlobalMaxPool",h,{format:T?"NHWC":"NCHW"})},838841:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr)=>{n.jb("MaxPool",h,{format:sr?"NHWC":"NCHW",auto_pad:T,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],strides:xt?Array.from(se().subarray(Number(xt)>>>0,Number(It)>>>0)):[]})},839316:(h,T)=>{n.jb("GlobalMaxPool",h,{format:T?"NHWC":"NCHW"})},839403:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr)=>{n.jb("MaxPool",h,{format:sr?"NHWC":"NCHW",auto_pad:T,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],pads:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],strides:xt?Array.from(se().subarray(Number(xt)>>>0,Number(It)>>>0)):[]})},839878:(h,T,I,L,U)=>{n.jb("Gemm",h,{alpha:T,beta:I,transA:L,transB:U})},839982:h=>{n.jb("MatMul",h,void 0)},840036:(h,T,I,L)=>{n.jb("ArgMax",h,{keepDims:!!T,selectLastIndex:!!I,axis:L})},840144:(h,T,I,L)=>{n.jb("ArgMin",h,{keepDims:!!T,selectLastIndex:!!I,axis:L})},840252:(h,T)=>{n.jb("Softmax",h,{axis:T})},840315:(h,T)=>{n.jb("Concat",h,{axis:T})},840375:(h,T,I,L,U)=>{n.jb("Split",h,{axis:T,numOutputs:I,splitSizes:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},840531:h=>{n.jb("Expand",h,void 0)},840585:(h,T)=>{n.jb("Gather",h,{axis:Number(T)})},840656:(h,T)=>{n.jb("GatherElements",h,{axis:Number(T)})},840735:(h,T)=>{n.jb("GatherND",h,{batch_dims:Number(T)})},840814:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht)=>{n.jb("Resize",h,{antialias:T,axes:I?Array.from(se().subarray(Number(I)>>>0,Number(L)>>>0)):[],coordinateTransformMode:Ft(U),cubicCoeffA:ue,excludeOutside:Te,extrapolationValue:Oe,keepAspectRatioPolicy:Ft(Ke),mode:Ft(Ye),nearestMode:Ft(ht)})},841176:(h,T,I,L,U,ue,Te)=>{n.jb("Slice",h,{starts:T?Array.from(se().subarray(Number(T)>>>0,Number(I)>>>0)):[],ends:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[],axes:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[]})},841440:h=>{n.jb("Tile",h,void 0)},841492:(h,T,I)=>{n.jb("InstanceNormalization",h,{epsilon:T,format:I?"NHWC":"NCHW"})},841606:(h,T,I)=>{n.jb("InstanceNormalization",h,{epsilon:T,format:I?"NHWC":"NCHW"})},841720:h=>{n.jb("Range",h,void 0)},841773:(h,T)=>{n.jb("Einsum",h,{equation:Ft(T)})},841854:(h,T,I,L,U)=>{n.jb("Pad",h,{mode:T,value:I,pads:L?Array.from(se().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},841997:(h,T,I,L,U,ue)=>{n.jb("BatchNormalization",h,{epsilon:T,momentum:I,spatial:!!U,trainingMode:!!L,format:ue?"NHWC":"NCHW"})},842166:(h,T,I,L,U,ue)=>{n.jb("BatchNormalization",h,{epsilon:T,momentum:I,spatial:!!U,trainingMode:!!L,format:ue?"NHWC":"NCHW"})},842335:(h,T,I)=>{n.jb("CumSum",h,{exclusive:Number(T),reverse:Number(I)})},842432:(h,T,I)=>{n.jb("DequantizeLinear",h,{axis:T,blockSize:I})},842522:(h,T,I,L,U)=>{n.jb("GridSample",h,{align_corners:T,mode:Ft(I),padding_mode:Ft(L),format:U?"NHWC":"NCHW"})},842692:(h,T,I,L,U)=>{n.jb("GridSample",h,{align_corners:T,mode:Ft(I),padding_mode:Ft(L),format:U?"NHWC":"NCHW"})},842862:(h,T)=>{n.jb("ScatterND",h,{reduction:Ft(T)})},842947:(h,T,I,L,U,ue,Te,Oe,Ke)=>{n.jb("Attention",h,{numHeads:T,isUnidirectional:I,maskFilterValue:L,scale:U,doRotary:ue,qkvHiddenSizes:Te?Array.from(se().subarray(Number(Oe)>>>0,Number(Oe)+Te>>>0)):[],pastPresentShareBuffer:!!Ke})},843219:h=>{n.jb("BiasAdd",h,void 0)},843274:h=>{n.jb("BiasSplitGelu",h,void 0)},843335:h=>{n.jb("FastGelu",h,void 0)},843391:(h,T,I,L,U,ue,Te,Oe,Ke,Ye,ht,xt,It,sr,$s,Ei)=>{n.jb("Conv",h,{format:xt?"NHWC":"NCHW",auto_pad:T,dilations:I?Array.from(se().subarray(Number(I)>>>0,Number(L)>>>0)):[],group:U,kernel_shape:ue?Array.from(se().subarray(Number(ue)>>>0,Number(Te)>>>0)):[],pads:Oe?Array.from(se().subarray(Number(Oe)>>>0,Number(Ke)>>>0)):[],strides:Ye?Array.from(se().subarray(Number(Ye)>>>0,Number(ht)>>>0)):[],w_is_const:()=>!!F()[Number(It)>>>0],activation:Ft(sr),activation_params:$s?Array.from($e().subarray(Number($s)>>>0,Number(Ei)>>>0)):[]})},843975:h=>{n.jb("Gelu",h,void 0)},844027:(h,T,I,L,U,ue,Te,Oe,Ke)=>{n.jb("GroupQueryAttention",h,{numHeads:T,kvNumHeads:I,scale:L,softcap:U,doRotary:ue,rotaryInterleaved:Te,smoothSoftmax:Oe,localWindowSize:Ke})},844244:(h,T,I,L)=>{n.jb("LayerNormalization",h,{axis:T,epsilon:I,simplified:!!L})},844355:(h,T,I,L)=>{n.jb("LayerNormalization",h,{axis:T,epsilon:I,simplified:!!L})},844466:(h,T,I,L,U,ue)=>{n.jb("MatMulNBits",h,{k:T,n:I,accuracyLevel:L,bits:U,blockSize:ue})},844593:(h,T,I,L,U,ue)=>{n.jb("MultiHeadAttention",h,{numHeads:T,isUnidirectional:I,maskFilterValue:L,scale:U,doRotary:ue})},844752:(h,T)=>{n.jb("QuickGelu",h,{alpha:T})},844816:(h,T,I,L,U)=>{n.jb("RotaryEmbedding",h,{interleaved:!!T,numHeads:I,rotaryEmbeddingDim:L,scale:U})},844955:(h,T,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:T,simplified:!!I})},845057:(h,T,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:T,simplified:!!I})},845159:(h,T,I,L)=>{n.jb("GatherBlockQuantized",h,{gatherAxis:T,quantizeAxis:I,blockSize:L})},845280:h=>{n.Zb(h)},845314:(h,T)=>n.ac(Number(h),Number(T),n.Fb.dc,n.Fb.errors)};function O(h,T,I){return zr(async()=>{await n.Xb(Number(h),Number(T),Number(I))})}function Y(){return typeof wasmOffsetConverter<"u"}class z{constructor(T){te(this,"name","ExitStatus");this.message=`Program terminated with exit(${T})`,this.status=T}}var J=h=>{h.terminate(),h.onmessage=()=>{}},le=[],ye=h=>{Ge.length==0&&(gs(),Yr(Ge[0]));var T=Ge.pop();if(!T)return 6;lt.push(T),Gt[h.Ab]=T,T.Ab=h.Ab;var I={Bb:"run",fc:h.ec,Hb:h.Hb,Ab:h.Ab};return T.postMessage(I,h.Mb),0},Ee=0,ke=(h,T,...I)=>{for(var L=2*I.length,U=qn(),ue=wn(8*L),Te=ue>>>3,Oe=0;Oe>>0]=Ke)}return h=So(h,0,L,ue,T),gn(U),h};function Ie(h){if(u)return ke(0,1,h);if(S=h,!(0{if(S=h,u)throw Be(h),"unwind";Ie(h)},Ge=[],lt=[],wt=[],Gt={},Ot=h=>{var T=h.Ab;delete Gt[T],Ge.push(h),lt.splice(lt.indexOf(h),1),h.Ab=0,Gn(T)};function lr(){wt.forEach(h=>h())}var Yr=h=>new Promise(T=>{h.onmessage=U=>{var ue=(U=U.data).Bb;if(U.Gb&&U.Gb!=Ws()){var Te=Gt[U.Gb];Te?Te.postMessage(U,U.Mb):y(`Internal error! Worker sent a message "${ue}" to target pthread ${U.Gb}, but that thread no longer exists!`)}else ue==="checkMailbox"?je():ue==="spawnThread"?ye(U):ue==="cleanupThread"?Ot(Gt[U.hc]):ue==="loaded"?(h.loaded=!0,T(h)):ue==="alert"?alert(`Thread ${U.ic}: ${U.text}`):U.target==="setimmediate"?h.postMessage(U):ue==="callHandler"?n[U.Qb](...U.args):ue&&y(`worker sent an unknown command ${ue}`)},h.onerror=U=>{throw y(`worker sent an error! ${U.filename}:${U.lineno}: ${U.message}`),U};var I,L=[];for(I of[])n.propertyIsEnumerable(I)&&L.push(I);h.postMessage({Bb:"load",Rb:L,kc:b,lc:x})});function gs(){var h=new Worker((()=>{let T=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new T("ort.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Ge.push(h)}var kr=h=>{R();var T=ce()[h+52>>>2>>>0];h=ce()[h+56>>>2>>>0],ko(T,T-h),gn(T)},Ds=(h,T)=>{Ee=0,h=Io(h,T),0>>=0);throw T>>>=0,I>>>=0,ce()[L.Ib+16>>>2>>>0]=0,ce()[L.Ib+4>>>2>>>0]=T,ce()[L.Ib+8>>>2>>>0]=I,h}function at(h,T,I,L){return u?ke(2,1,h,T,I,L):Zr(h,T,I,L)}function Zr(h,T,I,L){if(h>>>=0,I>>>=0,L>>>=0,p===void 0)return 6;var U=[];return u&&U.length===0?at(h,T>>>=0,I,L):(h={ec:I,Ab:h,Hb:L,Mb:U},u?(h.Bb="spawnThread",postMessage(h,U),0):ye(h))}var Ir=typeof TextDecoder<"u"?new TextDecoder:void 0,ws=(h,T=0,I=NaN)=>{var L=(T>>>=0)+I;for(I=T;h[I]&&!(I>=L);)++I;if(16(U=(240&U)==224?(15&U)<<12|ue<<6|Te:(7&U)<<18|ue<<12|Te<<6|63&h[T++])?L+=String.fromCharCode(U):(U-=65536,L+=String.fromCharCode(55296|U>>10,56320|1023&U))}}else L+=String.fromCharCode(U)}return L},Ft=(h,T)=>(h>>>=0)?ws(W(),h,T):"";function es(h,T,I){return u?ke(3,1,h,T,I):0}function ts(h,T){if(u)return ke(4,1,h,T)}var bs=h=>{for(var T=0,I=0;I=L?T++:2047>=L?T+=2:55296<=L&&57343>=L?(T+=4,++I):T+=3}return T},Xt=(h,T,I)=>{var L=W();if(T>>>=0,0=Te&&(Te=65536+((1023&Te)<<10)|1023&h.charCodeAt(++ue)),127>=Te){if(T>=I)break;L[T++>>>0]=Te}else{if(2047>=Te){if(T+1>=I)break;L[T++>>>0]=192|Te>>6}else{if(65535>=Te){if(T+2>=I)break;L[T++>>>0]=224|Te>>12}else{if(T+3>=I)break;L[T++>>>0]=240|Te>>18,L[T++>>>0]=128|Te>>12&63}L[T++>>>0]=128|Te>>6&63}L[T++>>>0]=128|63&Te}}L[T>>>0]=0,h=T-U}else h=0;return h};function De(h,T){if(u)return ke(5,1,h,T)}function Qe(h,T,I){if(u)return ke(6,1,h,T,I)}function et(h,T,I){return u?ke(7,1,h,T,I):0}function Bt(h,T){if(u)return ke(8,1,h,T)}function Or(h,T,I){if(u)return ke(9,1,h,T,I)}function Pr(h,T,I,L){if(u)return ke(10,1,h,T,I,L)}function rs(h,T,I,L){if(u)return ke(11,1,h,T,I,L)}function ss(h,T,I,L){if(u)return ke(12,1,h,T,I,L)}function Ur(h){if(u)return ke(13,1,h)}function ns(h,T){if(u)return ke(14,1,h,T)}function os(h,T,I){if(u)return ke(15,1,h,T,I)}var Wr,yr,Ys=()=>Fe(""),vr=h=>{for(var T="";W()[h>>>0];)T+=Wr[W()[h++>>>0]];return T},Ts={},Es={};function fr(h,T,I={}){return function(L,U,ue={}){var Te=U.name;if(!L)throw new yr(`type "${Te}" must have a positive integer typeid pointer`);if(Es.hasOwnProperty(L)){if(ue.Sb)return;throw new yr(`Cannot register type '${Te}' twice`)}Es[L]=U,Ts.hasOwnProperty(L)&&(U=Ts[L],delete Ts[L],U.forEach(Oe=>Oe()))}(h,T,I)}var zs=(h,T,I)=>{switch(T){case 1:return I?L=>F()[L>>>0]:L=>W()[L>>>0];case 2:return I?L=>re()[L>>>1>>>0]:L=>fe()[L>>>1>>>0];case 4:return I?L=>se()[L>>>2>>>0]:L=>ce()[L>>>2>>>0];case 8:return I?L=>Z[L>>>3]:L=>X[L>>>3];default:throw new TypeError(`invalid integer width (${T}): ${h}`)}};function Zs(h,T,I){I>>>=0,fr(h>>>=0,{name:T=vr(T>>>0),fromWireType:L=>L,toWireType:function(L,U){if(typeof U!="bigint"&&typeof U!="number")throw U=U===null?"null":(L=typeof U)=="object"||L==="array"||L==="function"?U.toString():""+U,new TypeError(`Cannot convert "${U}" to ${this.name}`);return typeof U=="number"&&(U=BigInt(U)),U},Cb:Ar,readValueFromPointer:zs(T,I,T.indexOf("u")==-1),Db:null})}var Ar=8;function en(h,T,I,L){fr(h>>>=0,{name:T=vr(T>>>0),fromWireType:function(U){return!!U},toWireType:function(U,ue){return ue?I:L},Cb:Ar,readValueFromPointer:function(U){return this.fromWireType(W()[U>>>0])},Db:null})}var Gr=[],xr=[];function Ps(h){9<(h>>>=0)&&--xr[h+1]==0&&(xr[h]=void 0,Gr.push(h))}var ur=h=>{if(!h)throw new yr("Cannot use deleted val. handle = "+h);return xr[h]},_r=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let T=Gr.pop()||xr.length;return xr[T]=h,xr[T+1]=1,T}};function Dr(h){return this.fromWireType(ce()[h>>>2>>>0])}var tn={name:"emscripten::val",fromWireType:h=>{var T=ur(h);return Ps(h),T},toWireType:(h,T)=>_r(T),Cb:Ar,readValueFromPointer:Dr,Db:null};function rn(h){return fr(h>>>0,tn)}var sn=(h,T)=>{switch(T){case 4:return function(I){return this.fromWireType($e()[I>>>2>>>0])};case 8:return function(I){return this.fromWireType(Ue()[I>>>3>>>0])};default:throw new TypeError(`invalid float width (${T}): ${h}`)}};function nn(h,T,I){I>>>=0,fr(h>>>=0,{name:T=vr(T>>>0),fromWireType:L=>L,toWireType:(L,U)=>U,Cb:Ar,readValueFromPointer:sn(T,I),Db:null})}function on(h,T,I,L,U){if(h>>>=0,I>>>=0,T=vr(T>>>0),U===-1&&(U=4294967295),U=Oe=>Oe,L===0){var ue=32-8*I;U=Oe=>Oe<>>ue}var Te=T.includes("unsigned")?function(Oe,Ke){return Ke>>>0}:function(Oe,Ke){return Ke};fr(h,{name:T,fromWireType:U,toWireType:Te,Cb:Ar,readValueFromPointer:zs(T,I,L!==0),Db:null})}function Ms(h,T,I){function L(ue){var Te=ce()[ue>>>2>>>0];return ue=ce()[ue+4>>>2>>>0],new U(F().buffer,ue,Te)}var U=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][T];fr(h>>>=0,{name:I=vr(I>>>0),fromWireType:L,Cb:Ar,readValueFromPointer:L},{Sb:!0})}function an(h,T){fr(h>>>=0,{name:T=vr(T>>>0),fromWireType:function(I){for(var L,U=ce()[I>>>2>>>0],ue=I+4,Te=ue,Oe=0;Oe<=U;++Oe){var Ke=ue+Oe;Oe!=U&&W()[Ke>>>0]!=0||(Te=Ft(Te,Ke-Te),L===void 0?L=Te:(L+="\0",L+=Te),Te=Ke+1)}return Br(I),L},toWireType:function(I,L){L instanceof ArrayBuffer&&(L=new Uint8Array(L));var U=typeof L=="string";if(!(U||L instanceof Uint8Array||L instanceof Uint8ClampedArray||L instanceof Int8Array))throw new yr("Cannot pass non-string to std::string");var ue=U?bs(L):L.length,Te=fn(4+ue+1),Oe=Te+4;if(ce()[Te>>>2>>>0]=ue,U)Xt(L,Oe,ue+1);else if(U)for(U=0;U>>0]=Ke}else for(U=0;U>>0]=L[U];return I!==null&&I.push(Br,Te),Te},Cb:Ar,readValueFromPointer:Dr,Db(I){Br(I)}})}var Bs=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,ln=(h,T)=>{for(var I=h>>1,L=I+T/2;!(I>=L)&&fe()[I>>>0];)++I;if(32<(I<<=1)-h&&Bs)return Bs.decode(W().slice(h,I));for(I="",L=0;!(L>=T/2);++L){var U=re()[h+2*L>>>1>>>0];if(U==0)break;I+=String.fromCharCode(U)}return I},un=(h,T,I)=>{if(I??(I=2147483647),2>I)return 0;var L=T;I=(I-=2)<2*h.length?I/2:h.length;for(var U=0;U>>1>>>0]=ue,T+=2}return re()[T>>>1>>>0]=0,T-L},ys=h=>2*h.length,dn=(h,T)=>{for(var I=0,L="";!(I>=T/4);){var U=se()[h+4*I>>>2>>>0];if(U==0)break;++I,65536<=U?(U-=65536,L+=String.fromCharCode(55296|U>>10,56320|1023&U)):L+=String.fromCharCode(U)}return L},he=(h,T,I)=>{if(T>>>=0,I??(I=2147483647),4>I)return 0;var L=T;I=L+I-4;for(var U=0;U=ue&&(ue=65536+((1023&ue)<<10)|1023&h.charCodeAt(++U)),se()[T>>>2>>>0]=ue,(T+=4)+4>I)break}return se()[T>>>2>>>0]=0,T-L},k=h=>{for(var T=0,I=0;I=L&&++I,T+=4}return T};function N(h,T,I){if(h>>>=0,T>>>=0,I=vr(I>>>=0),T===2)var L=ln,U=un,ue=ys,Te=Oe=>fe()[Oe>>>1>>>0];else T===4&&(L=dn,U=he,ue=k,Te=Oe=>ce()[Oe>>>2>>>0]);fr(h,{name:I,fromWireType:Oe=>{for(var Ke,Ye=ce()[Oe>>>2>>>0],ht=Oe+4,xt=0;xt<=Ye;++xt){var It=Oe+4+xt*T;xt!=Ye&&Te(It)!=0||(ht=L(ht,It-ht),Ke===void 0?Ke=ht:(Ke+="\0",Ke+=ht),ht=It+T)}return Br(Oe),Ke},toWireType:(Oe,Ke)=>{if(typeof Ke!="string")throw new yr(`Cannot pass non-string to C++ string type ${I}`);var Ye=ue(Ke),ht=fn(4+Ye+T);return ce()[ht>>>2>>>0]=Ye/T,U(Ke,ht+4,Ye+T),Oe!==null&&Oe.push(Br,ht),ht},Cb:Ar,readValueFromPointer:Dr,Db(Oe){Br(Oe)}})}function Q(h,T){fr(h>>>=0,{Tb:!0,name:T=vr(T>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function ie(h){_n(h>>>0,!l,1,!a,131072,!1),lr()}var de=h=>{if(!ae)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(se(),h>>>2,h).value.then(je),h+=128,Atomics.store(se(),h>>>2,1))}var je=()=>{var h=Ws();h&&(ve(h),de(Hn))};function He(h,T){(h>>>=0)==T>>>0?setTimeout(je):u?postMessage({Gb:h,Bb:"checkMailbox"}):(h=Gt[h])&&h.postMessage({Bb:"checkMailbox"})}var We=[];function Je(h,T,I,L,U){for(T>>>=0,L/=2,We.length=L,I=U>>>0>>>3,U=0;U>>0];return(T?Ve[T]:To[h])(...We)}var dt=()=>{Ee=0};function vt(h){h>>>=0,u?postMessage({Bb:"cleanupThread",hc:h}):Ot(Gt[h])}function Et(h){}var Rt=(h,T)=>{var I=Es[h];if(I===void 0)throw h=Eo(h),I=vr(h),Br(h),new yr(`${T} has unknown type ${I}`);return I},kt=(h,T,I)=>{var L=[];return h=h.toWireType(L,I),L.length&&(ce()[T>>>2>>>0]=_r(L)),h};function Kt(h,T,I){return T>>>=0,I>>>=0,h=ur(h>>>0),T=Rt(T,"emval::as"),kt(T,I,h)}function Mr(h,T){return T>>>=0,h=ur(h>>>0),(T=Rt(T,"emval::as")).toWireType(null,h)}var dr=h=>{try{h()}catch(T){Fe(T)}},cr=0,Nt=null,Kr=0,Dt=[],rr={},gr={},Hr=0,Lr=null,Yt=[];function zr(h){return function(T){if(!ae){if(cr===0){var I=!1,L=!1;T((U=0)=>{if(!ae&&(Kr=U,I=!0,L)){cr=2,dr(()=>Fo(Nt)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),U=!1;try{var ue=function(){var Ke=se()[Nt+8>>>2>>>0];return Ke=nt[gr[Ke]],--Ee,Ke()}()}catch(Ke){ue=Ke,U=!0}var Te=!1;if(!Nt){var Oe=Lr;Oe&&(Lr=null,(U?Oe.reject:Oe.resolve)(ue),Te=!0)}if(U&&!Te)throw ue}}),L=!0,I||(cr=1,Nt=function(){var U=fn(65548),ue=U+12;ce()[U>>>2>>>0]=ue,ce()[U+4>>>2>>>0]=ue+65536,ue=Dt[0];var Te=rr[ue];return Te===void 0&&(Te=Hr++,rr[ue]=Te,gr[Te]=ue),ue=Te,se()[U+8>>>2>>>0]=ue,U}(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),dr(()=>Xn(Nt)))}else cr===2?(cr=0,dr(Qn),Br(Nt),Nt=null,Yt.forEach(de)):Fe(`invalid state: ${cr}`);return Kr}}(T=>{h().then(T)})}function or(h){return h>>>=0,zr(async()=>{var T=await ur(h);return _r(T)})}var Vt=[];function Zt(h,T,I,L){return I>>>=0,L>>>=0,(h=Vt[h>>>0])(null,T=ur(T>>>0),I,L)}var er={},tr=h=>{var T=er[h];return T===void 0?vr(h):T};function Rs(h,T,I,L,U){return I>>>=0,L>>>=0,U>>>=0,(h=Vt[h>>>0])(T=ur(T>>>0),T[I=tr(I)],L,U)}var cn=()=>typeof globalThis=="object"?globalThis:Function("return this")();function ei(h){return(h>>>=0)==0?_r(cn()):(h=tr(h),_r(cn()[h]))}var ti=h=>{var T=Vt.length;return Vt.push(h),T},ri=(h,T)=>{for(var I=Array(h),L=0;L>>2>>>0],"parameter "+L);return I},Cs=(h,T)=>Object.defineProperty(T,"name",{value:h});function si(h,T,I){var L=(T=ri(h,T>>>0)).shift();h--;var U=`return function (obj, func, destructorsRef, args) { +`,ue=0,Te=[];I===0&&Te.push("obj");for(var Oe=["retType"],Ke=[L],Ye=0;Yeht.name).join(", ")}) => ${L.name}>`,ti(Cs(I,h))}function ni(h){return h=tr(h>>>0),_r(n[h])}function oi(h,T){return T>>>=0,h=ur(h>>>0),T=ur(T),_r(h[T])}function ii(h){9<(h>>>=0)&&(xr[h+1]+=1)}function ai(){return _r([])}function lo(h){h=ur(h>>>0);for(var T=Array(h.length),I=0;I>>0))}function ui(){return _r({})}function uo(h){for(var T=ur(h>>>=0);T.length;){var I=T.pop();T.pop()(I)}Ps(h)}function di(h,T,I){T>>>=0,I>>>=0,h=ur(h>>>0),T=ur(T),I=ur(I),h[T]=I}function co(h,T){return T>>>=0,h=(h=Rt(h>>>0,"_emval_take_value")).readValueFromPointer(T),_r(h)}function ci(h,T){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),se()[T>>>2>>>0]=h.getUTCSeconds(),se()[T+4>>>2>>>0]=h.getUTCMinutes(),se()[T+8>>>2>>>0]=h.getUTCHours(),se()[T+12>>>2>>>0]=h.getUTCDate(),se()[T+16>>>2>>>0]=h.getUTCMonth(),se()[T+20>>>2>>>0]=h.getUTCFullYear()-1900,se()[T+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,se()[T+28>>>2>>>0]=h}var Rn=h=>h%4==0&&(h%100!=0||h%400==0),pi=[0,31,60,91,121,152,182,213,244,274,305,335],po=[0,31,59,90,120,151,181,212,243,273,304,334];function ho(h,T){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),se()[T>>>2>>>0]=h.getSeconds(),se()[T+4>>>2>>>0]=h.getMinutes(),se()[T+8>>>2>>>0]=h.getHours(),se()[T+12>>>2>>>0]=h.getDate(),se()[T+16>>>2>>>0]=h.getMonth(),se()[T+20>>>2>>>0]=h.getFullYear()-1900,se()[T+24>>>2>>>0]=h.getDay();var I=(Rn(h.getFullYear())?pi:po)[h.getMonth()]+h.getDate()-1|0;se()[T+28>>>2>>>0]=I,se()[T+36>>>2>>>0]=-60*h.getTimezoneOffset(),I=new Date(h.getFullYear(),6,1).getTimezoneOffset();var L=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(I!=L&&h.getTimezoneOffset()==Math.min(L,I)),se()[T+32>>>2>>>0]=h}function hi(h){h>>>=0;var T=new Date(se()[h+20>>>2>>>0]+1900,se()[h+16>>>2>>>0],se()[h+12>>>2>>>0],se()[h+8>>>2>>>0],se()[h+4>>>2>>>0],se()[h>>>2>>>0],0),I=se()[h+32>>>2>>>0],L=T.getTimezoneOffset(),U=new Date(T.getFullYear(),6,1).getTimezoneOffset(),ue=new Date(T.getFullYear(),0,1).getTimezoneOffset(),Te=Math.min(ue,U);return 0>I?se()[h+32>>>2>>>0]=+(U!=ue&&Te==L):0>>2>>>0]=T.getDay(),I=(Rn(T.getFullYear())?pi:po)[T.getMonth()]+T.getDate()-1|0,se()[h+28>>>2>>>0]=I,se()[h>>>2>>>0]=T.getSeconds(),se()[h+4>>>2>>>0]=T.getMinutes(),se()[h+8>>>2>>>0]=T.getHours(),se()[h+12>>>2>>>0]=T.getDate(),se()[h+16>>>2>>>0]=T.getMonth(),se()[h+20>>>2>>>0]=T.getYear(),h=T.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function pn(h,T,I,L,U,ue,Te){return u?ke(16,1,h,T,I,L,U,ue,Te):-52}function mo(h,T,I,L,U,ue){if(u)return ke(17,1,h,T,I,L,U,ue)}var js={},mi=()=>performance.timeOrigin+performance.now();function fo(h,T){if(u)return ke(18,1,h,T);if(js[h]&&(clearTimeout(js[h].id),delete js[h]),!T)return 0;var I=setTimeout(()=>{delete js[h],de(()=>$o(h,performance.timeOrigin+performance.now()))},T);return js[h]={id:I,qc:T},0}function fi(h,T,I,L){h>>>=0,T>>>=0,I>>>=0,L>>>=0;var U=new Date().getFullYear(),ue=new Date(U,0,1).getTimezoneOffset();U=new Date(U,6,1).getTimezoneOffset();var Te=Math.max(ue,U);ce()[h>>>2>>>0]=60*Te,se()[T>>>2>>>0]=+(ue!=U),h=(T=Oe=>{var Ke=Math.abs(Oe);return`UTC${0<=Oe?"-":"+"}${String(Math.floor(Ke/60)).padStart(2,"0")}${String(Ke%60).padStart(2,"0")}`})(ue),T=T(U),UDate.now();function gi(h,T,I){return 0<=h&&3>=h?(h===0?h=Date.now():h=performance.timeOrigin+performance.now(),Z[I>>>0>>>3]=BigInt(Math.round(1e6*h)),0):28}var Ns=[],jn=(h,T)=>{Ns.length=0;for(var I;I=W()[h++>>>0];){var L=I!=105;T+=(L&=I!=112)&&T%8?4:0,Ns.push(I==112?ce()[T>>>2>>>0]:I==106?Z[T>>>3]:I==105?se()[T>>>2>>>0]:Ue()[T>>>3>>>0]),T+=L?8:4}return Ns};function wi(h,T,I){return h>>>=0,T=jn(T>>>0,I>>>0),Ve[h](...T)}function _o(h,T,I){return h>>>=0,T=jn(T>>>0,I>>>0),Ve[h](...T)}var Ss=()=>{};function bi(h,T){return y(Ft(h>>>0,T>>>0))}var ba=()=>{throw Ee+=1,"unwind"};function Mi(){return 4294901760}var Ma=()=>navigator.hardwareConcurrency;function yi(){return Fe("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function go(h){h>>>=0;var T=W().length;if(h<=T||4294901760=I;I*=2){var L=T*(1+.2/I);L=Math.min(L,h+100663296);e:{L=(Math.min(4294901760,65536*Math.ceil(Math.max(h,L)/65536))-b.buffer.byteLength+65535)/65536|0;try{b.grow(L),R();var U=1;break e}catch{}U=void 0}if(U)return!0}return!1}var hn=()=>(Fe("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Vs={},wo=h=>{h.forEach(T=>{hn()})};function vi(){var h=Error().stack.toString().split(` +`);return h[0]=="Error"&&h.shift(),wo(h),Vs.Lb=hn(),Vs.cc=h,Vs.Lb}function xi(h,T,I){if(h>>>=0,T>>>=0,Vs.Lb==h)var L=Vs.cc;else(L=Error().stack.toString().split(` +`))[0]=="Error"&&L.shift(),wo(L);for(var U=3;L[U]&&hn()!=h;)++U;for(h=0;h>>2>>>0]=hn();return h}var Us,Nn={},bo=()=>{if(!Us){var h,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(h in Nn)Nn[h]===void 0?delete T[h]:T[h]=Nn[h];var I=[];for(h in T)I.push(`${h}=${T[h]}`);Us=I}return Us};function Mo(h,T){if(u)return ke(19,1,h,T);h>>>=0,T>>>=0;var I=0;return bo().forEach((L,U)=>{var ue=T+I;for(U=ce()[h+4*U>>>2>>>0]=ue,ue=0;ue>>0]=L.charCodeAt(ue);F()[U>>>0]=0,I+=L.length+1}),0}function Vn(h,T){if(u)return ke(20,1,h,T);h>>>=0,T>>>=0;var I=bo();ce()[h>>>2>>>0]=I.length;var L=0;return I.forEach(U=>L+=U.length+1),ce()[T>>>2>>>0]=L,0}function yo(h){return u?ke(21,1,h):52}function vo(h,T,I,L){return u?ke(22,1,h,T,I,L):52}function Un(h,T,I,L){return u?ke(23,1,h,T,I,L):70}var Ti=[null,[],[]];function xo(h,T,I,L){if(u)return ke(24,1,h,T,I,L);T>>>=0,I>>>=0,L>>>=0;for(var U=0,ue=0;ue>>2>>>0],Oe=ce()[T+4>>>2>>>0];T+=8;for(var Ke=0;Ke>>0],ht=Ti[h];Ye===0||Ye===10?((h===1?E:y)(ws(ht)),ht.length=0):ht.push(Ye)}U+=Oe}return ce()[L>>>2>>>0]=U,0}u||function(){for(var h=n.numThreads-1;h--;)gs();le.unshift(()=>{Me++,function(T){u?T():Promise.all(Ge.map(Yr)).then(T)}(()=>Ae())})}();for(var Wn=Array(256),mn=0;256>mn;++mn)Wn[mn]=String.fromCharCode(mn);Wr=Wn,yr=n.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},n.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},xr.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>xr.length/2-5-Gr.length;var nt,To=[Ie,Be,at,es,ts,De,Qe,et,Bt,Or,Pr,rs,ss,Ur,ns,os,pn,mo,fo,Mo,Vn,yo,vo,Un,xo];(async function(){function h(L,U){return nt=L.exports,nt=function(){var ue=nt,Te={};for(let[Oe,Ke]of Object.entries(ue))Te[Oe]=typeof Ke=="function"?(...Ye)=>{Dt.push(Oe);try{return Ke(...Ye)}finally{ae||(Dt.pop(),Nt&&cr===1&&Dt.length===0&&(cr=0,Ee+=1,dr(Ao),typeof Fibers<"u"&&Fibers.rc()))}}:Ke;return Te}(),nt=function(){var ue=nt,Te=Ke=>Ye=>Ke(Ye)>>>0,Oe=Ke=>()=>Ke()>>>0;return(ue=Object.assign({},ue)).Da=Te(ue.Da),ue.fb=Oe(ue.fb),ue.hb=Te(ue.hb),ue.tb=Te(ue.tb),ue.ub=Oe(ue.ub),ue.__cxa_get_exception_ptr=Te(ue.__cxa_get_exception_ptr),ue}(),wt.push(nt.ib),x=U,Ae(),nt}Me++;var T=ze();if(n.instantiateWasm)return new Promise(L=>{n.instantiateWasm(T,(U,ue)=>{h(U,ue),L(U.exports)})});if(u)return new Promise(L=>{we=U=>{var ue=new WebAssembly.Instance(U,ze());L(h(ue,U))}});xe??(xe=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",import.meta.url).href);try{var I=await async function(L){var U=xe;if(!me&&typeof WebAssembly.instantiateStreaming=="function"&&!V(U))try{var ue=fetch(U,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ue,L)}catch(Te){y(`wasm streaming compile failed: ${Te}`),y("falling back to ArrayBuffer instantiation")}return async function(Te,Oe){try{var Ke=await async function(Ye){if(!me)try{var ht=await _(Ye);return new Uint8Array(ht)}catch{}if(Ye==xe&&me)Ye=new Uint8Array(me);else{if(!f)throw"both async and sync fetching of the wasm failed";Ye=f(Ye)}return Ye}(Te);return await WebAssembly.instantiate(Ke,Oe)}catch(Ye){y(`failed to asynchronously prepare wasm: ${Ye}`),Fe(Ye)}}(U,L)}(T);return h(I.instance,I.module)}catch(L){return o(L),Promise.reject(L)}})();var Eo=h=>(Eo=nt.Da)(h),Po=()=>(Po=nt.Ea)();n._OrtInit=(h,T)=>(n._OrtInit=nt.Fa)(h,T),n._OrtGetLastError=(h,T)=>(n._OrtGetLastError=nt.Ga)(h,T),n._OrtCreateSessionOptions=(h,T,I,L,U,ue,Te,Oe,Ke,Ye)=>(n._OrtCreateSessionOptions=nt.Ha)(h,T,I,L,U,ue,Te,Oe,Ke,Ye),n._OrtAppendExecutionProvider=(h,T,I,L,U)=>(n._OrtAppendExecutionProvider=nt.Ia)(h,T,I,L,U),n._OrtAddFreeDimensionOverride=(h,T,I)=>(n._OrtAddFreeDimensionOverride=nt.Ja)(h,T,I),n._OrtAddSessionConfigEntry=(h,T,I)=>(n._OrtAddSessionConfigEntry=nt.Ka)(h,T,I),n._OrtReleaseSessionOptions=h=>(n._OrtReleaseSessionOptions=nt.La)(h),n._OrtCreateSession=(h,T,I)=>(n._OrtCreateSession=nt.Ma)(h,T,I),n._OrtReleaseSession=h=>(n._OrtReleaseSession=nt.Na)(h),n._OrtGetInputOutputCount=(h,T,I)=>(n._OrtGetInputOutputCount=nt.Oa)(h,T,I),n._OrtGetInputOutputMetadata=(h,T,I,L)=>(n._OrtGetInputOutputMetadata=nt.Pa)(h,T,I,L),n._OrtFree=h=>(n._OrtFree=nt.Qa)(h),n._OrtCreateTensor=(h,T,I,L,U,ue)=>(n._OrtCreateTensor=nt.Ra)(h,T,I,L,U,ue),n._OrtGetTensorData=(h,T,I,L,U)=>(n._OrtGetTensorData=nt.Sa)(h,T,I,L,U),n._OrtReleaseTensor=h=>(n._OrtReleaseTensor=nt.Ta)(h),n._OrtCreateRunOptions=(h,T,I,L)=>(n._OrtCreateRunOptions=nt.Ua)(h,T,I,L),n._OrtAddRunConfigEntry=(h,T,I)=>(n._OrtAddRunConfigEntry=nt.Va)(h,T,I),n._OrtReleaseRunOptions=h=>(n._OrtReleaseRunOptions=nt.Wa)(h),n._OrtCreateBinding=h=>(n._OrtCreateBinding=nt.Xa)(h),n._OrtBindInput=(h,T,I)=>(n._OrtBindInput=nt.Ya)(h,T,I),n._OrtBindOutput=(h,T,I,L)=>(n._OrtBindOutput=nt.Za)(h,T,I,L),n._OrtClearBoundOutputs=h=>(n._OrtClearBoundOutputs=nt._a)(h),n._OrtReleaseBinding=h=>(n._OrtReleaseBinding=nt.$a)(h),n._OrtRunWithBinding=(h,T,I,L,U)=>(n._OrtRunWithBinding=nt.ab)(h,T,I,L,U),n._OrtRun=(h,T,I,L,U,ue,Te,Oe)=>(n._OrtRun=nt.bb)(h,T,I,L,U,ue,Te,Oe),n._OrtEndProfiling=h=>(n._OrtEndProfiling=nt.cb)(h),n._JsepOutput=(h,T,I)=>(n._JsepOutput=nt.db)(h,T,I),n._JsepGetNodeName=h=>(n._JsepGetNodeName=nt.eb)(h);var Ws=()=>(Ws=nt.fb)(),Br=n._free=h=>(Br=n._free=nt.gb)(h),fn=n._malloc=h=>(fn=n._malloc=nt.hb)(h),_n=(h,T,I,L,U,ue)=>(_n=nt.kb)(h,T,I,L,U,ue),Co=()=>(Co=nt.lb)(),So=(h,T,I,L,U)=>(So=nt.mb)(h,T,I,L,U),Gn=h=>(Gn=nt.nb)(h),Kn=h=>(Kn=nt.ob)(h),$o=(h,T)=>($o=nt.pb)(h,T),Hn=()=>(Hn=nt.qb)(),ko=(h,T)=>(ko=nt.rb)(h,T),gn=h=>(gn=nt.sb)(h),wn=h=>(wn=nt.tb)(h),qn=()=>(qn=nt.ub)(),Io=n.dynCall_ii=(h,T)=>(Io=n.dynCall_ii=nt.vb)(h,T),Xn=h=>(Xn=nt.wb)(h),Ao=()=>(Ao=nt.xb)(),Fo=h=>(Fo=nt.yb)(h),Qn=()=>(Qn=nt.zb)();return n.stackSave=()=>qn(),n.stackRestore=h=>gn(h),n.stackAlloc=h=>wn(h),n.setValue=function(h,T,I="i8"){switch(I.endsWith("*")&&(I="*"),I){case"i1":case"i8":F()[h>>>0]=T;break;case"i16":re()[h>>>1>>>0]=T;break;case"i32":se()[h>>>2>>>0]=T;break;case"i64":Z[h>>>3]=BigInt(T);break;case"float":$e()[h>>>2>>>0]=T;break;case"double":Ue()[h>>>3>>>0]=T;break;case"*":ce()[h>>>2>>>0]=T;break;default:Fe(`invalid type for setValue: ${I}`)}},n.getValue=function(h,T="i8"){switch(T.endsWith("*")&&(T="*"),T){case"i1":case"i8":return F()[h>>>0];case"i16":return re()[h>>>1>>>0];case"i32":return se()[h>>>2>>>0];case"i64":return Z[h>>>3];case"float":return $e()[h>>>2>>>0];case"double":return Ue()[h>>>3>>>0];case"*":return ce()[h>>>2>>>0];default:Fe(`invalid type for getValue: ${T}`)}},n.UTF8ToString=Ft,n.stringToUTF8=Xt,n.lengthBytesUTF8=bs,function h(){if(0{Ju(),Bl=typeof location>"u"?void 0:location.origin,Au=import.meta.url>"file:"&&import.meta.url<"file;",Pf=()=>{{if(Au){let e=URL;return new URL(new e("ort.bundle.min.mjs",import.meta.url).href,Bl).href}return import.meta.url}},jr=Pf(),kb=()=>{if(jr&&!jr.startsWith("blob:"))return jr.substring(0,jr.lastIndexOf("/")+1)},Xi=(e,r)=>{try{let t=r??jr;return(t?new URL(e,t):new URL(e)).origin===Bl}catch{return!1}},Cf=(e,r)=>{let t=r??jr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},Sf=(e,r)=>`${r??"./"}${e}`,Rl=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},$f=async e=>(await import(e)).default,jl=(ex(),Jo(Pb)).default,Ib=async()=>{if(!jr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Xi(jr))return[void 0,jl()];let e=await Rl(jr);return[e,jl(e)]},Nl=(tx(),Jo(Sb)).default,Ab=async(e,r,t)=>{if(!e&&!r&&Nl&&jr&&Xi(jr))return[void 0,Nl];{let s="ort-wasm-simd-threaded.jsep.mjs",o=e??Cf(s,r),n=t&&o&&!Xi(o,r),i=n?await Rl(o):o??Sf(s,r);return[n?i:void 0,await $f(i)]}}}),Vl,Qi,zo,Ul,kf,If,Af,Zu,zt,zn=Re(()=>{Yu(),Qi=!1,zo=!1,Ul=!1,kf=()=>{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}},If=()=>{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}},Af=()=>{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}},Zu=async e=>{if(Qi)return Promise.resolve();if(zo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ul)throw new Error("previous call to 'initializeWebAssembly()' failed.");zo=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Af())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!If())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=kf();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,u=(l==null?void 0:l.href)??l,p=e.wasmBinary,[d,c]=await Ab(a,n,t>1),_=!1,f=[];if(r>0&&f.push(new Promise(v=>{setTimeout(()=>{_=!0,v()},r)})),f.push(new Promise((v,$)=>{let w={numThreads:t};if(p)w.wasmBinary=p;else if(u||n)w.locateFile=g=>u??n+g;else if(a&&a.indexOf("blob:")!==0)w.locateFile=g=>new URL(g,a).href;else if(d){let g=kb();g&&(w.locateFile=C=>g+C)}c(w).then(g=>{zo=!1,Qi=!0,Vl=g,v(),d&&URL.revokeObjectURL(d)},g=>{zo=!1,Ul=!0,$(g)})})),await Promise.race(f),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},zt=()=>{if(Qi&&Vl)return Vl;throw new Error("WebAssembly is not initialized yet.")}}),ps,pa,At,ed=Re(()=>{zn(),ps=(e,r)=>{let t=zt(),s=t.lengthBytesUTF8(e)+1,o=t._malloc(s);return t.stringToUTF8(e,o,s),r.push(o),o},pa=(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")pa(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}`)})},At=e=>{let r=zt(),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)}}}),Fb,rx=Re(()=>{zn(),ed(),Fb=e=>{let r=zt(),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=ps(e.tag,s)),t=r._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,n),t===0&&At("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&pa(e.extra,"",new WeakSet,(i,a)=>{let l=ps(i,s),u=ps(a,s);r._OrtAddRunConfigEntry(t,l,u)!==0&&At(`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}}}),Ff,Of,Df,Bo,Lf,Ob,sx=Re(()=>{zn(),ed(),Ff=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}`)}},Of=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Df=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)},Bo=(e,r,t,s)=>{let o=ps(r,s),n=ps(t,s);zt()._OrtAddSessionConfigEntry(e,o,n)!==0&&At(`Can't set a session config entry: ${r} - ${t}.`)},Lf=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&&Bo(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}`);Bo(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=ps(o,t),a=n.length,l=0,u=0;if(a>0){l=zt()._malloc(a*zt().PTR_SIZE),t.push(l),u=zt()._malloc(a*zt().PTR_SIZE),t.push(u);for(let p=0;p{let r=zt(),t=0,s=[],o=e||{};Df(o);try{let n=Ff(o.graphOptimizationLevel??"all"),i=Of(o.executionMode??"sequential"),a=typeof o.logId=="string"?ps(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 u=o.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let p=typeof o.optimizedModelFilePath=="string"?ps(o.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,a,l,u,p),t===0&&At("Can't create session options."),o.executionProviders&&await Lf(t,o.executionProviders,s),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);Bo(t,"enableGraphCapture",o.enableGraphCapture.toString(),s)}if(o.freeDimensionOverrides)for(let[d,c]of Object.entries(o.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof c!="number"||!Number.isInteger(c)||c<0)throw new Error(`free dimension override value must be a non-negative integer: ${c}`);let _=ps(d,s);r._OrtAddFreeDimensionOverride(t,_,c)!==0&&At(`Can't set a free dimension override: ${d} - ${c}.`)}return o.extra!==void 0&&pa(o.extra,"",new WeakSet,(d,c)=>{Bo(t,d,c,s)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&At("Can't release session options."),s.forEach(i=>r._free(i)),n}}}),ro,Fs,An,td,ha,rd,sd,Fu,ut=Re(()=>{ro=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}`)}},Fs=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}`)}},An=(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},td=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}`)}},ha=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}`)}},rd=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",sd=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Fu=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}`)}}}),nd,Db=Re(()=>{Ju(),nd=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 u=l.byteLength;new Uint8Array(n,i,u).set(l),i+=u}return new Uint8Array(n,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),zf,Bf,Rf,jf,od,Nf,Tt,Os=Re(()=>{ut(),zf=["V","I","W","E","F"],Bf=(e,r)=>{console.log(`[${zf[e]},${new Date().toISOString()}]${r}`)},od=(e,r)=>{Rf=e,jf=r},Nf=(e,r)=>{let t=ha(e),s=ha(Rf);t>=s&&Bf(t,typeof r=="function"?r():r)},Tt=(...e)=>{jf&&Nf(...e)}}),Vf,oo,be,ma,Lb,zb,Bb,ft=Re(()=>{Vf=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},oo=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=Vf.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],u=o-a<0?1:r[o-a];if(l!==u&&l>1&&u>1)return;let p=Math.max(l,u);if(l&&u)i[n-a]=Math.max(l,u);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 da{static size(r){return da.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 da.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 da.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])}},ma=class Ho{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{ut(),id=(e,r)=>new(td(r))(e)}),Ou,Wl,Uf,Gl,Wf,Kl,Hl,ql,Gf,jb,nx=Re(()=>{Os(),Ou=(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},Wl=(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},Uf=1,Gl=()=>Uf++,Wf=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Kl=(e,r)=>{let t=Wf.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},Hl=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 Kl(this.dataType,this.tensorShape)}destroy(){Tt("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=Wl(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}},ql=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",Tt("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!==Kl(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=Ou(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else Tt("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?Wl(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)}},Gf=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=Gl();return this.tensorTrackersById.set(e,new ql(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){Tt("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){Tt("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=Gl(),i=new Hl({sessionId:e,context:o,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(n,new ql(this,i)),this.externalTensors.add(i),n}async getCachedTensor(e,r,t,s,o,n,i=!1){let a=this.getMLContext(e);for(let[u,p]of this.freeTensors.entries())if(p.canReuseTensor(a,r,t)){Tt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let d=this.freeTensors.splice(u,1)[0];return d.sessionId=e,d}Tt("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 Hl({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)}},jb=(...e)=>new Gf(...e)}),Ji,Kf,Nb,ox=Re(()=>{ut(),zn(),Rb(),nx(),Os(),Ji=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Kf=(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])},Nb=class{constructor(e){this.tensorManager=jb(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,od(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Tt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Tt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)Tt("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=>Kf(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){Tt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,o){let n=Ji.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){Tt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=Ji.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(!zt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Tt("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 id(t,r)}}registerMLTensor(e,r,t,s){let o=Ji.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(e,r,o,s);return Tt("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 u=l.slice(r,r+t).buffer,p;switch(o.dataType){case"float32":p=new Float32Array(u);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":p=new Int32Array(u);break;case"uint32":p=new Uint32Array(u);break;case"int64":i?(p=Ou(new Uint8Array(u),!1),o.dataType="int32"):p=new BigInt64Array(u);break;case"uint64":p=new BigUint64Array(u);break;case"int8":p=new Int8Array(u);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return Tt("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(){}}}),ad=Re(()=>{}),Xl,Yi,Zi,Hf,qf,Ql,Du,Xf,Vb,ix=Re(()=>{Os(),ad(),Xl=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]]),Yi=[],Zi=e=>Math.ceil(Number(e)/16)*16,Hf=e=>{for(let r=0;rqf++,Du=async(e,r,t,s)=>{let o=Zi(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()}},Xf=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 Xl)Yi.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=Zi(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 u=this.backend.device.createCommandEncoder();u.copyBufferToBuffer(a,0,i.gpuData.buffer,0,n),this.backend.device.queue.submit([u.finish()]),a.destroy(),Tt("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=Zi(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 Tt("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=Ql();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),Tt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Tt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=Hf(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:Ql(),type:0,buffer:s};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),Tt("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 Tt("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 Du(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=Xl.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&&(Tt("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Vb=(...e)=>new Xf(...e)}),Qf,$t,Jt=Re(()=>{Qf=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}},$t=e=>new Qf(e)}),io,ea,mr,Er,st,qt,Lu,no,Qs,rt,Ro,Pe,Ze,Ub,ld,Jf,Wb,_t=Re(()=>{ut(),ft(),io=64,ea=(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}`)}},mr=(e,r=1)=>{let t=ea(e,r);return typeof t=="string"?t:t[0]},Er=(e,r=1)=>{let t=ea(e,r);return typeof t=="string"?t:t[1]},st=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:be.computeStrides(t)})}),r},qt=e=>e%4===0?4:e%2===0?2:1,Lu=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,no=(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,rt=(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,Ro=(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`,u=ea(r,o),p=typeof u=="string"?u:u[1],d=typeof u=="string"?u:u[0],c={indices:l,value:p,storage:d,tensor:r},_=V=>typeof V=="string"?V:`${V}u`,f={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},v=n?"uniforms.":"",$=`${v}${e}_shape`,w=`${v}${e}_strides`,g="";for(let V=0;V ${c.indices} { + var indices: ${c.indices}; + var current = offset; + ${g} + return indices; + }`,E=V=>(f.offsetToIndices=!0,i<2?V:`o2i_${e}(${V})`),y=[];if(i>=2)for(let V=i-1;V>=0;V--)y.push(`${rt(w,V,i)} * (indices[${V}])`);let b=i<2?"":` + fn i2o_${e}(indices: ${c.indices}) -> u32 { + return ${y.join("+")}; + }`,x=V=>(f.indicesToOffset=!0,i<2?V:`i2o_${e}(${V})`),S=(...V)=>i===0?"0u":`${c.indices}(${V.map(_).join(",")})`,A=(V,F)=>i<2?`${V}`:`${rt(V,F,i)}`,B=(V,F,W)=>i<2?`${V}=${W};`:`${rt(V,F,i)}=${W};`,K={},G=(V,F)=>{f.broadcastedIndicesToOffset=!0;let W=`${F.name}broadcastedIndicesTo${e}Offset`;if(W in K)return`${W}(${V})`;let re=[];for(let fe=i-1;fe>=0;fe--){let se=F.indicesGet("outputIndices",fe+F.rank-i);re.push(`${A(w,fe)} * (${se} % ${A($,fe)})`)}return K[W]=`fn ${W}(outputIndices: ${F.type.indices}) -> u32 { + return ${re.length>0?re.join("+"):"0u"}; + }`,`${W}(${V})`},j=(V,F)=>(()=>{if(c.storage===c.value)return`${e}[${V}]=${F};`;if(c.storage==="vec2"&&c.value==="i32")return`${e}[${V}]=vec2(u32(${F}), select(0u, 0xFFFFFFFFu, ${F} < 0));`;if(c.storage==="vec2"&&c.value==="u32")return`${e}[${V}]=vec2(u32(${F}), 0u);`;if(c.storage==="u32"&&c.value==="vec4")return`${e}[${V}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${F}));`;throw new Error(`not supported combination of storage type ${c.storage} and value type ${c.value} yet`)})(),ee=V=>(()=>{if(c.storage===c.value)return`${e}[${V}]`;if(c.storage==="vec2"&&c.value==="i32")return`i32(${e}[${V}].x)`;if(c.storage==="vec2"&&c.value==="u32")return`u32(${e}[${V}].x)`;if(c.storage==="u32"&&c.value==="vec4")return`vec4(bool(${e}[${V}] & 0xFFu), bool(${e}[${V}] & 0xFF00u), bool(${e}[${V}] & 0xFF0000u), bool(${e}[${V}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${c.storage} and value type ${c.value} yet`)})(),H=i<2?"":` + fn get_${e}ByIndices(indices: ${c.indices}) -> ${p} { + return ${ee(`i2o_${e}(indices)`)}; + }`,Z=i<2?"":(()=>{let V=a.map(W=>`d${W}: u32`).join(", "),F=a.map(W=>`d${W}`).join(", ");return` + fn get_${e}(${V}) -> ${p} { + return get_${e}ByIndices(${S(F)}); + }`})(),X=(...V)=>{if(V.length!==i)throw new Error(`indices length must be ${i}`);let F=V.map(_).join(",");return i===0?ee("0u"):i===1?ee(F[0]):(f.get=!0,f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}(${F})`)},oe=V=>i<2?ee(V):(f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}ByIndices(${V})`),me=i<2?"":` + fn set_${e}ByIndices(indices: ${c.indices}, value: ${p}) { + ${j(`i2o_${e}(indices)`,"value")} + }`,ae=i<2?"":(()=>{let V=a.map(W=>`d${W}: u32`).join(", "),F=a.map(W=>`d${W}`).join(", ");return` + fn set_${e}(${V}, value: ${p}) { + set_${e}ByIndices(${S(F)}, value); + }`})();return{impl:()=>{let V=[],F=!1;return f.offsetToIndices&&(V.push(C),F=!0),f.indicesToOffset&&(V.push(b),F=!0),f.broadcastedIndicesToOffset&&(Object.values(K).forEach(W=>V.push(W)),F=!0),f.set&&(V.push(ae),F=!0),f.setByIndices&&(V.push(me),F=!0),f.get&&(V.push(Z),F=!0),f.getByIndices&&(V.push(H),F=!0),!n&&F&&V.unshift(`const ${$} = ${c.indices}(${t.join(",")});`,`const ${w} = ${c.indices}(${be.computeStrides(t).join(",")});`),V.join(` +`)},type:c,offsetToIndices:E,indicesToOffset:x,broadcastedIndicesToOffset:G,indices:S,indicesGet:A,indicesSet:B,set:(...V)=>{if(V.length!==i+1)throw new Error(`indices length must be ${i}`);let F=V[i];if(typeof F!="string")throw new Error("value must be string");let W=V.slice(0,i).map(_).join(",");return i===0?j("0u",F):i===1?j(W[0],F):(f.set=!0,f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}(${W}, ${F})`)},setByOffset:j,setByIndices:(V,F)=>i<2?j(V,F):(f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}ByIndices(${V}, ${F});`),get:X,getByOffset:ee,getByIndices:oe,usage:s,name:e,strides:w,shape:$,rank:i}},Pe=(e,r,t,s=1)=>Ro(e,r,t,"input",s),Ze=(e,r,t,s=1)=>Ro(e,r,t,"output",s),Ub=(e,r,t)=>Ro(e,r,t,"atomicOutput",1),ld=(e,r,t,s=1)=>Ro(e,r,t,"internal",s),Jf=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=io){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])}},Wb=(e,r)=>new Jf(e,r)}),Yf,Jl,Zf,e_,t_,r_,Vr,Gb,Kb,Js=Re(()=>{ut(),ft(),Jt(),_t(),Yf=(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}`)},Jl=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),Zf=(e,r)=>be.sortBasedOnPerm(e,Jl(e.length,r)),e_=(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=Jl(s,r),n=Zf(e.dims,o),i=e.dims,a=n,l=s<2||r_(o,e.dims),u;if(l)return u=f=>{let v=Pe("input",t,i,4),$=Ze("output",t,a,4);return` + ${f.registerUniform("output_size","u32").declareVariables(v,$)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let f=be.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64/4)},programUniforms:[{type:12,data:Math.ceil(f/4)}]}},getShaderSource:u};let{newShape:p,newPerm:d}=t_(e.dims,o),c=be.areEqual(d,[2,3,1]),_=be.areEqual(d,[3,1,2]);if(p.length===2||c||_){i=c?[p[0],p[1]*p[2]]:_?[p[0]*p[1],p[2]]:p,a=[i[1],i[0]];let f=16;return u=v=>{let $=Pe("a",t,i.length),w=Ze("output",t,a.length);return` + ${v.registerUniform("output_size","u32").declareVariables($,w)} + var tile : array, ${f}>; + ${v.mainStart([f,f,1])} + let stride = (uniforms.output_shape[1] - 1) / ${f} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${f}u + local_id.x; + let input_row = workgroup_id_x * ${f}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${$.getByIndices(`${$.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${f}u + local_id.x; + let output_row = workgroup_id_y * ${f}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 v=be.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/f),y:Math.ceil(a[0]/f)},programUniforms:[{type:12,data:v},...st(i,a)]}},getShaderSource:u}}return u=f=>{let v=Pe("a",t,i.length),$=Ze("output",t,a.length);return` + ${f.registerUniform("output_size","u32").declareVariables(v,$)} + + ${e_(o,s,v,$)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${$.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${$.setByOffset("global_idx",v.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let f=be.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...st(i,a)]}},getShaderSource:u}},Gb=(e,r)=>{Yf(e.inputs,r.perm),e.compute(Vr(e.inputs[0],r.perm))},Kb=e=>$t({perm:e.perm})}),s_,n_,o_,i_,a_,l_,u_,d_,c_,p_,as,Hb,qb,Xb,Qb,Jb,Yb,Zb,eM,tM,rM,ax=Re(()=>{ut(),ft(),_t(),ud(),Js(),s_={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"},n_={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"},o_={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},i_={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},a_=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,o]},u_=(e,r)=>{let t=e.length+r.length,s=[],o=0;for(let n=0;n{for(let t=0;t{let t=[];if(!d_(e,r)){for(let s=0;st.push(s))}return t},p_=(e,r,t,s,o,n,i)=>{let a=t[0].dims,l=be.size(n),u=be.size(i),p=Pe("_A",t[0].dataType,a),d=Ze("output",o,n),c=64;l===1&&(c=256);let _=` + var aBestValues : array; + `,f=v=>` + ${v.registerUniform("reduceSize","u32").declareVariables(p,d)} + ${_} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${v.mainStart(c)} + + let outputIndex = global_idx / ${c}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${o_[s]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${c}) { + let candidate = f32(${p.getByOffset("offset + k")}); + bestValue = ${s_[s]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${c}u); + for (var currentSize = reduceSize / 2u; reduceSize > 1u; + currentSize = reduceSize / 2u) { + let interval = DIV_CEIL(reduceSize, 2u); + if (local_idx < currentSize) { + let candidate = aBestValues[local_idx + interval]; + bestValue = ${n_[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}(${i_[s]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${r};${c}`,inputDependencies:["type"]},getShaderSource:f,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},as=(e,r,t,s)=>{let o=e.inputs.length===1?t:zu(e.inputs,t),n=o.axes;n.length===0&&!o.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((_,f)=>f));let i=be.normalizeAxes(n,e.inputs[0].dims.length),a=i,l=e.inputs[0],u=c_(a,e.inputs[0].dims.length);u.length>0&&(l=e.compute(Vr(e.inputs[0],u),{inputs:[0],outputs:[-1]})[0],a=a_(a.length,l.dims.length));let[p,d]=l_(l.dims,a),c=p;o.keepDims&&(c=u_(p,i)),e.compute(p_(r,o.cacheKey,[l],s,e.inputs[0].dataType,c,d),{inputs:[l]})},Hb=(e,r)=>{as(e,"ReduceMeanShared",r,"mean")},qb=(e,r)=>{as(e,"ReduceL1Shared",r,"l1")},Xb=(e,r)=>{as(e,"ReduceL2Shared",r,"l2")},Qb=(e,r)=>{as(e,"ReduceLogSumExpShared",r,"logSumExp")},Jb=(e,r)=>{as(e,"ReduceMaxShared",r,"max")},Yb=(e,r)=>{as(e,"ReduceMinShared",r,"min")},Zb=(e,r)=>{as(e,"ReduceProdShared",r,"prod")},eM=(e,r)=>{as(e,"ReduceSumShared",r,"sum")},tM=(e,r)=>{as(e,"ReduceSumSquareShared",r,"sumSquare")},rM=(e,r)=>{as(e,"ReduceLogSumShared",r,"logSum")}}),ls,h_,fa,zu,us,m_,f_,__,g_,w_,b_,M_,y_,v_,x_,ds,sM,nM,oM,iM,aM,lM,uM,dM,cM,pM,ud=Re(()=>{ut(),ft(),Jt(),_t(),ax(),ls=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.")},h_=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],fa=(e,r,t,s,o,n,i=!1,a=!1)=>{let l=[],u=t[0].dims,p=u.length,d=be.normalizeAxes(o,p),c=!a&&d.length===0;u.forEach((v,$)=>{c||d.indexOf($)>=0?i&&l.push(1):l.push(v)});let _=l.length,f=be.size(l);return{name:e,shaderCache:r,getShaderSource:v=>{let $=[],w=Pe("_A",t[0].dataType,p),g=Ze("output",n,_),C=s(w,g,d),E=C[2];for(let y=0,b=0;y=0?(i&&b++,E=`for(var j${y}: u32 = 0; j${y} < ${u[y]}; j${y}++) { + ${C[2].includes("last_index")?`let last_index = j${y};`:""} + ${w.indicesSet("input_indices",y,`j${y}`)} + ${E} + }`):($.push(`${w.indicesSet("input_indices",y,g.indicesGet("output_indices",b))};`),b++);return` + + ${v.registerUniform("output_size","u32").declareVariables(w,g)} + + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${w.type.indices}; + let output_indices = ${g.offsetToIndices("global_idx")}; + + ${$.join(` +`)} + ${C[0]} // init ops for reduce max/min + ${C[1]} + ${E} + ${C[3]} + ${C.length===4?g.setByOffset("global_idx","value"):C.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:l,dataType:n}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...st(u,l)]})}},zu=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),$t({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},us=(e,r,t,s)=>{let o=e.inputs,n=o.length===1?t:zu(o,t);e.compute(fa(r,{hint:n.cacheKey,inputDependencies:["rank"]},[o[0]],n.noopWithEmptyAxes&&n.axes.length===0?h_:s,n.axes,o[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},m_=(e,r)=>{ls(e.inputs),us(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},f_=(e,r)=>{ls(e.inputs),us(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},__=(e,r)=>{ls(e.inputs),us(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);"])},g_=(e,r)=>{ls(e.inputs),us(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},w_=(e,r)=>{ls(e.inputs),us(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")});`,""]})},b_=(e,r)=>{ls(e.inputs),us(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});`]})},M_=(e,r)=>{ls(e.inputs),us(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")});`,""]})},y_=(e,r)=>{ls(e.inputs),us(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},v_=(e,r)=>{ls(e.inputs),us(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},x_=(e,r)=>{ls(e.inputs),us(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;`,""])},ds=(e,r,t)=>{if(r.length===0)return t;let s=1,o=1;for(let n=0;n1024},sM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?b_(e,r):Hb(e,r)},nM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?f_(e,r):qb(e,r)},oM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?__(e,r):Xb(e,r)},iM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?g_(e,r):Qb(e,r)},aM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?w_(e,r):Jb(e,r)},lM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?M_(e,r):Yb(e,r)},uM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?y_(e,r):Zb(e,r)},dM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?v_(e,r):eM(e,r)},cM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?x_(e,r):tM(e,r)},pM=(e,r)=>{ds(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?m_(e,r):rM(e,r)}}),Yl,hM,mM,Bu,lx=Re(()=>{ut(),Jt(),ud(),Yl=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.")},hM=(e,r)=>{Yl(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(fa("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},mM=(e,r)=>{Yl(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(fa("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Bu=e=>$t(e)}),T_,ta,E_,P_,C_,Zo,S_,fM,dd=Re(()=>{ut(),ft(),ad(),_t(),T_=(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],u=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,c=d,_=c;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let C of r.qkvHiddenSizes)if(C%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");d=r.qkvHiddenSizes[0],c=r.qkvHiddenSizes[1],_=r.qkvHiddenSizes[2]}let f=u;if(d!==c)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==d+c+_)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let v=0;if(i){if(c!==_)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]!==c/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(v=i.dims[3])}let $=f+v,w=-1,g=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]!==u||a.dims[3]!==$)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:u,pastSequenceLength:v,kvSequenceLength:f,totalSequenceLength:$,maxSequenceLength:w,inputHiddenSize:p,hiddenSize:d,vHiddenSize:_,headSize:Math.floor(d/r.numHeads),vHeadSize:Math.floor(_/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ta=(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; + `,E_=(e,r,t,s,o,n,i,a)=>{let l=qt(i?1:n),u=64,p=n/l;p{let g=Ze("x",e.dataType,e.dims,l),C=[g],E=i?Pe("seq_lens",i.dataType,i.dims):void 0;E&&C.push(E);let y=a?Pe("total_sequence_length_input",a.dataType,a.dims):void 0;y&&C.push(y);let b=Er(e.dataType),x=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + var thread_max: array; + var thread_sum: array; + ${w.registerUniforms(x).declareVariables(...C)} + ${w.mainStart([u,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; + ${ta(E,y,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${u}) * 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 = ${f}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${f}(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 < ${u}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${f}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${f}(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 < ${u}; 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] = ${g.type.value}(${b}(1.0) / ${b}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${f}(x[offset + i]); + x[offset + i] = ${g.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] = ${g.type.value}(${b}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${u};${_};${l}`,inputDependencies:v},getShaderSource:$,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:r*t},programUniforms:c})}},P_=(e,r,t,s,o,n,i,a,l)=>{let u=i+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,u],d=e>1&&s,c=n.kvNumHeads?n.kvNumHeads:n.numHeads,_=d?[n.batchSize,c,u,n.headSize]:void 0,f=n.nReps?n.nReps:1,v=n.scale===0?1/Math.sqrt(n.headSize):n.scale,$=qt(n.headSize),w=n.headSize/$,g=12,C={x:Math.ceil(u/g),y:Math.ceil(n.sequenceLength/g),z:n.batchSize*n.numHeads},E=[{type:12,data:n.sequenceLength},{type:12,data:w},{type:12,data:u},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:v},{type:12,data:i},{type:12,data:n.kvSequenceLength},{type:12,data:f}],y=d&&s&&be.size(s.dims)>0,b=["type","type"];y&&b.push("type"),o&&b.push("type"),a&&b.push("type"),l&&b.push("type");let x=[{dims:p,dataType:r.dataType,gpuDataType:0}];d&&x.push({dims:_,dataType:r.dataType,gpuDataType:0});let S=A=>{let B=Pe("q",r.dataType,r.dims,$),K=Pe("key",t.dataType,t.dims,$),G=[B,K];if(y){let me=Pe("past_key",s.dataType,s.dims,$);G.push(me)}o&&G.push(Pe("attention_bias",o.dataType,o.dims));let j=a?Pe("seq_lens",a.dataType,a.dims):void 0;j&&G.push(j);let ee=l?Pe("total_sequence_length_input",l.dataType,l.dims):void 0;ee&&G.push(ee);let H=Ze("output",r.dataType,p),Z=[H];d&&Z.push(Ze("present_key",r.dataType,_,$));let X=Er(1,$),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 = ${g}u; + + var tileQ: array<${B.type.storage}, ${g*g}>; + var tileK: array<${B.type.storage}, ${g*g}>; + ${A.registerUniforms(oe).declareVariables(...G,...Z)} + ${A.mainStart([g,g,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${f===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${f===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; + ${ta(j,ee,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${y&&d?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${d?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${X}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${y&&d?` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }`:` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${d?`if (n + local_id.y < present_sequence_length) { + present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; + }`:""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${X}(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($){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: ${$}`)}})()}; + output[outputIdx] = ${H.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${$};${o!==void 0};${s!==void 0};${e}`,inputDependencies:b},getRunData:()=>({outputs:x,dispatchGroup:C,programUniforms:E}),getShaderSource:S}},C_=(e,r,t,s,o,n,i=void 0,a=void 0)=>{let l=n+o.kvSequenceLength,u=o.nReps?o.nReps:1,p=o.vHiddenSize*u,d=e>1&&s,c=o.kvNumHeads?o.kvNumHeads:o.numHeads,_=d?[o.batchSize,c,l,o.headSize]:void 0,f=[o.batchSize,o.sequenceLength,p],v=12,$={x:Math.ceil(o.vHeadSize/v),y:Math.ceil(o.sequenceLength/v),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:u}],g=d&&s&&be.size(s.dims)>0,C=["type","type"];g&&C.push("type"),i&&C.push("type"),a&&C.push("type");let E=[{dims:f,dataType:r.dataType,gpuDataType:0}];d&&E.push({dims:_,dataType:r.dataType,gpuDataType:0});let y=b=>{let x=Pe("probs",r.dataType,r.dims),S=Pe("v",t.dataType,t.dims),A=[x,S];g&&A.push(Pe("past_value",s.dataType,s.dims));let B=i?Pe("seq_lens",i.dataType,i.dims):void 0;i&&A.push(B);let K=a?Pe("total_sequence_length_input",a.dataType,a.dims):void 0;a&&A.push(K);let G=[Ze("output",r.dataType,f)];d&&G.push(Ze("present_value",r.dataType,_));let j=[{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 = ${v}u; + var tileQ: array<${x.type.value}, ${v*v}>; + var tileV: array<${x.type.value}, ${v*v}>; + ${b.registerUniforms(j).declareVariables(...A,...G)} + ${b.mainStart([v,v,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${u===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${u===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; + ${ta(B,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 + ${g&&d?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${d?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${x.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${g&&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:C},getRunData:()=>({outputs:E,dispatchGroup:$,programUniforms:w}),getShaderSource:y}},Zo=(e,r,t,s,o,n,i,a,l,u,p=void 0,d=void 0)=>{let c=Math.min(e.outputCount,1+(i?1:0)+(a?1:0)),_=c>1?u.pastSequenceLength:0,f=_+u.kvSequenceLength,v=l&&be.size(l.dims)>0?l:void 0,$=[r,t];c>1&&i&&be.size(i.dims)>0&&$.push(i),v&&$.push(v),p&&$.push(p),d&&$.push(d);let w=e.compute(P_(c,r,t,i,v,u,_,p,d),{inputs:$,outputs:c>1?[-1,1]:[-1]})[0];e.compute(E_(w,u.batchSize,u.numHeads,_,u.sequenceLength,f,p,d),{inputs:p&&d?[w,p,d]:[w],outputs:[]});let g=[w,s];c>1&&a&&be.size(a.dims)>0&&g.push(a),p&&g.push(p),d&&g.push(d),e.compute(C_(c,w,s,a,u,_,p,d),{inputs:g,outputs:c>1?[0,2]:[0]})},S_=(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]],u=[{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 c=Ze("output_q",l[0].dataType,t),_=Ze("output_k",l[0].dataType,t),f=Ze("output_v",l[0].dataType,t),v=Pe("input",l[0].dataType,l[0].dims),$=Pe("weight",l[1].dataType,l[1].dims),w=Pe("bias",l[2].dataType,l[2].dims),g=v.type.storage,C=[{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<${g}, ${i*i}>; + var tileWeightQ: array<${g}, ${i*i}>; + var tileWeightK: array<${g}, ${i*i}>; + var tileWeightV: array<${g}, ${i*i}>; + ${d.registerUniforms(C).declareVariables(v,$,w,c,_,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 = ${g}(0); + var valueK = ${g}(0); + var valueV = ${g}(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:u}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},fM=(e,r)=>{let t=T_(e.inputs,r),[s,o,n]=S_(e,t);return Zo(e,s,o,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),$_,k_,I_,_M,ux=Re(()=>{_s(),ut(),ft(),Jt(),_t(),$_=(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")},k_=(e,r)=>{let{epsilon:t,spatial:s,format:o}=r,n=e[0].dims,i=s?qt(n[n.length-1]):1,a=o==="NHWC"&&n.length>1?i:1,l=be.size(n)/i,u=s,p=u?n.length:n,d=Pe("x",e[0].dataType,e[0].dims,i),c=Pe("scale",e[1].dataType,e[1].dims,a),_=Pe("bias",e[2].dataType,e[2].dims,a),f=Pe("inputMean",e[3].dataType,e[3].dims,a),v=Pe("inputVar",e[4].dataType,e[4].dims,a),$=Ze("y",e[0].dataType,p,i),w=()=>{let C="";if(s)C=`let cOffset = ${n.length===1?"0u":o==="NHWC"?`outputIndices[${n.length-1}] / ${i}`:"outputIndices[1]"};`;else if(o==="NCHW")C=` + ${$.indicesSet("outputIndices","0","0")} + let cOffset = ${$.indicesToOffset("outputIndices")};`;else{C=`var cIndices = ${c.type.indices}(0); + cIndices[0] = outputIndices[${n.length-1}];`;for(let E=1;E` + const epsilon = ${t}; + ${C.registerUniform("outputSize","u32").declareVariables(d,c,_,f,v,$)} + ${C.mainStart()} + ${C.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${$.offsetToIndices(`global_idx * ${i}`)}; + ${w()} + let scale = ${c.getByOffset("cOffset")}; + let bias = ${_.getByOffset("cOffset")}; + let inputMean = ${f.getByOffset("cOffset")}; + let inputVar = ${v.getByOffset("cOffset")}; + let x = ${d.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${$.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${i}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...st(n)]:[{type:12,data:l}]})}},I_=e=>$t(e),_M=(e,r)=>{let{inputs:t,outputCount:s}=e,o=I_({...r,outputCount:s});if(jt.webgpu.validateInputContent&&$_(t,o),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(k_(t,o))}}),A_,F_,gM,dx=Re(()=>{ft(),_t(),A_=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")},F_=e=>{let r=e[0].dims,t=e[0].dims[2],s=be.size(r)/4,o=e[0].dataType,n=Pe("input",o,r,4),i=Pe("bias",o,[t],4),a=Pe("residual",o,r,4),l=Ze("output",o,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:u=>` + const channels = ${t}u / 4; + ${u.declareVariables(n,i,a,l)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(s)} + let value = ${n.getByOffset("global_idx")} + + ${i.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; + ${l.setByOffset("global_idx","value")} + }`}},gM=e=>{A_(e.inputs),e.compute(F_(e.inputs))}}),O_,Ct,wM,bM,MM,yM,vM,xM,TM,EM,PM,D_,CM,SM,$M,kM,qo,IM,ca,AM,FM,OM,DM,LM,zM,BM,RM,jM,NM,VM,UM,WM,GM,KM,HM,Zl,qM,Ru,ju,XM,QM,JM,L_,z_,YM,cd=Re(()=>{ut(),ft(),Jt(),_t(),O_=(e,r,t,s,o,n,i)=>{let a=Math.ceil(r/4),l="";typeof o=="string"?l=`${o}(a)`:l=o("a");let u=Pe("inputData",t,[a],4),p=Ze("outputData",s,[a],4),d=[{name:"vec_size",type:"u32"}];return i&&d.push(...i),` + ${e.registerUniforms(d).declareVariables(u,p)} + + ${n??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${u.getByOffset("global_idx")}; + ${p.setByOffset("global_idx",l)} + }`},Ct=(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:u=>O_(u,be.size(e.dims),e.dataType,n,t,s,a),getRunData:u=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(be.size(u[0].dims)/64/4)},programUniforms:l})}},wM=e=>{e.compute(Ct(e.inputs[0],"Abs","abs"))},bM=e=>{e.compute(Ct(e.inputs[0],"Acos","acos"))},MM=e=>{e.compute(Ct(e.inputs[0],"Acosh","acosh"))},yM=e=>{e.compute(Ct(e.inputs[0],"Asin","asin"))},vM=e=>{e.compute(Ct(e.inputs[0],"Asinh","asinh"))},xM=e=>{e.compute(Ct(e.inputs[0],"Atan","atan"))},TM=e=>{e.compute(Ct(e.inputs[0],"Atanh","atanh"))},EM=e=>$t(e),PM=(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(Ct(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},D_=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 $t({min:r,max:t})},CM=(e,r)=>{let t=r||D_(e.inputs),s=Er(e.inputs[0].dataType);e.compute(Ct(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]})},SM=e=>{e.compute(Ct(e.inputs[0],"Ceil","ceil"))},$M=e=>{e.compute(Ct(e.inputs[0],"Cos","cos"))},kM=e=>{e.compute(Ct(e.inputs[0],"Cosh","cosh"))},qo=e=>$t(e),IM=(e,r)=>{let t=Er(e.inputs[0].dataType);e.compute(Ct(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))},ca=(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)); +}`,AM=e=>{let r=Er(e.inputs[0].dataType);e.compute(Ct(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,ca(r)))},FM=e=>{e.compute(Ct(e.inputs[0],"Exp","exp"))},OM=e=>{e.compute(Ct(e.inputs[0],"Floor","floor"))},DM=e=>{let r=Er(e.inputs[0].dataType);e.compute(Ct(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,ca(r)))},LM=(e,r)=>{let t=Er(e.inputs[0].dataType);e.compute(Ct(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))},zM=e=>{e.compute(Ct(e.inputs[0],"Not",r=>`!${r}`))},BM=e=>{e.compute(Ct(e.inputs[0],"Neg",r=>`-${r}`))},RM=e=>{e.compute(Ct(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},jM=e=>{let r=Er(e.inputs[0].dataType);e.compute(Ct(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},NM=e=>{e.compute(Ct(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},VM=e=>$t(e),UM=(e,r)=>{let t=Er(e.inputs[0].dataType);e.compute(Ct(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))},WM=e=>{e.compute(Ct(e.inputs[0],"Sin","sin"))},GM=e=>{e.compute(Ct(e.inputs[0],"Sinh","sinh"))},KM=e=>{e.compute(Ct(e.inputs[0],"Sqrt","sqrt"))},HM=e=>{e.compute(Ct(e.inputs[0],"Tan","tan"))},Zl=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,qM=e=>{e.compute(Ct(e.inputs[0],"Tanh",Zl))},Ru=(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 ${Zl("v")}; +} +`,ju=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,XM=e=>{let r=Er(e.inputs[0].dataType);e.compute(Ct(e.inputs[0],"FastGelu",ju,Ru(r),void 0,e.inputs[0].dataType))},QM=(e,r)=>{let t=Er(e.inputs[0].dataType);return e.compute(Ct(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},JM=e=>{e.compute(Ct(e.inputs[0],"Log","log"))},L_=(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; +} +`,z_=e=>`quick_gelu_impl(${e})`,YM=(e,r)=>{let t=Er(e.inputs[0].dataType);e.compute(Ct(e.inputs[0],"QuickGelu",z_,L_(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),B_,R_,ZM,cx=Re(()=>{ft(),_t(),cd(),B_=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")},R_=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=Pe("input",e[0].dataType,e[0].dims,4),s=Pe("bias",e[0].dataType,[e[0].dims[2]],4),o=Ze("output",e[0].dataType,r,4),n=be.size(r)/4,i=mr(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)} + + ${ca(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")} + }`}},ZM=e=>{B_(e.inputs),e.compute(R_(e.inputs))}}),j_,N_,cs,ey,ty,ry,sy,ny,oy,iy,ay,ly,uy,px=Re(()=>{ut(),ft(),_t(),j_=(e,r,t,s,o,n,i,a,l,u,p,d)=>{let c,_;typeof a=="string"?c=_=(g,C)=>`${a}((${g}),(${C}))`:typeof a=="function"?c=_=a:(c=a.scalar,_=a.vector);let f=Ze("outputData",p,s.length,4),v=Pe("aData",l,r.length,4),$=Pe("bData",u,t.length,4),w;if(o)if(n){let g=be.size(r)===1,C=be.size(t)===1,E=r.length>0&&r[r.length-1]%4===0,y=t.length>0&&t[t.length-1]%4===0;g||C?w=f.setByOffset("global_idx",_(g?`${v.type.value}(${v.getByOffset("0")}.x)`:v.getByOffset("global_idx"),C?`${$.type.value}(${$.getByOffset("0")}.x)`:$.getByOffset("global_idx"))):w=` + let outputIndices = ${f.offsetToIndices("global_idx * 4u")}; + let offsetA = ${v.broadcastedIndicesToOffset("outputIndices",f)}; + let offsetB = ${$.broadcastedIndicesToOffset("outputIndices",f)}; + ${f.setByOffset("global_idx",_(i||E?v.getByOffset("offsetA / 4u"):`${v.type.value}(${v.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||y?$.getByOffset("offsetB / 4u"):`${$.type.value}(${$.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else w=f.setByOffset("global_idx",_(v.getByOffset("global_idx"),$.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let g=(C,E,y="")=>{let b=`aData[indexA${E}][componentA${E}]`,x=`bData[indexB${E}][componentB${E}]`;return` + let outputIndices${E} = ${f.offsetToIndices(`global_idx * 4u + ${E}u`)}; + let offsetA${E} = ${v.broadcastedIndicesToOffset(`outputIndices${E}`,f)}; + let offsetB${E} = ${$.broadcastedIndicesToOffset(`outputIndices${E}`,f)}; + let indexA${E} = offsetA${E} / 4u; + let indexB${E} = offsetB${E} / 4u; + let componentA${E} = offsetA${E} % 4u; + let componentB${E} = offsetB${E} % 4u; + ${C}[${E}] = ${y}(${c(b,x)}); + `};p===9?w=` + var data = vec4(0); + ${g("data",0,"u32")} + ${g("data",1,"u32")} + ${g("data",2,"u32")} + ${g("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:w=` + ${g("outputData[global_idx]",0)} + ${g("outputData[global_idx]",1)} + ${g("outputData[global_idx]",2)} + ${g("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(v,$,f)} + + ${d??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${w} + }`},N_=(e,r,t,s,o,n,i=t.dataType)=>{let a=t.dims.map(v=>Number(v)??1),l=s.dims.map(v=>Number(v)??1),u=!be.areEqual(a,l),p=a,d=be.size(a),c=!1,_=!1,f=[u];if(u){let v=oo.calcShape(a,l,!1);if(!v)throw new Error("Can't perform binary op on the given tensors");p=v.slice(),d=be.size(p);let $=be.size(a)===1,w=be.size(l)===1,g=a.length>0&&a[a.length-1]%4===0,C=l.length>0&&l[l.length-1]%4===0;f.push($),f.push(w),f.push(g),f.push(C);let E=1;for(let y=1;yv.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:v=>j_(v,a,l,p,c,u,_,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)},...st(a,l,p)]})}},cs=(e,r,t,s,o,n)=>{e.compute(N_(r,o??"",e.inputs[0],e.inputs[1],t,s,n))},ey=e=>{cs(e,"Add",(r,t)=>`${r}+${t}`)},ty=e=>{cs(e,"Div",(r,t)=>`${r}/${t}`)},ry=e=>{cs(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},sy=e=>{cs(e,"Mul",(r,t)=>`${r}*${t}`)},ny=e=>{let r=Pe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;cs(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)); + } + `)},oy=e=>{cs(e,"Sub",(r,t)=>`${r}-${t}`)},iy=e=>{cs(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},ay=e=>{cs(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},ly=e=>{cs(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},uy=e=>{cs(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),V_,U_,W_,G_,dy,cy,hx=Re(()=>{ut(),ft(),Jt(),_t(),V_=(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,u)=>{if(u!==r&&l!==s.dims[u])throw new Error("non concat dimensions must match")})}})},U_=(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; + }`,W_=(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=[],u=[],p=[{type:12,data:o}];for(let v=0;v`uniforms.sizeInConcatAxis${v}`).join(","),f=v=>` + + ${(()=>{v.registerUniform("outputSize","u32");for(let $=0;$(${_}); + ${c} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${W_(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:f}},dy=(e,r)=>{let t=e.inputs,s=t[0].dims,o=be.normalizeAxis(r.axis,s.length);V_(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(G_(i,o,n,t[0].dataType),{inputs:i})},cy=e=>$t({axis:e.axis})}),On,Dn,Ln,pd,Bn=Re(()=>{ut(),ft(),On=(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}`)}},Dn=(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})},Ln=(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"})},pd=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)||[zb,Bb];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}}}),br,py,hd=Re(()=>{br=(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.`)}},py=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),hy,mx=Re(()=>{hy=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)); +} +`}),Qo,md,fd=Re(()=>{ut(),ft(),_t(),Bn(),Qo=(e,r,t,s,o)=>{let n=s-t;return` + ${Array.from({length:t}).map((i,a)=>` + if (${rt(r.shape,a,r.rank)} != 1) { + ${r.indicesSet(e,a,rt(o,a+n,s))} + } else { + ${r.indicesSet(e,a,0)} + }`).join("")} +`},md=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i[i.length-2],u=a[a.length-1],p=i[i.length-1],d=qt(u),c=qt(p),_=qt(l),f=be.size(t)/d/_,v=e.length>2,$=s?s.slice(0,-2):t.slice(0,-2),w=[be.size($),l,u],g=[{type:12,data:f},{type:12,data:l},{type:12,data:u},{type:12,data:p}];Dn(r,g),g.push(...st($,i,a)),v&&g.push(...st(e[2].dims)),g.push(...st(w));let C=E=>{let y=ld("batch_dims",e[0].dataType,$.length),b=Pe("a",e[0].dataType,i.length,c),x=Pe("b",e[1].dataType,a.length,d),S=Ze("output",e[0].dataType,w.length,d),A=mr(S.type.tensor),B=On(r,S.type.value,A),K=[b,x],G="";if(v){let H=o?d:1;K.push(Pe("bias",e[2].dataType,e[2].dims.length,H)),G=`${o?`value += bias[col / ${H}];`:`value += ${S.type.value}(bias[row + i]);`}`}let j=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Ln(r,j);let ee=()=>{let H=`var a_data: ${b.type.value};`;for(let Z=0;Z; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${c}) { + ${ee()} + } + for (var i = 0u; i < ${_}u; i++) { + var value = values[i]; + ${G} + ${B} + let cur_indices = ${S.type.indices}(batch, row + i, col); + let offset = ${S.indicesToOffset("cur_indices")}; + ${S.setByOffset(`offset / ${d}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${d};${c};${_};${o}`,inputDependencies:v?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:g}),getShaderSource:C}}}),K_,H_,Nu,eu,q_,Vu,X_,_a,_d=Re(()=>{ut(),ft(),_t(),Bn(),fd(),hd(),K_=(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":""}); + `,H_=(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];"} + }`,Nu=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32)=>{let l=r[1]*e[1],u=r[0]*e[0],p=o?l:n,d=o?n:l,c=p/r[0],_=n/r[1];if(!((o&&c===4&&e[1]===4||!o&&(c===3||c===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} is true, innerElementSize ${c} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${c} must be 3 or 4. + tileAWidth ${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/c}>, ${d}>; +var mm_Bsub: array, ${u/e[0]}>, ${n}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${c}; +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 * ${_}; + 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; + ${K_(o,s)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${c===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${H_(o,c)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},eu=(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":""}); + `,q_=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Vu=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32,l=!1)=>{let u=e[1]*r[1],p=e[0]*r[0],d=o?u:n,c=o?n:u;if(!(c%r[1]===0&&d%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${c} 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 _=c/r[1],f=d/r[0],v=n/r[1],$=l?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${u}; + 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 < ${c}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${r[0]}) { + ${eu(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) * ${u}; + +let tileRowA = i32(localId.y) * ${_}; +let tileColA = i32(localId.x) * ${f}; +let tileRowB = i32(localId.y) * ${v}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${f}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${eu(o,s)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${v}; 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) { + ${q_(o)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${c}>; + var mm_Bsub : array, ${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>; + ${$} + } +`},X_=(e,r,t,s,o=!1)=>{let[n,i,a,l]=s,u=mr(s[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${br(e,u)} { + var value = ${br(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${i.type.indices}; + ${Qo("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}) -> ${br(e,u)} { + var value = ${br(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${a.type.indices}; + ${Qo("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: ${br(e,u)}) { + 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]":`${br(e,u)}(bias[row])`};`:""} + ${t} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},_a=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i.slice(0,-2),u=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),d=be.size(p),c=i[i.length-2],_=i[i.length-1],f=a[a.length-1],v=_%4===0&&f%4===0,$=c<=8?[4,1,1]:[4,4,1],w=[8,8,1],g=[Math.ceil(f/w[0]/$[0]),Math.ceil(c/w[1]/$[1]),Math.ceil(d/w[2]/$[2])],C=v?4:1,E=[...l,c,_/C],y=E.length,b=[...u,_,f/C],x=b.length,S=[d,c,f/C],A=[{type:6,data:c},{type:6,data:f},{type:6,data:_}];Dn(r,A),A.push(...st(p,E,b));let B=["rank","rank"],K=e.length>2;K&&(A.push(...st(e[2].dims)),B.push("rank")),A.push(...st(S));let G=j=>{let ee=p.length,H=ld("batchDims",e[0].dataType,ee,1),Z=mr(e[0].dataType),X=Pe("a",e[0].dataType,y,C),oe=Pe("b",e[1].dataType,x,C),me=Ze("result",e[0].dataType,S.length,C),ae=[X,oe];if(K){let fe=o?C:1;ae.push(Pe("bias",e[2].dataType,e[2].dims.length,fe))}let V=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Ln(r,V);let F=mr(me.type.tensor),W=On(r,me.type.value,F),re=X_(C,K,W,[H,X,oe,me],o);return` + ${j.registerUniforms(V).registerInternalVariables(H).declareVariables(...ae,me)} + ${re} + ${v?Nu($,w,Z,H):Vu($,w,Z,H)} + `};return{name:"MatMul",shaderCache:{hint:`${$};${r.activation};${v};${o}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:g[0],y:g[1],z:g[2]},programUniforms:A}),getShaderSource:G}}}),Q_,my,fx=Re(()=>{ut(),Os(),_t(),Bn(),hd(),mx(),_d(),Q_=(e,r,t,s,o=!1,n,i=4,a=4,l=4,u="f32")=>{let p=A=>{switch(A){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${u}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${A} is not supported.`)}},d=A=>{switch(A){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 ${A} is not supported.`)}},c=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,_=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,f=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",v=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",$=e?"row":"col",w=e?"col":"row",g=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${$} / outWidth; + let outCol = ${$} % 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 = ${br(i,u)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${f} && xCol >= 0 && xCol < ${v}) { + ${c} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${p(i)} + } + return resData;`,C=e?r&&s?` + let col = colIn * ${i}; + ${g}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${g} + } + return ${br(i,u)}(0.0);`:s&&t?` + let col = colIn * ${i}; + ${g}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${g} + } + return ${br(i,u)}(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 ${br(a,u)}(0.0);`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${d(a)} + } + return ${br(a,u)}(0.0);`,y=br(l,u),b=br(e?i:a,u),x=br(e?a:i,u),S=On(n,y,u);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${b} { + ${e?C:E} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${x} { + ${e?E:C} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${y}) { + let col = colIn * ${l}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${_} + ${py(o)} + ${S} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},my=(e,r,t,s,o,n,i,a,l)=>{let u=r.format==="NHWC",p=u?e[0].dims[3]:e[0].dims[1],d=t[0],c=u?t[2]:t[3],_=u?t[1]:t[2],f=u?t[3]:t[1],v=u&&(p%4===0||p%3===0)&&f%4===0,$=u?f:c*_,w=u?c*_:f,g=[8,8,1],C=s<=8?[4,1,1]:[4,4,1],E=[Math.ceil($/g[0]/C[0]),Math.ceil(w/g[1]/C[1]),Math.ceil(d/g[2]/C[2])];Tt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let y=v?u&&p%4!==0?3:4:1,b=g[1]*C[1],x=g[0]*C[0],S=Math.max(g[0]*y,g[1]),A=s%b===0,B=o%x===0,K=n%S===0,G=v?[y,4,4]:[1,1,1],j=[{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}];Dn(r,j),j.push(...st(e[0].dims,e[1].dims));let ee=["rank","rank"];i&&(j.push(...st(e[2].dims)),ee.push("rank")),j.push(...st(t));let H=Z=>{let X=[{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}];Ln(r,X);let oe=v?4:1,me=mr(e[0].dataType),ae=` + fn setOutputAtIndex(flatIndex : i32, value : ${v?`vec4<${me}>`:me}) { + result[flatIndex] = ${v?`vec4<${me}>`:me}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${v?`vec4<${me}>`:me}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${v?"/ 4":""}, value); + }`,V=Pe("x",e[0].dataType,e[0].dims.length,y===3?1:y),F=Pe("w",e[1].dataType,e[1].dims.length,oe),W=[V,F],re=Ze("result",e[0].dataType,t.length,oe);if(i){let fe=Pe("bias",e[2].dataType,e[2].dims.length,oe);W.push(fe),ae+=` + fn getBiasByOutputCoords(coords : vec4) -> ${v?`vec4<${me}>`:me} { + return bias[coords.${u?"w":"y"}${v?"/ 4":""}]; + }`}return` + ${hy("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 }; + ${Z.registerUniforms(X).declareVariables(...W,re)} + ${ae} + ${Q_(u,A,B,K,i,r,G[0],G[1],G[2],me)} + ${v?Nu(C,g,me,void 0,!u,S):Vu(C,g,me,void 0,!u,S,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${y};${v};${A};${B};${K};${b};${x};${S}`,inputDependencies:ee},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:j}),getShaderSource:H}}}),J_,tu,jo,Y_,ru,Z_,fy,_y,_x=Re(()=>{ut(),Os(),ft(),_t(),Bn(),hd(),J_=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,jo=(e,r)=>r<=1?e:e+(e-1)*(r-1),Y_=(e,r,t,s=1)=>{let o=jo(r,s);return Math.floor((e[0]*(t-1)-t+o)/2)},ru=(e,r,t,s,o)=>{o==null&&(o=Y_(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},Z_=(e,r,t,s,o,n,i,a,l,u)=>{let p,d,c,_;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let f=ru([r,t,s,1],[a,l,u],1,[o,n,i],e);d=f[0],c=f[1],_=f[2]}else if(Array.isArray(e)){if(!e.every((v,$,w)=>v===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 f=ru([r,t,s,1],[a,l,u],1,[o,n,i],e[0]);d=f[0],c=f[1],_=f[2]}else if(e==="SAME_UPPER"){d=Math.ceil(r/o),c=Math.ceil(t/n),_=Math.ceil(s/i);let f=(d-1)*o+a-r,v=(c-1)*n+l-t,$=(_-1)*i+u-s,w=Math.floor(f/2),g=f-w,C=Math.floor(v/2),E=v-C,y=Math.floor($/2),b=$-y;p={top:C,bottom:E,left:y,right:b,front:w,back:g}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:c,outWidth:_}},fy=(e,r,t,s,o,n=!1,i="channelsLast")=>{let a,l,u,p,d;if(i==="channelsLast")[a,l,u,p,d]=e;else if(i==="channelsFirst")[a,d,l,u,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[c,,_,f,v]=r,[$,w,g]=tu(t),[C,E,y]=tu(s),b=jo(_,C),x=jo(f,E),S=jo(v,y),{padInfo:A,outDepth:B,outHeight:K,outWidth:G}=Z_(o,l,u,p,$,w,g,b,x,S),j=n?c*d:c,ee=[0,0,0,0,0];return i==="channelsFirst"?ee=[a,j,B,K,G]:i==="channelsLast"&&(ee=[a,B,K,G,j]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:u,inWidth:p,inChannels:d,outDepth:B,outHeight:K,outWidth:G,outChannels:j,padInfo:A,strideDepth:$,strideHeight:w,strideWidth:g,filterDepth:_,filterHeight:f,filterWidth:v,effectiveFilterDepth:b,effectiveFilterHeight:x,effectiveFilterWidth:S,dilationDepth:C,dilationHeight:E,dilationWidth:y,inShape:e,outShape:ee,filterShape:r}},_y=(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(($,w)=>w)},u=[Math.ceil(J_(l.x.map($=>t[$]))/a[0]),1,1];Tt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let p=1,d=be.size(t),c=[{type:12,data:d},{type:12,data:s},{type:12,data:o},{type:12,data:r.strides},{type:12,data:r.dilations}];Dn(r,c),c.push(...st(e[0].dims,e[1].dims));let _=["rank","rank"],f=e.length===3;f&&(c.push(...st(e[2].dims)),_.push("rank")),c.push(...st(t));let v=$=>{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}];Ln(r,w);let g=1,C=mr(e[0].dataType),E=Pe("x",e[0].dataType,e[0].dims.length,p),y=Pe("W",e[1].dataType,e[1].dims.length,g),b=[E,y],x=Ze("result",e[0].dataType,t.length,g),S="";if(f){let K=Pe("bias",e[2].dataType,e[2].dims.length,g);b.push(K),S+=` + fn getBiasByOutputCoords(coords : array) -> ${C} { + return bias[${i?rt("coords",4,5):rt("coords",1,5)}]; + }`}let A=br(p,C),B=On(r,A,C);return` + ${S} + 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 ${y.getByIndices("aIndices")}; + } + ${$.registerUniforms(w).declareVariables(...b,x)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${x.offsetToIndices("global_idx")}; + let batch = ${rt("coords",0,E.rank)}; + let d2 = ${i?rt("coords",E.rank-1,E.rank):rt("coords",1,E.rank)}; + let xFRCCorner = vec3(${i?rt("coords",1,E.rank):rt("coords",2,E.rank)}, + ${i?rt("coords",2,E.rank):rt("coords",3,E.rank)}, + ${i?rt("coords",3,E.rank):rt("coords",4,E.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${i?rt("uniforms.x_shape",1,E.rank):rt("uniforms.x_shape",2,E.rank)}; + let xShapeZ = ${i?rt("uniforms.x_shape",2,E.rank):rt("uniforms.x_shape",3,E.rank)}; + let xShapeW = ${i?rt("uniforms.x_shape",3,E.rank):rt("uniforms.x_shape",4,E.rank)}; + let xShapeU = ${i?rt("uniforms.x_shape",4,E.rank):rt("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); + } + } + } + } + ${f?"value = value + getBiasByOutputCoords(coords)":""}; + ${B} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${i};${p};${f}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:c}),getShaderSource:v}}}),gy,wy,gx=Re(()=>{ut(),ft(),_t(),Bn(),gy=(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",u=l?t[3]:t[1],p=u/r.group,d=l&&p>=4?qt(u):1,c=be.size(t)/d,_=[{type:12,data:c},{type:12,data:r.dilations},{type:12,data:[r.strides[0],r.strides[1]]},{type:12,data:[r.pads[0],r.pads[1]]},{type:12,data:p}];Dn(r,_),_.push(...st(i,[a[0],a[1],a[2],a[3]/d]));let f=o?["rank","rank","rank"]:["rank","rank"];_.push(...st([t[0],t[1],t[2],t[3]/d]));let v=$=>{let w=Ze("output",e[0].dataType,t.length,d),g=mr(w.type.tensor),C=On(r,w.type.value,g),E=Pe("x",e[0].dataType,i.length),y=Pe("w",e[1].dataType,a.length,d),b=[E,y];o&&b.push(Pe("b",e[2].dataType,e[2].dims,d));let x=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:r.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];Ln(r,x);let S=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 = ${y.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { + continue; + } + + let xVal = ${E.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${y.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${$.registerUniforms(x).declareVariables(...b,w)} + + ${$.mainStart()} + ${$.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); + ${S} + ${n} + ${C} + ${w.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${d}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:_}),getShaderSource:v}},wy=(e,r,t,s)=>{let o=e.length>2,n=qt(t[3]),i=qt(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],u=[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]]}];Dn(r,d),d.push(...st(l,u,p));let c=(i-1)*r.strides[1]+u[1],_=f=>{let v=Ze("output",e[0].dataType,p.length,n),$=mr(v.type.tensor),w=On(r,v.type.value,$),g=Pe("x",e[0].dataType,l.length,n),C=Pe("w",e[1].dataType,u.length,n),E=[g,C];o&&E.push(Pe("b",e[2].dataType,e[2].dims,n));let y=o?"value += b[output_channel];":"",b=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Ln(r,b),` + ${f.registerUniforms(b).declareVariables(...E,v)} + ${f.mainStart()} + ${f.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<${g.type.value}, ${c}>; + var values: array<${v.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 < ${u[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${c}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${g.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${g.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${u[1]}; w_width++) { + let w_val = ${C.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${i}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${i}u; i++) { + var value = values[i]; + ${y} + ${w} + ${v.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${i};${c};${u[0]};${u[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:_}}}),eg,ra,tg,sa,Uu,su,rg,sg,Wu,wx=Re(()=>{ft(),fx(),_x(),_d(),gx(),Bn(),fd(),Js(),eg=(e,r,t,s,o,n)=>{let i=e[0],a=e.slice(n?1:2,n?3:4),l=a.length,u=r[0],p=r.slice(2).map((c,_)=>c+(c-1)*(t[_]-1)),d=a.map((c,_)=>c+s[_]+s[_+l]).map((c,_)=>Math.floor((c-p[_]+o[_])/o[_]));return d.splice(0,0,i),d.splice(n?3:1,0,u),d},ra=[2,3,1,0],tg=(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")},sa=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=pd(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,u=e.w_is_const();return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},su=(e,r,t,s)=>{let o=t.format==="NHWC",n=eg(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,o);if(t.group!==1){let b=[r[0]];if(o){let x=e.kernelCustomData.wT??e.compute(Vr(r[1],ra),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=x),b.push(x)}else b.push(r[1]);r.length===3&&b.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(wy(b,t,n,s),{inputs:b}):e.compute(gy(b,t,n,s),{inputs:b});return}let i=r.length===3,a=r[0].dims[o?1:2],l=r[0].dims[o?2:3],u=r[0].dims[o?3:1],p=r[1].dims[2],d=r[1].dims[3],c=n[o?1:2],_=n[o?2:3],f=n[o?3:1],v=o&&p===a&&d===l&&t.pads[0]===0&&t.pads[1]===0;if(v||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 b=n[0],x,S,A,B=[];if(o){let j=e.kernelCustomData.wT??e.compute(Vr(r[1],ra),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=j),v){let ee=a*l*u;x=r[0].reshape([1,b,ee]),S=j.reshape([1,ee,f]),A=[1,b,f]}else x=r[0].reshape([b,a*l,u]),S=j.reshape([1,u,f]),A=[b,c*_,f];B.push(x),B.push(S)}else x=r[0].reshape([b,u,a*l]),S=r[1].reshape([1,f,u]),A=[b,f,c*_],B.push(S),B.push(x);i&&B.push(r[2]);let K=A[2],G=B[0].dims[B[0].dims.length-1];K<8&&G<8?e.compute(md(B,t,n,A,o,s),{inputs:B}):e.compute(_a(B,t,n,A,o,s),{inputs:B});return}let $=!0,w=e.kernelCustomData.wT??e.compute(Vr(r[1],ra),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=w);let g=[r[0],w];i&&g.push(r[2]);let C=o?c*_:f,E=o?f:c*_,y=p*d*u;e.compute(my(g,t,n,C,E,y,i,$,s),{inputs:g})},rg=(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=sa({...r,pads:o,strides:n,dilations:i,kernelShape:a},s);su(e,s,l,u=>t?[u[0],u[2],u[3]]:[u[0],u[1],u[3]])},sg=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",o=sa(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=fy(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(_y(r,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},Wu=(e,r)=>{if(tg(e.inputs,r),e.inputs[0].dims.length===3)rg(e,r);else if(e.inputs[0].dims.length===5)sg(e,e.inputs,r);else{let t=sa(r,e.inputs);su(e,e.inputs,t)}}}),by,bx=Re(()=>{ut(),Os(),ft(),_t(),by=(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,u=a[3],p=n?qt(l):1,d=n&&u===1&&l>=4,c=d?Math.floor(l/4)*4:Math.floor(l/p)*p,_=l-c,f=n?qt(u):1,v=n?u===1?p:f:1,$=be.size(o)/f,w=[Math.ceil($/64),1,1];Tt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${w}`);let g=["rank","rank"],C=[r.strides[0],r.strides[1]],E=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],y=[r.dilations[0],r.dilations[1]],b=[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))],x=[b[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),b[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],S=[{type:12,data:$},{type:12,data:C},{type:12,data:E},{type:12,data:y},{type:12,data:b},{type:6,data:x},{type:12,data:c},{type:12,data:l},{type:12,data:u},...st(e[0].dims,e[1].dims)];s&&(S.push(...st(e[2].dims)),g.push("rank")),S.push(...st(o));let A=B=>{let K=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:C.length},{name:"filter_dims",type:"u32",length:E.length},{name:"dilations",type:"u32",length:E.length},{name:"effective_filter_dims",type:"u32",length:b.length},{name:"pads",type:"i32",length:x.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],G=mr(e[0].dataType),j=n?1:2,ee=n?2:3,H=n?3:1,Z=Pe("W",e[1].dataType,e[1].dims.length,v),X=Pe("Dy",e[0].dataType,e[0].dims.length,p),oe=[X,Z];s&&oe.push(Pe("bias",e[2].dataType,[o[H]].length,f));let me=Ze("result",e[0].dataType,o.length,f),ae=()=>{let W="";if(d)p===4?W+=` + let xValue = ${X.getByOffset("x_offset")}; + let wValue = ${Z.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue); + x_offset += 1u; + w_offset += 1u;`:p===2?W+=` + dotProd = dotProd + dot(vec4<${G}>(${X.getByOffset("x_offset")}, ${X.getByOffset("x_offset + 1u")}), vec4<${G}>(${Z.getByOffset("w_offset")}, ${Z.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;`:p===1&&(W+=` + dotProd = dotProd + dot(vec4<${G}>(${X.getByOffset("x_offset")}, ${X.getByOffset("x_offset + 1u")}, ${X.getByOffset("x_offset + 2u")}, ${X.getByOffset("x_offset + 3u")}), vec4<${G}>(${Z.getByOffset("w_offset")}, ${Z.getByOffset("w_offset + 1u")}, ${Z.getByOffset("w_offset + 2u")}, ${Z.getByOffset("w_offset + 3u")})); + x_offset += 4u; + w_offset += 4u;`);else if(W+=` + let xValue = ${n?X.getByOffset(`${X.indicesToOffset(`${X.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):X.get("batch","inputChannel","idyR","idyC")}; + `,p===1)W+=` + let w_offset = ${Z.indicesToOffset(`${Z.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${Z.getByOffset(`w_offset / ${v}`)}; + dotProd = dotProd + xValue * wValue;`;else for(let re=0;re{if(_===0)return"";if(!d)throw new Error(`packInputAs4 ${d} is not true.`);let W="";if(p===1){W+="dotProd = dotProd";for(let re=0;re<_;re++)W+=` + + ${X.getByOffset(`x_offset + ${re}`)} * ${Z.getByOffset(`w_offset + ${re}`)}`;W+=";"}else if(p===2){if(_!==2)throw new Error(`Invalid inputChannelsRemainder ${_}.`);W+=` + let xValue = ${X.getByOffset("x_offset")}; + let wValue = ${Z.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue);`}return W},F=` + let outputIndices = ${me.offsetToIndices(`global_idx * ${f}`)}; + let batch = ${me.indicesGet("outputIndices",0)}; + let d1 = ${me.indicesGet("outputIndices",H)}; + let r = ${me.indicesGet("outputIndices",j)}; + let c = ${me.indicesGet("outputIndices",ee)}; + let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + let groupId = d1 / uniforms.output_channels_per_group; + let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = ${me.type.value}(0.0); + var wR: u32 = 0; + if (uniforms.dilations.x == 1) { + // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 + wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); + } + for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${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[${j}]) || 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[${ee}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + ${d?` + var x_offset = ${X.indicesToOffset(`${X.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; + var w_offset = ${Z.indicesToOffset(`${Z.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${v}; + `:""} + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${d?4:p}) { + ${ae()} + inputChannel = inputChannel + ${d?4:p}; + } + ${V()} + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${s?` + bias[d1 / ${f}]`:""}; + ${me.setByOffset("global_idx","value")}; + `;return` + ${B.registerUniforms(K).declareVariables(...oe,me)} + ${B.mainStart()} + ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${F}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${v}${f}${d}${_}`,inputDependencies:g},getRunData:()=>({dispatchGroup:{x:w[0],y:w[1],z:w[2]},outputs:[{dims:t?t(o):o,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:A}}}),ng,og,ig,nu,My,ag,ou,lg,yy,Mx=Re(()=>{bx(),Bn(),Js(),ng=(e,r,t,s,o,n)=>(e-1)*r+t+(s-1)*o+1-n,og=(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)},ig=(e,r,t,s,o,n,i,a,l,u)=>{let p=e.length-2,d=u.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((d,c)=>d*c,1)===0){t.length=0;for(let d=2;dd+c,0)===0){let d=r[0].dims.length-2;l=new Array(d).fill(1)}let u=e.strides.slice();if(u.reduce((d,c)=>d+c,0)===0){let d=r[0].dims.length-2;u=new Array(d).fill(1)}ig(a,t,l,e.autoPad,e.group,o,u,s,i,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:o,outputPadding:i,outputShape:n,dilations:l,strides:u}),p},My=e=>{let r=pd(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,u=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:u,...r,cacheKey:`${e.format};${r.activation};`}},ag=(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")},ou=(e,r,t,s)=>{let o=e.kernelCustomData.wT??e.compute(Vr(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(by(n,t,s),{inputs:n})},lg=(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 u=nu({...r,pads:a,strides:i,dilations:n,kernelShape:o,outputPadding:l},s);ou(e,s,u,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},yy=(e,r)=>{if(ag(e.inputs,r),e.inputs[0].dims.length===3)lg(e,r);else{let t=nu(r,e.inputs);ou(e,e.inputs,t)}}}),ug,vy,xy,yx=Re(()=>{ut(),ft(),Jt(),_t(),ug=(e,r,t,s)=>{let o=be.size(r),n=r.length,i=Pe("input",e,n),a=Ze("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),u=be.normalizeAxis(l,n),p=d=>{let c=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,_=rt("uniforms.input_shape","uniforms.axis",n),f=s.reverse?c+(s.exclusive?" + 1":""):"0",v=s.reverse?_:c+(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 = ${f}; + let last : i32 = ${v}; + 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:u},...st(r,r)]}),getShaderSource:p}},vy=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,o=e.inputs[1];e.compute(ug(s,t,o,r),{inputs:[0]})},xy=e=>{let r=e.exclusive===1,t=e.reverse===1;return $t({exclusive:r,reverse:t})}}),dg,cg,pg,Ty,Ey,vx=Re(()=>{ut(),ft(),Jt(),_t(),dg=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.")},cg=(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",u=r.blocksize,p=r.mode==="DCR";l?([t,s,o,n]=e.dims,i=p?[t,s,o,u,u,n/u**2]:[t,s,o,n/u**2,u,u],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,u,u,n/u**2,s,o]:[t,n/u**2,u,u,s,o],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(i),c=d.dims.length,_=e.dataType,f=Pe("a",_,c),v=Ze("output",_,c),$=w=>` + ${w.registerUniform("output_size","u32").declareVariables(f,v)} + + ${cg(a,c,f,v)} + + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${v.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${v.setByOffset("global_idx",f.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:w=>{let g=l?[t,s*u,o*u,n/u**2]:[t,n/u**2,s*u,o*u],C=be.size(g),E=d.dims,y=be.sortBasedOnPerm(E,a);return{outputs:[{dims:g,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil(C/64)},programUniforms:[{type:12,data:C},...st(E,y)]}},getShaderSource:$}},Ty=(e,r)=>{dg(e.inputs),e.compute(pg(e.inputs[0],r))},Ey=e=>$t({blocksize:e.blocksize,mode:e.mode,format:e.format})}),na,No,iu,hg,mg,fg,_g,au,gg,Py,Cy,xx=Re(()=>{ut(),ft(),Jt(),_t(),na="[a-zA-Z]|\\.\\.\\.",No="("+na+")+",iu="^"+No+"$",hg="("+No+",)*"+No,mg="^"+hg+"$",fg=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)}},_g=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(mg)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,i)=>{let a=e[i].dims.slice();if(!n.match(RegExp(iu)))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(No)))throw new Error("Invalid RHS");(o=s.match(RegExp(na,"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(iu))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(na,"g")),u=new fg(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 c=o-l.length+1;if(c<0)throw new Error("Ellipsis out of bounds");if(i=t.slice(a,a+c),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 _=0;_e+"_max",gg=(e,r,t,s)=>{let o=e.map(u=>u.length).map((u,p)=>Pe(`input${p}`,r,u)),n=be.size(s),i=Ze("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(u=>!t.rhs.symbolToIndices.has(u)),l=u=>{let p=[],d="var prod = 1.0;",c="var sum = 0.0;",_="sum += prod;",f=[],v=[],$=[],w=[],g=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((E,y)=>{var b;if(t.rhs.symbolToIndices.has(y)){let x=(b=t.rhs.symbolToIndices.get(y))==null?void 0:b[0];x!==void 0&&t.lhs.forEach((S,A)=>{if(E.inputIndices.includes(A)){let B=S.symbolToIndices.get(y);if(B===void 0)throw new Error("Invalid symbol error");B.forEach(K=>{p.push(`${o[A].indicesSet(`input${A}Indices`,K,i.indicesGet("outputIndices",x))}`)})}})}else t.lhs.forEach((x,S)=>{if(E.inputIndices.includes(S)){let A=x.symbolToIndices.get(y);if(A===void 0)throw new Error("Invalid symbol error");A.forEach(B=>{f.push(`${o[S].indicesSet(`input${S}Indices`,B,`${y}`)}`)}),w.push(`prod *= ${o[S].getByIndices(`input${S}Indices`)};`)}}),v.push(`for(var ${y}: u32 = 0; ${y} < uniforms.${au(y)}; ${y}++) {`),$.push("}")});let C=g?[...p,`let sum = ${o.map((E,y)=>E.getByIndices(`input${y}Indices`)).join(" * ")};`]:[...p,c,...v,...f,d,...w,_,...$];return` + ${u.registerUniforms(a.map(E=>({name:`${au(E)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${o.map((E,y)=>`var input${y}Indices: ${o[y].type.indices};`).join(` +`)} + ${C.join(` +`)}; + ${i.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let u=a.filter(d=>t.symbolToInfo.has(d)).map(d=>{var c;return{type:12,data:((c=t.symbolToInfo.get(d))==null?void 0:c.dimValue)||0}});u.push({type:12,data:n});let p=e.map((d,c)=>[...st(d)]).reduce((d,c)=>d.concat(c),u);return p.push(...st(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},Py=(e,r)=>{let t=new _g(e.inputs,r.equation),s=t.outputDims,o=e.inputs.map((n,i)=>n.dims);e.compute(gg(o,e.inputs[0].dataType,t,s))},Cy=e=>{let r=e.equation.replace(/\s+/g,"");return $t({equation:r})}}),wg,lu,bg,Mg,Sy,Tx=Re(()=>{ut(),ft(),_t(),wg=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?lu(e,r):lu(r,e),Mg=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=bg(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),u=d=>{let c=Pe("input",o,r.length,i),_=Ze("output",o,s.length,a),f;if(o===9){let v=($,w,g="")=>` + let outputIndices${w} = ${_.offsetToIndices(`outputOffset + ${w}u`)}; + let offset${w} = ${c.broadcastedIndicesToOffset(`outputIndices${w}`,_)}; + let index${w} = offset${w} / 4u; + let component${w} = offset${w} % 4u; + ${$}[${w}] = ${g}(${c.getByOffset(`index${w}`)}[component${w}]); + `;f=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${v("data",0,"u32")} + ${v("data",1,"u32")} + ${v("data",2,"u32")} + ${v("data",3,"u32")} + ${_.setByOffset("global_idx","data")} + }`}else f=` + let outputIndices = ${_.offsetToIndices(`global_idx * ${a}`)}; + let inputOffset = ${c.broadcastedIndicesToOffset("outputIndices",_)}; + let data = ${_.type.value}(${c.getByOffset(`inputOffset / ${i}`)}); + ${_.setByOffset("global_idx","data")} + }`;return` + ${d.registerUniform("vec_size","u32").declareVariables(c,_)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${f}`},p=[{type:12,data:l},...st(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${i}${a}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},Sy=e=>{wg(e.inputs),e.compute(Mg(e.inputs),{inputs:[0]})}}),yg,$y,Ex=Re(()=>{ut(),ft(),_t(),cd(),yg=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=Pe("x",r,[1],4),l=Pe("bias",r,[1],4),u=Ze("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],d=_=>` + let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size; + let bias${_} = ${l.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,c=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,u)} + + ${Ru(Er(r))} + + ${i.mainStart(io)} + ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${a.getByOffset("global_idx")}; + ${c} + let x_in = x + bias; + ${u.setByOffset("global_idx",ju("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/io/4)}})}},$y=e=>{e.inputs.length<2||be.size(e.inputs[1].dims)===0?XM(e):e.compute(yg(e.inputs))}}),vg,xg,ky,Iy,Px=Re(()=>{ut(),ft(),Jt(),_t(),vg=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},xg=(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,u=Math.ceil(be.size(i)/l),p=[{type:12,data:u},{type:6,data:a},{type:12,data:n},...st(e[0].dims,e[1].dims,i)],d=c=>{let _=Pe("data",e[0].dataType,e[0].dims.length,l),f=Pe("inputIndices",e[1].dataType,e[1].dims.length),v=Ze("output",e[0].dataType,i.length,l),$=g=>{let C=s.length,E=`var indicesIndices${g} = ${f.type.indices}(0);`;for(let y=0;y1?`indicesIndices${g}[${y}]`:`indicesIndices${g}`} = ${i.length>1?`outputIndices${g}[uniforms.axis + ${y}]`:`outputIndices${g}`};`;E+=` + var idx${g} = ${f.getByIndices(`indicesIndices${g}`)}; + if (idx${g} < 0) { + idx${g} = idx${g} + uniforms.axisDimLimit; + } + var dataIndices${g} : ${_.type.indices}; + `;for(let y=0,b=0;y1?`dataIndices${g}[${y}]`:`dataIndices${g}`} = u32(idx${g});`,b+=C):(E+=`${o>1?`dataIndices${g}[${y}]`:`dataIndices${g}`} = ${i.length>1?`outputIndices${g}[${b}]`:`outputIndices${g}`};`,b++);return E},w;if(e[0].dataType===9){let g=(C,E,y="")=>` + let outputIndices${E} = ${v.offsetToIndices(`outputOffset + ${E}u`)}; + ${$(E)}; + let offset${E} = ${_.indicesToOffset(`dataIndices${E}`)}; + let index${E} = offset${E} / 4u; + let component${E} = offset${E} % 4u; + ${C}[${E}] = ${y}(${_.getByOffset(`index${E}`)}[component${E}]); + `;w=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${g("value",0,"u32")} + ${g("value",1,"u32")} + ${g("value",2,"u32")} + ${g("value",3,"u32")} + ${v.setByOffset("global_idx","value")} + `}else w=` + let outputIndices = ${v.offsetToIndices("global_idx")}; + ${$("")}; + let value = ${_.getByIndices("dataIndices")}; + ${v.setByOffset("global_idx","value")}; + `;return` + ${c.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,f,v)} + ${c.mainStart()} + ${c.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(u/64)},programUniforms:p}),getShaderSource:d}},ky=e=>$t({axis:e.axis}),Iy=(e,r)=>{let t=e.inputs;vg(t),e.compute(xg(e.inputs,r))}}),Tg,Ay,Fy,Cx=Re(()=>{ut(),ft(),_t(),Tg=(e,r,t,s,o,n,i,a,l)=>{let u=[{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];u.push(...st(r.dims,p));let d=c=>{let _=Pe("indices_data",r.dataType,r.dims.length),f=Ze("input_slice_offsets_data",12,1,1),v=[_,f],$=[{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` + ${c.registerUniforms($).declareVariables(...v)} + ${c.mainStart()} + ${c.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:u}),getShaderSource:d},{inputs:[r],outputs:[-1]})[0]},Ay=(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),u=be.sizeToDimension(s,r.batchDims),p=be.sizeFromDimension(s,r.batchDims),d=a/u,c=new Array(i),_=l;for(let E=0;Es.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let $=n.slice(0,-1).concat(s.slice(v)),w=be.size($),g=[{type:12,data:w},{type:12,data:l},...st(t[0].dims,f.dims,$)],C=E=>{let y=Pe("data",t[0].dataType,t[0].dims.length),b=Pe("slice_offsets",12,f.dims.length),x=Ze("output",t[0].dataType,$.length);return` + ${E.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(y,b,x)} + ${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:$,dataType:o}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:g}),getShaderSource:C},{inputs:[t[0],f]})},Fy=e=>({batchDims:e.batch_dims,cacheKey:""})}),Eg,Pg,Oy,Dy,Sx=Re(()=>{ut(),ft(),Jt(),_t(),Eg=(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.")}},Pg=(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),u=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},...st(...e.map((_,f)=>_.dims),a)],c=_=>{let f=Pe("data",e[0].dataType,e[0].dims.length),v=Pe("inputIndices",e[1].dataType,e[1].dims.length),$=Pe("scales",e[2].dataType,e[2].dims.length),w=e.length>3?Pe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,g=Ze("output",u,a.length),C=[f,v,$];w&&C.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` + ${_.registerUniforms(E).declareVariables(...C,g)} + ${_.mainStart()} + let output_indices = ${g.offsetToIndices("global_idx")}; + var indices_indices = ${v.type.indices}(0); + ${s.length>1?` + for (var i: u32 = 0; i < ${s.length}; i++) { + let index = ${g.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${v.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${g.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${f.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${g.indicesGet("output_indices","i")}; + ${f.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${v.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${t[n]}; + } + ${f.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${a.length}; i++) { + let index = ${g.indicesGet("output_indices",`i + ${s.length} - 1`)}; + ${f.indicesSet("data_indices","i","index")}; + } + let data_offset = ${f.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${f.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 = ${$.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${$.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${$.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 = ${Er(u)}(quantized_data - zero_point) * scale; + ${g.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((_,f)=>f!==1).map(_=>_.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(_,f)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:u}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:c}},Oy=(e,r)=>{let t=e.inputs;Eg(t,r),e.compute(Pg(e.inputs,r))},Dy=e=>$t({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Cg,Sg,Ly,zy,$x=Re(()=>{ut(),ft(),Jt(),_t(),Cg=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.`)},Sg=(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],u=n.slice(0),p=be.size(u),d=Pe("input",s,o),c=Pe("indicesInput",i,n.length),_=Ze("output",s,u.length),f=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return f.push(...st(t,n,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:f}),getShaderSource:v=>` + ${v.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,c,_)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${_.offsetToIndices("global_idx")}; + + var idx = ${c.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")}; + + ${_.setByOffset("global_idx","value")}; + }`}},Ly=e=>$t({axis:e.axis}),zy=(e,r)=>{let t=e.inputs;Cg(t),e.compute(Sg(e.inputs,r))}}),$g,kg,By,Ry,kx=Re(()=>{ut(),ft(),_t(),$g=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")},kg=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[o,n,i]=Lb.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,u=Math.ceil(n/l),p=Math.ceil(o/l),d=!0,c=be.size(a),_=[{type:12,data:d?u:c},{type:12,data:o},{type:12,data:n},{type:12,data:i},{type:1,data:r.alpha},{type:1,data:r.beta}],f=["type","type"];e.length===3&&(_.push(...st(e[2].dims)),f.push("rank")),_.push(...st(a));let v=w=>{let g="";r.transA&&r.transB?g="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?g="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?g="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(g="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let C=r.alpha===1?"":"value *= uniforms.alpha;",E=Pe("a",e[0].dataType,e[0].dims),y=Pe("b",e[1].dataType,e[1].dims),b=E.type.value,x=null,S=[E,y];e.length===3&&(x=Pe("c",e[2].dataType,e[2].dims.length),S.push(x));let A=Ze("output",e[0].dataType,a.length);S.push(A);let B=[{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(B).declareVariables(...S)} + + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${b}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${g} + } + + ${C} + ${x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",A)}; value += ${b}(uniforms.beta) * ${x.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},$=w=>{let g=Pe("a",e[0].dataType,e[0].dims),C=Pe("b",e[1].dataType,e[1].dims),E=null,y=[g,C];e.length===3&&(E=Pe("c",e[2].dataType,e[2].dims.length),y.push(E));let b=Ze("output",e[0].dataType,a.length);y.push(b);let x=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],S="",A="";r.transA&&r.transB?(A=` + 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] = ${g.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] = ${C.type.value}(0); + } + `,S="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(A=` + 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] = ${g.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] = ${C.type.value}(0); + } + `,S="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(A=` + 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] = ${g.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] = ${C.type.value}(0); + } + `,S="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(A=` + 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] = ${g.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] = ${C.type.value}(0); + } + `,S="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let B=r.alpha===1?"":"value *= uniforms.alpha;";return` + ${w.registerUniforms(x).declareVariables(...y)} + 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 = ${b.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${A} + k_start = k_start + ${l}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${l}; k++) { + ${S} + } + workgroupBarrier(); + } + + ${B} + 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)",b)}; value += ${b.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:f},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:u*p},programUniforms:_}),getShaderSource:$}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:_}),getShaderSource:v}},By=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}`}},Ry=(e,r)=>{$g(e.inputs),e.compute(kg(e.inputs,r))}}),vs,Is,Pn,Cn,Ig,Ag,Fg,Og,Dg,Lg,zg,Bg,jy,Ny,Ix=Re(()=>{ut(),ft(),Jt(),_t(),[vs,Is,Pn,Cn]=[0,1,2,3],Ig=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")},Ag=` + 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; + } +`,Fg=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; + } +`,Og=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)); + `} + } +`,Dg=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); + }`:""} +`,Lg=(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[${vs}] = batch; + indices[${Is}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${Pn}] = u32(r); + indices[${Cn}] = u32(c); + } else { + return ${r}(0); + } + `;case"border":return` + indices[${Pn}] = u32(clamp(r, 0, H - 1)); + indices[${Cn}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${Pn}] = gs_reflect(r, border[1], border[3]); + indices[${Cn}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,zg=(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[${vs}], indices[${Is}], 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[${vs}], indices[${Is}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${vs}], indices[${Is}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${vs}], indices[${Is}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${vs}], indices[${Is}], 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[${vs}], indices[${Is}], 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")}`,Bg=(e,r)=>{let t=Pe("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=Pe("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]],[vs,Is,Pn,Cn]=[0,3,1,2]);let i=Ze("output",e[0].dataType,n.length),a=t.type.value,l=be.size(n),u=[{type:12,data:l},...st(e[0].dims,s,n)],p=d=>` + ${d.registerUniform("output_size","u32").declareVariables(t,o,i)} + ${Ag} + ${Fg(a)} + ${Og(r)} + ${Dg(r)} + ${Lg(t,a,r)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${Pn}]); + let W_in = i32(uniforms.x_shape[${Cn}]); + + ${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[${vs}], indices[${Pn}], indices[${Cn}]); + let nxy = ${o.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${zg(i,a,r)} + }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:d=>{let c=be.size(n);return{outputs:[{dims:n,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:u}},getShaderSource:p}},jy=(e,r)=>{Ig(e.inputs),e.compute(Bg(e.inputs,r))},Ny=e=>$t({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),$r,Rg,Vy,uu,jg,Xo,Uy,Wy=Re(()=>{ut(),ft(),Jt(),ad(),dd(),_t(),Js(),$r=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,Rg=(e,r)=>{let t=e[0],s=$r(e,1),o=$r(e,2),n=$r(e,3),i=$r(e,4),a=$r(e,5),l=$r(e,6),u=$r(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],c=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],_=d,f=0,v=0,$=Math.floor(c/r.numHeads);if(l&&u&&be.size(l.dims)&&be.size(u.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]!==$)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[0]!==p||u.dims[1]!==r.numHeads||u.dims[3]!==$)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(u.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');f=l.dims[2],v=l.dims[2]}else if(l&&be.size(l.dims)||u&&be.size(u.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,_=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.');w=5,_=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');w=0,_=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 g=f+_,C=0;if(i&&be.size(i.dims)>0){C=8;let x=i.dims;throw x.length===1?x[0]===p?C=1:x[0]===3*p+2&&(C=3):x.length===2&&x[0]===p&&x[1]===g&&(C=5),C===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,y=c;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(_!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');y=o.dims[2]}else{if(_!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');y=o.dims[1]*o.dims[3],E=!0}}let b=!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]!==g)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:d,pastSequenceLength:f,kvSequenceLength:_,totalSequenceLength:g,maxSequenceLength:v,inputHiddenSize:0,hiddenSize:c,vHiddenSize:y,headSize:$,vHeadSize:Math.floor(y/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:C,scale:r.scale,broadcastResPosBias:b,passPastInKv:E,qkvFormat:w}},Vy=e=>$t({...e}),uu=$t({perm:[0,2,1,3]}),jg=(e,r,t,s,o,n,i)=>{let a=[s,o,n],l=be.size(a),u=[{type:12,data:l},{type:12,data:i},{type:12,data:n}],p=d=>{let c=Ze("qkv_with_bias",r.dataType,a),_=Pe("qkv",r.dataType,a),f=Pe("bias",t.dataType,a),v=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${d.registerUniforms(v).declareVariables(_,f,c)} + ${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:u}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},Xo=(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=jg(e,n,i,r,s,t*o,a),l=l.reshape([r,s,t,o]),t===1||s===1?l:e.compute(Vr(l,uu.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(Vr(l,uu.perm),{inputs:[l],outputs:[-1]})[0]},Uy=(e,r)=>{let t=Rg(e.inputs,r),s=e.inputs[0],o=$r(e.inputs,1),n=$r(e.inputs,2),i=$r(e.inputs,3),a=$r(e.inputs,4),l=$r(e.inputs,5),u=$r(e.inputs,6),p=$r(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,c=Xo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(d)return Zo(e,c,o,n,a,void 0,u,p,l,t);if(!o||!n)throw new Error("key and value must be provided");let _=Xo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,o,i,t.hiddenSize),f=Xo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,i,2*t.hiddenSize);Zo(e,c,_,f,a,void 0,u,p,l,t)}}),Ng,Vg,Ug,Wg,Gu,Gy,Ky,Hy=Re(()=>{ut(),ft(),Jt(),_t(),Ng=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Vg=(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),$t({numOutputs:s,axis:r.axis,splitSizes:t})},Ug=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${rt("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,Wg=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=Pe("input",o,t.length),l=new Array(r.numOutputs),u=[],p=[],d=0,c=[{type:12,data:s}];for(let f=0;f` + ${f.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...i)} + ${Ug(l.length)} + ${Wg(i)} + + ${f.mainStart()} + ${f.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 -= ${rt("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:_,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:c})}},Gy=(e,r)=>{Ng(e.inputs);let t=e.inputs.length===1?r:Vg(e.inputs,r);e.compute(Gu(e.inputs,t),{inputs:[0]})},Ky=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 $t({axis:r,numOutputs:s,splitSizes:t})}}),Gg,ga,qy,Xy=Re(()=>{ut(),ft(),Jt(),_t(),Gg=(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],u=t.dims[t.dims.length-2],p=o.dims[0],d=be.sizeFromDimension(t.dims,1)/u,c=a===0?o.dims[1]*2:d/i;if(a>c)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(u!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(c/2!==o.dims[1]&&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(u>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},ga=(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],u=a/l,p=e[2].dims[1],d=o===0?p*2:u/s,c=new Array(i,l,u/d,d-p),_=be.computeStrides(c),f=[{type:1,data:n},{type:12,data:c},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[a,u,d,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,d,l*d,1]}):[],...st(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],v=$=>{let w=Pe("input",e[0].dataType,e[0].dims.length),g=Pe("position_ids",e[1].dataType,e[1].dims.length),C=Pe("cos_cache",e[2].dataType,e[2].dims.length),E=Pe("sin_cache",e[3].dataType,e[3].dims.length),y=Ze("output",e[0].dataType,e[0].dims.length);return $.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:c.length},{name:"global_strides",type:"u32",length:_.length},{name:"input_output_strides",type:"u32",length:_.length}]),` + ${$.declareVariables(w,g,C,E,y)} + + ${$.mainStart(io)} + let half_rotary_emb_dim = uniforms.${C.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${$.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${g.broadcastedIndicesToOffset("bsnh.xy",Ze("",g.type.tensor,2))}; + let position_id = + u32(${g.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")} * ${C.get("position_id","bsnh[3]")} - + ${w.getByOffset("j")} * ${E.get("position_id","bsnh[3]")}; + ${y.setByOffset("i","re")} + let im = ${w.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} + + ${w.getByOffset("j")} * ${C.get("position_id","bsnh[3]")}; + ${y.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${y.setByOffset("k",w.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:$t({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(be.size(c)/io)},programUniforms:f})}},qy=(e,r)=>{Gg(e.inputs,r),e.compute(ga(e.inputs,r))}}),Kg,Hg,du,qg,Qy,Ax=Re(()=>{Jt(),ut(),dd(),Wy(),Hy(),Js(),Xy(),_t(),Kg=(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],u=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],d=u,c=0,_=!s||s.dims.length===0,f=Math.floor(_?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);_&&(p=f*r.numHeads);let v=n&&n.dims.length!==0,$=i&&i.dims.length!==0;if(v&&n.dims.length===4&&n.dims[0]===l&&n.dims[1]!==r.kvNumHeads&&n.dims[2]===r.kvNumHeads&&n.dims[3]===f)throw new Error("BSNH pastKey/pastValue is not supported");if(v&&$){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');c=n.dims[2]}else if(v||$)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]!==f)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]!==f)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 g=0,C=!1,E=r.kvNumHeads?f*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],C=!0}}let y=e.length>4?e[5]:void 0;if(y&&y.dims.length!==1&&y.dims[0]!==l)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:l,sequenceLength:u,pastSequenceLength:c,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:E,headSize:f,vHeadSize:Math.floor(E/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:C,qkvFormat:w}},Hg=$t({perm:[0,2,1,3]}),du=(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(Vr(s,Hg.perm),{inputs:[s],outputs:[-1]})[0]),s},qg=(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}],u=p=>{let d=Pe("seq_lens",t.dataType,t.dims),c=Pe("total_seq_lens",s.dataType,s.dims),_=Ze("pos_ids",o,i),f=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` + ${p.registerUniforms(f).declareVariables(d,c,_)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let total_sequence_length = u32(${c.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; + } + ${_.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; + } + ${_.setByOffset("global_idx","pos_id")} + } else if (global_idx < uniforms.batch_size) { + ${_.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:u}},Qy=(e,r)=>{var E;let t=Kg(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,u=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,d=$t({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[c,_,f]=!o&&!n?e.compute(Gu([s],d),{inputs:[s],outputs:[-1,-1,-1]}):[s,o,n],v,$;if(r.doRotary){let y=e.compute(qg(t.batchSize,t.sequenceLength,l,u),{inputs:[l,u],outputs:[-1]})[0],b=e.inputs[7],x=e.inputs[8],S=$t({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),A=[c,y,b,x],B=[-1];v=e.compute(ga(A,S),{inputs:A,outputs:B})[0],A.splice(0,1,_);let K=$t({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});$=e.compute(ga(A,K),{inputs:A,outputs:B})[0]}let w=Xo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?v:c,void 0,0),g=du(e,r.doRotary?$:_,t),C=du(e,f,t);Zo(e,w,g,C,void 0,void 0,i,a,void 0,t,l,u)}}),cu,Xg,Qg,Jy,Fx=Re(()=>{ut(),ft(),Js(),_t(),cu=(e,r,t,s,o,n,i,a)=>{let l=qt(n),u=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,d=o*i,c=64;d===1&&(c=256);let _=[o,i,n/l],f=[o,i,2],v=["rank","type","type"],$=[];$.push(...st(_,f));let w=g=>{let C=Pe("x",r.dataType,3,l),E=Pe("scale",t.dataType,t.dims),y=Pe("bias",s.dataType,s.dims),b=Ze("output",1,3,2),x=[C,E,y,b];return` + var workgroup_shared : array<${p}, ${c}>; + const workgroup_size = ${c}u; + ${g.declareVariables(...x)} + ${g.mainStart(c)} + 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 = ${u}(0); + var squared_sum = ${u}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${u}(${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};${c}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:f,dataType:1}],dispatchGroup:{x:d},programUniforms:$}),getShaderSource:w},{inputs:[r,t,s],outputs:[-1]})[0]},Xg=(e,r,t)=>{let s=r[0].dims,o=s,n=2,i=s[0],a=s[1],l=be.sizeFromDimension(s,n),u=qt(l),p=be.size(o)/u,d=cu(e,r[0],r[1],r[2],i,l,a,t.epsilon),c=[i,a,l/u],_=[i,a],f=["type","none"],v=$=>{let w=Pe("x",r[0].dataType,c.length,u),g=Pe("scale_shift",1,_.length,2),C=Ze("output",r[0].dataType,c.length,u),E=[w,g,C];return` + ${$.registerUniform("output_size","u32").declareVariables(...E)} + ${$.mainStart()} + ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${C.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${g.getByIndices("vec2(batch, channel)")}; + let value = ${w.getByOffset("global_idx")} * ${C.type.value}(scale_shift.x) + ${C.type.value}(scale_shift.y); + ${C.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${u}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...st(c,_,c)]}),getShaderSource:v},{inputs:[r[0],d]})},Qg=(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=qt(i),u=be.size(o)/l,p=[{type:12,data:a},{type:12,data:Math.floor(i/l)}],d=["type","type"],c=!1,_=[0,s.length-1];for(let w=0;ws[_[g]])),v=cu(e,f,r[1],r[2],n,a,i,t.epsilon),$=w=>{let g=mr(r[0].dataType),C=l===1?"vec2f":`mat${l}x2f`,E=x=>{let S=x===0?"x":"y",A=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${g}(${A}(scale.${S}))`;case 2:return`vec2<${g}>(${A}(scale[0].${S}, scale[1].${S}))`;case 4:return`vec4<${g}>(${A}(scale[0].${S}, scale[1].${S}, scale[2].${S}, scale[3].${S}))`;default:throw new Error(`Not supported compoents ${l}`)}},y=Pe("input",r[0].dataType,r[0].dims,l),b=Ze("output",r[0].dataType,o,l);return` + @group(0) @binding(0) var input : array<${y.type.storage}>; + @group(0) @binding(1) var scale_input : array<${C}>; + @group(0) @binding(2) var output : array<${b.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(u/64)},programUniforms:p}),getShaderSource:$},{inputs:[r[0],v]})},Jy=(e,r)=>{r.format==="NHWC"?Qg(e,e.inputs,r):Xg(e,e.inputs,r)}}),Jg,Yg,Yy,Ox=Re(()=>{ut(),ft(),_t(),Jg=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Yg=(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),u=be.sizeToDimension(o,l),p=be.sizeFromDimension(o,l),d=be.size(n.dims),c=i?be.size(i.dims):0;if(d!==p||i&&c!==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 ${c}`);let _=[];for(let y=0;y1,g=t>2,C=y=>{let b=mr(e[0].dataType),x=[Pe("x",e[0].dataType,e[0].dims,f),Pe("scale",n.dataType,n.dims,f)];i&&x.push(Pe("bias",i.dataType,i.dims,f)),x.push(Ze("output",e[0].dataType,a,f)),w&&x.push(Ze("mean_data_output",1,_)),g&&x.push(Ze("inv_std_output",1,_));let S=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${y.registerUniforms(S).declareVariables(...x)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Lu("f32",f)}; + var mean_square_vector = ${Lu("f32",f)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${no(b,f,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Qs("mean_vector",f)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Qs("mean_square_vector",f)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${no(b,f,"x[j + offset]")}; + let f32scale = ${no(b,f,"scale[j]")}; + output[j + offset] = ${x[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${no(b,f,"bias[j]")}`:""} + ); + } + + ${w?"mean_data_output[global_idx] = mean":""}; + ${g?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},E=[{dims:a,dataType:e[0].dataType}];return w&&E.push({dims:_,dataType:1}),g&&E.push({dims:_,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${f};${t};${s}`,inputDependencies:v},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:$}),getShaderSource:C}},Yy=(e,r)=>{Jg(e.inputs),e.compute(Yg(e.inputs,r,e.outputCount))}}),Zg,Zy,Dx=Re(()=>{ft(),fd(),_d(),Zg=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},Zy=e=>{Zg(e.inputs);let r=oo.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(md(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]),u=[1,n,t],p=[a,l];e.compute(_a(p,{activation:""},r,u),{inputs:p})}else e.compute(_a(e.inputs,{activation:""},r))}}}),ew,tw,rw,e0,t0,Lx=Re(()=>{ut(),ft(),Jt(),_t(),ew=(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,u=r.bits>4?r.n*o:r.n*Math.floor((o+1)/2);if(be.size(l)!==u)throw new Error("zeroPoints input size error.")}},tw=(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),u=e[1].dims[2]/4,p=e[0].dataType,d=qt(r.k),c=qt(u),_=qt(i),f=a.concat([o,i]),v=o>1&&i/_%2===0?2:1,$=be.size(f)/_/v,w=64,g=[],C=[l,o,n/d],E=be.convertShape(e[1].dims).slice();E.splice(-1,1,u/c),g.push(...st(C)),g.push(...st(E)),g.push(...st(e[2].dims)),e.length===4&&g.push(...st(be.convertShape(e[3].dims)));let y=[l,o,i/_];g.push(...st(y));let b=x=>{let S=C.length,A=Pe("a",e[0].dataType,S,d),B=Pe("b",12,E.length,c),K=Pe("scales",e[2].dataType,e[2].dims.length),G=[A,B,K],j=e.length===4?Pe("zero_points",12,e[3].dims.length):void 0;j&&G.push(j);let ee=y.length,H=Ze("output",e[0].dataType,ee,_),Z=mr(e[0].dataType),X=(()=>{switch(d){case 1:return`array<${Z}, 8>`;case 2:return`mat4x2<${Z}>`;case 4:return`mat2x4<${Z}>`;default:throw new Error(`${d}-component is not supported.`)}})(),oe=()=>{let V=` + // reuse a data + var input_offset = ${A.indicesToOffset(`${A.type.indices}(batch, row, word_offset)`)}; + var a_data: ${X}; + for (var j: u32 = 0; j < ${8/d}; j++) { + a_data[j] = ${A.getByOffset("input_offset")}; + input_offset++; + } + `;for(let F=0;F<_*v;F++)V+=` + b_value = ${c===1?`b${F}_data`:`b${F}_data[i]`}; + b_value_lower = unpack4xU8(b_value & b_mask); + b_value_upper = unpack4xU8((b_value >> 4) & b_mask); + b_quantized_values = ${X}(${Array.from({length:4},(W,re)=>`${Z}(b_value_lower[${re}]), ${Z}(b_value_upper[${re}])`).join(", ")}); + b_dequantized_values = ${d===1?`${X}(${Array.from({length:8},(W,re)=>`(b_quantized_values[${re}] - ${j?`zero_point${F}`:"zero_point"}) * scale${F}`).join(", ")});`:`(b_quantized_values - ${X}(${Array(8).fill(`${j?`zero_point${F}`:"zero_point"}`).join(",")})) * scale${F};`}; + workgroup_shared[local_id.x * ${v} + ${Math.floor(F/_)}]${_>1?`[${F%_}]`:""} += ${Array.from({length:8/d},(W,re)=>`${d===1?`a_data[${re}] * b_dequantized_values[${re}]`:`dot(a_data[${re}], b_dequantized_values[${re}])`}`).join(" + ")}; + `;return V},me=()=>{let V=` + var col_index = col * ${_}; + ${j?` + 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 = ${Z}(8);`} + `;for(let F=0;F<_*v;F++)V+=` + let scale${F} = ${K.getByOffset("col_index * nBlocksPerCol + block")}; + ${j?` + zero_point_byte_count = col_index * zero_point_bytes_per_col + (block >> 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 = ${j.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${F} = ${Z}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return V},ae=()=>{let V=`col_index = col * ${_};`;for(let F=0;F<_*v;F++)V+=` + let b${F}_data = ${B.getByIndices(`${B.type.indices}(col_index, block, word)`)}; + col_index += 1;`;return V+=` + var b_value: u32; + let b_mask: u32 = 0x0F0F0F0Fu; + var b_value_lower: vec4; + var b_value_upper: vec4; + var b_quantized_values: ${X}; + var b_dequantized_values: ${X};`,V};return` + var workgroup_shared: array<${H.type.value}, ${v*w}>; + ${x.declareVariables(...G,H)} + ${x.mainStart([w,1,1])} + let output_indices = ${H.offsetToIndices(`(global_idx / ${w}) * ${v}`)}; + 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}; + ${me()} + for (var word: u32 = 0; word < ${u}; word += ${c}) { + ${ae()} + for (var i: u32 = 0; i < ${c}; i++) { + ${oe()} + word_offset += ${8/d}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${v}) { + 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 += ${v}; + } + ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${d};${c};${_};${v};${w}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:$},programUniforms:g}),getShaderSource:b}},rw=(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),u=e[1].dims[2]/4,p=e[0].dataType,d=qt(r.k),c=qt(u),_=a.concat([o,i]),f=128,v=i%8===0?8:i%4===0?4:1,$=f/v,w=$*c*8,g=w/d,C=w/r.blockSize,E=be.size(_)/v,y=[],b=[l,o,n/d],x=be.convertShape(e[1].dims).slice();x.splice(-1,1,u/c),y.push(...st(b)),y.push(...st(x)),y.push(...st(e[2].dims)),e.length===4&&y.push(...st(be.convertShape(e[3].dims)));let S=[l,o,i];y.push(...st(S));let A=B=>{let K=b.length,G=Pe("a",e[0].dataType,K,d),j=Pe("b",12,x.length,c),ee=Pe("scales",e[2].dataType,e[2].dims.length),H=[G,j,ee],Z=e.length===4?Pe("zero_points",12,e[3].dims.length):void 0;Z&&H.push(Z);let X=S.length,oe=Ze("output",e[0].dataType,X),me=mr(e[0].dataType),ae=()=>{switch(d){case 1:return` + let a_data0 = vec4<${me}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${me}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` + let a_data0 = vec4<${me}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${me}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` + let a_data0 = sub_a[word_offset]; + let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${d}-component is not supported.`)}};return` + var sub_a: array<${G.type.value}, ${g}>; + var inter_results: array, ${v}>; + ${B.declareVariables(...H,oe)} + ${B.mainStart([$,v,1])} + let output_indices = ${oe.offsetToIndices(`workgroup_index * ${v}`)}; + 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) / ${C} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${g}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${g}; a_offset += ${f}) + { + 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 * ${C} + local_id.x; + ${Z?` + 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 = ${Z.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${me}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${me}(8);`} + let scale = ${ee.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${j.getByIndices(`${j.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${r.blockSize/d}; + for (var i: u32 = 0; i < ${c}; i++) { + ${ae()} + let b_value = ${c===1?"b_data":"b_data[i]"}; + let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); + let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); + let b_quantized_values = mat2x4<${me}>(${Array.from({length:4},(V,F)=>`${me}(b_value_lower[${F}]), ${me}(b_value_upper[${F}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${me}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(V,F)=>`${`dot(a_data${F}, b_dequantized_values[${F}])`}`).join(" + ")}; + word_offset += ${8/d}; + } + workgroupBarrier(); + } + + if (local_idx < ${v}) { + var output_value: ${oe.type.value} = ${oe.type.value}(0); + for (var b = 0u; b < ${$}; 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};${c};${$};${v}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:E},programUniforms:y}),getShaderSource:A}},e0=(e,r)=>{ew(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(rw(e.inputs,r)):e.compute(tw(e.inputs,r))},t0=e=>$t(e)}),sw,nw,ow,iw,aw,lw,uw,dw,r0,zx=Re(()=>{ut(),ft(),_t(),sw=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].")}},nw=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${rt("uniforms.pads",o,t)}; + if (k < 0) { + break; + } + if (k >= i32(${rt("uniforms.x_shape",o,r)})) { + break; + } + offset += k * i32(${rt("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]; + } + `},ow=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${rt("uniforms.pads",o,t)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${rt("uniforms.x_shape",o,r)}) - 1); + k = k % _2n_1; + if(k >= i32(${rt("uniforms.x_shape",o,r)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${rt("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},iw=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${rt("uniforms.pads",o,t)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${rt("uniforms.x_shape",o,r)})) { + k = i32(${rt("uniforms.x_shape",o,r)}) - 1; + } + offset += k * i32(${rt("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},aw=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${rt("uniforms.pads",o,t)}; + if (k < 0) { + k += i32(${rt("uniforms.x_shape",o,r)}]); + } + if (k >= i32(${rt("uniforms.x_shape",o,r)})) { + k -= i32(${rt("uniforms.x_shape",o,r)}); + } + offset += k * i32(${rt("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},lw=(e,r,t)=>{switch(t.mode){case 0:return nw(e,r,t.pads.length);case 1:return ow(e,r,t.pads.length);case 2:return iw(e,r,t.pads.length);case 3:return aw(e,r,t.pads.length);default:throw new Error("Invalid mode")}},uw=(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(...st(e[0].dims,t));let a=["rank"],l=u=>{let p=Ze("output",e[0].dataType,t.length),d=Pe("x",e[0].dataType,s.length),c=d.type.value,_=lw(p,s.length,r),f=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&f.push({name:"constant_value",type:i?c:"f32"}),` + ${u.registerUniforms(f).declareVariables(d,p)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${p.offsetToIndices("global_idx")}; + + var value = ${c}(0); + ${_} + 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}},dw=(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},r0=(e,r)=>{sw(e.inputs);let t=dw(e.inputs,r);e.compute(uw(e.inputs,t),{inputs:[0]})}}),Vo,pu,hu,mu,fu,cw,pw,_u,gu,s0,n0,wu,o0,i0,bu,a0,l0,u0,d0,Bx=Re(()=>{_s(),ut(),ft(),_t(),Vo=e=>{if(jt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},pu=(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():[],u=r.pads.slice();ma.adjustPoolAttributes(t,o,i,a,l,u);let p=ma.computePoolOutputShape(t,o,a,l,i,u,r.autoPad),d=Object.assign({},r);n?Object.assign(d,{kernelShape:i,strides:a,pads:u,dilations:l,cacheKey:r.cacheKey}):Object.assign(d,{kernelShape:i,strides:a,pads:u,cacheKey:r.cacheKey});let c=p.slice();return c.push(c.splice(1,1)[0]),[d,s?c:p]},hu=(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],u=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],d=!!(u+p);n.push({type:12,data:a},{type:12,data:l},{type:12,data:u},{type:12,data:p}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let c=!1;if(r.kernelShape.length===2){let _=r.kernelShape[r.kernelShape.length-2],f=r.strides[r.strides.length-2],v=r.pads[r.pads.length/2-2],$=r.pads[r.pads.length-2];c=!!(v+$),n.push({type:12,data:_},{type:12,data:f},{type:12,data:v},{type:12,data:$}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,i,!0,d,c]}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((u,p)=>u+p);return[n,i,!!l,!1,!1]}},mu=(e,r,t,s,o,n,i,a,l,u,p,d)=>{let c=o.format==="NHWC",_=r.type.value,f=Ze("output",r.type.tensor,s);if(o.kernelShape.length<=2){let v="",$="",w="",g=t-(c?2:1);if(p?v=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${g}] < 0 || xIndices[${g}] + >= uniforms.x_shape[${g}]) { + pad++; + continue; + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:v=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`,o.kernelShape.length===2){let C=t-(c?3:2);d?$=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${C}] = indices[${C}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${C}] < 0 || xIndices[${C}] >= uniforms.x_shape[${C}]) { + pad += i32(uniforms.kw); + continue; + } + `:$=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${C}] = indices[${C}] * uniforms.sh - uniforms.phStart + j; + `,w=` + } + `}return` + ${e.registerUniforms(l).declareVariables(r,f)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${f.offsetToIndices("global_idx")}; + var xIndices = ${f.offsetToIndices("global_idx")}; + + var value = ${_}(${a}); + var pad = 0; + ${$} + ${v} + ${w} + ${i} + + output[global_idx] = value; + }`}else{if(c)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let v=o.kernelShape.length,$=o.pads.length,w="";return u?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,f)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${f.offsetToIndices("global_idx")}; + var xIndices = ${f.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${_}(${a}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${v-1}u; j++) { + offsets[j] = offset / ${rt("uniforms.kernelStrides","j",v)}; + offset -= offsets[j] * ${rt("uniforms.kernelStrides","j",v)}; + } + offsets[${v-1}] = offset; + + isPad = false; + for (var j = ${t-v}u; j < ${t}u; j++) { + xIndices[j] = indices[j] * ${rt("uniforms.strides",`j - ${t-v}u`,v)} + + offsets[j - ${t-v}u] - ${rt("uniforms.pads","j - 2u",$)}; + ${w} + } + ${i} + + output[global_idx] = value; + }`}},fu=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,cw=e=>`${fu(e)};${e.countIncludePad}`,pw=e=>`${fu(e)};${e.storageOrder};${e.dilations}`,_u=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}),gu=(e,r,t,s)=>{let[o,n]=pu(r,s,t),i=Pe("x",r.dataType,r.dims.length),a=i.type.value,l="value += x_val;",u="";o.countIncludePad?u+=`value /= ${a}(uniforms.kernelSize);`:u+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,d,c,_,f]=hu(n,o);p.push(...st(r.dims,n));let v=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${c};${_};${f}`,inputDependencies:v},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(be.size(n)/64)},programUniforms:p}),getShaderSource:$=>mu($,i,r.dims.length,n.length,o,l,u,0,d,c,_,f)}},s0=e=>{let r=e.count_include_pad!==0,t=_u(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:cw(s)}},n0=(e,r)=>{Vo(e.inputs),e.compute(gu("AveragePool",e.inputs[0],!1,r))},wu={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},o0=e=>{let r=e.format;return{format:r,...wu,cacheKey:r}},i0=(e,r)=>{Vo(e.inputs),e.compute(gu("GlobalAveragePool",e.inputs[0],!0,r))},bu=(e,r,t,s)=>{let[o,n]=pu(r,s,t),i=` + value = max(x_val, value); + `,a="",l=Pe("x",r.dataType,r.dims.length),u=["rank"],[p,d,c,_,f]=hu(n,o);return p.push(...st(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${c};${_};${f}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(be.size(n)/64)},programUniforms:p}),getShaderSource:v=>mu(v,l,r.dims.length,n.length,o,i,a,r.dataType===10?-65504:-1e5,d,c,_,f)}},a0=(e,r)=>{Vo(e.inputs),e.compute(bu("MaxPool",e.inputs[0],!1,r))},l0=e=>{let r=e.storage_order,t=e.dilations,s=_u(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:pw(o)}},u0=e=>{let r=e.format;return{format:r,...wu,cacheKey:r}},d0=(e,r)=>{Vo(e.inputs),e.compute(bu("GlobalMaxPool",e.inputs[0],!0,r))}}),hw,mw,c0,p0,Rx=Re(()=>{ut(),ft(),Jt(),_t(),hw=(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)].")}},mw=(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,u=l?[Math.ceil(be.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,d=e.length>2?e[2]:void 0,c=d?l?[Math.ceil(be.size(d.dims)/4)]:d.dims:void 0,_=p.length===0||p.length===1&&p[0]===1,f=_===!1&&p.length===1,v=qt(a),$=_&&(!l||v===4),w=$?v:1,g=$&&!l?v:1,C=Pe("input",l?12:s,u.length,g),E=Pe("scale",i,p.length),y=d?Pe("zero_point",l?12:s,c.length):void 0,b=Ze("output",i,n.length,w),x=[C,E];y&&x.push(y);let S=[u,p];d&&S.push(c);let A=[{type:12,data:a/w},{type:12,data:t},{type:12,data:r.blockSize},...st(...S,n)],B=K=>{let G=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${K.registerUniforms(G).declareVariables(...x,b)} + ${K.mainStart()} + ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${b.offsetToIndices("global_idx")}; + + // Set input x + ${l?` + let input = ${C.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 = ${C.getByOffset("global_idx")};`}; + + // Set scale input + ${_?`let scale_value= ${E.getByOffset("0")}`:f?` + let scale_index = ${b.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 + ${y?_?l?` + let zero_point_input = ${y.getByOffset("0")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${y.getByOffset("0")}`:f?l?` + let zero_point_index = ${b.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${y.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${b.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${y.getByOffset("zero_point_index")};`:l?` + let zero_point_offset = ${E.indicesToOffset("scale_indices")}; + let zero_point_input = ${y.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${y.getByIndices("scale_indices")};`:`let zero_point_value = ${l?o?"i32":"u32":C.type.value}(0);`}; + // Compute and write output + ${b.setByOffset("global_idx",`${b.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getShaderSource:B,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(a/w/64),y:1,z:1},programUniforms:A})}},c0=(e,r)=>{hw(e.inputs,r),e.compute(mw(e.inputs,r))},p0=e=>$t({axis:e.axis,blockSize:e.blockSize})}),fw,_w,h0,jx=Re(()=>{_s(),ut(),_t(),fw=(e,r,t)=>{let s=e===r,o=er&&t>0;if(s||o||n)throw new Error("Range these inputs' contents are invalid.")},_w=(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},...st(n)],l=u=>{let p=Ze("output",s,n.length),d=p.type.value,c=[{name:"outputSize",type:"u32"},{name:"start",type:d},{name:"delta",type:d}];return` + ${u.registerUniforms(c).declareVariables(p)} + ${u.mainStart()} + ${u.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})}},h0=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&&fw(r,t,s),e.compute(_w(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),gw,Mu,yu,ww,m0,f0,Nx=Re(()=>{ut(),ft(),Jt(),_t(),gw=(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.`)}},Mu=(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));`,yu=(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]; + ${gw(e.reduction,"output[data_offset + i]","value",r)} + }`,ww=(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),u=be.sizeFromDimension(s,0)/a,p=[{type:12,data:i},{type:12,data:a},{type:12,data:l},...st(e[1].dims,e[2].dims,o)],d=c=>{let _=Pe("indices",e[1].dataType,e[1].dims.length),f=Pe("updates",e[2].dataType,e[2].dims.length,n),v=r.reduction!=="none"&&r.reduction!==""?Ub("output",e[0].dataType,o.length):Ze("output",e[0].dataType,o.length,n);return` + ${c.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(_,f,v)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var hasDuplicates = false; + if (${r.reduction==="none"}) { + for (var i = 0; i < ${u}; i = i + 1) { + for (var j = i + 1; j < ${u}; 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 < ${u}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); + ${Mu(t.length,!1)} + } + ${yu(r,v.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); + ${Mu(t.length,!0)} + } + ${yu(r,v.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}},m0=e=>$t({reduction:e.reduction}),f0=(e,r)=>{e.compute(ww(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),bw,Mw,yw,vu,vw,xw,Tw,Ew,Pw,Cw,Sw,$w,xu,kw,Iw,Aw,Fw,Ow,_0,g0,Vx=Re(()=>{ut(),ft(),Jt(),_t(),bw=(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")}},Mw=(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},yw=(e,r,t,s,o,n)=>{let[i,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],u=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!==u&&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");bw(s,r),r.axes.length>0&&Mw(s,r.axes,u).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!==u&&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>u)throw new Error("Resize requires only of scales or sizes to be specified")},vu=(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; +`,vw=(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 { + ${vu("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 { + ${vu("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`)}})()+"}",xw=(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`)}})()+"}",Tw=(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},Ew=(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},Pw=(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},Cw=(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 = ${rt("uniforms.scales","i",s)}; + var roi_low = ${rt("uniforms.roi","i",o)}; + var roi_hi = ${rt("uniforms.roi",`i + ${r.length}`,o)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${rt("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${rt("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; + }`,Sw=(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 = ${rt("uniforms.scales","i",o)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${rt("uniforms.roi","i",n)}; + var roi_hi = ${rt("uniforms.roi",`i + ${t.length}`,n)}; + var input_shape_i = ${rt("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${rt("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; + }`,$w=(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 >= ${rt("uniforms.input_shape","i",r.length)}) { + return false; + } + } + return true; + }`,xu=(e,r,t,s)=>e.rank>s?` + ${e.indicesSet("input_indices",r,"channel")}; + ${e.indicesSet("input_indices",t,"batch")}; +`:"",kw=(e,r,t,s,o)=>{let[n,i,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],u=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${u} { + 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))`)}; + ${xu(e,l,n,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${u} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${u} = originalIndices[${i}]; + var col:${u} = 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: ${u} = getInputValue(batch, channel, row1, col1); + var x12: ${u} = getInputValue(batch, channel, row1, col2); + var x21: ${u} = getInputValue(batch, channel, row2, col1); + var x22: ${u} = getInputValue(batch, channel, row2, col2); + var dx1: ${u} = abs(row - ${u}(row1)); + var dx2: ${u} = abs(${u}(row2) - row); + var dy1: ${u} = abs(col - ${u}(col1)); + var dy2: ${u} = abs(${u}(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); + }`},Iw=(e,r,t,s,o,n,i,a,l,u)=>{let p=t.length===2,[d,c]=p?[0,1]:[2,3],_=e.type.value,f=v=>{let $=v===d?"row":"col";return` + fn ${$}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${_} { + var output_index = ${r.indicesGet("output_indices",v)}; + var originalIdx: ${_} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[v]}, + ${s[v]}, ${t[v]}, ${n[v]}, ${n[v]} + ${t.length}); + var fractOriginalIdx: ${_} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${a} && (originalIdx < 0 || originalIdx > (${t[v]} - 1))) { + return ${l}; + } + var data: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${$}: ${_} = originalIdx + ${_}(i); + if (${$} < 0 || ${$} >= ${t[v]}) { + ${u?`coefs[i + 1] = 0.0; + continue;`:a?`return ${l};`:`${$} = max(0, min(${$}, ${t[v]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",v,`u32(${$})`)}; + data[i + 1] = ${v===d?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${f(d)}; + ${f(c)}; + fn getCubicInterpolationCoefs(s: ${_}) -> array<${_}, 4> { + var absS = abs(s); + var coeffs: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${_} = 1.0 - absS; + var twoMinusAbsS: ${_} = 2.0 - absS; + var onePlusAbsS: ${_} = 1.0 + absS; + coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; + coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; + coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${_}, 4>, coefs: array<${_}, 4>) -> ${_} { + var coefsSum: ${_} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; + return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; + } + + fn bicubicInterpolation(output_indices: ${r.type.indices}) -> ${_} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},Aw=(e,r,t,s,o)=>{let[n,i,a,l,u]=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))`)}; + ${xu(e,u,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[${u}])`:"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); + }`},Fw=(e,r,t,s,o,n)=>{let i=e.dims,a=Tw(n,r.axes,i.length),l=Ew(i,s,o,r.axes),u=s.slice();s.length===0&&(u=i.map((g,C)=>g===0?1:l[C]/g),r.keepAspectRatioPolicy!=="stretch"&&(l=Pw(i,u,r)));let p=Ze("output",e.dataType,l.length),d=Pe("input",e.dataType,i.length),c=be.size(l),_=i.length===l.length&&i.every((g,C)=>g===l[C]),f=r.coordinateTransformMode==="tf_crop_and_resize",v=r.extrapolationValue,$=d.type.value,w=g=>` + ${_?"":` + ${vw(r.coordinateTransformMode,$)}; + ${(()=>{switch(r.mode){case"nearest":return` + ${$w(d,i)}; + ${xw(r.nearestMode,t,$)}; + ${Sw(d,p,i,l,u.length,a.length,f)}; + `;case"linear":return` + ${Cw(p,i,l,u.length,a.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${kw(d,p,i,f,v)}`;if(i.length===3||i.length===5)return`${Aw(d,p,i,f,v)}`;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`${Iw(d,p,i,l,u,a,r.cubicCoeffA,f,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")}})()}; + `} + ${g.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",a.length).declareVariables(d,p)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${_?"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}|${u.length>0?r.mode==="cubic"?u:u.length:""}|${o.length>0?o:""}|${a.length>0?a:""}|${_}|${r.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:[{type:12,data:c},{type:1,data:u},{type:1,data:a},...st(i,l)]})}},Ow=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},_0=(e,r)=>{let t=[],s=[],o=[],n=Ow(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");yw(e.inputs,r,n,t,s,o),e.compute(Fw(e.inputs[0],r,n,t,s,o),{inputs:[0]})},g0=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,u=e.nearestMode===""?"simple":e.nearestMode;return $t({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:o,excludeOutside:n,extrapolationValue:i,keepAspectRatioPolicy:a,mode:l,nearestMode:u})}}),Dw,Lw,w0,Ux=Re(()=>{ut(),ft(),_t(),Dw=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")}},Lw=(e,r,t,s)=>{let o=r.simplified,n=e[0].dims,i=be.size(n),a=n,l=i,u=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],d=!o&&e.length>3,c=e.length>4,_=s&&t>1,f=s&&t>2,v=t>3,$=64,w=qt(u),g=[{type:12,data:l},{type:12,data:w},{type:12,data:u},{type:1,data:r.epsilon}],C=y=>{let b=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],x=[Pe("x",e[0].dataType,e[0].dims,w),Pe("skip",e[1].dataType,e[1].dims,w),Pe("gamma",e[2].dataType,e[2].dims,w)];d&&x.push(Pe("beta",e[3].dataType,e[3].dims,w)),c&&x.push(Pe("bias",e[4].dataType,e[4].dims,w)),x.push(Ze("output",e[0].dataType,a,w)),_&&x.push(Ze("mean_output",1,p)),f&&x.push(Ze("inv_std_output",1,p)),v&&x.push(Ze("input_skip_bias_sum",e[0].dataType,a,w));let S=mr(e[0].dataType),A=mr(1,w);return` + + ${y.registerUniforms(b).declareVariables(...x)} + var sum_shared : array<${A}, ${$}>; + var sum_squared_shared : array<${A}, ${$}>; + + ${y.mainStart([$,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${$}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${$}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${$-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${c?"bias[offset1d + i]":S+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${v?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${no(S,w,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${$}; + 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); + ${_?"mean_output[global_idx] = mean;":""} + ${f?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${o?"":`- ${S}(mean)`}) * + ${S}(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};${v}`,inputDependencies:e.map((y,b)=>"type")},getShaderSource:C,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/u)},programUniforms:g})}},w0=(e,r)=>{Dw(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(Lw(e.inputs,r,e.outputCount,!1),{outputs:t})}}),zw,Uo,Bw,Tu,Rw,jw,b0,M0,Wx=Re(()=>{ut(),ft(),Jt(),_t(),zw=(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`)})},Uo=(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},Bw=(e,r)=>{if(e.length>1){let t=Uo(e,1),s=Uo(e,2),o=Uo(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),$t({starts:t,ends:s,axes:o})}else return r},Tu=(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]]))},Rw=(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 = ${rt("uniforms.input_shape","i",t.length)}; + let steps_i = ${rt("uniforms.steps","i",t.length)}; + let signs_i = ${rt("uniforms.signs","i",t.length)}; + let starts_i = ${rt("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; + }`,jw=(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=Uo(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,g)=>Tu(w,g,t,o,n)),a=r.ends.map((w,g)=>Tu(w,g,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,g,C)=>{if(w<0){let E=(a[g]-i[g])/w,y=i[g],b=y+E*n[g];i[g]=b,a[g]=y,C[g]=-w}});let u=t.slice(0);o.forEach((w,g)=>{u[w]=Math.ceil((a[w]-i[w])/n[w])});let p={dims:u,dataType:e[0].dataType},d=Ze("output",e[0].dataType,u.length),c=Pe("input",e[0].dataType,e[0].dims.length),_=be.size(u),f=[{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}],v=[{type:12,data:_},{type:12,data:i},{type:6,data:l},{type:12,data:n},...st(e[0].dims,u)],$=w=>` + ${w.registerUniforms(f).declareVariables(c,d)} + ${Rw(c,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",c.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:$,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:v})}},b0=(e,r)=>{zw(e.inputs,r);let t=Bw(e.inputs,r);e.compute(jw(e.inputs,t),{inputs:[0]})},M0=e=>{let r=e.starts,t=e.ends,s=e.axes;return $t({starts:r,ends:t,axes:s})}}),Nw,Vw,y0,v0,Gx=Re(()=>{ut(),ft(),Jt(),Js(),_t(),Nw=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Vw=(e,r)=>{let t=e.inputs[0],s=t.dims,o=be.size(s),n=s.length,i=be.normalizeAxis(r.axis,n),a=iS),u[i]=n-1,u[n-1]=i,l=e.compute(Vr(t,u),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,d=p[n-1],c=o/d,_=qt(d),f=d/_,v=64;c===1&&(v=256);let $=(x,S)=>S===4?`max(max(${x}.x, ${x}.y), max(${x}.z, ${x}.w))`:S===2?`max(${x}.x, ${x}.y)`:S===3?`max(max(${x}.x, ${x}.y), ${x}.z)`:x,w=Pe("x",l.dataType,l.dims,_),g=Ze("result",l.dataType,l.dims,_),C=w.type.value,E=mr(l.dataType)==="f32"?`var threadMax = ${C}(-3.402823e+38f);`:`var threadMax = ${C}(-65504.0h);`,y=x=>` + var rowMaxShared : ${C}; + var rowSumShared : ${C}; + var threadShared : array<${C}, ${v}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${C} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${C}) { + let index = row * row_stride + col; + result[index] = value; + } + ${x.registerUniform("packedCols","i32").declareVariables(w,g)} + ${x.mainStart(v)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${v}; + 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 = ${C}(${$("threadShared[0]",_)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${C}(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 = ${C}(${Qs("threadShared[0]",_)}); + } + 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); + } + }`,b=e.compute({name:"Softmax",shaderCache:{hint:`${_};${v}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:c},programUniforms:[{type:6,data:f}]}),getShaderSource:y},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(Vr(b,u),{inputs:[b]})},y0=(e,r)=>{Nw(e.inputs),Vw(e,r)},v0=e=>$t({axis:e.axis})}),Eu,Uw,Ww,Gw,x0,Kx=Re(()=>{ut(),ft(),_t(),Eu=e=>Array.from(e.getBigInt64Array(),Number),Uw=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(Eu(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")},Ww=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Eu(e[1]),o=Ww(t,s),n=be.size(o),i=e[0].dataType,a=Pe("input",i,t.length),l=Ze("output",i,o.length),u=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},...st(e[0].dims,o)]}),getShaderSource:u}},x0=e=>{Uw(e.inputs),e.compute(Gw(e.inputs),{inputs:[0]})}}),Kw,Hw,T0,Hx=Re(()=>{ut(),ft(),_t(),Kw=(e,r,t,s,o)=>{let n=Ze("output_data",o,t.length,4),i=Pe("a_data",r[1].dataType,r[1].dims.length,4),a=Pe("b_data",r[2].dataType,r[2].dims.length,4),l=Pe("c_data",r[0].dataType,r[0].dims.length,4),u,p=(d,c,_)=>`select(${c}, ${d}, ${_})`;if(!s)u=n.setByOffset("global_idx",p(i.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let d=(c,_,f="")=>{let v=`a_data[index_a${_}][component_a${_}]`,$=`b_data[index_b${_}][component_b${_}]`,w=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return` + let output_indices${_} = ${n.offsetToIndices(`global_idx * 4u + ${_}u`)}; + let offset_a${_} = ${i.broadcastedIndicesToOffset(`output_indices${_}`,n)}; + let offset_b${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,n)}; + let offset_c${_} = ${l.broadcastedIndicesToOffset(`output_indices${_}`,n)}; + let index_a${_} = offset_a${_} / 4u; + let index_b${_} = offset_b${_} / 4u; + let index_c${_} = offset_c${_} / 4u; + let component_a${_} = offset_a${_} % 4u; + let component_b${_} = offset_b${_} % 4u; + let component_c${_} = offset_c${_} % 4u; + ${c}[${_}] = ${f}(${p(v,$,w)}); + `};o===9?u=` + 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));`:u=` + ${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")} + ${u} + }`},Hw=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 u=oo.calcShape(oo.calcShape(r,t,!1),s,!1);if(!u)throw new Error("Can't perform where op on the given tensors");i=u,a=be.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:u=>Kw(u,e,i,n,o),getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...st(s,r,t,i)]})}},T0=e=>{e.compute(Hw(e.inputs))}}),E0,qx=Re(()=>{lx(),dd(),ux(),dx(),cx(),px(),hx(),wx(),Mx(),yx(),vx(),xx(),Tx(),Ex(),Px(),Cx(),Sx(),$x(),kx(),Ix(),Ax(),Fx(),Ox(),Dx(),Lx(),Wy(),zx(),Bx(),Rx(),jx(),Nx(),ud(),Vx(),Xy(),Ux(),Wx(),Gx(),Hy(),Kx(),Js(),cd(),Hx(),E0=new Map([["Abs",[wM]],["Acos",[bM]],["Acosh",[MM]],["Add",[ey]],["ArgMax",[mM,Bu]],["ArgMin",[hM,Bu]],["Asin",[yM]],["Asinh",[vM]],["Atan",[xM]],["Atanh",[TM]],["Attention",[fM]],["AveragePool",[n0,s0]],["BatchNormalization",[_M]],["BiasAdd",[gM]],["BiasSplitGelu",[ZM]],["Cast",[PM,EM]],["Ceil",[SM]],["Clip",[CM]],["Concat",[dy,cy]],["Conv",[Wu,Uu]],["ConvTranspose",[yy,My]],["Cos",[$M]],["Cosh",[kM]],["CumSum",[vy,xy]],["DepthToSpace",[Ty,Ey]],["DequantizeLinear",[c0,p0]],["Div",[ty]],["Einsum",[Py,Cy]],["Elu",[IM,qo]],["Equal",[ry]],["Erf",[AM]],["Exp",[FM]],["Expand",[Sy]],["FastGelu",[$y]],["Floor",[OM]],["FusedConv",[Wu,Uu]],["Gather",[Iy,ky]],["GatherElements",[zy,Ly]],["GatherBlockQuantized",[Oy,Dy]],["GatherND",[Ay,Fy]],["Gelu",[DM]],["Gemm",[Ry,By]],["GlobalAveragePool",[i0,o0]],["GlobalMaxPool",[d0,u0]],["Greater",[iy]],["GreaterOrEqual",[ly]],["GridSample",[jy,Ny]],["GroupQueryAttention",[Qy]],["HardSigmoid",[UM,VM]],["InstanceNormalization",[Jy]],["LayerNormalization",[Yy]],["LeakyRelu",[LM,qo]],["Less",[ay]],["LessOrEqual",[uy]],["Log",[JM]],["MatMul",[Zy]],["MatMulNBits",[e0,t0]],["MaxPool",[a0,l0]],["Mul",[sy]],["MultiHeadAttention",[Uy,Vy]],["Neg",[BM]],["Not",[zM]],["Pad",[r0]],["Pow",[ny]],["QuickGelu",[YM,qo]],["Range",[h0]],["Reciprocal",[RM]],["ReduceMin",[lM]],["ReduceMean",[sM]],["ReduceMax",[aM]],["ReduceSum",[dM]],["ReduceProd",[uM]],["ReduceL1",[nM]],["ReduceL2",[oM]],["ReduceLogSum",[pM]],["ReduceLogSumExp",[iM]],["ReduceSumSquare",[cM]],["Relu",[jM]],["Resize",[_0,g0]],["RotaryEmbedding",[qy]],["ScatterND",[f0,m0]],["Sigmoid",[NM]],["Sin",[WM]],["Sinh",[GM]],["Slice",[b0,M0]],["SkipLayerNormalization",[w0]],["Split",[Gy,Ky]],["Sqrt",[KM]],["Softmax",[y0,v0]],["Sub",[oy]],["Tan",[HM]],["Tanh",[qM]],["ThresholdedRelu",[QM,qo]],["Tile",[x0]],["Transpose",[Gb,Kb]],["Where",[T0]]])}),P0,Xx=Re(()=>{_s(),Os(),_t(),P0=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t,s,o){fs(e.programInfo.name);let n=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let u of r)a.push({binding:a.length,resource:{buffer:u.buffer}});for(let u of t)a.push({binding:a.length,resource:{buffer:u.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 u={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(u)}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(),Jr(e.programInfo.name)}dispose(){}build(e,r){fs(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(u=>{t.features.has(u.feature)&&s.push(`enable ${u.extension};`)});let o=Wb(r,this.backend.device.limits),n=e.getShaderSource(o),i=`${s.join(` +`)} +${o.additionalImplementations} +${n}`,a=t.createShaderModule({code:i,label:e.name});Tt("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return Jr(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]}}}),C0={};ao(C0,{WebGpuBackend:()=>S0});var qw,Xw,Qw,S0,Qx=Re(()=>{_s(),ut(),Os(),Rb(),ix(),qx(),Xx(),qw=(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+`:${qw(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},Qw=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},S0=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 Qw(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Vb(this),this.programManager=new P0(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,od(e.logLevel,!!e.debug),this.device.onuncapturederror=n=>{n.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${n.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;fs(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var s;let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let o=0;o"u"&&(this.queryTimeBase=_);let v=Number(_-this.queryTimeBase),$=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(v)||!Number.isSafeInteger($))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:Fs(w.dataType)})),outputsMetadata:c.map(w=>({dims:w.dims,dataType:Fs(w.dataType)})),kernelId:i,kernelType:l,kernelName:u,programName:p,startTime:v,endTime:$});else{let w="";d.forEach((C,E)=>{w+=`input[${E}]: [${C.dims}] | ${Fs(C.dataType)}, `});let g="";c.forEach((C,E)=>{g+=`output[${E}]: [${C.dims}] | ${Fs(C.dataType)}, `}),console.log(`[profiling] kernel "${i}|${l}|${u}|${p}" ${w}${g}execution time: ${$-v} ns`)}Yo("GPU",`${p}::${_}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),Jr()}run(e,r,t,s,o,n){fs(e.name);let i=[];for(let g=0;gC):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let d=[],c=[];for(let g=0;g=n)throw new Error(`Invalid output index: ${p[g]}`);if(p[g]===-3)continue;let C=p[g]===-1,E=p[g]===-2,y=C||E?o(a[g].dataType,a[g].dims):s(p[g],a[g].dataType,a[g].dims);if(d.push(y),y.data===0)continue;let b=this.gpuDataManager.get(y.data);if(!b)throw new Error(`no GPU data for output: ${y.data}`);if(C&&this.temporaryData.push(b),E){let x=this.kernelPersistentData.get(this.currentKernelId);x||(x=[],this.kernelPersistentData.set(this.currentKernelId,x)),x.push(b)}c.push(b)}if(i.length!==r.length||c.length!==d.length){if(c.length===0)return Jr(e.name),d;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let _;if(u){let g=0,C=[];u.forEach(x=>{let S=typeof x.data=="number"?[x.data]:x.data;if(S.length===0)return;let A=x.type===10?2:4,B,K;x.type===10?(K=S.length>4?16:S.length>2?8:S.length*A,B=S.length>4?16:A*S.length):(K=S.length<=2?S.length*A:16,B=16),g=Math.ceil(g/K)*K,C.push(g);let G=x.type===10?8:4;g+=S.length>4?Math.ceil(S.length/G)*B:S.length*A});let E=16;g=Math.ceil(g/E)*E;let y=new ArrayBuffer(g);u.forEach((x,S)=>{let A=C[S],B=typeof x.data=="number"?[x.data]:x.data;if(x.type===6)new Int32Array(y,A,B.length).set(B);else if(x.type===12)new Uint32Array(y,A,B.length).set(B);else if(x.type===10)new Uint16Array(y,A,B.length).set(B);else if(x.type===1)new Float32Array(y,A,B.length).set(B);else throw new Error(`Unsupported uniform type: ${Fs(x.type)}`)});let b=this.gpuDataManager.create(g,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(b.buffer,0,y,0,g),this.gpuDataManager.release(b.id),_={offset:0,size:g,buffer:b.buffer}}let f=this.programManager.normalizeDispatchGroupSize(l),v=f[1]===1&&f[2]===1,$=Xw(e,r,v),w=this.programManager.getArtifact($);if(w||(w=this.programManager.build(e,f),this.programManager.setArtifact($,w),Tt("info",()=>`[artifact] key: ${$}, programName: ${e.name}`)),u&&w.uniformVariablesInfo){if(u.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${u.length} in program "${w.programInfo.name}".`);for(let g=0;g`[ProgramManager] run "${e.name}" (key=${$}) with ${f[0]}x${f[1]}x${f[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let g={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:r,outputTensorViews:d};this.pendingKernels.push(g),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(g)}return this.programManager.run(w,i,c,f,_),Jr(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=E0.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),Tt("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(u){return t.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${n}" failed. ${u}`)),1}finally{l&&t.push(this.device.popErrorScope().then(u=>u?`GPU validation error for kernel "[${o}] ${n}": ${u.message}`:null));for(let u of this.temporaryData)this.gpuDataManager.release(u.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 Du(this,e,r);return id(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(){Tt("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(){Tt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Tt("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()}}}),$0={};ao($0,{init:()=>k0});var oa,Jw,k0,Jx=Re(()=>{ut(),Os(),ft(),ox(),oa=class I0{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 I0(this.module,this.dataType,this.data,r)}},Jw=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,u)=>new oa(this.module,l,this.output(a,u),u),n=(a,l)=>{let u=An(a,l);if(!u)throw new Error(`Unsupported data type: ${a}`);let p=u>0?this.backend.gpuDataManager.create(u).id:0;return new oa(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=(Qx(),Jo(C0)).WebGpuBackend,i=new n;await i.initialize(t,s),o("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,u,p=!1)=>{if(p)Tt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(u)}`),i.memcpy(Number(a),Number(l));else{Tt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(u)}`);let d=r.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(u));i.upload(Number(l),d)}},async(a,l,u)=>{Tt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${u}`),await i.download(Number(a),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+u)>>>0))},(a,l,u)=>i.createKernel(a,Number(l),u,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,u,p)=>{Tt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${u}, kernel=${a}, contextDataOffset=${l}`);let d=new Jw(r,i,Number(l));return i.computeKernel(Number(a),d,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let n=new Nb(t);o("webnn",[n,()=>n.reserveTensorId(),i=>n.releaseTensorId(i),async(i,a,l,u,p)=>n.ensureTensor(i,a,l,u,p),(i,a)=>{n.uploadTensor(i,a)},async(i,a)=>n.downloadTensor(i,a)])}}}),Yw,gd,wd,qs,Zw,Pu,wa,bd,Md,Cu,yd,vd,xd,A0=Re(()=>{rx(),sx(),ut(),zn(),ed(),Db(),Yw=(e,r)=>{zt()._OrtInit(e,r)!==0&&At("Can't initialize onnxruntime.")},gd=async e=>{Yw(e.wasm.numThreads,ha(e.logLevel))},wd=async(e,r)=>{var t,s;(s=(t=zt()).asyncInit)==null||s.call(t);{let o=(Jx(),Jo($0)).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",zt(),e,n)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await o("webnn",zt(),e)}}},qs=new Map,Zw=e=>{let r=zt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,o,o+s)!==0&&At("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)}},Pu=(e,r)=>{let t=zt(),s=t.stackSave(),o=0;try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputMetadata(e,r,i,i+n)!==0&&At("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 u=t.HEAPU32[o/4+1],p=[];for(let d=0;d{let r=zt(),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]},bd=async(e,r)=>{var d,c,_,f;let t,s,o=zt();Array.isArray(e)?[t,s]=e:e.buffer===o.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=wa(e);let n=0,i=0,a=0,l=[],u=[],p=[];try{if([i,l]=await Ob(r),(r==null?void 0:r.externalData)&&o.mountExternalData){let S=[];for(let A of r.externalData){let B=typeof A=="string"?A:A.path;S.push(nd(typeof A=="string"?A:A.data).then(K=>{o.mountExternalData(B,K)}))}await Promise.all(S)}for(let S of(r==null?void 0:r.executionProviders)??[])if((typeof S=="string"?S:S.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof S!="string"){let A=S,B=A==null?void 0:A.context,K=A==null?void 0:A.gpuDevice,G=A==null?void 0:A.deviceType,j=A==null?void 0:A.powerPreference;B?o.currentContext=B:K?o.currentContext=await o.webnnCreateMLContext(K):o.currentContext=await o.webnnCreateMLContext({deviceType:G,powerPreference:j})}else o.currentContext=await o.webnnCreateMLContext();break}n=await o._OrtCreateSession(t,s,i),(d=o.webgpuOnCreateSession)==null||d.call(o,n),n===0&&At("Can't create a session."),(c=o.jsepOnCreateSession)==null||c.call(o),o.currentContext&&(o.webnnRegisterMLContext(n,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[v,$]=Zw(n),w=!!(r!=null&&r.enableGraphCapture),g=[],C=[],E=[],y=[],b=[];for(let S=0;SS==="gpu-buffer"||S==="ml-tensor")&&(a=o._OrtCreateBinding(n),a===0&&At("Can't create IO binding."),x={handle:a,outputPreferredLocations:b,outputPreferredLocationsEncoded:b.map(S=>Fu(S))}),qs.set(n,[n,u,p,x,w,!1]),[n,g,C,E,y]}catch(v){throw u.forEach($=>o._OrtFree($)),p.forEach($=>o._OrtFree($)),a!==0&&o._OrtReleaseBinding(a)!==0&&At("Can't release IO binding."),n!==0&&o._OrtReleaseSession(n)!==0&&At("Can't release session."),v}finally{o._free(t),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&At("Can't release session options."),l.forEach(v=>o._free(v)),(f=o.unmountExternalData)==null||f.call(o)}},Md=e=>{var l,u,p;let r=zt(),t=qs.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,o,n,i,a]=t;i&&(a&&r._OrtClearBoundOutputs(i.handle)!==0&&At("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&At("Can't release IO binding.")),(l=r.jsepOnReleaseSession)==null||l.call(r,e),(u=r.webnnOnReleaseSession)==null||u.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&&At("Can't release session."),qs.delete(e)},Cu=async(e,r,t,s,o,n,i=!1)=>{if(!e){r.push(0);return}let a=zt(),l=a.PTR_SIZE,u=e[0],p=e[1],d=e[3],c=d,_,f;if(u==="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;f=An(ro(u),p);{let g=a.jsepRegisterBuffer;if(!g)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=g(s,n,w,f)}}else if(d==="ml-tensor"){let w=e[2].mlTensor;f=An(ro(u),p);let g=a.webnnRegisterMLTensor;if(!g)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=g(s,w,ro(u),p)}else{let w=e[2];if(Array.isArray(w)){f=l*w.length,_=a._malloc(f),t.push(_);for(let g=0;ga.setValue($+C*l,g,l===4?"i32":"i64"));let w=a._OrtCreateTensor(ro(u),_,f,$,p.length,Fu(c));w===0&&At(`Can't create tensor for input/output. session=${s}, index=${n}.`),r.push(w)}finally{a.stackRestore(v)}},yd=async(e,r,t,s,o,n)=>{var K,G,j,ee;let i=zt(),a=i.PTR_SIZE,l=qs.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],p=l[1],d=l[2],c=l[3],_=l[4],f=l[5],v=r.length,$=s.length,w=0,g=[],C=[],E=[],y=[],b=i.stackSave(),x=i.stackAlloc(v*a),S=i.stackAlloc(v*a),A=i.stackAlloc($*a),B=i.stackAlloc($*a);try{[w,g]=Fb(n);for(let X=0;Xq*R,1);F=Fs(fe);let we=c==null?void 0:c.outputPreferredLocations[s[X]];if(F==="string"){if(we==="gpu-buffer"||we==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let q=[];for(let R=0;R0){let q=i.jsepGetBuffer;if(!q)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let R=q(W),pe=An(fe,Ue);if(pe===void 0||!rd(F))throw new Error(`Unsupported data type: ${F}`);V=!0,Z.push([F,$e,{gpuBuffer:R,download:i.jsepCreateDownloader(R,pe,F),dispose:()=>{i._OrtReleaseTensor(oe)!==0&&At("Can't release tensor.")}},"gpu-buffer"])}else if(we==="ml-tensor"&&Ue>0){let q=i.webnnEnsureTensor,R=i.webnnIsInt64Supported;if(!q||!R)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(An(fe,Ue)===void 0||!sd(F))throw new Error(`Unsupported data type: ${F}`);if(F==="int64"&&!R(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let pe=await q(e,W,fe,$e,!1);V=!0,Z.push([F,$e,{mlTensor:pe,download:i.webnnCreateMLTensorDownloader(W,F),dispose:()=>{i.webnnReleaseTensorId(W),i._OrtReleaseTensor(oe)}},"ml-tensor"])}else{let q=td(F),R=new q(Ue);new Uint8Array(R.buffer,R.byteOffset,R.byteLength).set(i.HEAPU8.subarray(W,W+R.byteLength)),Z.push([F,$e,R,"cpu"])}}finally{i.stackRestore(me),F==="string"&&W&&i._free(W),V||i._OrtReleaseTensor(oe),(ee=i.webnnOnRunEnd)==null||ee.call(i,u)}}return c&&!_&&(i._OrtClearBoundOutputs(c.handle)!==0&&At("Can't clear bound outputs."),qs.set(e,[u,p,d,c,_,!1])),Z}finally{i.stackRestore(b),C.forEach(H=>i._OrtReleaseTensor(H)),E.forEach(H=>i._OrtReleaseTensor(H)),y.forEach(H=>i._free(H)),w!==0&&i._OrtReleaseRunOptions(w),g.forEach(H=>i._free(H))}},vd=e=>{let r=zt(),t=qs.get(e);if(!t)throw new Error("invalid session id");let s=t[0],o=r._OrtEndProfiling(s);o===0&&At("Can't get an profile file name."),r._OrtFree(o)},xd=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),Xs,Fr,eo,Wo,Go,ia,Su,aa,Sn,$n,eb,F0,O0,D0,L0,z0,B0,R0,j0=Re(()=>{_s(),A0(),zn(),Yu(),Xs=()=>!!jt.wasm.proxy&&typeof document<"u",eo=!1,Wo=!1,Go=!1,aa=new Map,Sn=(e,r)=>{let t=aa.get(e);t?t.push(r):aa.set(e,[r])},$n=()=>{if(eo||!Wo||Go||!Fr)throw new Error("worker not ready")},eb=e=>{switch(e.data.type){case"init-wasm":eo=!1,e.data.err?(Go=!0,Su[1](e.data.err)):(Wo=!0,Su[0]()),ia&&(URL.revokeObjectURL(ia),ia=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=aa.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},F0=async()=>{if(!Wo){if(eo)throw new Error("multiple calls to 'initWasm()' detected.");if(Go)throw new Error("previous call to 'initWasm()' failed.");if(eo=!0,Xs())return new Promise((e,r)=>{Fr==null||Fr.terminate(),Ib().then(([t,s])=>{try{Fr=s,Fr.onerror=n=>r(n),Fr.onmessage=eb,Su=[e,r];let o={type:"init-wasm",in:jt};!o.in.wasm.wasmPaths&&(t||Au)&&(o.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href}),Fr.postMessage(o),ia=t}catch(o){r(o)}},r)});try{await Zu(jt.wasm),await gd(jt),Wo=!0}catch(e){throw Go=!0,e}finally{eo=!1}}},O0=async e=>{if(Xs())return $n(),new Promise((r,t)=>{Sn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:jt}};Fr.postMessage(s)});await wd(jt,e)},D0=async e=>Xs()?($n(),new Promise((r,t)=>{Sn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};Fr.postMessage(s,[e.buffer])})):wa(e),L0=async(e,r)=>{if(Xs()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return $n(),new Promise((t,s)=>{Sn("create",[t,s]);let o={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),Fr.postMessage(o,n)})}else return bd(e,r)},z0=async e=>{if(Xs())return $n(),new Promise((r,t)=>{Sn("release",[r,t]);let s={type:"release",in:e};Fr.postMessage(s)});Md(e)},B0=async(e,r,t,s,o,n)=>{if(Xs()){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 $n(),new Promise((i,a)=>{Sn("run",[i,a]);let l=t,u={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};Fr.postMessage(u,xd(l))})}else return yd(e,r,t,s,o,n)},R0=async e=>{if(Xs())return $n(),new Promise((r,t)=>{Sn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};Fr.postMessage(s)});vd(e)}}),$u,tb,N0,Yx=Re(()=>{_s(),j0(),ut(),Ju(),Db(),$u=(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()}`)}},tb=e=>{switch(e[3]){case"cpu":return new hs(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!rd(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:o}=e[2];return hs.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:o})}case"ml-tensor":{let r=e[0];if(!sd(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:o}=e[2];return hs.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},N0=class{async fetchModelAndCopyToWasmMemory(e){return D0(await nd(e))}async loadModel(e,r){fs();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await L0(t,r),Jr()}async dispose(){return z0(this.sessionId)}async run(e,r,t){fs();let s=[],o=[];Object.entries(e).forEach(d=>{let c=d[0],_=d[1],f=this.inputNames.indexOf(c);if(f===-1)throw new Error(`invalid input '${c}'`);s.push(_),o.push(f)});let n=[],i=[];Object.entries(r).forEach(d=>{let c=d[0],_=d[1],f=this.outputNames.indexOf(c);if(f===-1)throw new Error(`invalid output '${c}'`);n.push(_),i.push(f)});let a=s.map((d,c)=>$u(d,()=>`input "${this.inputNames[o[c]]}"`)),l=n.map((d,c)=>d?$u(d,()=>`output "${this.outputNames[i[c]]}"`):null),u=await B0(this.sessionId,o,a,i,l,t),p={};for(let d=0;dHu,initializeFlags:()=>Ku,wasmBackend:()=>U0});var Ku,Hu,U0,Zx=Re(()=>{_s(),j0(),Yx(),Ku=()=>{(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"?Rv("node:os").cpus().length:navigator.hardwareConcurrency;jt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},Hu=class{async init(e){Ku(),await F0(),await O0(e)}async createInferenceSessionHandler(e,r){let t=new N0;return await t.loadModel(e,r),t}},U0=new Hu});_s();_s();_s();var eT="1.22.0-dev.20250409-89f8206ba4",tT=Eb;{let e=(Zx(),Jo(V0)).wasmBackend;Fn("webgpu",e,5),Fn("webnn",e,5),Fn("cpu",e,10),Fn("wasm",e,10)}Object.defineProperty(jt.versions,"web",{value:eT,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. + * ============================================================================= + */const rT=Object.freeze(Object.defineProperty({__proto__:null,get InferenceSession(){return Qu},get TRACE(){return Yo},get TRACE_FUNC_BEGIN(){return fs},get TRACE_FUNC_END(){return Jr},get Tensor(){return hs},default:tT,get env(){return jt},get registerBackend(){return Fn}},Symbol.toStringTag,{value:"Module"}));var As={},sT={"onnxruntime-common":e=>{e.exports=Dv},"onnxruntime-web":e=>{e.exports=rT},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,r,t)=>{t.r(r),t.d(r,{Environment:()=>Se,Interpreter:()=>Ae,Template:()=>Ve,parse:()=>V,tokenize:()=>d});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndSet:"EndSet",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),o=Object.freeze({set:s.Set,for:s.For,in:s.In,is:s.Is,if:s.If,else:s.Else,endset:s.EndSet,endif:s.EndIf,elif:s.ElseIf,endfor:s.EndFor,and:s.And,or:s.Or,not:s.Not,"not in":s.NotIn,macro:s.Macro,endmacro:s.EndMacro,true:s.BooleanLiteral,false:s.BooleanLiteral,none:s.NullLiteral,True:s.BooleanLiteral,False:s.BooleanLiteral,None:s.NullLiteral}),n=class{constructor(O,Y){this.value=O,this.type=Y}};function i(O){return/\w/.test(O)}function a(O){return/[0-9]/.test(O)}var l=[["{%",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.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],u=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function p(O,Y={}){return O.endsWith(` +`)&&(O=O.slice(0,-1)),O=O.replace(/{#.*?#}/gs,"{##}"),Y.lstrip_blocks&&(O=O.replace(/^[ \t]*({[#%])/gm,"$1")),Y.trim_blocks&&(O=O.replace(/([#%]})\n/g,"$1")),O.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function d(O,Y={}){var Ee,ke,Ie;const z=[],J=p(O,Y);let le=0;const ye=Be=>{let Xe="";for(;Be(J[le]);){if(J[le]==="\\"){if(++le,le>=J.length)throw new SyntaxError("Unexpected end of input");const Ge=J[le++],lt=u.get(Ge);if(lt===void 0)throw new SyntaxError(`Unexpected escaped character: ${Ge}`);Xe+=lt;continue}if(Xe+=J[le++],le>=J.length)throw new SyntaxError("Unexpected end of input")}return Xe};e:for(;le0){z.push(new n(Ge,s.Text));continue}}ye(Ge=>/\s/.test(Ge));const Xe=J[le];if(Xe==="-"||Xe==="+"){const Ge=(ke=z.at(-1))==null?void 0:ke.type;if(Ge===s.Text||Ge===void 0)throw new SyntaxError(`Unexpected character: ${Xe}`);switch(Ge){case s.Identifier:case s.NumericLiteral:case s.BooleanLiteral:case s.NullLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++le;const lt=ye(a);z.push(new n(`${Xe}${lt}`,lt.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[Ge,lt]of l)if(J.slice(le,le+Ge.length)===Ge){z.push(new n(Ge,lt)),le+=Ge.length;continue e}if(Xe==="'"||Xe==='"'){++le;const Ge=ye(lt=>lt!==Xe);z.push(new n(Ge,s.StringLiteral)),++le;continue}if(a(Xe)){const Ge=ye(a);z.push(new n(Ge,s.NumericLiteral));continue}if(i(Xe)){const Ge=ye(i),lt=Object.hasOwn(o,Ge)?o[Ge]:s.Identifier;lt===s.In&&((Ie=z.at(-1))==null?void 0:Ie.type)===s.Not?(z.pop(),z.push(new n("not in",s.NotIn))):z.push(new n(Ge,lt));continue}throw new SyntaxError(`Unexpected character: ${Xe}`)}return z}var c=class{constructor(){te(this,"type","Statement")}},_=class extends c{constructor(Y){super();te(this,"type","Program");this.body=Y}},f=class extends c{constructor(Y,z,J){super();te(this,"type","If");this.test=Y,this.body=z,this.alternate=J}},v=class extends c{constructor(Y,z,J,le){super();te(this,"type","For");this.loopvar=Y,this.iterable=z,this.body=J,this.defaultBlock=le}},$=class extends c{constructor(Y,z,J){super();te(this,"type","Set");this.assignee=Y,this.value=z,this.body=J}},w=class extends c{constructor(Y,z,J){super();te(this,"type","Macro");this.name=Y,this.args=z,this.body=J}},g=class extends c{constructor(){super(...arguments);te(this,"type","Expression")}},C=class extends g{constructor(Y,z,J){super();te(this,"type","MemberExpression");this.object=Y,this.property=z,this.computed=J}},E=class extends g{constructor(Y,z){super();te(this,"type","CallExpression");this.callee=Y,this.args=z}},y=class extends g{constructor(Y){super();te(this,"type","Identifier");this.value=Y}},b=class extends g{constructor(Y){super();te(this,"type","Literal");this.value=Y}},x=class extends b{constructor(){super(...arguments);te(this,"type","NumericLiteral")}},S=class extends b{constructor(){super(...arguments);te(this,"type","StringLiteral")}},A=class extends b{constructor(){super(...arguments);te(this,"type","BooleanLiteral")}},B=class extends b{constructor(){super(...arguments);te(this,"type","NullLiteral")}},K=class extends b{constructor(){super(...arguments);te(this,"type","ArrayLiteral")}},G=class extends b{constructor(){super(...arguments);te(this,"type","TupleLiteral")}},j=class extends b{constructor(){super(...arguments);te(this,"type","ObjectLiteral")}},ee=class extends g{constructor(Y,z,J){super();te(this,"type","BinaryExpression");this.operator=Y,this.left=z,this.right=J}},H=class extends g{constructor(Y,z){super();te(this,"type","FilterExpression");this.operand=Y,this.filter=z}},Z=class extends g{constructor(Y,z){super();te(this,"type","SelectExpression");this.iterable=Y,this.test=z}},X=class extends g{constructor(Y,z,J){super();te(this,"type","TestExpression");this.operand=Y,this.negate=z,this.test=J}},oe=class extends g{constructor(Y,z){super();te(this,"type","UnaryExpression");this.operator=Y,this.argument=z}},me=class extends g{constructor(Y=void 0,z=void 0,J=void 0){super();te(this,"type","SliceExpression");this.start=Y,this.stop=z,this.step=J}},ae=class extends g{constructor(Y,z){super();te(this,"type","KeywordArgumentExpression");this.key=Y,this.value=z}};function V(O){const Y=new _([]);let z=0;function J(De,Qe){const et=O[z++];if(!et||et.type!==De)throw new Error(`Parser Error: ${Qe}. ${et.type} !== ${De}.`);return et}function le(){switch(O[z].type){case s.Text:return ke();case s.OpenStatement:return Ie();case s.OpenExpression:return Be();default:throw new SyntaxError(`Unexpected token type: ${O[z].type}`)}}function ye(...De){return z+De.length<=O.length&&De.some((Qe,et)=>Qe!==O[z+et].type)}function Ee(...De){return z+De.length<=O.length&&De.every((Qe,et)=>Qe===O[z+et].type)}function ke(){return new S(J(s.Text,"Expected text token").value)}function Ie(){J(s.OpenStatement,"Expected opening statement token");let De;switch(O[z].type){case s.Set:++z,De=Xe(),J(s.CloseStatement,"Expected closing statement token");break;case s.If:++z,De=Ge(),J(s.OpenStatement,"Expected {% token"),J(s.EndIf,"Expected endif token"),J(s.CloseStatement,"Expected %} token");break;case s.Macro:++z,De=lt(),J(s.OpenStatement,"Expected {% token"),J(s.EndMacro,"Expected endmacro token"),J(s.CloseStatement,"Expected %} token");break;case s.For:++z,De=Gt(),J(s.OpenStatement,"Expected {% token"),J(s.EndFor,"Expected endfor token"),J(s.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${O[z].type}`)}return De}function Be(){J(s.OpenExpression,"Expected opening expression token");const De=Ot();return J(s.CloseExpression,"Expected closing expression token"),De}function Xe(){var Qe,et;const De=Ot();if(Ee(s.Equals)){++z;const Bt=Ot();return new $(De,Bt,[])}else{const Bt=[];for(J(s.CloseStatement,"Expected %} token");!(((Qe=O[z])==null?void 0:Qe.type)===s.OpenStatement&&((et=O[z+1])==null?void 0:et.type)===s.EndSet);){const Or=le();Bt.push(Or)}return J(s.OpenStatement,"Expected {% token"),J(s.EndSet,"Expected endset token"),new $(De,null,Bt)}}function Ge(){var Bt,Or,Pr,rs,ss,Ur,ns,os;const De=Ot();J(s.CloseStatement,"Expected closing statement token");const Qe=[],et=[];for(;!(((Bt=O[z])==null?void 0:Bt.type)===s.OpenStatement&&(((Or=O[z+1])==null?void 0:Or.type)===s.ElseIf||((Pr=O[z+1])==null?void 0:Pr.type)===s.Else||((rs=O[z+1])==null?void 0:rs.type)===s.EndIf));)Qe.push(le());if(((ss=O[z])==null?void 0:ss.type)===s.OpenStatement&&((Ur=O[z+1])==null?void 0:Ur.type)!==s.EndIf)if(++z,Ee(s.ElseIf))J(s.ElseIf,"Expected elseif token"),et.push(Ge());else for(J(s.Else,"Expected else token"),J(s.CloseStatement,"Expected closing statement token");!(((ns=O[z])==null?void 0:ns.type)===s.OpenStatement&&((os=O[z+1])==null?void 0:os.type)===s.EndIf);)et.push(le());return new f(De,Qe,et)}function lt(){const De=Xt();if(De.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Qe=Zr();J(s.CloseStatement,"Expected closing statement token");const et=[];for(;ye(s.OpenStatement,s.EndMacro);)et.push(le());return new w(De,Qe,et)}function wt(De=!1){const Qe=De?Xt:Ot,et=[Qe()],Bt=Ee(s.Comma);for(;Bt&&(++z,et.push(Qe()),!!Ee(s.Comma)););return Bt?new G(et):et[0]}function Gt(){const De=wt(!0);if(!(De instanceof y||De instanceof G))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${De.type} instead`);J(s.In,"Expected `in` keyword following loop variable");const Qe=Ot();J(s.CloseStatement,"Expected closing statement token");const et=[];for(;ye(s.OpenStatement,s.EndFor)&&ye(s.OpenStatement,s.Else);)et.push(le());const Bt=[];if(Ee(s.OpenStatement,s.Else))for(++z,++z,J(s.CloseStatement,"Expected closing statement token");ye(s.OpenStatement,s.EndFor);)Bt.push(le());return new v(De,Qe,et,Bt)}function Ot(){return lr()}function lr(){const De=Yr();if(Ee(s.If)){++z;const Qe=Yr();if(Ee(s.Else)){++z;const et=Yr();return new f(Qe,[De],[et])}else return new Z(De,Qe)}return De}function Yr(){let De=gs();for(;Ee(s.Or);){const Qe=O[z];++z;const et=gs();De=new ee(Qe,De,et)}return De}function gs(){let De=kr();for(;Ee(s.And);){const Qe=O[z];++z;const et=kr();De=new ee(Qe,De,et)}return De}function kr(){let De;for(;Ee(s.Not);){const Qe=O[z];++z;const et=kr();De=new oe(Qe,et)}return De??Ds()}function Ds(){let De=xs();for(;Ee(s.ComparisonBinaryOperator)||Ee(s.In)||Ee(s.NotIn);){const Qe=O[z];++z;const et=xs();De=new ee(Qe,De,et)}return De}function xs(){let De=es();for(;Ee(s.AdditiveBinaryOperator);){const Qe=O[z];++z;const et=es();De=new ee(Qe,De,et)}return De}function Ls(){const De=Ft(Xt());return Ee(s.OpenParen)?at(De):De}function at(De){let Qe=new E(De,Zr());return Qe=Ft(Qe),Ee(s.OpenParen)&&(Qe=at(Qe)),Qe}function Zr(){J(s.OpenParen,"Expected opening parenthesis for arguments list");const De=Ir();return J(s.CloseParen,"Expected closing parenthesis for arguments list"),De}function Ir(){const De=[];for(;!Ee(s.CloseParen);){let Qe=Ot();if(Ee(s.Equals)){if(++z,!(Qe instanceof y))throw new SyntaxError("Expected identifier for keyword argument");const et=Ot();Qe=new ae(Qe,et)}De.push(Qe),Ee(s.Comma)&&++z}return De}function ws(){const De=[];let Qe=!1;for(;!Ee(s.CloseSquareBracket);)Ee(s.Colon)?(De.push(void 0),++z,Qe=!0):(De.push(Ot()),Ee(s.Colon)&&(++z,Qe=!0));if(De.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Qe){if(De.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new me(...De)}return De[0]}function Ft(De){for(;Ee(s.Dot)||Ee(s.OpenSquareBracket);){const Qe=O[z];++z;let et;const Bt=Qe.type!==s.Dot;if(Bt)et=ws(),J(s.CloseSquareBracket,"Expected closing square bracket");else if(et=Xt(),et.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");De=new C(De,et,Bt)}return De}function es(){let De=ts();for(;Ee(s.MultiplicativeBinaryOperator);){const Qe=O[z];++z;const et=ts();De=new ee(Qe,De,et)}return De}function ts(){let De=bs();for(;Ee(s.Is);){++z;const Qe=Ee(s.Not);Qe&&++z;let et=Xt();if(et instanceof A?et=new y(et.value.toString()):et instanceof B&&(et=new y("none")),!(et instanceof y))throw new SyntaxError("Expected identifier for the test");De=new X(De,Qe,et)}return De}function bs(){let De=Ls();for(;Ee(s.Pipe);){++z;let Qe=Xt();if(!(Qe instanceof y))throw new SyntaxError("Expected identifier for the filter");Ee(s.OpenParen)&&(Qe=at(Qe)),De=new H(De,Qe)}return De}function Xt(){const De=O[z];switch(De.type){case s.NumericLiteral:return++z,new x(Number(De.value));case s.StringLiteral:return++z,new S(De.value);case s.BooleanLiteral:return++z,new A(De.value.toLowerCase()==="true");case s.NullLiteral:return++z,new B(null);case s.Identifier:return++z,new y(De.value);case s.OpenParen:{++z;const Qe=wt();if(O[z].type!==s.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${O[z].type} instead`);return++z,Qe}case s.OpenSquareBracket:{++z;const Qe=[];for(;!Ee(s.CloseSquareBracket);)Qe.push(Ot()),Ee(s.Comma)&&++z;return++z,new K(Qe)}case s.OpenCurlyBracket:{++z;const Qe=new Map;for(;!Ee(s.CloseCurlyBracket);){const et=Ot();J(s.Colon,"Expected colon between key and value in object literal");const Bt=Ot();Qe.set(et,Bt),Ee(s.Comma)&&++z}return++z,new j(Qe)}default:throw new SyntaxError(`Unexpected token: ${De.type}`)}}for(;z=0?(Y=(Y??(Y=0))<0?Math.max(O.length+Y,0):Math.min(Y,O.length),z=(z??(z=O.length))<0?Math.max(O.length+z,0):Math.min(z,O.length)):(Y=(Y??(Y=O.length-1))<0?Math.max(O.length+Y,-1):Math.min(Y,O.length-1),z=(z??(z=-1))<-1?Math.max(O.length+z,-1):Math.min(z,O.length-1));const ye=[];for(let Ee=Y;le*EeY.toUpperCase())}var fe=class{constructor(O=void 0){te(this,"type","RuntimeValue");te(this,"value");te(this,"builtins",new Map);this.value=O}__bool__(){return new $e(!!this.value)}},se=class extends fe{constructor(){super(...arguments);te(this,"type","NumericValue")}},ce=class extends fe{constructor(){super(...arguments);te(this,"type","StringValue");te(this,"builtins",new Map([["upper",new pe(()=>new ce(this.value.toUpperCase()))],["lower",new pe(()=>new ce(this.value.toLowerCase()))],["strip",new pe(()=>new ce(this.value.trim()))],["title",new pe(()=>new ce(re(this.value)))],["length",new se(this.value.length)],["rstrip",new pe(()=>new ce(this.value.trimEnd()))],["lstrip",new pe(()=>new ce(this.value.trimStart()))],["split",new pe(Y=>{const z=Y[0]??new xe;if(!(z instanceof ce||z instanceof xe))throw new Error("sep argument must be a string or null");const J=Y[1]??new se(-1);if(!(J instanceof se))throw new Error("maxsplit argument must be a number");let le=[];if(z instanceof xe){const ye=this.value.trimStart();for(const{0:Ee,index:ke}of ye.matchAll(/\S+/g)){if(J.value!==-1&&le.length>=J.value&&ke!==void 0){le.push(Ee+ye.slice(ke+Ee.length));break}le.push(Ee)}}else{if(z.value==="")throw new Error("empty separator");le=this.value.split(z.value),J.value!==-1&&le.length>J.value&&le.push(le.splice(J.value).join(z.value))}return new q(le.map(ye=>new ce(ye)))})]]))}},$e=class extends fe{constructor(){super(...arguments);te(this,"type","BooleanValue")}},Ue=class extends fe{constructor(){super(...arguments);te(this,"type","ObjectValue");te(this,"builtins",new Map([["get",new pe(([Y,z])=>{if(!(Y instanceof ce))throw new Error(`Object key must be a string: got ${Y.type}`);return this.value.get(Y.value)??z??new xe})],["items",new pe(()=>new q(Array.from(this.value.entries()).map(([Y,z])=>new q([new ce(Y),z]))))]]))}__bool__(){return new $e(this.value.size>0)}},we=class extends Ue{constructor(){super(...arguments);te(this,"type","KeywordArgumentsValue")}},q=class extends fe{constructor(){super(...arguments);te(this,"type","ArrayValue");te(this,"builtins",new Map([["length",new se(this.value.length)]]))}__bool__(){return new $e(this.value.length>0)}},R=class extends q{constructor(){super(...arguments);te(this,"type","TupleValue")}},pe=class extends fe{constructor(){super(...arguments);te(this,"type","FunctionValue")}},xe=class extends fe{constructor(){super(...arguments);te(this,"type","NullValue")}},Me=class extends fe{constructor(){super(...arguments);te(this,"type","UndefinedValue")}},Se=class{constructor(O){te(this,"variables",new Map([["namespace",new pe(O=>{if(O.length===0)return new Ue(new Map);if(O.length!==1||!(O[0]instanceof Ue))throw new Error("`namespace` expects either zero arguments or a single object argument");return O[0]})]]));te(this,"tests",new Map([["boolean",O=>O.type==="BooleanValue"],["callable",O=>O instanceof pe],["odd",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${O.type}`);return O.value%2!==0}],["even",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${O.type}`);return O.value%2===0}],["false",O=>O.type==="BooleanValue"&&!O.value],["true",O=>O.type==="BooleanValue"&&O.value],["none",O=>O.type==="NullValue"],["string",O=>O.type==="StringValue"],["number",O=>O.type==="NumericValue"],["integer",O=>O.type==="NumericValue"&&Number.isInteger(O.value)],["iterable",O=>O.type==="ArrayValue"||O.type==="StringValue"],["mapping",O=>O.type==="ObjectValue"],["lower",O=>{const Y=O.value;return O.type==="StringValue"&&Y===Y.toLowerCase()}],["upper",O=>{const Y=O.value;return O.type==="StringValue"&&Y===Y.toUpperCase()}],["none",O=>O.type==="NullValue"],["defined",O=>O.type!=="UndefinedValue"],["undefined",O=>O.type==="UndefinedValue"],["equalto",(O,Y)=>O.value===Y.value],["eq",(O,Y)=>O.value===Y.value]]));this.parent=O}set(O,Y){return this.declareVariable(O,Fe(Y))}declareVariable(O,Y){if(this.variables.has(O))throw new SyntaxError(`Variable already declared: ${O}`);return this.variables.set(O,Y),Y}setVariable(O,Y){return this.variables.set(O,Y),Y}resolve(O){if(this.variables.has(O))return this;if(this.parent)return this.parent.resolve(O);throw new Error(`Unknown variable: ${O}`)}lookupVariable(O){try{return this.resolve(O).variables.get(O)??new Me}catch{return new Me}}},Ae=class{constructor(O){te(this,"global");this.global=O??new Se}run(O){return this.evaluate(O,this.global)}evaluateBinaryExpression(O,Y){const z=this.evaluate(O.left,Y);switch(O.operator.value){case"and":return z.__bool__().value?this.evaluate(O.right,Y):z;case"or":return z.__bool__().value?z:this.evaluate(O.right,Y)}const J=this.evaluate(O.right,Y);switch(O.operator.value){case"==":return new $e(z.value==J.value);case"!=":return new $e(z.value!=J.value)}if(z instanceof Me||J instanceof Me)throw new Error("Cannot perform operation on undefined values");if(z instanceof xe||J instanceof xe)throw new Error("Cannot perform operation on null values");if(z instanceof se&&J instanceof se)switch(O.operator.value){case"+":return new se(z.value+J.value);case"-":return new se(z.value-J.value);case"*":return new se(z.value*J.value);case"/":return new se(z.value/J.value);case"%":return new se(z.value%J.value);case"<":return new $e(z.value":return new $e(z.value>J.value);case">=":return new $e(z.value>=J.value);case"<=":return new $e(z.value<=J.value)}else if(z instanceof q&&J instanceof q)switch(O.operator.value){case"+":return new q(z.value.concat(J.value))}else if(J instanceof q){const le=J.value.find(ye=>ye.value===z.value)!==void 0;switch(O.operator.value){case"in":return new $e(le);case"not in":return new $e(!le)}}if(z instanceof ce||J instanceof ce)switch(O.operator.value){case"+":return new ce(z.value.toString()+J.value.toString())}if(z instanceof ce&&J instanceof ce)switch(O.operator.value){case"in":return new $e(J.value.includes(z.value));case"not in":return new $e(!J.value.includes(z.value))}if(z instanceof ce&&J instanceof Ue)switch(O.operator.value){case"in":return new $e(J.value.has(z.value));case"not in":return new $e(!J.value.has(z.value))}throw new SyntaxError(`Unknown operator "${O.operator.value}" between ${z.type} and ${J.type}`)}evaluateArguments(O,Y){const z=[],J=new Map;for(const le of O)if(le.type==="KeywordArgumentExpression"){const ye=le;J.set(ye.key.value,this.evaluate(ye.value,Y))}else{if(J.size>0)throw new Error("Positional arguments must come before keyword arguments");z.push(this.evaluate(le,Y))}return[z,J]}evaluateFilterExpression(O,Y){const z=this.evaluate(O.operand,Y);if(O.filter.type==="Identifier"){const J=O.filter;if(J.value==="tojson")return new ce(ze(z));if(z instanceof q)switch(J.value){case"list":return z;case"first":return z.value[0];case"last":return z.value[z.value.length-1];case"length":return new se(z.value.length);case"reverse":return new q(z.value.reverse());case"sort":return new q(z.value.sort((le,ye)=>{if(le.type!==ye.type)throw new Error(`Cannot compare different types: ${le.type} and ${ye.type}`);switch(le.type){case"NumericValue":return le.value-ye.value;case"StringValue":return le.value.localeCompare(ye.value);default:throw new Error(`Cannot compare type: ${le.type}`)}}));case"join":return new ce(z.value.map(le=>le.value).join(""));case"string":return new ce(ze(z));default:throw new Error(`Unknown ArrayValue filter: ${J.value}`)}else if(z instanceof ce)switch(J.value){case"length":return new se(z.value.length);case"upper":return new ce(z.value.toUpperCase());case"lower":return new ce(z.value.toLowerCase());case"title":return new ce(re(z.value));case"capitalize":return new ce(z.value.charAt(0).toUpperCase()+z.value.slice(1));case"trim":return new ce(z.value.trim());case"indent":return new ce(z.value.split(` +`).map((le,ye)=>ye===0||le.length===0?le:" "+le).join(` +`));case"join":case"string":return z;default:throw new Error(`Unknown StringValue filter: ${J.value}`)}else if(z instanceof se)switch(J.value){case"abs":return new se(Math.abs(z.value));default:throw new Error(`Unknown NumericValue filter: ${J.value}`)}else if(z instanceof Ue)switch(J.value){case"items":return new q(Array.from(z.value.entries()).map(([le,ye])=>new q([new ce(le),ye])));case"length":return new se(z.value.size);default:throw new Error(`Unknown ObjectValue filter: ${J.value}`)}throw new Error(`Cannot apply filter "${J.value}" to type: ${z.type}`)}else if(O.filter.type==="CallExpression"){const J=O.filter;if(J.callee.type!=="Identifier")throw new Error(`Unknown filter: ${J.callee.type}`);const le=J.callee.value;if(le==="tojson"){const[,ye]=this.evaluateArguments(J.args,Y),Ee=ye.get("indent")??new xe;if(!(Ee instanceof se||Ee instanceof xe))throw new Error("If set, indent must be a number");return new ce(ze(z,Ee.value))}else if(le==="join"){let ye;if(z instanceof ce)ye=Array.from(z.value);else if(z instanceof q)ye=z.value.map(Be=>Be.value);else throw new Error(`Cannot apply filter "${le}" to type: ${z.type}`);const[Ee,ke]=this.evaluateArguments(J.args,Y),Ie=Ee.at(0)??ke.get("separator")??new ce("");if(!(Ie instanceof ce))throw new Error("separator must be a string");return new ce(ye.join(Ie.value))}if(z instanceof q){switch(le){case"selectattr":case"rejectattr":{const ye=le==="selectattr";if(z.value.some(Ge=>!(Ge instanceof Ue)))throw new Error(`\`${le}\` can only be applied to array of objects`);if(J.args.some(Ge=>Ge.type!=="StringLiteral"))throw new Error(`arguments of \`${le}\` must be strings`);const[Ee,ke,Ie]=J.args.map(Ge=>this.evaluate(Ge,Y));let Be;if(ke){const Ge=Y.tests.get(ke.value);if(!Ge)throw new Error(`Unknown test: ${ke.value}`);Be=Ge}else Be=(...Ge)=>Ge[0].__bool__().value;const Xe=z.value.filter(Ge=>{const lt=Ge.value.get(Ee.value),wt=lt?Be(lt,Ie):!1;return ye?wt:!wt});return new q(Xe)}case"map":{const[,ye]=this.evaluateArguments(J.args,Y);if(ye.has("attribute")){const Ee=ye.get("attribute");if(!(Ee instanceof ce))throw new Error("attribute must be a string");const ke=ye.get("default"),Ie=z.value.map(Be=>{if(!(Be instanceof Ue))throw new Error("items in map must be an object");return Be.value.get(Ee.value)??ke??new Me});return new q(Ie)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${le}`)}else if(z instanceof ce){switch(le){case"indent":{const[ye,Ee]=this.evaluateArguments(J.args,Y),ke=ye.at(0)??Ee.get("width")??new se(4);if(!(ke instanceof se))throw new Error("width must be a number");const Ie=ye.at(1)??Ee.get("first")??new $e(!1),Be=ye.at(2)??Ee.get("blank")??new $e(!1),Xe=z.value.split(` +`),Ge=" ".repeat(ke.value),lt=Xe.map((wt,Gt)=>!Ie.value&&Gt===0||!Be.value&&wt.length===0?wt:Ge+wt);return new ce(lt.join(` +`))}}throw new Error(`Unknown StringValue filter: ${le}`)}else throw new Error(`Cannot apply filter "${le}" to type: ${z.type}`)}throw new Error(`Unknown filter: ${O.filter.type}`)}evaluateTestExpression(O,Y){const z=this.evaluate(O.operand,Y),J=Y.tests.get(O.test.value);if(!J)throw new Error(`Unknown test: ${O.test.value}`);const le=J(z);return new $e(O.negate?!le:le)}evaluateUnaryExpression(O,Y){const z=this.evaluate(O.argument,Y);switch(O.operator.value){case"not":return new $e(!z.value);default:throw new SyntaxError(`Unknown operator: ${O.operator.value}`)}}evalProgram(O,Y){return this.evaluateBlock(O.body,Y)}evaluateBlock(O,Y){let z="";for(const J of O){const le=this.evaluate(J,Y);le.type!=="NullValue"&&le.type!=="UndefinedValue"&&(z+=le.value)}return new ce(z)}evaluateIdentifier(O,Y){return Y.lookupVariable(O.value)}evaluateCallExpression(O,Y){const[z,J]=this.evaluateArguments(O.args,Y);J.size>0&&z.push(new we(J));const le=this.evaluate(O.callee,Y);if(le.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${le.type}`);return le.value(z,Y)}evaluateSliceExpression(O,Y,z){if(!(O instanceof q||O instanceof ce))throw new Error("Slice object must be an array or string");const J=this.evaluate(Y.start,z),le=this.evaluate(Y.stop,z),ye=this.evaluate(Y.step,z);if(!(J instanceof se||J instanceof Me))throw new Error("Slice start must be numeric or undefined");if(!(le instanceof se||le instanceof Me))throw new Error("Slice stop must be numeric or undefined");if(!(ye instanceof se||ye instanceof Me))throw new Error("Slice step must be numeric or undefined");return O instanceof q?new q(W(O.value,J.value,le.value,ye.value)):new ce(W(Array.from(O.value),J.value,le.value,ye.value).join(""))}evaluateMemberExpression(O,Y){const z=this.evaluate(O.object,Y);let J;if(O.computed){if(O.property.type==="SliceExpression")return this.evaluateSliceExpression(z,O.property,Y);J=this.evaluate(O.property,Y)}else J=new ce(O.property.value);let le;if(z instanceof Ue){if(!(J instanceof ce))throw new Error(`Cannot access property with non-string: got ${J.type}`);le=z.value.get(J.value)??z.builtins.get(J.value)}else if(z instanceof q||z instanceof ce)if(J instanceof se)le=z.value.at(J.value),z instanceof ce&&(le=new ce(z.value.at(J.value)));else if(J instanceof ce)le=z.builtins.get(J.value);else throw new Error(`Cannot access property with non-string/non-number: got ${J.type}`);else{if(!(J instanceof ce))throw new Error(`Cannot access property with non-string: got ${J.type}`);le=z.builtins.get(J.value)}return le instanceof fe?le:new Me}evaluateSet(O,Y){const z=O.value?this.evaluate(O.value,Y):this.evaluateBlock(O.body,Y);if(O.assignee.type==="Identifier"){const J=O.assignee.value;Y.setVariable(J,z)}else if(O.assignee.type==="MemberExpression"){const J=O.assignee,le=this.evaluate(J.object,Y);if(!(le instanceof Ue))throw new Error("Cannot assign to member of non-object");if(J.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");le.value.set(J.property.value,z)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(O.assignee)}`);return new xe}evaluateIf(O,Y){const z=this.evaluate(O.test,Y);return this.evaluateBlock(z.__bool__().value?O.body:O.alternate,Y)}evaluateFor(O,Y){const z=new Se(Y);let J,le;if(O.iterable.type==="SelectExpression"){const Be=O.iterable;le=this.evaluate(Be.iterable,z),J=Be.test}else le=this.evaluate(O.iterable,z);if(!(le instanceof q))throw new Error(`Expected iterable type in for loop: got ${le.type}`);const ye=[],Ee=[];for(let Be=0;Bewt.setVariable(O.loopvar.value,Ge);else if(O.loopvar.type==="TupleLiteral"){const wt=O.loopvar;if(Ge.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Ge.type}`);const Gt=Ge;if(wt.value.length!==Gt.value.length)throw new Error(`Too ${wt.value.length>Gt.value.length?"few":"many"} items to unpack`);lt=Ot=>{for(let lr=0;lr0?ye[Be-1]:new Me],["nextitem",Be{var Ee;const le=new Se(J);z=z.slice();let ye;((Ee=z.at(-1))==null?void 0:Ee.type)==="KeywordArgumentsValue"&&(ye=z.pop());for(let ke=0;kethis.evaluate(z,Y)));case"TupleLiteral":return new R(O.value.map(z=>this.evaluate(z,Y)));case"ObjectLiteral":{const z=new Map;for(const[J,le]of O.value){const ye=this.evaluate(J,Y);if(!(ye instanceof ce))throw new Error(`Object keys must be strings: got ${ye.type}`);z.set(ye.value,this.evaluate(le,Y))}return new Ue(z)}case"Identifier":return this.evaluateIdentifier(O,Y);case"CallExpression":return this.evaluateCallExpression(O,Y);case"MemberExpression":return this.evaluateMemberExpression(O,Y);case"UnaryExpression":return this.evaluateUnaryExpression(O,Y);case"BinaryExpression":return this.evaluateBinaryExpression(O,Y);case"FilterExpression":return this.evaluateFilterExpression(O,Y);case"TestExpression":return this.evaluateTestExpression(O,Y);default:throw new SyntaxError(`Unknown node type: ${O.type}`)}}};function Fe(O){switch(typeof O){case"number":return new se(O);case"string":return new ce(O);case"boolean":return new $e(O);case"undefined":return new Me;case"object":return O===null?new xe:Array.isArray(O)?new q(O.map(Fe)):new Ue(new Map(Object.entries(O).map(([Y,z])=>[Y,Fe(z)])));case"function":return new pe((Y,z)=>{const J=O(...Y.map(le=>le.value))??null;return Fe(J)});default:throw new Error(`Cannot convert to runtime value: ${O}`)}}function ze(O,Y,z){const J=z??0;switch(O.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(O.value);case"ArrayValue":case"ObjectValue":{const le=Y?" ".repeat(Y):"",ye=` +`+le.repeat(J),Ee=ye+le;if(O.type==="ArrayValue"){const ke=O.value.map(Ie=>ze(Ie,Y,J+1));return Y?`[${Ee}${ke.join(`,${Ee}`)}${ye}]`:`[${ke.join(", ")}]`}else{const ke=Array.from(O.value.entries()).map(([Ie,Be])=>{const Xe=`"${Ie}": ${ze(Be,Y,J+1)}`;return Y?`${Ee}${Xe}`:Xe});return Y?`{${ke.join(",")}${ye}}`:`{${ke.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${O.type}`)}}var Ve=class{constructor(O){te(this,"parsed");const Y=d(O,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=V(Y)}render(O){const Y=new Se;if(Y.set("false",!1),Y.set("true",!0),Y.set("raise_exception",le=>{throw new Error(le)}),Y.set("range",F),O)for(const[le,ye]of Object.entries(O))Y.set(le,ye);return new Ae(Y).run(this.parsed).value}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>$,deviceToExecutionProviders:()=>f,isONNXProxy:()=>C,isONNXTensor:()=>w});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"}}),u=[];let p,d;const c=Symbol.for("onnxruntime");if(c in globalThis)d=globalThis[c];else if(o.apis.IS_NODE_ENV){switch(d=n??(s||(s=t.t(n,2))),process.platform){case"win32":u.push("dml");break;case"linux":process.arch==="x64"&&u.push("cuda");break}u.push("cpu"),p=["cpu"]}else d=i,o.apis.IS_WEBNN_AVAILABLE&&u.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&u.push("webgpu"),u.push("wasm"),p=["wasm"];const _=d.InferenceSession;function f(E=null){if(!E)return p;switch(E){case"auto":return u;case"gpu":return u.filter(y=>["webgpu","cuda","dml","webnn-gpu"].includes(y))}if(u.includes(E))return[l[E]??E];throw new Error(`Unsupported device: "${E}". Should be one of: ${u.join(", ")}.`)}let v=null;async function $(E,y,b){v&&await v;const x=_.create(E,y);v??(v=x);const S=await x;return S.config=b,S}function w(E){return E instanceof d.Tensor}const g=d==null?void 0:d.env;g!=null&&g.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!g.wasm.wasmPaths&&(g.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`),g.wasm.proxy=!1),g!=null&&g.webgpu&&(g.webgpu.powerPreference="high-performance");function C(){var E;return(E=g==null?void 0:g.wasm)==null?void 0:E.proxy}o.env.backends.onnx=g},"./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(u){super(),this.config=u}static async from_pretrained(u,p){const d=await(0,n.getModelJSON)(u,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(d)}}function a(l,u){var p;if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${u} 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:()=>C,post_process_object_detection:()=>c,post_process_panoptic_segmentation:()=>g,post_process_semantic_segmentation:()=>_});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 u(y,b,x=0,S=null){const A=y/b;let B=(0,n.bankers_round)(A)*b;return S!==null&&B>S&&(B=Math.floor(A)*b),Bb&&F.push(re)}else{let re=(0,n.max)(V.data)[1];if(re===j-1||(W=(0,n.softmax)(V.data),W[re]se*Z[(ce+1)%2])),X.boxes.push(fe),X.classes.push(re),X.scores.push(W[re])}}ee.push(X)}return ee}function _(y,b=null){const x=y.logits,S=x.dims[0];if(b!==null&&b.length!==S)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const A=[];for(let B=0;BZ[F]&&(Z[F]=V[F],X[F]=ae)}const oe=new Array(G.dims[0]);for(let ae=0;aeae!==void 0);A.push({segmentation:H,labels:me})}return A}function f(y,b,x,S){const A=[],B=[],K=[];for(let G=0;Gx&&(A.push(ee),B.push(X),K.push(H))}return[A,B,K]}function v(y,b,x,S=.5,A=.8){const B=[];let K=0,G=0;const j=b[x].data;for(let H=0;H=S&&++G;let ee=K>0&&G>0;return ee&&(ee=K/G>A),[ee,B]}function $(y,b,x,S,A,B=null,K=null){const[G,j]=K??y[0].dims,ee=new o.Tensor("int32",new Int32Array(G*j),[G,j]),H=[];if(K!==null)for(let ae=0;aeX[W]&&(Z[W]=ae,X[W]=F[W])}let oe=0;const me=ee.data;for(let ae=0;ae200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(y,b)/Math.min(y,b)}`);let B=Math.round(y/x)*x,K=Math.round(b/x)*x;if(B*K>A){const G=Math.sqrt(y*b/A);B=Math.floor(y/G/x)*x,K=Math.floor(b/G/x)*x}else if(B*KB?ee=Math.floor(B*j/A):B>A&&(j=Math.floor(A*ee/B)),await b.resize(ee,j,{resample:S}))}async crop_margin(b,x=200){const S=b.clone().grayscale(),A=(0,n.min)(S.data)[0],K=(0,n.max)(S.data)[0]-A;if(K===0)return b;const G=x/255;let j=S.width,ee=S.height,H=0,Z=0;const X=S.data;for(let oe=0;oethis.preprocess(B)));return{pixel_values:(0,o.stack)(S.map(B=>B.pixel_values),0),original_sizes:S.map(B=>B.original_size),reshaped_input_sizes:S.map(B=>B.reshaped_input_size)}}static async from_pretrained(b,x){const S=await(0,a.getModelJSON)(b,l.IMAGE_PROCESSOR_NAME,!0,x);return new this(S)}}},"./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,u){super(),this.config=l,this.components=u}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,u={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,...u})}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,...u){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...u);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,u){const[p,d]=await Promise.all([this.uses_processor_config?(0,n.getModelJSON)(l,s.PROCESSOR_NAME,!0,u):{},Promise.all(this.classes.filter(c=>c in this).map(async c=>{const _=await this[c].from_pretrained(l,u);return[c.replace(/_class$/,""),_]})).then(Object.fromEntries)]);return new this(p,d)}}te(i,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),te(i,"uses_processor_config",!1)},"./src/configs.js":(e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>u,PretrainedConfig:()=>l,getKeyValueShapes:()=>a});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js");async function n(p,d){return await(0,o.getModelJSON)(p,"config.json",!0,d)}function i(p){const d={};let c={};switch(p.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":c=i(p.text_config);break;case"moondream1":c=i(p.phi_config);break;case"musicgen":c=i(p.decoder);break;case"multi_modality":c=i(p.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":d.num_heads="n_head",d.num_layers="n_layer",d.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":d.num_heads="num_attention_heads",d.num_layers="num_hidden_layers",d.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":d.num_heads="num_key_value_heads",d.num_layers="num_hidden_layers",d.hidden_size="hidden_size",d.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":case"gemma3_text":case"glm":case"helium":d.num_heads="num_key_value_heads",d.num_layers="num_hidden_layers",d.dim_kv="head_dim";break;case"openelm":d.num_heads="num_kv_heads",d.num_layers="num_transformer_layers",d.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":d.num_heads="num_heads",d.num_layers="num_layers",d.hidden_size="hidden_size";break;case"bloom":d.num_heads="n_head",d.num_layers="n_layer",d.hidden_size="hidden_size";break;case"mpt":d.num_heads="n_heads",d.num_layers="n_layers",d.hidden_size="d_model";break;case"exaone":d.num_heads="num_key_value_heads",d.num_layers="num_layers",d.dim_kv="head_dim",d.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":d.num_decoder_layers="num_decoder_layers",d.num_decoder_heads="num_heads",d.decoder_dim_kv="d_kv",d.num_encoder_layers="num_layers",d.num_encoder_heads="num_heads",d.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":d.num_decoder_layers="decoder_layers",d.num_decoder_heads="decoder_attention_heads",d.decoder_hidden_size="d_model",d.num_encoder_layers="encoder_layers",d.num_encoder_heads="encoder_attention_heads",d.encoder_hidden_size="d_model";break;case"speecht5":d.num_decoder_layers="decoder_layers",d.num_decoder_heads="decoder_attention_heads",d.decoder_hidden_size="hidden_size",d.num_encoder_layers="encoder_layers",d.num_encoder_heads="encoder_attention_heads",d.encoder_hidden_size="hidden_size";break;case"trocr":d.num_encoder_layers=d.num_decoder_layers="decoder_layers",d.num_encoder_heads=d.num_decoder_heads="decoder_attention_heads",d.encoder_hidden_size=d.decoder_hidden_size="d_model";break;case"musicgen_decoder":d.num_encoder_layers=d.num_decoder_layers="num_hidden_layers",d.num_encoder_heads=d.num_decoder_heads="num_attention_heads",d.encoder_hidden_size=d.decoder_hidden_size="hidden_size";break;case"moonshine":d.num_decoder_layers="decoder_num_hidden_layers",d.num_decoder_heads="decoder_num_key_value_heads",d.num_encoder_layers="encoder_num_hidden_layers",d.num_encoder_heads="encoder_num_key_value_heads",d.encoder_hidden_size=d.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const f=i(p.decoder),v="num_decoder_layers"in f,$=(0,s.pick)(p,["model_type","is_encoder_decoder"]);return v?($.num_decoder_layers=f.num_decoder_layers,$.num_decoder_heads=f.num_decoder_heads,$.decoder_hidden_size=f.decoder_hidden_size,$.num_encoder_layers=f.num_encoder_layers,$.num_encoder_heads=f.num_encoder_heads,$.encoder_hidden_size=f.encoder_hidden_size):($.num_layers=f.num_layers,$.num_heads=f.num_heads,$.hidden_size=f.hidden_size),$}const _={...c,...(0,s.pick)(p,["model_type","multi_query","is_encoder_decoder"])};for(const f in d)_[f]=p[d[f]];return _}function a(p,{prefix:d="past_key_values",batch_size:c=1}={}){const _={},f=p.normalized_config;if(f.is_encoder_decoder&&"num_encoder_heads"in f&&"num_decoder_heads"in f){const v=f.encoder_dim_kv??f.encoder_hidden_size/f.num_encoder_heads,$=f.decoder_dim_kv??f.decoder_hidden_size/f.num_decoder_heads,w=[c,f.num_encoder_heads,0,v],g=[c,f.num_decoder_heads,0,$];for(let C=0;C{var S,A;t.r(r),t.d(r,{apis:()=>$,env:()=>b});var s=t("?569f"),o=t("?3f59"),n=t("?154a");const i="3.5.0",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&((S=self.constructor)==null?void 0:S.name)==="DedicatedWorkerGlobalScope",u=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,d=typeof navigator<"u"&&"ml"in navigator,c=typeof process<"u",_=c&&((A=process==null?void 0:process.release)==null?void 0:A.name)==="node",f=!x(s),v=!x(o),$=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:u,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:d,IS_PROCESS_AVAILABLE:c,IS_NODE_ENV:_,IS_FS_AVAILABLE:f,IS_PATH_AVAILABLE:v}),w=f&&v;let g="./";if(w){const B=Object(import.meta).url;B?g=o.dirname(o.dirname(n.fileURLToPath(B))):typeof __dirname<"u"&&(g=o.dirname(__dirname))}const C=w?o.join(g,"/.cache/"):null,E="/models/",y=w?o.join(g,E):E,b={version:i,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:y,useFS:f,useBrowserCache:u,useFSCache:f,cacheDir:C,useCustomCache:!1,customCache:null};function x(B){return Object.keys(B).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){te(this,"max_length",20);te(this,"max_new_tokens",null);te(this,"min_length",0);te(this,"min_new_tokens",null);te(this,"early_stopping",!1);te(this,"max_time",null);te(this,"do_sample",!1);te(this,"num_beams",1);te(this,"num_beam_groups",1);te(this,"penalty_alpha",null);te(this,"use_cache",!0);te(this,"temperature",1);te(this,"top_k",50);te(this,"top_p",1);te(this,"typical_p",1);te(this,"epsilon_cutoff",0);te(this,"eta_cutoff",0);te(this,"diversity_penalty",0);te(this,"repetition_penalty",1);te(this,"encoder_repetition_penalty",1);te(this,"length_penalty",1);te(this,"no_repeat_ngram_size",0);te(this,"bad_words_ids",null);te(this,"force_words_ids",null);te(this,"renormalize_logits",!1);te(this,"constraints",null);te(this,"forced_bos_token_id",null);te(this,"forced_eos_token_id",null);te(this,"remove_invalid_values",!1);te(this,"exponential_decay_length_penalty",null);te(this,"suppress_tokens",null);te(this,"streamer",null);te(this,"begin_suppress_tokens",null);te(this,"forced_decoder_ids",null);te(this,"guidance_scale",null);te(this,"num_return_sequences",1);te(this,"output_attentions",!1);te(this,"output_hidden_states",!1);te(this,"output_scores",!1);te(this,"return_dict_in_generate",!1);te(this,"pad_token_id",null);te(this,"bos_token_id",null);te(this,"eos_token_id",null);te(this,"encoder_no_repeat_ngram_size",0);te(this,"decoder_start_token_id",null);te(this,"generation_kwargs",{});Object.assign(this,(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:()=>u,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>f,MinNewTokensLengthLogitsProcessor:()=>v,NoBadWordsLogitsProcessor:()=>$,NoRepeatNGramLogitsProcessor:()=>c,RepetitionPenaltyLogitsProcessor:()=>_,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>g,TopKLogitsWarper:()=>E,TopPLogitsWarper:()=>C,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(b,x){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(b,x){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(b){this.processors.push(b)}extend(b){this.processors.push(...b)}_call(b,x){let S=x;for(const A of this.processors)S=A(b,S);return S}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(b){super(),this.bos_token_id=b}_call(b,x){for(let S=0;S=1&&B[B.length-1]>=this.timestamp_begin,G=B.length<2||B[B.length-2]>=this.timestamp_begin;if(K&&(G?A.subarray(this.timestamp_begin).fill(-1/0):A.subarray(0,this.eos_token_id).fill(-1/0)),b[S].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Z=this.timestamp_begin+this.max_initial_timestamp_index;A.subarray(Z+1).fill(-1/0)}const j=(0,o.log_softmax)(A),ee=Math.log(j.subarray(this.timestamp_begin).map(Math.exp).reduce((Z,X)=>Z+X)),H=(0,o.max)(j.subarray(0,this.timestamp_begin))[0];ee>H&&A.subarray(0,this.timestamp_begin).fill(-1/0)}return x}}class c extends n{constructor(b){super(),this.no_repeat_ngram_size=b}getNgrams(b){const x=b.length,S=[];for(let B=0;B1 to use the classifier free guidance processor, got guidance scale ${b}.`);this.guidance_scale=b}_call(b,x){if(x.dims[0]!==2*b.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${x.dims[0]} for the logits and ${b.length} for the input ids.`);const S=b.length,A=x.slice([0,S],null),B=x.slice([S,x.dims[0]],null);for(let K=0;K1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${b}`);if(!Number.isInteger(S)||S<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${S}`);this.top_p=b,this.filter_value=x,this.min_tokens_to_keep=S}}class E extends i{constructor(b,{filter_value:x=-1/0,min_tokens_to_keep:S=1}={}){if(super(),!Number.isInteger(b)||b<0)throw new Error(`\`top_k\` must be a positive integer, but is ${b}`);this.top_k=Math.max(b,S),this.filter_value=x}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>i});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class i extends s.Callable{constructor(d){super(),this.generation_config=d}async _call(d){return this.sample(d)}async sample(d){throw Error("sample should be implemented in subclasses.")}getLogits(d,c){let _=d.dims.at(-1),f=d.data;if(c===-1)f=f.slice(-_);else{let v=c*_;f=f.slice(v,v+_)}return f}randomSelect(d){let c=0;for(let f=0;f1)return new u(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 c=(0,n.max)(d.data)[1];return[[BigInt(c),0]]}}class l extends i{async sample(d){let c=d.dims.at(-1);this.generation_config.top_k>0&&(c=Math.min(this.generation_config.top_k,c));const[_,f]=await(0,o.topk)(d,c),v=(0,n.softmax)(_.data);return Array.from({length:this.generation_config.num_beams},()=>{const $=this.randomSelect(v);return[f.data[$],Math.log(v[$])]})}}class u extends i{async sample(d){let c=d.dims.at(-1);this.generation_config.top_k>0&&(c=Math.min(this.generation_config.top_k,c));const[_,f]=await(0,o.topk)(d,c),v=(0,n.softmax)(_.data);return Array.from({length:this.generation_config.num_beams},($,w)=>[f.data[w],Math.log(v[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 c=new Array(p.length).fill(!1);for(const _ of this.criteria){const f=_(p,d);for(let v=0;vd.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(c=>{const _=c.at(-1);return this.eos_token_id.some(f=>_==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:()=>u});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:c=!1,callback_function:_=null,token_callback_function:f=null,skip_special_tokens:v=!0,decode_kwargs:$={},...w}={}){super(),this.tokenizer=d,this.skip_prompt=c,this.callback_function=_??a,this.token_callback_function=f,this.decode_kwargs={skip_special_tokens:v,...$,...w},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(d){var $;if(d.length>1)throw Error("TextStreamer only supports batch size of 1");const c=this.next_tokens_are_prompt;if(c&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const _=d[0];($=this.token_callback_function)==null||$.call(this,_),this.token_cache=(0,s.mergeArrays)(this.token_cache,_);const f=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let v;c||f.endsWith(` +`)?(v=f.slice(this.print_len),this.token_cache=[],this.print_len=0):f.length>0&&(0,o.is_chinese_char)(f.charCodeAt(f.length-1))?(v=f.slice(this.print_len),this.print_len+=v.length):(v=f.slice(this.print_len,f.lastIndexOf(" ")+1),this.print_len+=v.length),this.on_finalized_text(v,!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,c){var _,f;d.length>0&&((_=this.callback_function)==null||_.call(this,d)),c&&this.callback_function===a&&n.apis.IS_PROCESS_AVAILABLE&&((f=this.callback_function)==null||f.call(this,` +`))}}class u extends l{constructor(d,{skip_prompt:c=!1,callback_function:_=null,token_callback_function:f=null,on_chunk_start:v=null,on_chunk_end:$=null,on_finalize:w=null,time_precision:g=.02,skip_special_tokens:C=!0,decode_kwargs:E={}}={}){super(d,{skip_prompt:c,skip_special_tokens:C,callback_function:_,token_callback_function:f,decode_kwargs:E}),this.timestamp_begin=d.timestamp_begin,this.on_chunk_start=v,this.on_chunk_end=$,this.on_finalize=w,this.time_precision=g,this.waiting_for_timestamp=!1}put(d){var _,f;if(d.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const c=d[0];if(c.length===1){const v=Number(c[0])-this.timestamp_begin;if(v>=0){const $=v*this.time_precision;this.waiting_for_timestamp?(_=this.on_chunk_end)==null||_.call(this,$):(f=this.on_chunk_start)==null||f.call(this,$),this.waiting_for_timestamp=!this.waiting_for_timestamp,d=[[]]}}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:()=>ui,ASTModel:()=>li,ASTPreTrainedModel:()=>lo,AlbertForMaskedLM:()=>N,AlbertForQuestionAnswering:()=>k,AlbertForSequenceClassification:()=>he,AlbertModel:()=>dn,AlbertPreTrainedModel:()=>ys,AutoModel:()=>xl,AutoModelForAudioClassification:()=>tf,AutoModelForAudioFrameClassification:()=>sf,AutoModelForAudioTextToText:()=>hf,AutoModelForCTC:()=>ef,AutoModelForCausalLM:()=>Um,AutoModelForDepthEstimation:()=>lf,AutoModelForDocumentQuestionAnswering:()=>nf,AutoModelForImageClassification:()=>Hm,AutoModelForImageFeatureExtraction:()=>cf,AutoModelForImageMatting:()=>of,AutoModelForImageSegmentation:()=>qm,AutoModelForImageTextToText:()=>pf,AutoModelForImageToImage:()=>af,AutoModelForMaskGeneration:()=>Zm,AutoModelForMaskedLM:()=>Wm,AutoModelForNormalEstimation:()=>uf,AutoModelForObjectDetection:()=>Jm,AutoModelForPoseEstimation:()=>df,AutoModelForQuestionAnswering:()=>Gm,AutoModelForSemanticSegmentation:()=>Xm,AutoModelForSeq2SeqLM:()=>Rm,AutoModelForSequenceClassification:()=>zm,AutoModelForSpeechSeq2Seq:()=>jm,AutoModelForTextToSpectrogram:()=>Nm,AutoModelForTextToWaveform:()=>Vm,AutoModelForTokenClassification:()=>Bm,AutoModelForUniversalSegmentation:()=>Qm,AutoModelForVision2Seq:()=>Km,AutoModelForXVector:()=>rf,AutoModelForZeroShotObjectDetection:()=>Ym,BartForConditionalGeneration:()=>Rt,BartForSequenceClassification:()=>kt,BartModel:()=>Et,BartPretrainedModel:()=>vt,BaseModelOutput:()=>xe,BeitForImageClassification:()=>yc,BeitModel:()=>Mc,BeitPreTrainedModel:()=>Na,BertForMaskedLM:()=>Ae,BertForQuestionAnswering:()=>Ve,BertForSequenceClassification:()=>Fe,BertForTokenClassification:()=>ze,BertModel:()=>Se,BertPreTrainedModel:()=>Me,BlenderbotForConditionalGeneration:()=>rr,BlenderbotModel:()=>Dt,BlenderbotPreTrainedModel:()=>Kr,BlenderbotSmallForConditionalGeneration:()=>Lr,BlenderbotSmallModel:()=>Hr,BlenderbotSmallPreTrainedModel:()=>gr,BloomForCausalLM:()=>Ud,BloomModel:()=>Vd,BloomPreTrainedModel:()=>$a,CLIPModel:()=>bi,CLIPPreTrainedModel:()=>Ss,CLIPSegForImageSegmentation:()=>vo,CLIPSegModel:()=>yo,CLIPSegPreTrainedModel:()=>Vn,CLIPTextModel:()=>ba,CLIPTextModelWithProjection:()=>Mi,CLIPVisionModel:()=>Ma,CLIPVisionModelWithProjection:()=>yi,CamembertForMaskedLM:()=>Ft,CamembertForQuestionAnswering:()=>bs,CamembertForSequenceClassification:()=>es,CamembertForTokenClassification:()=>ts,CamembertModel:()=>ws,CamembertPreTrainedModel:()=>Ir,CausalLMOutput:()=>bn,CausalLMOutputWithPast:()=>nv,ChineseCLIPModel:()=>xi,ChineseCLIPPreTrainedModel:()=>vi,ClapAudioModelWithProjection:()=>bh,ClapModel:()=>gh,ClapPreTrainedModel:()=>Fi,ClapTextModelWithProjection:()=>wh,CodeGenForCausalLM:()=>gn,CodeGenModel:()=>ko,CodeGenPreTrainedModel:()=>Hn,CohereForCausalLM:()=>Ed,CohereModel:()=>Td,CoherePreTrainedModel:()=>ya,ConvBertForMaskedLM:()=>Ot,ConvBertForQuestionAnswering:()=>gs,ConvBertForSequenceClassification:()=>lr,ConvBertForTokenClassification:()=>Yr,ConvBertModel:()=>Gt,ConvBertPreTrainedModel:()=>wt,ConvNextForImageClassification:()=>hp,ConvNextModel:()=>pp,ConvNextPreTrainedModel:()=>tl,ConvNextV2ForImageClassification:()=>fp,ConvNextV2Model:()=>mp,ConvNextV2PreTrainedModel:()=>rl,DPTForDepthEstimation:()=>qc,DPTModel:()=>Hc,DPTPreTrainedModel:()=>Ya,DacDecoderModel:()=>am,DacDecoderOutput:()=>nm,DacEncoderModel:()=>im,DacEncoderOutput:()=>sm,DacModel:()=>om,DacPreTrainedModel:()=>ji,DebertaForMaskedLM:()=>Qe,DebertaForQuestionAnswering:()=>Or,DebertaForSequenceClassification:()=>et,DebertaForTokenClassification:()=>Bt,DebertaModel:()=>De,DebertaPreTrainedModel:()=>Xt,DebertaV2ForMaskedLM:()=>ss,DebertaV2ForQuestionAnswering:()=>os,DebertaV2ForSequenceClassification:()=>Ur,DebertaV2ForTokenClassification:()=>ns,DebertaV2Model:()=>rs,DebertaV2PreTrainedModel:()=>Pr,DecisionTransformerModel:()=>jh,DecisionTransformerPreTrainedModel:()=>Rh,DeiTForImageClassification:()=>zc,DeiTModel:()=>Lc,DeiTPreTrainedModel:()=>qa,DepthAnythingForDepthEstimation:()=>Qc,DepthAnythingPreTrainedModel:()=>Xc,DepthProForDepthEstimation:()=>tp,DepthProPreTrainedModel:()=>ep,DetrForObjectDetection:()=>xc,DetrForSegmentation:()=>Va,DetrModel:()=>vc,DetrObjectDetectionOutput:()=>Ua,DetrPreTrainedModel:()=>Pi,DetrSegmentationOutput:()=>Tc,Dinov2ForImageClassification:()=>gp,Dinov2Model:()=>_p,Dinov2PreTrainedModel:()=>sl,Dinov2WithRegistersForImageClassification:()=>bp,Dinov2WithRegistersModel:()=>wp,Dinov2WithRegistersPreTrainedModel:()=>nl,DistilBertForMaskedLM:()=>Es,DistilBertForQuestionAnswering:()=>Ts,DistilBertForSequenceClassification:()=>Ys,DistilBertForTokenClassification:()=>vr,DistilBertModel:()=>yr,DistilBertPreTrainedModel:()=>Wr,DonutSwinModel:()=>cp,DonutSwinPreTrainedModel:()=>dp,EfficientNetForImageClassification:()=>Ph,EfficientNetModel:()=>Eh,EfficientNetPreTrainedModel:()=>ml,ElectraForMaskedLM:()=>xs,ElectraForQuestionAnswering:()=>Zr,ElectraForSequenceClassification:()=>Ls,ElectraForTokenClassification:()=>at,ElectraModel:()=>Ds,ElectraPreTrainedModel:()=>kr,EsmForMaskedLM:()=>Zs,EsmForSequenceClassification:()=>Ar,EsmForTokenClassification:()=>en,EsmModel:()=>zs,EsmPreTrainedModel:()=>fr,ExaoneForCausalLM:()=>L,ExaoneModel:()=>I,ExaonePreTrainedModel:()=>T,FalconForCausalLM:()=>_h,FalconModel:()=>fh,FalconPreTrainedModel:()=>cl,FastViTForImageClassification:()=>uc,FastViTModel:()=>lc,FastViTPreTrainedModel:()=>La,Florence2ForConditionalGeneration:()=>fo,Florence2PreTrainedModel:()=>mi,GLPNForDepthEstimation:()=>up,GLPNModel:()=>lp,GLPNPreTrainedModel:()=>el,GPT2LMHeadModel:()=>xo,GPT2Model:()=>Ti,GPT2PreTrainedModel:()=>Un,GPTBigCodeForCausalLM:()=>$o,GPTBigCodeModel:()=>Kn,GPTBigCodePreTrainedModel:()=>Gn,GPTJForCausalLM:()=>So,GPTJModel:()=>Co,GPTJPreTrainedModel:()=>_n,GPTNeoForCausalLM:()=>Po,GPTNeoModel:()=>Eo,GPTNeoPreTrainedModel:()=>To,GPTNeoXForCausalLM:()=>fn,GPTNeoXModel:()=>Br,GPTNeoXPreTrainedModel:()=>Ws,Gemma2ForCausalLM:()=>$d,Gemma2Model:()=>Sd,Gemma2PreTrainedModel:()=>xa,Gemma3ForCausalLM:()=>Id,Gemma3Model:()=>kd,Gemma3PreTrainedModel:()=>Ta,GemmaForCausalLM:()=>Cd,GemmaModel:()=>Pd,GemmaPreTrainedModel:()=>va,GlmForCausalLM:()=>h,GlmModel:()=>Oo,GlmPreTrainedModel:()=>Qn,GraniteForCausalLM:()=>Ei,GraniteModel:()=>$s,GranitePreTrainedModel:()=>sr,GroundingDinoForObjectDetection:()=>yp,GroundingDinoPreTrainedModel:()=>Mp,GroupViTModel:()=>ac,GroupViTPreTrainedModel:()=>ic,HeliumForCausalLM:()=>Fo,HeliumModel:()=>Ao,HeliumPreTrainedModel:()=>Xn,HieraForImageClassification:()=>Rc,HieraModel:()=>Bc,HieraPreTrainedModel:()=>Xa,HubertForCTC:()=>Jp,HubertForSequenceClassification:()=>Yp,HubertModel:()=>Qp,HubertPreTrainedModel:()=>W0,IJepaForImageClassification:()=>Jd,IJepaModel:()=>Qd,IJepaPreTrainedModel:()=>Fa,Idefics3ForConditionalGeneration:()=>Ns,Idefics3PreTrainedModel:()=>gi,ImageMattingOutput:()=>ff,JAISLMHeadModel:()=>nt,JAISModel:()=>mn,JAISPreTrainedModel:()=>Wn,JinaCLIPModel:()=>Nn,JinaCLIPPreTrainedModel:()=>Us,JinaCLIPTextModel:()=>bo,JinaCLIPVisionModel:()=>Mo,LiteWhisperForConditionalGeneration:()=>ci,LlamaForCausalLM:()=>Io,LlamaModel:()=>qn,LlamaPreTrainedModel:()=>wn,LlavaForConditionalGeneration:()=>pn,LlavaOnevisionForConditionalGeneration:()=>mo,LlavaPreTrainedModel:()=>hi,LongT5ForConditionalGeneration:()=>He,LongT5Model:()=>je,LongT5PreTrainedModel:()=>ve,M2M100ForConditionalGeneration:()=>Ip,M2M100Model:()=>kp,M2M100PreTrainedModel:()=>al,MBartForCausalLM:()=>Nt,MBartForConditionalGeneration:()=>dr,MBartForSequenceClassification:()=>cr,MBartModel:()=>Mr,MBartPreTrainedModel:()=>Kt,MPNetForMaskedLM:()=>rn,MPNetForQuestionAnswering:()=>on,MPNetForSequenceClassification:()=>sn,MPNetForTokenClassification:()=>nn,MPNetModel:()=>tn,MPNetPreTrainedModel:()=>Dr,MT5ForConditionalGeneration:()=>dt,MT5Model:()=>Je,MT5PreTrainedModel:()=>We,MarianMTModel:()=>$p,MarianModel:()=>Sp,MarianPreTrainedModel:()=>il,MaskFormerForInstanceSegmentation:()=>ap,MaskFormerModel:()=>ip,MaskFormerPreTrainedModel:()=>Za,MaskedLMOutput:()=>wr,Metric3DForDepthEstimation:()=>sp,Metric3DPreTrainedModel:()=>rp,Metric3Dv2ForDepthEstimation:()=>op,Metric3Dv2PreTrainedModel:()=>np,MgpstrForSceneTextRecognition:()=>Gh,MgpstrModelOutput:()=>Uh,MgpstrPreTrainedModel:()=>Wh,MimiDecoderModel:()=>rm,MimiDecoderOutput:()=>Zh,MimiEncoderModel:()=>tm,MimiEncoderOutput:()=>Yh,MimiModel:()=>em,MimiPreTrainedModel:()=>Ri,MistralForCausalLM:()=>ph,MistralModel:()=>ch,MistralPreTrainedModel:()=>ul,MobileBertForMaskedLM:()=>Ps,MobileBertForQuestionAnswering:()=>_r,MobileBertForSequenceClassification:()=>ur,MobileBertModel:()=>xr,MobileBertPreTrainedModel:()=>Gr,MobileLLMForCausalLM:()=>Te,MobileLLMModel:()=>ue,MobileLLMPreTrainedModel:()=>U,MobileNetV1ForImageClassification:()=>Sh,MobileNetV1ForSemanticSegmentation:()=>$h,MobileNetV1Model:()=>Ch,MobileNetV1PreTrainedModel:()=>Di,MobileNetV2ForImageClassification:()=>Ih,MobileNetV2ForSemanticSegmentation:()=>Ah,MobileNetV2Model:()=>kh,MobileNetV2PreTrainedModel:()=>Li,MobileNetV3ForImageClassification:()=>Oh,MobileNetV3ForSemanticSegmentation:()=>Dh,MobileNetV3Model:()=>Fh,MobileNetV3PreTrainedModel:()=>zi,MobileNetV4ForImageClassification:()=>zh,MobileNetV4ForSemanticSegmentation:()=>Bh,MobileNetV4Model:()=>Lh,MobileNetV4PreTrainedModel:()=>Bi,MobileViTForImageClassification:()=>hc,MobileViTModel:()=>pc,MobileViTPreTrainedModel:()=>za,MobileViTV2ForImageClassification:()=>fc,MobileViTV2Model:()=>mc,MobileViTV2PreTrainedModel:()=>Ba,ModelOutput:()=>pe,ModernBertForMaskedLM:()=>z,ModernBertForSequenceClassification:()=>J,ModernBertForTokenClassification:()=>le,ModernBertModel:()=>Y,ModernBertPreTrainedModel:()=>O,Moondream1ForConditionalGeneration:()=>js,MoonshineForConditionalGeneration:()=>po,MoonshineModel:()=>pi,MoonshinePreTrainedModel:()=>Rn,MptForCausalLM:()=>Gd,MptModel:()=>Wd,MptPreTrainedModel:()=>ka,MultiModalityCausalLM:()=>Vh,MultiModalityPreTrainedModel:()=>Nh,MusicgenForCausalLM:()=>q0,MusicgenForConditionalGeneration:()=>_l,MusicgenModel:()=>H0,MusicgenPreTrainedModel:()=>fl,NomicBertModel:()=>Ee,NomicBertPreTrainedModel:()=>ye,OPTForCausalLM:()=>Hd,OPTModel:()=>Kd,OPTPreTrainedModel:()=>Ia,Olmo2ForCausalLM:()=>It,Olmo2Model:()=>xt,Olmo2PreTrainedModel:()=>ht,OlmoForCausalLM:()=>Ye,OlmoModel:()=>Ke,OlmoPreTrainedModel:()=>Oe,OpenELMForCausalLM:()=>Fd,OpenELMModel:()=>Ad,OpenELMPreTrainedModel:()=>Ea,OwlViTForObjectDetection:()=>gc,OwlViTModel:()=>_c,OwlViTPreTrainedModel:()=>Ra,Owlv2ForObjectDetection:()=>bc,Owlv2Model:()=>wc,Owlv2PreTrainedModel:()=>ja,PaliGemmaForConditionalGeneration:()=>_i,PaliGemmaPreTrainedModel:()=>fi,PatchTSMixerForPrediction:()=>Xh,PatchTSMixerModel:()=>qh,PatchTSMixerPreTrainedModel:()=>wl,PatchTSTForPrediction:()=>Hh,PatchTSTModel:()=>Kh,PatchTSTPreTrainedModel:()=>gl,Phi3ForCausalLM:()=>Nd,Phi3Model:()=>jd,Phi3PreTrainedModel:()=>Sa,Phi3VForCausalLM:()=>_o,Phi3VPreTrainedModel:()=>wi,PhiForCausalLM:()=>Rd,PhiModel:()=>Bd,PhiPreTrainedModel:()=>Ca,PreTrainedModel:()=>R,PretrainedMixin:()=>Pt,PvtForImageClassification:()=>tc,PvtModel:()=>ec,PvtPreTrainedModel:()=>Oa,PyAnnoteForAudioFrameClassification:()=>zp,PyAnnoteModel:()=>Lp,PyAnnotePreTrainedModel:()=>ll,QuestionAnsweringModelOutput:()=>Tr,Qwen2ForCausalLM:()=>Dd,Qwen2Model:()=>Od,Qwen2PreTrainedModel:()=>Pa,Qwen2VLForConditionalGeneration:()=>zd,Qwen2VLPreTrainedModel:()=>Ld,RFDetrForObjectDetection:()=>Ic,RFDetrModel:()=>kc,RFDetrObjectDetectionOutput:()=>Ac,RFDetrPreTrainedModel:()=>Ka,RTDetrForObjectDetection:()=>Pc,RTDetrModel:()=>Ec,RTDetrObjectDetectionOutput:()=>Ci,RTDetrPreTrainedModel:()=>Wa,RTDetrV2ForObjectDetection:()=>Sc,RTDetrV2Model:()=>Cc,RTDetrV2ObjectDetectionOutput:()=>$c,RTDetrV2PreTrainedModel:()=>Ga,ResNetForImageClassification:()=>Nc,ResNetModel:()=>jc,ResNetPreTrainedModel:()=>Qa,RoFormerForMaskedLM:()=>Be,RoFormerForQuestionAnswering:()=>lt,RoFormerForSequenceClassification:()=>Xe,RoFormerForTokenClassification:()=>Ge,RoFormerModel:()=>Ie,RoFormerPreTrainedModel:()=>ke,RobertaForMaskedLM:()=>or,RobertaForQuestionAnswering:()=>er,RobertaForSequenceClassification:()=>Vt,RobertaForTokenClassification:()=>Zt,RobertaModel:()=>zr,RobertaPreTrainedModel:()=>Yt,SamImageSegmentationOutput:()=>Cp,SamModel:()=>Pp,SamPreTrainedModel:()=>Ep,SapiensForDepthEstimation:()=>Yc,SapiensForNormalEstimation:()=>Zc,SapiensForSemanticSegmentation:()=>Jc,SapiensPreTrainedModel:()=>$i,SegformerForImageClassification:()=>yh,SegformerForSemanticSegmentation:()=>vh,SegformerModel:()=>K0,SegformerPreTrainedModel:()=>Oi,Seq2SeqLMOutput:()=>sv,SequenceClassifierOutput:()=>mt,SiglipModel:()=>hn,SiglipPreTrainedModel:()=>go,SiglipTextModel:()=>Vs,SiglipVisionModel:()=>wo,SmolVLMForConditionalGeneration:()=>jn,SnacDecoderModel:()=>dm,SnacEncoderModel:()=>um,SnacModel:()=>lm,SnacPreTrainedModel:()=>Ni,SpeechT5ForSpeechToText:()=>ih,SpeechT5ForTextToSpeech:()=>ah,SpeechT5HifiGan:()=>lh,SpeechT5Model:()=>G0,SpeechT5PreTrainedModel:()=>Ai,SqueezeBertForMaskedLM:()=>Bs,SqueezeBertForQuestionAnswering:()=>un,SqueezeBertForSequenceClassification:()=>ln,SqueezeBertModel:()=>an,SqueezeBertPreTrainedModel:()=>Ms,StableLmForCausalLM:()=>Th,StableLmModel:()=>xh,StableLmPreTrainedModel:()=>hl,Starcoder2ForCausalLM:()=>mh,Starcoder2Model:()=>hh,Starcoder2PreTrainedModel:()=>dl,StyleTextToSpeech2Model:()=>oh,StyleTextToSpeech2PreTrainedModel:()=>nh,Swin2SRForImageSuperResolution:()=>Kc,Swin2SRModel:()=>Gc,Swin2SRPreTrainedModel:()=>Ja,SwinForImageClassification:()=>Uc,SwinForSemanticSegmentation:()=>Wc,SwinModel:()=>Vc,SwinPreTrainedModel:()=>Si,T5ForConditionalGeneration:()=>de,T5Model:()=>ie,T5PreTrainedModel:()=>Q,TableTransformerForObjectDetection:()=>Oc,TableTransformerModel:()=>Fc,TableTransformerObjectDetectionOutput:()=>Dc,TableTransformerPreTrainedModel:()=>Ha,TokenClassifierOutput:()=>pr,TrOCRForCausalLM:()=>dh,TrOCRPreTrainedModel:()=>uh,UltravoxModel:()=>Jh,UltravoxPreTrainedModel:()=>Qh,UniSpeechForCTC:()=>Np,UniSpeechForSequenceClassification:()=>Vp,UniSpeechModel:()=>jp,UniSpeechPreTrainedModel:()=>ki,UniSpeechSatForAudioFrameClassification:()=>Kp,UniSpeechSatForCTC:()=>Wp,UniSpeechSatForSequenceClassification:()=>Gp,UniSpeechSatModel:()=>Up,UniSpeechSatPreTrainedModel:()=>Do,ViTForImageClassification:()=>Xd,ViTMAEModel:()=>sc,ViTMAEPreTrainedModel:()=>rc,ViTMSNForImageClassification:()=>oc,ViTMSNModel:()=>nc,ViTMSNPreTrainedModel:()=>Da,ViTModel:()=>qd,ViTPreTrainedModel:()=>Aa,VisionEncoderDecoderModel:()=>ho,VitMatteForImageMatting:()=>cc,VitMattePreTrainedModel:()=>dc,VitPoseForPoseEstimation:()=>Zd,VitPosePreTrainedModel:()=>Yd,VitsModel:()=>pl,VitsModelOutput:()=>_f,VitsPreTrainedModel:()=>Mh,Wav2Vec2BertForCTC:()=>qp,Wav2Vec2BertForSequenceClassification:()=>Xp,Wav2Vec2BertModel:()=>Hp,Wav2Vec2BertPreTrainedModel:()=>Ii,Wav2Vec2ForAudioFrameClassification:()=>Dp,Wav2Vec2ForCTC:()=>Fp,Wav2Vec2ForSequenceClassification:()=>Op,Wav2Vec2Model:()=>Ap,Wav2Vec2PreTrainedModel:()=>Gs,WavLMForAudioFrameClassification:()=>sh,WavLMForCTC:()=>eh,WavLMForSequenceClassification:()=>th,WavLMForXVector:()=>rh,WavLMModel:()=>Zp,WavLMPreTrainedModel:()=>Jn,WeSpeakerResNetModel:()=>Rp,WeSpeakerResNetPreTrainedModel:()=>Bp,WhisperForConditionalGeneration:()=>co,WhisperModel:()=>di,WhisperPreTrainedModel:()=>uo,XLMForQuestionAnswering:()=>ri,XLMForSequenceClassification:()=>ei,XLMForTokenClassification:()=>ti,XLMModel:()=>Rs,XLMPreTrainedModel:()=>tr,XLMRobertaForMaskedLM:()=>ni,XLMRobertaForQuestionAnswering:()=>ai,XLMRobertaForSequenceClassification:()=>oi,XLMRobertaForTokenClassification:()=>ii,XLMRobertaModel:()=>si,XLMRobertaPreTrainedModel:()=>Cs,XLMWithLMHeadModel:()=>cn,XVectorOutput:()=>mf,YolosForObjectDetection:()=>xp,YolosModel:()=>vp,YolosObjectDetectionOutput:()=>Tp,YolosPreTrainedModel:()=>ol});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"),u=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),d=t("./src/generation/configuration_utils.js"),c=t("./src/utils/tensor.js"),_=t("./src/utils/image.js"),f=t("./src/utils/maths.js"),v=t("./src/generation/stopping_criteria.js"),$=t("./src/generation/logits_sampler.js"),w=t("./src/env.js"),g=t("./src/models/whisper/generation_whisper.js"),C=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},y=new Map,b=new Map,x=new Map;async function S(M,P,D){var hr;let ne=((hr=D.config)==null?void 0:hr["transformers.js_config"])??{},ge=D.device??ne.device;ge&&typeof ge!="string"&&(ge.hasOwnProperty(P)?ge=ge[P]:(console.warn(`device not specified for "${P}". Using the default device.`),ge=null));const _e=ge??(w.apis.IS_NODE_ENV?"cpu":"wasm"),Ce=(0,o.deviceToExecutionProviders)(_e),Le=ne.device_config??{};Le.hasOwnProperty(_e)&&(ne={...ne,...Le[_e]});let Ne=D.dtype??ne.dtype;if(typeof Ne!="string"&&(Ne&&Ne.hasOwnProperty(P)?Ne=Ne[P]:(Ne=n.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??n.DATA_TYPES.fp32,console.warn(`dtype not specified for "${P}". Using the default dtype (${Ne}) for this device (${_e}).`))),Ne===n.DATA_TYPES.auto){let Mt=ne.dtype;typeof Mt!="string"&&(Mt=Mt==null?void 0:Mt[P]),Mt&&Mt!==n.DATA_TYPES.auto&&n.DATA_TYPES.hasOwnProperty(Mt)?Ne=Mt:Ne=n.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??n.DATA_TYPES.fp32}const qe=Ne;if(n.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(qe)){if(qe===n.DATA_TYPES.fp16&&_e==="webgpu"&&!await(0,n.isWebGpuFp16Supported)())throw new Error(`The device (${_e}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${qe}. Should be one of: ${Object.keys(n.DATA_TYPES).join(", ")}`);const it=ne.kv_cache_dtype,pt=it?typeof it=="string"?it:it[qe]??"float32":void 0;if(pt&&!["float32","float16"].includes(pt))throw new Error(`Invalid kv_cache_dtype: ${pt}. Should be one of: float32, float16`);const ot={dtype:qe,kv_cache_dtype:pt},bt=n.DEFAULT_DTYPE_SUFFIX_MAPPING[qe],ct=`${P}${bt}.onnx`,gt=`${D.subfolder??""}/${ct}`,tt={...D.session_options};tt.executionProviders??(tt.executionProviders=Ce);const yt=ne.free_dimension_overrides;yt?tt.freeDimensionOverrides??(tt.freeDimensionOverrides=yt):_e.startsWith("webnn")&&!tt.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"]["${_e}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const Lt=w.apis.IS_NODE_ENV&&w.env.useFSCache,Ut=(0,l.getModelFile)(M,gt,!0,D,Lt),Qt=D.use_external_data_format??ne.use_external_data_format;let Ht=[];if(Qt){let Mt;typeof Qt=="object"?Qt.hasOwnProperty(ct)?Mt=Qt[ct]:Qt.hasOwnProperty(P)?Mt=Qt[P]:Mt=!1:Mt=Qt;const ir=+Mt;if(ir>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${ir}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let Rr=0;Rr{const yn=await(0,l.getModelFile)(M,Cr,!0,D,Lt);qr(yn instanceof Uint8Array?{path:Mn,data:yn}:Mn)}))}}else tt.externalData!==void 0&&(Ht=tt.externalData.map(async Mt=>{if(typeof Mt.data=="string"){const ir=await(0,l.getModelFile)(M,Mt.data,!0,D);return{...Mt,data:ir}}return Mt}));if(Ht.length>0){const Mt=await Promise.all(Ht);w.apis.IS_NODE_ENV||(tt.externalData=Mt)}if(_e==="webgpu"){const Mt=(0,s.getKeyValueShapes)(D.config,{prefix:"present"});if(Object.keys(Mt).length>0&&!(0,o.isONNXProxy)()){const ir={};for(const Rr in Mt)ir[Rr]="gpu-buffer";tt.preferredOutputLocation=ir}}return{buffer_or_path:await Ut,session_options:tt,session_config:ot}}async function A(M,P,D){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const{buffer_or_path:ge,session_options:_e,session_config:Ce}=await S(M,P[ne],D),Le=await(0,o.createInferenceSession)(ge,_e,Ce);return[ne,Le]})))}async function B(M,P,D){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const ge=await(0,l.getModelJSON)(M,P[ne],!1,D);return[ne,ge]})))}function K(M,P){const D=Object.create(null),ne=[];for(const Ce of M.inputNames){const Le=P[Ce];if(!(Le instanceof c.Tensor)){ne.push(Ce);continue}D[Ce]=(0,o.isONNXProxy)()?Le.clone():Le}if(ne.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ne.join(", ")}.`);const ge=Object.keys(P).length,_e=M.inputNames.length;if(ge>_e){let Ce=Object.keys(P).filter(Le=>!M.inputNames.includes(Le));console.warn(`WARNING: Too many inputs were provided (${ge} > ${_e}). The following inputs will be ignored: "${Ce.join(", ")}".`)}return D}async function G(M,P){const D=K(M,P);try{const ne=Object.fromEntries(Object.entries(D).map(([_e,Ce])=>[_e,Ce.ort_tensor]));let ge=await M.run(ne);return ge=j(ge),ge}catch(ne){const ge=Object.fromEntries(Object.entries(D).map(([_e,{type:Ce,dims:Le,data:Ne}])=>[_e,{type:Ce,dims:Le,data:Ne}]));throw console.error(`An error occurred during model execution: "${ne}".`),console.error("Inputs given to model:",ge),ne}}function j(M){for(let P in M)(0,o.isONNXTensor)(M[P])?M[P]=new c.Tensor(M[P]):typeof M[P]=="object"&&j(M[P]);return M}function ee(M){if(M instanceof c.Tensor)return M;if(M.length===0)throw Error("items must be non-empty");if(Array.isArray(M[0])){if(M.some(P=>P.length!==M[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 c.Tensor("int64",BigInt64Array.from(M.flat().map(P=>BigInt(P))),[M.length,M[0].length])}else return new c.Tensor("int64",BigInt64Array.from(M.map(P=>BigInt(P))),[1,M.length])}function H(M){return new c.Tensor("bool",[M],[1])}async function Z(M,P){let{encoder_outputs:D,input_ids:ne,decoder_input_ids:ge,..._e}=P;if(!D){const Le=(0,a.pick)(P,M.sessions.model.inputNames);D=(await X(M,Le)).last_hidden_state}return _e.input_ids=ge,_e.encoder_hidden_states=D,M.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(_e.encoder_attention_mask=P.attention_mask),await me(M,_e,!0)}async function X(M,P){const D=M.sessions.model,ne=(0,a.pick)(P,D.inputNames);if(D.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds){if(!P.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ne.inputs_embeds=await M.encode_text({input_ids:P.input_ids})}if(D.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,c.zeros_like)(ne.input_ids)}if(D.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 ge=ne.pixel_values.dims;ne.pixel_mask=(0,c.ones)([ge[0],ge[2],ge[3]])}return await G(D,ne)}async function oe(M,P){const D=await M.encode(P);return await M.decode(D)}async function me(M,P,D=!1){const ne=M.sessions[D?"decoder_model_merged":"model"],{past_key_values:ge,..._e}=P;if(ne.inputNames.includes("use_cache_branch")&&(_e.use_cache_branch=H(!!ge)),ne.inputNames.includes("position_ids")&&_e.attention_mask&&!_e.position_ids){const Le=["paligemma","gemma3_text","gemma3"].includes(M.config.model_type)?1:0;_e.position_ids=ce(_e,ge,Le)}M.addPastKeyValues(_e,ge);const Ce=(0,a.pick)(_e,ne.inputNames);return await G(ne,Ce)}function ae({modality_token_id:M,inputs_embeds:P,modality_features:D,input_ids:ne,attention_mask:ge}){const _e=ne.tolist().map(qe=>qe.reduce((it,pt,ot)=>(pt==M&&it.push(ot),it),[])),Ce=_e.reduce((qe,it)=>qe+it.length,0),Le=D.dims[0];if(Ce!==Le)throw new Error(`Number of tokens and features do not match: tokens: ${Ce}, features ${Le}`);let Ne=0;for(let qe=0;qe<_e.length;++qe){const it=_e[qe],pt=P[qe];for(let ot=0;ot_e.dims[1])){if(ge<_e.dims[1])D.input_ids=_e.slice(null,[ge,null]);else if(M.config.image_token_index!=null&&_e.data.some(Le=>Le==M.config.image_token_index)){const Le=M.config.num_image_tokens;if(!Le)throw new Error("`num_image_tokens` is missing in the model configuration.");const Ne=_e.dims[1]-(ge-Le);D.input_ids=_e.slice(null,[-Ne,null]),D.attention_mask=(0,c.ones)([1,ge+Ne])}}}return D}function Ue(M,P,D,ne){return D.past_key_values&&(P=P.map(ge=>[ge.at(-1)])),{...D,decoder_input_ids:ee(P)}}function we(M,...P){return M.config.is_encoder_decoder?Ue(M,...P):$e(M,...P)}function q(M,P,D,ne){const ge=!!D.past_key_values;return ne.guidance_scale!==null&&ne.guidance_scale>1&&(ge?D.input_ids=(0,c.cat)([D.input_ids,D.input_ids],0):(D.input_ids=(0,c.cat)([D.input_ids,(0,c.full_like)(D.input_ids,BigInt(ne.pad_token_id))],0),D.attention_mask=(0,c.cat)([D.attention_mask,(0,c.full_like)(D.attention_mask,0n)],0))),(ge||!D.pixel_values)&&(D.pixel_values=(0,c.full)([0,0,3,384,384],1)),ge&&(D.images_seq_mask=new c.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),D.images_emb_mask=new c.Tensor("bool",new Array(0).fill(!1),[1,1,0])),D}class R extends i.Callable{constructor(D,ne,ge){super();te(this,"main_input_name","input_ids");te(this,"forward_params",["input_ids","attention_mask"]);this.config=D,this.sessions=ne,this.configs=ge;const _e=x.get(this.constructor),Ce=y.get(_e);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ce){case E.DecoderOnly:this.can_generate=!0,this._forward=me,this._prepare_inputs_for_generation=$e;break;case E.Seq2Seq:case E.Vision2Seq:case E.Musicgen:this.can_generate=!0,this._forward=Z,this._prepare_inputs_for_generation=Ue;break;case E.EncoderDecoder:this._forward=Z;break;case E.ImageTextToText:this.can_generate=!0,this._forward=fe,this._prepare_inputs_for_generation=we;break;case E.AudioTextToText:this.can_generate=!0,this._forward=re,this._prepare_inputs_for_generation=we;break;case E.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=we;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=X;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ne;const D=[];for(const ge of Object.values(this.sessions))(ne=ge==null?void 0:ge.handler)!=null&&ne.dispose&&D.push(ge.handler.dispose());return await Promise.all(D)}static async from_pretrained(D,{progress_callback:ne=null,config:ge=null,cache_dir:_e=null,local_files_only:Ce=!1,revision:Le="main",model_file_name:Ne=null,subfolder:qe="onnx",device:it=null,dtype:pt=null,use_external_data_format:ot=null,session_options:bt={}}={}){let ct={progress_callback:ne,config:ge,cache_dir:_e,local_files_only:Ce,revision:Le,model_file_name:Ne,subfolder:qe,device:it,dtype:pt,use_external_data_format:ot,session_options:bt};const gt=x.get(this),tt=y.get(gt);ge=ct.config=await s.AutoConfig.from_pretrained(D,ct);let yt;if(tt===E.DecoderOnly)yt=await Promise.all([A(D,{model:ct.model_file_name??"model"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(tt===E.Seq2Seq||tt===E.Vision2Seq)yt=await Promise.all([A(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(tt===E.MaskGeneration)yt=await Promise.all([A(D,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},ct)]);else if(tt===E.EncoderDecoder)yt=await Promise.all([A(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},ct)]);else if(tt===E.ImageTextToText){const Lt={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};ge.is_encoder_decoder&&(Lt.model="encoder_model"),yt=await Promise.all([A(D,Lt,ct),B(D,{generation_config:"generation_config.json"},ct)])}else if(tt===E.AudioTextToText){const Lt={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};yt=await Promise.all([A(D,Lt,ct),B(D,{generation_config:"generation_config.json"},ct)])}else if(tt===E.Musicgen)yt=await Promise.all([A(D,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(tt===E.MultiModality)yt=await Promise.all([A(D,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(tt===E.Phi3V)yt=await Promise.all([A(D,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},ct),B(D,{generation_config:"generation_config.json"},ct)]);else if(tt===E.AutoEncoder)yt=await Promise.all([A(D,{encoder_model:"encoder_model",decoder_model:"decoder_model"},ct)]);else{if(tt!==E.EncoderOnly){const Lt=gt??(ge==null?void 0:ge.model_type);Lt!=="custom"&&console.warn(`Model type for '${Lt}' not found, assuming encoder-only architecture. Please report this at ${u.GITHUB_ISSUE_URL}.`)}yt=await Promise.all([A(D,{model:ct.model_file_name??"model"},ct)])}return new this(ge,...yt)}async _call(D){return await this.forward(D)}async forward(D){return await this._forward(this,D)}get generation_config(){var D;return((D=this.configs)==null?void 0:D.generation_config)??null}_get_logits_warper(D){const ne=new p.LogitsProcessorList;return D.temperature!==null&&D.temperature!==1&&ne.push(new p.TemperatureLogitsWarper(D.temperature)),D.top_k!==null&&D.top_k!==0&&ne.push(new p.TopKLogitsWarper(D.top_k)),D.top_p!==null&&D.top_p<1&&ne.push(new p.TopPLogitsWarper(D.top_p)),ne}_get_logits_processor(D,ne,ge=null){const _e=new p.LogitsProcessorList;if(D.repetition_penalty!==null&&D.repetition_penalty!==1&&_e.push(new p.RepetitionPenaltyLogitsProcessor(D.repetition_penalty)),D.no_repeat_ngram_size!==null&&D.no_repeat_ngram_size>0&&_e.push(new p.NoRepeatNGramLogitsProcessor(D.no_repeat_ngram_size)),D.bad_words_ids!==null&&_e.push(new p.NoBadWordsLogitsProcessor(D.bad_words_ids,D.eos_token_id)),D.min_length!==null&&D.eos_token_id!==null&&D.min_length>0&&_e.push(new p.MinLengthLogitsProcessor(D.min_length,D.eos_token_id)),D.min_new_tokens!==null&&D.eos_token_id!==null&&D.min_new_tokens>0&&_e.push(new p.MinNewTokensLengthLogitsProcessor(ne,D.min_new_tokens,D.eos_token_id)),D.forced_bos_token_id!==null&&_e.push(new p.ForcedBOSTokenLogitsProcessor(D.forced_bos_token_id)),D.forced_eos_token_id!==null&&_e.push(new p.ForcedEOSTokenLogitsProcessor(D.max_length,D.forced_eos_token_id)),D.begin_suppress_tokens!==null){const Ce=ne>1||D.forced_bos_token_id===null?ne:ne+1;_e.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ce))}return D.guidance_scale!==null&&D.guidance_scale>1&&_e.push(new p.ClassifierFreeGuidanceLogitsProcessor(D.guidance_scale)),ge!==null&&_e.extend(ge),_e}_prepare_generation_config(D,ne,ge=d.GenerationConfig){const _e={...this.config};for(const Le of["decoder","generator","text_config"])Le in _e&&Object.assign(_e,_e[Le]);const Ce=new ge(_e);return Object.assign(Ce,this.generation_config??{}),D&&Object.assign(Ce,D),ne&&Object.assign(Ce,(0,a.pick)(ne,Object.getOwnPropertyNames(Ce))),Ce}_get_stopping_criteria(D,ne=null){const ge=new v.StoppingCriteriaList;return D.max_length!==null&&ge.push(new v.MaxLengthCriteria(D.max_length,this.config.max_position_embeddings??null)),D.eos_token_id!==null&&ge.push(new v.EosTokenCriteria(D.eos_token_id)),ne&&ge.extend(ne),ge}_validate_model_class(){if(!this.can_generate){const D=[yl,vl,Ml,bl],ne=x.get(this.constructor),ge=new Set,_e=this.config.model_type;for(const Le of D){const Ne=Le.get(_e);Ne&&ge.add(Ne[0])}let Ce=`The current model class (${ne}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ge.size>0&&(Ce+=` Please use the following class instead: ${[...ge].join(", ")}`),Error(Ce)}}prepare_inputs_for_generation(...D){return this._prepare_inputs_for_generation(this,...D)}_update_model_kwargs_for_generation({generated_input_ids:D,outputs:ne,model_inputs:ge,is_encoder_decoder:_e}){return ge.past_key_values=this.getPastKeyValues(ne,ge.past_key_values),ge.input_ids=new c.Tensor("int64",D.flat(),[D.length,1]),_e||(ge.attention_mask=(0,c.cat)([ge.attention_mask,(0,c.ones)([ge.attention_mask.dims[0],1])],1)),ge.position_ids=null,ge}_prepare_model_inputs({inputs:D,bos_token_id:ne,model_kwargs:ge}){const _e=(0,a.pick)(ge,this.forward_params),Ce=this.main_input_name;if(Ce in _e){if(D)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else _e[Ce]=D;return{inputs_tensor:_e[Ce],model_inputs:_e,model_input_name:Ce}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:D,model_inputs:ne,model_input_name:ge,generation_config:_e}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Le,pixel_values:Ne,attention_mask:qe,...it}=ne,pt=await this._prepare_inputs_embeds(ne);ne={...it,...(0,a.pick)(pt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ce}=await X(this,ne);if(_e.guidance_scale!==null&&_e.guidance_scale>1)Ce=(0,c.cat)([Ce,(0,c.full_like)(Ce,0)],0),"attention_mask"in ne&&(ne.attention_mask=(0,c.cat)([ne.attention_mask,(0,c.zeros_like)(ne.attention_mask)],0));else if(ne.decoder_input_ids){const Le=ee(ne.decoder_input_ids).dims[0];if(Le!==Ce.dims[0]){if(Ce.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ce.dims[0]}) than the decoder inputs (${Le}).`);Ce=(0,c.cat)(Array.from({length:Le},()=>Ce),0)}}return ne.encoder_outputs=Ce,ne}_prepare_decoder_input_ids_for_generation({batch_size:D,model_input_name:ne,model_kwargs:ge,decoder_start_token_id:_e,bos_token_id:Ce,generation_config:Le}){let{decoder_input_ids:Ne,...qe}=ge;if(!(Ne instanceof c.Tensor)){if(Ne)Array.isArray(Ne[0])||(Ne=Array.from({length:D},()=>Ne));else if(_e??(_e=Ce),this.config.model_type==="musicgen")Ne=Array.from({length:D*this.config.decoder.num_codebooks},()=>[_e]);else if(Array.isArray(_e)){if(_e.length!==D)throw new Error(`\`decoder_start_token_id\` expcted to have length ${D} but got ${_e.length}`);Ne=_e}else Ne=Array.from({length:D},()=>[_e]);Ne=ee(Ne)}return ge.decoder_attention_mask=(0,c.ones_like)(Ne),{input_ids:Ne,model_inputs:qe}}async generate({inputs:D=null,generation_config:ne=null,logits_processor:ge=null,stopping_criteria:_e=null,streamer:Ce=null,...Le}){this._validate_model_class(),ne=this._prepare_generation_config(ne,Le);let{inputs_tensor:Ne,model_inputs:qe,model_input_name:it}=this._prepare_model_inputs({inputs:D,model_kwargs:Le});const pt=this.config.is_encoder_decoder;pt&&("encoder_outputs"in qe||(qe=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Ne,model_inputs:qe,model_input_name:it,generation_config:ne})));let ot;pt?{input_ids:ot,model_inputs:qe}=this._prepare_decoder_input_ids_for_generation({batch_size:qe[it].dims.at(0),model_input_name:it,model_kwargs:qe,decoder_start_token_id:ne.decoder_start_token_id,bos_token_id:ne.bos_token_id,generation_config:ne}):ot=qe[it];let bt=ot.dims.at(-1);ne.max_new_tokens!==null&&(ne.max_length=bt+ne.max_new_tokens);const ct=this._get_logits_processor(ne,bt,ge),gt=this._get_stopping_criteria(ne,_e),tt=qe[it].dims.at(0),yt=$.LogitsSampler.getSampler(ne),Lt=new Array(tt).fill(0),Ut=ot.tolist();Ce&&Ce.put(Ut);let Qt,Ht={};for(;;){if(qe=this.prepare_inputs_for_generation(Ut,qe,ne),Qt=await this.forward(qe),ne.output_attentions&&ne.return_dict_in_generate){const Cr=this.getAttentions(Qt);for(const qr in Cr)qr in Ht||(Ht[qr]=[]),Ht[qr].push(Cr[qr])}const Mt=Qt.logits.slice(null,-1,null),ir=ct(Ut,Mt),Rr=[];for(let Cr=0;CrCr))break;qe=this._update_model_kwargs_for_generation({generated_input_ids:Rr,outputs:Qt,model_inputs:qe,is_encoder_decoder:pt})}Ce&&Ce.end();const nr=this.getPastKeyValues(Qt,qe.past_key_values,!0),hr=new c.Tensor("int64",Ut.flat(),[Ut.length,Ut[0].length]);if(ne.return_dict_in_generate)return{sequences:hr,past_key_values:nr,...Ht};for(const Mt of Object.values(Qt))Mt.location==="gpu-buffer"&&Mt.dispose();return hr}getPastKeyValues(D,ne,ge=!1){const _e=Object.create(null);for(const Ce in D)if(Ce.startsWith("present")){const Le=Ce.replace("present","past_key_values"),Ne=Ce.includes("encoder");if(Ne&&ne?_e[Le]=ne[Le]:_e[Le]=D[Ce],ne&&(!Ne||ge)){const qe=ne[Le];qe.location==="gpu-buffer"&&qe.dispose()}}return _e}getAttentions(D){const ne={};for(const ge of["cross_attentions","encoder_attentions","decoder_attentions"])for(const _e in D)_e.startsWith(ge)&&(ge in ne||(ne[ge]=[]),ne[ge].push(D[_e]));return ne}addPastKeyValues(D,ne){var ge,_e,Ce;if(ne)Object.assign(D,ne);else{const Le=this.sessions.decoder_model_merged??this.sessions.model,Ne=((ge=Le==null?void 0:Le.config)==null?void 0:ge.kv_cache_dtype)??"float32",qe=Ne==="float16"?new c.DataTypeMap.float16:[],it=((Ce=(_e=D[this.main_input_name]??D.attention_mask)==null?void 0:_e.dims)==null?void 0:Ce[0])??1,pt=(0,s.getKeyValueShapes)(this.config,{batch_size:it});for(const ot in pt)D[ot]=new c.Tensor(Ne,qe,pt[ot])}}async encode_image({pixel_values:D}){const ne=(await G(this.sessions.vision_encoder,{pixel_values:D})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${ne.dims[1]}).`),this.config.num_image_tokens=ne.dims[1]),ne}async encode_text({input_ids:D}){return(await G(this.sessions.embed_tokens,{input_ids:D})).inputs_embeds}async encode_audio({audio_values:D}){return(await G(this.sessions.audio_encoder,{audio_values:D})).audio_features}}class pe{}class xe extends pe{constructor({last_hidden_state:P,hidden_states:D=null,attentions:ne=null}){super(),this.last_hidden_state=P,this.hidden_states=D,this.attentions=ne}}class Me extends R{}class Se extends Me{}class Ae extends Me{async _call(P){return new wr(await super._call(P))}}class Fe extends Me{async _call(P){return new mt(await super._call(P))}}class ze extends Me{async _call(P){return new pr(await super._call(P))}}class Ve extends Me{async _call(P){return new Tr(await super._call(P))}}class O extends R{}class Y extends O{}class z extends O{async _call(P){return new wr(await super._call(P))}}class J extends O{async _call(P){return new mt(await super._call(P))}}class le extends O{async _call(P){return new pr(await super._call(P))}}class ye extends R{}class Ee extends ye{}class ke extends R{}class Ie extends ke{}class Be extends ke{async _call(P){return new wr(await super._call(P))}}class Xe extends ke{async _call(P){return new mt(await super._call(P))}}class Ge extends ke{async _call(P){return new pr(await super._call(P))}}class lt extends ke{async _call(P){return new Tr(await super._call(P))}}class wt extends R{}class Gt extends wt{}class Ot extends wt{async _call(P){return new wr(await super._call(P))}}class lr extends wt{async _call(P){return new mt(await super._call(P))}}class Yr extends wt{async _call(P){return new pr(await super._call(P))}}class gs extends wt{async _call(P){return new Tr(await super._call(P))}}class kr extends R{}class Ds extends kr{}class xs extends kr{async _call(P){return new wr(await super._call(P))}}class Ls extends kr{async _call(P){return new mt(await super._call(P))}}class at extends kr{async _call(P){return new pr(await super._call(P))}}class Zr extends kr{async _call(P){return new Tr(await super._call(P))}}class Ir extends R{}class ws extends Ir{}class Ft extends Ir{async _call(P){return new wr(await super._call(P))}}class es extends Ir{async _call(P){return new mt(await super._call(P))}}class ts extends Ir{async _call(P){return new pr(await super._call(P))}}class bs extends Ir{async _call(P){return new Tr(await super._call(P))}}class Xt extends R{}class De extends Xt{}class Qe extends Xt{async _call(P){return new wr(await super._call(P))}}class et extends Xt{async _call(P){return new mt(await super._call(P))}}class Bt extends Xt{async _call(P){return new pr(await super._call(P))}}class Or extends Xt{async _call(P){return new Tr(await super._call(P))}}class Pr extends R{}class rs extends Pr{}class ss extends Pr{async _call(P){return new wr(await super._call(P))}}class Ur extends Pr{async _call(P){return new mt(await super._call(P))}}class ns extends Pr{async _call(P){return new pr(await super._call(P))}}class os extends Pr{async _call(P){return new Tr(await super._call(P))}}class Wr extends R{}class yr extends Wr{}class Ys extends Wr{async _call(P){return new mt(await super._call(P))}}class vr extends Wr{async _call(P){return new pr(await super._call(P))}}class Ts extends Wr{async _call(P){return new Tr(await super._call(P))}}class Es extends Wr{async _call(P){return new wr(await super._call(P))}}class fr extends R{}class zs extends fr{}class Zs extends fr{async _call(P){return new wr(await super._call(P))}}class Ar extends fr{async _call(P){return new mt(await super._call(P))}}class en extends fr{async _call(P){return new pr(await super._call(P))}}class Gr extends R{}class xr extends Gr{}class Ps extends Gr{async _call(P){return new wr(await super._call(P))}}class ur extends Gr{async _call(P){return new mt(await super._call(P))}}class _r extends Gr{async _call(P){return new Tr(await super._call(P))}}class Dr extends R{}class tn extends Dr{}class rn extends Dr{async _call(P){return new wr(await super._call(P))}}class sn extends Dr{async _call(P){return new mt(await super._call(P))}}class nn extends Dr{async _call(P){return new pr(await super._call(P))}}class on extends Dr{async _call(P){return new Tr(await super._call(P))}}class Ms extends R{}class an extends Ms{}class Bs extends Ms{async _call(P){return new wr(await super._call(P))}}class ln extends Ms{async _call(P){return new mt(await super._call(P))}}class un extends Ms{async _call(P){return new Tr(await super._call(P))}}class ys extends R{}class dn extends ys{}class he extends ys{async _call(P){return new mt(await super._call(P))}}class k extends ys{async _call(P){return new Tr(await super._call(P))}}class N extends ys{async _call(P){return new wr(await super._call(P))}}class Q extends R{constructor(){super(...arguments);te(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class ie extends Q{}class de extends Q{}class ve extends R{}class je extends ve{}class He extends ve{}class We extends R{}class Je extends We{}class dt extends We{}class vt extends R{}class Et extends vt{}class Rt extends vt{}class kt extends vt{async _call(P){return new mt(await super._call(P))}}class Kt extends R{}class Mr extends Kt{}class dr extends Kt{}class cr extends Kt{async _call(P){return new mt(await super._call(P))}}class Nt extends Kt{}class Kr extends R{}class Dt extends Kr{}class rr extends Kr{}class gr extends R{}class Hr extends gr{}class Lr extends gr{}class Yt extends R{}class zr extends Yt{}class or extends Yt{async _call(P){return new wr(await super._call(P))}}class Vt extends Yt{async _call(P){return new mt(await super._call(P))}}class Zt extends Yt{async _call(P){return new pr(await super._call(P))}}class er extends Yt{async _call(P){return new Tr(await super._call(P))}}class tr extends R{}class Rs extends tr{}class cn extends tr{async _call(P){return new wr(await super._call(P))}}class ei extends tr{async _call(P){return new mt(await super._call(P))}}class ti extends tr{async _call(P){return new pr(await super._call(P))}}class ri extends tr{async _call(P){return new Tr(await super._call(P))}}class Cs extends R{}class si extends Cs{}class ni extends Cs{async _call(P){return new wr(await super._call(P))}}class oi extends Cs{async _call(P){return new mt(await super._call(P))}}class ii extends Cs{async _call(P){return new pr(await super._call(P))}}class ai extends Cs{async _call(P){return new Tr(await super._call(P))}}class lo extends R{}class li extends lo{}class ui extends lo{}class uo extends R{constructor(){super(...arguments);te(this,"requires_attention_mask",!1);te(this,"main_input_name","input_features");te(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class di extends uo{}class co extends uo{_prepare_generation_config(P,D){return super._prepare_generation_config(P,D,g.WhisperGenerationConfig)}_retrieve_init_tokens(P){const D=[P.decoder_start_token_id];let ne=P.language;const ge=P.task;if(P.is_multilingual){ne||(console.warn("No language specified - defaulting to English (en)."),ne="en");const Ce=`<|${(0,C.whisper_language_to_code)(ne)}|>`;D.push(P.lang_to_id[Ce]),D.push(P.task_to_id[ge??"transcribe"])}else if(ne||ge)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!P.return_timestamps&&P.no_timestamps_token_id&&D.at(-1)!==P.no_timestamps_token_id?D.push(P.no_timestamps_token_id):P.return_timestamps&&D.at(-1)===P.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),D.pop()),D.filter(_e=>_e!=null)}async generate({inputs:P=null,generation_config:D=null,logits_processor:ne=null,stopping_criteria:ge=null,..._e}){D=this._prepare_generation_config(D,_e);const Ce=_e.decoder_input_ids??this._retrieve_init_tokens(D);if(D.return_timestamps&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.WhisperTimeStampLogitsProcessor(D,Ce))),D.begin_suppress_tokens&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ce.length))),D.return_token_timestamps){if(!D.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");D.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),D.output_attentions=!0,D.return_dict_in_generate=!0}const Le=await super.generate({inputs:P,generation_config:D,logits_processor:ne,decoder_input_ids:Ce,..._e});return D.return_token_timestamps&&(Le.token_timestamps=this._extract_token_timestamps(Le,D.alignment_heads,D.num_frames)),Le}_extract_token_timestamps(P,D,ne=null,ge=.02){if(!P.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 _e=this.config.median_filter_width;_e===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),_e=7);const Ce=P.cross_attentions,Le=Array.from({length:this.config.decoder_layers},(gt,tt)=>(0,c.cat)(Ce.map(yt=>yt[tt]),2)),Ne=(0,c.stack)(D.map(([gt,tt])=>{if(gt>=Le.length)throw new Error(`Layer index ${gt} is out of bounds for cross attentions (length ${Le.length}).`);return ne?Le[gt].slice(null,tt,null,[0,ne]):Le[gt].slice(null,tt)})).transpose(1,0,2,3),[qe,it]=(0,c.std_mean)(Ne,-2,0,!0),pt=Ne.clone();for(let gt=0;gtyt[hr+1]-yt[hr]),Qt=(0,a.mergeArrays)([1],Ut).map(nr=>!!nr),Ht=[];for(let nr=0;nrot.findIndex(bt=>bt==_e)),Ne=Le.every(ot=>ot===-1),qe=Le.every(ot=>ot!==-1);if(!Ne&&!qe)throw new Error("Every input should contain either 0 or 1 image token.");if(Ne)return{inputs_embeds:P,attention_mask:ge};const it=[],pt=[];for(let ot=0;otArray.from({length:P.dims[0]},Ut=>Array.from({length:P.dims[1]},Qt=>1))),ct=D?D.tolist():[],gt=ne?ne.tolist():[];let tt=0,yt=0;for(let Lt=0;Ltot[Lt][ar]==1),Ht=Ut.reduce((Wt,ar,Ks)=>(ar==Ne&&Wt.push(Ks),Wt),[]).map(Wt=>Ut[Wt+1]),nr=Ht.filter(Wt=>Wt==Ce).length,hr=Ht.filter(Wt=>Wt==Le).length;let Mt=[],ir=0,Rr=nr,Mn=hr;for(let Wt=0;Wtis>ir&&xn==Ce),Ks=Ut.findIndex((xn,is)=>is>ir&&xn==Le),vn=Rr>0&&ar!==-1?ar:Ut.length+1,Zn=Mn>0&&Ks!==-1?Ks:Ut.length+1;let Gi,Tl,El,Pl;vn0?(0,f.max)(Mt.at(-1))[0]+1:0;Mt.push(Array.from({length:3*Sl},(xn,is)=>gf+is%Sl));const $l=Sl+gf,Hi=ov*Cl*Ki,iv=Array.from({length:Hi},(xn,is)=>$l+Math.floor(is/(Cl*Ki))),av=Array.from({length:Hi},(xn,is)=>$l+Math.floor(is/Ki)%Cl),lv=Array.from({length:Hi},(xn,is)=>$l+is%Ki);Mt.push([iv,av,lv].flat()),ir=Gi+Hi}if(ir0?(0,f.max)(Mt.at(-1))[0]+1:0,ar=Ut.length-ir;Mt.push(Array.from({length:3*ar},(Ks,vn)=>Wt+vn%ar))}const Cr=Mt.reduce((Wt,ar)=>Wt+ar.length,0),qr=new Array(Cr);let Vi=0;for(let Wt=0;Wt<3;++Wt)for(let ar=0;arpt[tt%pt.length]),ct=Array.from({length:ot[0]},(gt,tt)=>(0,f.max)(pt.subarray(ot[1]*tt,ot[1]*(tt+1)))[0]+1n+BigInt(ot[1]));return[new c.Tensor("int64",bt,[3,...ot]),new c.Tensor("int64",ct,[ct.length,1])]}else{const[pt,ot]=P.dims,bt=BigInt64Array.from({length:3*pt*ot},(ct,gt)=>BigInt(Math.floor(gt%ot/pt)));return[new c.Tensor("int64",bt,[3,...P.dims]),(0,c.zeros)([pt,1])]}}async encode_image({pixel_values:P,image_grid_thw:D}){return(await G(this.sessions.vision_encoder,{pixel_values:P,grid_thw:D})).image_features}_merge_input_ids_with_image_features(P){return V({image_token_id:this.config.image_token_id,...P})}prepare_inputs_for_generation(P,D,ne){if(D.attention_mask&&!D.position_ids)if(!D.past_key_values)[D.position_ids,D.rope_deltas]=this.get_rope_index(D.input_ids,D.image_grid_thw,D.video_grid_thw,D.attention_mask);else{D.pixel_values=null;const ge=BigInt(Object.values(D.past_key_values)[0].dims.at(-2)),_e=D.rope_deltas.map(Ce=>ge+Ce);D.position_ids=(0,c.stack)([_e,_e,_e],0)}return D}}class Ca extends R{}class Bd extends Ca{}class Rd extends Ca{}class Sa extends R{}class jd extends Sa{}class Nd extends Sa{}class $a extends R{}class Vd extends $a{}class Ud extends $a{}class ka extends R{}class Wd extends ka{}class Gd extends ka{}class Ia extends R{}class Kd extends Ia{}class Hd extends Ia{}class Aa extends R{}class qd extends Aa{}class Xd extends Aa{async _call(P){return new mt(await super._call(P))}}class Fa extends R{}class Qd extends Fa{}class Jd extends Fa{async _call(P){return new mt(await super._call(P))}}class Yd extends R{}class Zd extends Yd{}class Oa extends R{}class ec extends Oa{}class tc extends Oa{async _call(P){return new mt(await super._call(P))}}class rc extends R{}class sc extends rc{}class Da extends R{}class nc extends Da{}class oc extends Da{async _call(P){return new mt(await super._call(P))}}class ic extends R{}class ac extends ic{}class La extends R{}class lc extends La{}class uc extends La{async _call(P){return new mt(await super._call(P))}}class dc extends R{}class cc extends dc{async _call(P){return new ff(await super._call(P))}}class za extends R{}class pc extends za{}class hc extends za{async _call(P){return new mt(await super._call(P))}}class Ba extends R{}class mc extends Ba{}class fc extends Ba{async _call(P){return new mt(await super._call(P))}}class Ra extends R{}class _c extends Ra{}class gc extends Ra{}class ja extends R{}class wc extends ja{}class bc extends ja{}class Na extends R{}class Mc extends Na{}class yc extends Na{async _call(P){return new mt(await super._call(P))}}class Pi extends R{}class vc extends Pi{}class xc extends Pi{async _call(P){return new Ua(await super._call(P))}}class Va extends Pi{async _call(P){return new Tc(await super._call(P))}}class Ua extends pe{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class Tc extends pe{constructor({logits:P,pred_boxes:D,pred_masks:ne}){super(),this.logits=P,this.pred_boxes=D,this.pred_masks=ne}}class Wa extends R{}class Ec extends Wa{}class Pc extends Wa{async _call(P){return new Ci(await super._call(P))}}class Ci extends pe{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class Ga extends R{}class Cc extends Ga{}class Sc extends Ga{async _call(P){return new $c(await super._call(P))}}class $c extends Ci{}class Ka extends R{}class kc extends Ka{}class Ic extends Ka{async _call(P){return new Ac(await super._call(P))}}class Ac extends Ci{}class Ha extends R{}class Fc extends Ha{}class Oc extends Ha{async _call(P){return new Dc(await super._call(P))}}class Dc extends Ua{}class qa extends R{}class Lc extends qa{}class zc extends qa{async _call(P){return new mt(await super._call(P))}}class Xa extends R{}class Bc extends Xa{}class Rc extends Xa{async _call(P){return new mt(await super._call(P))}}class Qa extends R{}class jc extends Qa{}class Nc extends Qa{async _call(P){return new mt(await super._call(P))}}class Si extends R{}class Vc extends Si{}class Uc extends Si{async _call(P){return new mt(await super._call(P))}}class Wc extends Si{}class Ja extends R{}class Gc extends Ja{}class Kc extends Ja{}class Ya extends R{}class Hc extends Ya{}class qc extends Ya{}class Xc extends R{}class Qc extends Xc{}class $i extends R{}class Jc extends $i{}class Yc extends $i{}class Zc extends $i{}class ep extends R{}class tp extends ep{}class rp extends R{}class sp extends rp{}class np extends R{}class op extends np{}class Za extends R{}class ip extends Za{}class ap extends Za{}class el extends R{}class lp extends el{}class up extends el{}class dp extends R{}class cp extends dp{}class tl extends R{}class pp extends tl{}class hp extends tl{async _call(P){return new mt(await super._call(P))}}class rl extends R{}class mp extends rl{}class fp extends rl{async _call(P){return new mt(await super._call(P))}}class sl extends R{}class _p extends sl{}class gp extends sl{async _call(P){return new mt(await super._call(P))}}class nl extends R{}class wp extends nl{}class bp extends nl{async _call(P){return new mt(await super._call(P))}}class Mp extends R{}class yp extends Mp{}class ol extends R{}class vp extends ol{}class xp extends ol{async _call(P){return new Tp(await super._call(P))}}class Tp extends pe{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class Ep extends R{}class Pp extends Ep{async get_image_embeddings({pixel_values:P}){return await X(this,{pixel_values:P})}async forward(P){if((!P.image_embeddings||!P.image_positional_embeddings)&&(P={...P,...await this.get_image_embeddings(P)}),!P.input_labels&&P.input_points){const ne=P.input_points.dims.slice(0,-1),ge=ne.reduce((_e,Ce)=>_e*Ce,1);P.input_labels=new c.Tensor("int64",new BigInt64Array(ge).fill(1n),ne)}const D={image_embeddings:P.image_embeddings,image_positional_embeddings:P.image_positional_embeddings};return P.input_points&&(D.input_points=P.input_points),P.input_labels&&(D.input_labels=P.input_labels),P.input_boxes&&(D.input_boxes=P.input_boxes),await G(this.sessions.prompt_encoder_mask_decoder,D)}async _call(P){return new Cp(await super._call(P))}}class Cp extends pe{constructor({iou_scores:P,pred_masks:D}){super(),this.iou_scores=P,this.pred_masks=D}}class il extends R{}class Sp extends il{}class $p extends il{}class al extends R{}class kp extends al{}class Ip extends al{}class Gs extends R{}class Ap extends Gs{}class Fp extends Gs{async _call(P){return new bn(await super._call(P))}}class Op extends Gs{async _call(P){return new mt(await super._call(P))}}class Dp extends Gs{async _call(P){return new pr(await super._call(P))}}class ll extends R{}class Lp extends ll{}class zp extends ll{async _call(P){return new pr(await super._call(P))}}class Bp extends R{}class Rp extends Bp{}class ki extends R{}class jp extends ki{}class Np extends ki{async _call(P){return new bn(await super._call(P))}}class Vp extends ki{async _call(P){return new mt(await super._call(P))}}class Do extends R{}class Up extends Do{}class Wp extends Do{async _call(P){return new bn(await super._call(P))}}class Gp extends Do{async _call(P){return new mt(await super._call(P))}}class Kp extends Do{async _call(P){return new pr(await super._call(P))}}class Ii extends R{}class Hp extends Ii{}class qp extends Ii{async _call(P){return new bn(await super._call(P))}}class Xp extends Ii{async _call(P){return new mt(await super._call(P))}}class W0 extends R{}class Qp extends Gs{}class Jp extends Gs{async _call(P){return new bn(await super._call(P))}}class Yp extends Gs{async _call(P){return new mt(await super._call(P))}}class Jn extends R{}class Zp extends Jn{}class eh extends Jn{async _call(P){return new bn(await super._call(P))}}class th extends Jn{async _call(P){return new mt(await super._call(P))}}class rh extends Jn{async _call(P){return new mf(await super._call(P))}}class sh extends Jn{async _call(P){return new pr(await super._call(P))}}class nh extends R{}class oh extends nh{}class Ai extends R{}class G0 extends Ai{}class ih extends Ai{}class ah extends Ai{async generate_speech(P,D,{threshold:ne=.5,minlenratio:ge=0,maxlenratio:_e=20,vocoder:Ce=null}={}){const Le={input_ids:P},{encoder_outputs:Ne,encoder_attention_mask:qe}=await X(this,Le),it=Ne.dims[1]/this.config.reduction_factor,pt=Math.floor(it*_e),ot=Math.floor(it*ge),bt=this.config.num_mel_bins;let ct=[],gt=null,tt=null,yt=0;for(;;){++yt;const Qt=H(!!tt);let Ht;tt?Ht=tt.output_sequence_out:Ht=new c.Tensor("float32",new Float32Array(bt),[1,1,bt]);let nr={use_cache_branch:Qt,output_sequence:Ht,encoder_attention_mask:qe,speaker_embeddings:D,encoder_hidden_states:Ne};this.addPastKeyValues(nr,gt),tt=await G(this.sessions.decoder_model_merged,nr),gt=this.getPastKeyValues(tt,gt);const{prob:hr,spectrum:Mt}=tt;if(ct.push(Mt),yt>=ot&&(Array.from(hr.data).filter(ir=>ir>=ne).length>0||yt>=pt))break}const Lt=(0,c.cat)(ct),{waveform:Ut}=await G(Ce.sessions.model,{spectrogram:Lt});return{spectrogram:Lt,waveform:Ut}}}class lh extends R{constructor(){super(...arguments);te(this,"main_input_name","spectrogram")}}class uh extends R{}class dh extends uh{}class ul extends R{}class ch extends ul{}class ph extends ul{}class dl extends R{}class hh extends dl{}class mh extends dl{}class cl extends R{}class fh extends cl{}class _h extends cl{}class Fi extends R{}class gh extends Fi{}class wh extends Fi{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"text_model"})}}class bh extends Fi{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"audio_model"})}}class Mh extends R{}class pl extends Mh{async _call(P){return new _f(await super._call(P))}}class Oi extends R{}class K0 extends Oi{}class yh extends Oi{}class vh extends Oi{}class hl extends R{}class xh extends hl{}class Th extends hl{}class ml extends R{}class Eh extends ml{}class Ph extends ml{async _call(P){return new mt(await super._call(P))}}class fl extends R{}class H0 extends fl{}class q0 extends fl{}class _l extends R{constructor(){super(...arguments);te(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(D){const[ne,ge]=D.dims,_e=this.config.decoder.num_codebooks,Ce=ge-_e;let Le=0;for(let it=0;it0&&bt<=Ce&&(D.data[Le++]=D.data[it])}const Ne=Math.floor(ne/_e),qe=Le/(Ne*_e);return new c.Tensor(D.type,D.data.slice(0,Le),[Ne,_e,qe])}prepare_inputs_for_generation(D,ne,ge){let _e=structuredClone(D);for(let Le=0;Le<_e.length;++Le)for(let Ne=0;Ne<_e[Le].length;++Ne)Le%this.config.decoder.num_codebooks>=Ne&&(_e[Le][Ne]=BigInt(this.config.decoder.pad_token_id));return ge.guidance_scale!==null&&ge.guidance_scale>1&&(_e=_e.concat(_e)),super.prepare_inputs_for_generation(_e,ne,ge)}async generate(D){const ne=await super.generate(D),ge=this._apply_and_filter_by_delay_pattern_mask(ne).unsqueeze_(0),{audio_values:_e}=await G(this.sessions.encodec_decode,{audio_codes:ge});return _e}}class Di extends R{}class Ch extends Di{}class Sh extends Di{async _call(P){return new mt(await super._call(P))}}class $h extends Di{}class Li extends R{}class kh extends Li{}class Ih extends Li{async _call(P){return new mt(await super._call(P))}}class Ah extends Li{}class zi extends R{}class Fh extends zi{}class Oh extends zi{async _call(P){return new mt(await super._call(P))}}class Dh extends zi{}class Bi extends R{}class Lh extends Bi{}class zh extends Bi{async _call(P){return new mt(await super._call(P))}}class Bh extends Bi{}class Rh extends R{}class jh extends Rh{}class Nh extends R{}class Vh extends Nh{constructor(...D){super(...D);te(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(D){const ne=this._generation_mode??"text";let ge;if(ne==="text"||!D.past_key_values){const qe=this.sessions.prepare_inputs_embeds,it=(0,a.pick)(D,qe.inputNames);ge=await G(qe,it)}else{const qe=this.sessions.gen_img_embeds,it=(0,a.pick)({image_ids:D.input_ids},qe.inputNames);ge=await G(qe,it)}const _e={...D,...ge},Ce=await me(this,_e),Le=this.sessions[ne==="text"?"lm_head":"gen_head"];if(!Le)throw new Error(`Unable to find "${Le}" generation head`);const Ne=await G(Le,(0,a.pick)(Ce,Le.inputNames));return{...ge,...Ce,...Ne}}async generate(D){return this._generation_mode="text",super.generate(D)}async generate_images(D){this._generation_mode="image";const ne=(D.inputs??D[this.main_input_name]).dims[1],_e=(await super.generate(D)).slice(null,[ne,null]),Ce=this.sessions.image_decode,{decoded_image:Le}=await G(Ce,{generated_tokens:_e}),Ne=Le.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),qe=[];for(const it of Ne){const pt=_.RawImage.fromTensor(it);qe.push(pt)}return qe}}class Uh extends pe{constructor({char_logits:P,bpe_logits:D,wp_logits:ne}){super(),this.char_logits=P,this.bpe_logits=D,this.wp_logits=ne}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Wh extends R{}class Gh extends Wh{async _call(P){return new Uh(await super._call(P))}}class gl extends R{}class Kh extends gl{}class Hh extends gl{}class wl extends R{}class qh extends wl{}class Xh extends wl{}class Qh extends R{constructor(){super(...arguments);te(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class Jh extends Qh{_merge_input_ids_with_audio_features(P){const D=P.audio_features.dims.at(-1),ne=P.audio_features.view(-1,D);return F({audio_token_id:this.config.ignore_index,...P,audio_features:ne})}}class Ri extends R{constructor(){super(...arguments);te(this,"main_input_name","input_values");te(this,"forward_params",["input_values"])}}class Yh extends pe{constructor({audio_codes:P}){super(),this.audio_codes=P}}class Zh extends pe{constructor({audio_values:P}){super(),this.audio_values=P}}class em extends Ri{async encode(P){return new Yh(await G(this.sessions.encoder_model,P))}async decode(P){return new Zh(await G(this.sessions.decoder_model,P))}}class tm extends Ri{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class rm extends Ri{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class ji extends R{constructor(){super(...arguments);te(this,"main_input_name","input_values");te(this,"forward_params",["input_values"])}}class sm extends pe{constructor({audio_codes:P}){super(),this.audio_codes=P}}class nm extends pe{constructor({audio_values:P}){super(),this.audio_values=P}}class om extends ji{async encode(P){return new sm(await G(this.sessions.encoder_model,P))}async decode(P){return new nm(await G(this.sessions.decoder_model,P))}}class im extends ji{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class am extends ji{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class Ni extends R{constructor(){super(...arguments);te(this,"main_input_name","input_values");te(this,"forward_params",["input_values"])}}class lm extends Ni{async encode(P){return await G(this.sessions.encoder_model,P)}async decode(P){return await G(this.sessions.decoder_model,P)}}class um extends Ni{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class dm extends Ni{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class Pt{static async from_pretrained(P,{progress_callback:D=null,config:ne=null,cache_dir:ge=null,local_files_only:_e=!1,revision:Ce="main",model_file_name:Le=null,subfolder:Ne="onnx",device:qe=null,dtype:it=null,use_external_data_format:pt=null,session_options:ot={}}={}){const bt={progress_callback:D,config:ne,cache_dir:ge,local_files_only:_e,revision:Ce,model_file_name:Le,subfolder:Ne,device:qe,dtype:it,use_external_data_format:pt,session_options:ot};if(bt.config=await s.AutoConfig.from_pretrained(P,bt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const ct=bt.config.model_type;for(const gt of this.MODEL_CLASS_MAPPINGS){let tt=gt.get(ct);if(!tt){for(const yt of gt.values())if(yt[0]===ct){tt=yt;break}if(!tt)continue}return await tt[1].from_pretrained(P,bt)}if(this.BASE_IF_FAIL)return Lm.has(ct)||console.warn(`Unknown model class "${ct}", attempting to construct from base class.`),await R.from_pretrained(P,bt);throw Error(`Unsupported model type: ${ct}`)}}te(Pt,"MODEL_CLASS_MAPPINGS",null),te(Pt,"BASE_IF_FAIL",!1);const X0=new Map([["bert",["BertModel",Se]],["modernbert",["ModernBertModel",Y]],["nomic_bert",["NomicBertModel",Ee]],["roformer",["RoFormerModel",Ie]],["electra",["ElectraModel",Ds]],["esm",["EsmModel",zs]],["convbert",["ConvBertModel",Gt]],["camembert",["CamembertModel",ws]],["deberta",["DebertaModel",De]],["deberta-v2",["DebertaV2Model",rs]],["mpnet",["MPNetModel",tn]],["albert",["AlbertModel",dn]],["distilbert",["DistilBertModel",yr]],["roberta",["RobertaModel",zr]],["xlm",["XLMModel",Rs]],["xlm-roberta",["XLMRobertaModel",si]],["clap",["ClapModel",gh]],["clip",["CLIPModel",bi]],["clipseg",["CLIPSegModel",yo]],["chinese_clip",["ChineseCLIPModel",xi]],["siglip",["SiglipModel",hn]],["jina_clip",["JinaCLIPModel",Nn]],["mobilebert",["MobileBertModel",xr]],["squeezebert",["SqueezeBertModel",an]],["wav2vec2",["Wav2Vec2Model",Ap]],["wav2vec2-bert",["Wav2Vec2BertModel",Hp]],["unispeech",["UniSpeechModel",jp]],["unispeech-sat",["UniSpeechSatModel",Up]],["hubert",["HubertModel",Qp]],["wavlm",["WavLMModel",Zp]],["audio-spectrogram-transformer",["ASTModel",li]],["vits",["VitsModel",pl]],["pyannote",["PyAnnoteModel",Lp]],["wespeaker-resnet",["WeSpeakerResNetModel",Rp]],["detr",["DetrModel",vc]],["rt_detr",["RTDetrModel",Ec]],["rt_detr_v2",["RTDetrV2Model",Cc]],["rf_detr",["RFDetrModel",kc]],["table-transformer",["TableTransformerModel",Fc]],["vit",["ViTModel",qd]],["ijepa",["IJepaModel",Qd]],["pvt",["PvtModel",ec]],["vit_msn",["ViTMSNModel",nc]],["vit_mae",["ViTMAEModel",sc]],["groupvit",["GroupViTModel",ac]],["fastvit",["FastViTModel",lc]],["mobilevit",["MobileViTModel",pc]],["mobilevitv2",["MobileViTV2Model",mc]],["owlvit",["OwlViTModel",_c]],["owlv2",["Owlv2Model",wc]],["beit",["BeitModel",Mc]],["deit",["DeiTModel",Lc]],["hiera",["HieraModel",Bc]],["convnext",["ConvNextModel",pp]],["convnextv2",["ConvNextV2Model",mp]],["dinov2",["Dinov2Model",_p]],["dinov2_with_registers",["Dinov2WithRegistersModel",wp]],["resnet",["ResNetModel",jc]],["swin",["SwinModel",Vc]],["swin2sr",["Swin2SRModel",Gc]],["donut-swin",["DonutSwinModel",cp]],["yolos",["YolosModel",vp]],["dpt",["DPTModel",Hc]],["glpn",["GLPNModel",lp]],["hifigan",["SpeechT5HifiGan",lh]],["efficientnet",["EfficientNetModel",Eh]],["decision_transformer",["DecisionTransformerModel",jh]],["patchtst",["PatchTSTForPrediction",Kh]],["patchtsmixer",["PatchTSMixerForPrediction",qh]],["mobilenet_v1",["MobileNetV1Model",Ch]],["mobilenet_v2",["MobileNetV2Model",kh]],["mobilenet_v3",["MobileNetV3Model",Fh]],["mobilenet_v4",["MobileNetV4Model",Lh]],["maskformer",["MaskFormerModel",ip]],["mgp-str",["MgpstrForSceneTextRecognition",Gh]],["style_text_to_speech_2",["StyleTextToSpeech2Model",oh]]]),Q0=new Map([["t5",["T5Model",ie]],["longt5",["LongT5Model",je]],["mt5",["MT5Model",Je]],["bart",["BartModel",Et]],["mbart",["MBartModel",Mr]],["marian",["MarianModel",Sp]],["whisper",["WhisperModel",di]],["m2m_100",["M2M100Model",kp]],["blenderbot",["BlenderbotModel",Dt]],["blenderbot-small",["BlenderbotSmallModel",Hr]]]),J0=new Map([["mimi",["MimiModel",em]],["dac",["DacModel",om]],["snac",["SnacModel",lm]]]),Y0=new Map([["bloom",["BloomModel",Vd]],["jais",["JAISModel",mn]],["gpt2",["GPT2Model",Ti]],["gptj",["GPTJModel",Co]],["gpt_bigcode",["GPTBigCodeModel",Kn]],["gpt_neo",["GPTNeoModel",Eo]],["gpt_neox",["GPTNeoXModel",Br]],["codegen",["CodeGenModel",ko]],["llama",["LlamaModel",qn]],["exaone",["ExaoneModel",I]],["olmo",["OlmoModel",Ke]],["olmo2",["Olmo2Model",xt]],["mobilellm",["MobileLLMModel",ue]],["granite",["GraniteModel",$s]],["cohere",["CohereModel",Td]],["gemma",["GemmaModel",Pd]],["gemma2",["Gemma2Model",Sd]],["gemma3_text",["Gemma3Model",kd]],["helium",["HeliumModel",Ao]],["glm",["GlmModel",Oo]],["openelm",["OpenELMModel",Ad]],["qwen2",["Qwen2Model",Od]],["phi",["PhiModel",Bd]],["phi3",["Phi3Model",jd]],["mpt",["MptModel",Wd]],["opt",["OPTModel",Kd]],["mistral",["MistralModel",ch]],["starcoder2",["Starcoder2Model",hh]],["falcon",["FalconModel",fh]],["stablelm",["StableLmModel",xh]]]),bl=new Map([["speecht5",["SpeechT5ForSpeechToText",ih]],["whisper",["WhisperForConditionalGeneration",co]],["lite-whisper",["LiteWhisperForConditionalGeneration",ci]],["moonshine",["MoonshineForConditionalGeneration",po]]]),cm=new Map([["speecht5",["SpeechT5ForTextToSpeech",ah]]]),pm=new Map([["vits",["VitsModel",pl]],["musicgen",["MusicgenForConditionalGeneration",_l]]]),hm=new Map([["bert",["BertForSequenceClassification",Fe]],["modernbert",["ModernBertForSequenceClassification",J]],["roformer",["RoFormerForSequenceClassification",Xe]],["electra",["ElectraForSequenceClassification",Ls]],["esm",["EsmForSequenceClassification",Ar]],["convbert",["ConvBertForSequenceClassification",lr]],["camembert",["CamembertForSequenceClassification",es]],["deberta",["DebertaForSequenceClassification",et]],["deberta-v2",["DebertaV2ForSequenceClassification",Ur]],["mpnet",["MPNetForSequenceClassification",sn]],["albert",["AlbertForSequenceClassification",he]],["distilbert",["DistilBertForSequenceClassification",Ys]],["roberta",["RobertaForSequenceClassification",Vt]],["xlm",["XLMForSequenceClassification",ei]],["xlm-roberta",["XLMRobertaForSequenceClassification",oi]],["bart",["BartForSequenceClassification",kt]],["mbart",["MBartForSequenceClassification",cr]],["mobilebert",["MobileBertForSequenceClassification",ur]],["squeezebert",["SqueezeBertForSequenceClassification",ln]]]),mm=new Map([["bert",["BertForTokenClassification",ze]],["modernbert",["ModernBertForTokenClassification",le]],["roformer",["RoFormerForTokenClassification",Ge]],["electra",["ElectraForTokenClassification",at]],["esm",["EsmForTokenClassification",en]],["convbert",["ConvBertForTokenClassification",Yr]],["camembert",["CamembertForTokenClassification",ts]],["deberta",["DebertaForTokenClassification",Bt]],["deberta-v2",["DebertaV2ForTokenClassification",ns]],["mpnet",["MPNetForTokenClassification",nn]],["distilbert",["DistilBertForTokenClassification",vr]],["roberta",["RobertaForTokenClassification",Zt]],["xlm",["XLMForTokenClassification",ti]],["xlm-roberta",["XLMRobertaForTokenClassification",ii]]]),Ml=new Map([["t5",["T5ForConditionalGeneration",de]],["longt5",["LongT5ForConditionalGeneration",He]],["mt5",["MT5ForConditionalGeneration",dt]],["bart",["BartForConditionalGeneration",Rt]],["mbart",["MBartForConditionalGeneration",dr]],["marian",["MarianMTModel",$p]],["m2m_100",["M2M100ForConditionalGeneration",Ip]],["blenderbot",["BlenderbotForConditionalGeneration",rr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Lr]]]),yl=new Map([["bloom",["BloomForCausalLM",Ud]],["gpt2",["GPT2LMHeadModel",xo]],["jais",["JAISLMHeadModel",nt]],["gptj",["GPTJForCausalLM",So]],["gpt_bigcode",["GPTBigCodeForCausalLM",$o]],["gpt_neo",["GPTNeoForCausalLM",Po]],["gpt_neox",["GPTNeoXForCausalLM",fn]],["codegen",["CodeGenForCausalLM",gn]],["llama",["LlamaForCausalLM",Io]],["exaone",["ExaoneForCausalLM",L]],["olmo",["OlmoForCausalLM",Ye]],["olmo2",["Olmo2ForCausalLM",It]],["mobilellm",["MobileLLMForCausalLM",Te]],["granite",["GraniteForCausalLM",Ei]],["cohere",["CohereForCausalLM",Ed]],["gemma",["GemmaForCausalLM",Cd]],["gemma2",["Gemma2ForCausalLM",$d]],["gemma3_text",["Gemma3ForCausalLM",Id]],["helium",["HeliumForCausalLM",Fo]],["glm",["GlmForCausalLM",h]],["openelm",["OpenELMForCausalLM",Fd]],["qwen2",["Qwen2ForCausalLM",Dd]],["phi",["PhiForCausalLM",Rd]],["phi3",["Phi3ForCausalLM",Nd]],["mpt",["MptForCausalLM",Gd]],["opt",["OPTForCausalLM",Hd]],["mbart",["MBartForCausalLM",Nt]],["mistral",["MistralForCausalLM",ph]],["starcoder2",["Starcoder2ForCausalLM",mh]],["falcon",["FalconForCausalLM",_h]],["trocr",["TrOCRForCausalLM",dh]],["stablelm",["StableLmForCausalLM",Th]],["phi3_v",["Phi3VForCausalLM",_o]]]),Z0=new Map([["multi_modality",["MultiModalityCausalLM",Vh]]]),fm=new Map([["bert",["BertForMaskedLM",Ae]],["modernbert",["ModernBertForMaskedLM",z]],["roformer",["RoFormerForMaskedLM",Be]],["electra",["ElectraForMaskedLM",xs]],["esm",["EsmForMaskedLM",Zs]],["convbert",["ConvBertForMaskedLM",Ot]],["camembert",["CamembertForMaskedLM",Ft]],["deberta",["DebertaForMaskedLM",Qe]],["deberta-v2",["DebertaV2ForMaskedLM",ss]],["mpnet",["MPNetForMaskedLM",rn]],["albert",["AlbertForMaskedLM",N]],["distilbert",["DistilBertForMaskedLM",Es]],["roberta",["RobertaForMaskedLM",or]],["xlm",["XLMWithLMHeadModel",cn]],["xlm-roberta",["XLMRobertaForMaskedLM",ni]],["mobilebert",["MobileBertForMaskedLM",Ps]],["squeezebert",["SqueezeBertForMaskedLM",Bs]]]),_m=new Map([["bert",["BertForQuestionAnswering",Ve]],["roformer",["RoFormerForQuestionAnswering",lt]],["electra",["ElectraForQuestionAnswering",Zr]],["convbert",["ConvBertForQuestionAnswering",gs]],["camembert",["CamembertForQuestionAnswering",bs]],["deberta",["DebertaForQuestionAnswering",Or]],["deberta-v2",["DebertaV2ForQuestionAnswering",os]],["mpnet",["MPNetForQuestionAnswering",on]],["albert",["AlbertForQuestionAnswering",k]],["distilbert",["DistilBertForQuestionAnswering",Ts]],["roberta",["RobertaForQuestionAnswering",er]],["xlm",["XLMForQuestionAnswering",ri]],["xlm-roberta",["XLMRobertaForQuestionAnswering",ai]],["mobilebert",["MobileBertForQuestionAnswering",_r]],["squeezebert",["SqueezeBertForQuestionAnswering",un]]]),vl=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ho]],["idefics3",["Idefics3ForConditionalGeneration",Ns]],["smolvlm",["SmolVLMForConditionalGeneration",jn]]]),gm=new Map([["llava",["LlavaForConditionalGeneration",pn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",mo]],["moondream1",["Moondream1ForConditionalGeneration",js]],["florence2",["Florence2ForConditionalGeneration",fo]],["qwen2-vl",["Qwen2VLForConditionalGeneration",zd]],["idefics3",["Idefics3ForConditionalGeneration",Ns]],["smolvlm",["SmolVLMForConditionalGeneration",jn]],["paligemma",["PaliGemmaForConditionalGeneration",_i]]]),wm=new Map([["ultravox",["UltravoxModel",Jh]]]),ev=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ho]]]),bm=new Map([["vit",["ViTForImageClassification",Xd]],["ijepa",["IJepaForImageClassification",Jd]],["pvt",["PvtForImageClassification",tc]],["vit_msn",["ViTMSNForImageClassification",oc]],["fastvit",["FastViTForImageClassification",uc]],["mobilevit",["MobileViTForImageClassification",hc]],["mobilevitv2",["MobileViTV2ForImageClassification",fc]],["beit",["BeitForImageClassification",yc]],["deit",["DeiTForImageClassification",zc]],["hiera",["HieraForImageClassification",Rc]],["convnext",["ConvNextForImageClassification",hp]],["convnextv2",["ConvNextV2ForImageClassification",fp]],["dinov2",["Dinov2ForImageClassification",gp]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",bp]],["resnet",["ResNetForImageClassification",Nc]],["swin",["SwinForImageClassification",Uc]],["segformer",["SegformerForImageClassification",yh]],["efficientnet",["EfficientNetForImageClassification",Ph]],["mobilenet_v1",["MobileNetV1ForImageClassification",Sh]],["mobilenet_v2",["MobileNetV2ForImageClassification",Ih]],["mobilenet_v3",["MobileNetV3ForImageClassification",Oh]],["mobilenet_v4",["MobileNetV4ForImageClassification",zh]]]),Mm=new Map([["detr",["DetrForObjectDetection",xc]],["rt_detr",["RTDetrForObjectDetection",Pc]],["rt_detr_v2",["RTDetrV2ForObjectDetection",Sc]],["rf_detr",["RFDetrForObjectDetection",Ic]],["table-transformer",["TableTransformerForObjectDetection",Oc]],["yolos",["YolosForObjectDetection",xp]]]),ym=new Map([["owlvit",["OwlViTForObjectDetection",gc]],["owlv2",["Owlv2ForObjectDetection",bc]],["grounding-dino",["GroundingDinoForObjectDetection",yp]]]),Yn=new Map([["detr",["DetrForSegmentation",Va]],["clipseg",["CLIPSegForImageSegmentation",vo]]]),vm=new Map([["segformer",["SegformerForSemanticSegmentation",vh]],["sapiens",["SapiensForSemanticSegmentation",Jc]],["swin",["SwinForSemanticSegmentation",Wc]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",$h]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",Ah]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Dh]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Bh]]]),xm=new Map([["detr",["DetrForSegmentation",Va]],["maskformer",["MaskFormerForInstanceSegmentation",ap]]]),Tm=new Map([["sam",["SamModel",Pp]]]),Em=new Map([["wav2vec2",["Wav2Vec2ForCTC",Fp]],["wav2vec2-bert",["Wav2Vec2BertForCTC",qp]],["unispeech",["UniSpeechForCTC",Np]],["unispeech-sat",["UniSpeechSatForCTC",Wp]],["wavlm",["WavLMForCTC",eh]],["hubert",["HubertForCTC",Jp]]]),Pm=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Op]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Xp]],["unispeech",["UniSpeechForSequenceClassification",Vp]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Gp]],["wavlm",["WavLMForSequenceClassification",th]],["hubert",["HubertForSequenceClassification",Yp]],["audio-spectrogram-transformer",["ASTForAudioClassification",ui]]]),Cm=new Map([["wavlm",["WavLMForXVector",rh]]]),Sm=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Kp]],["wavlm",["WavLMForAudioFrameClassification",sh]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Dp]],["pyannote",["PyAnnoteForAudioFrameClassification",zp]]]),$m=new Map([["vitmatte",["VitMatteForImageMatting",cc]]]),tv=new Map([["patchtst",["PatchTSTForPrediction",Hh]],["patchtsmixer",["PatchTSMixerForPrediction",Xh]]]),km=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Kc]]]),Im=new Map([["dpt",["DPTForDepthEstimation",qc]],["depth_anything",["DepthAnythingForDepthEstimation",Qc]],["glpn",["GLPNForDepthEstimation",up]],["sapiens",["SapiensForDepthEstimation",Yc]],["depth_pro",["DepthProForDepthEstimation",tp]],["metric3d",["Metric3DForDepthEstimation",sp]],["metric3dv2",["Metric3Dv2ForDepthEstimation",op]]]),Am=new Map([["sapiens",["SapiensForNormalEstimation",Zc]]]),Fm=new Map([["vitpose",["VitPoseForPoseEstimation",Zd]]]),Om=new Map([["clip",["CLIPVisionModelWithProjection",yi]],["siglip",["SiglipVisionModel",wo]],["jina_clip",["JinaCLIPVisionModel",Mo]]]),Dm=[[X0,E.EncoderOnly],[Q0,E.EncoderDecoder],[Y0,E.DecoderOnly],[J0,E.AutoEncoder],[hm,E.EncoderOnly],[mm,E.EncoderOnly],[Ml,E.Seq2Seq],[bl,E.Seq2Seq],[yl,E.DecoderOnly],[Z0,E.MultiModality],[fm,E.EncoderOnly],[_m,E.EncoderOnly],[vl,E.Vision2Seq],[gm,E.ImageTextToText],[wm,E.AudioTextToText],[bm,E.EncoderOnly],[Yn,E.EncoderOnly],[xm,E.EncoderOnly],[vm,E.EncoderOnly],[$m,E.EncoderOnly],[tv,E.EncoderOnly],[km,E.EncoderOnly],[Im,E.EncoderOnly],[Am,E.EncoderOnly],[Fm,E.EncoderOnly],[Mm,E.EncoderOnly],[ym,E.EncoderOnly],[Tm,E.MaskGeneration],[Em,E.EncoderOnly],[Pm,E.EncoderOnly],[cm,E.Seq2Seq],[pm,E.EncoderOnly],[Cm,E.EncoderOnly],[Sm,E.EncoderOnly],[Om,E.EncoderOnly]];for(const[M,P]of Dm)for(const[D,ne]of M.values())y.set(D,P),x.set(ne,D),b.set(D,ne);const rv=[["MusicgenForConditionalGeneration",_l,E.Musicgen],["Phi3VForCausalLM",_o,E.Phi3V],["CLIPTextModelWithProjection",Mi,E.EncoderOnly],["SiglipTextModel",Vs,E.EncoderOnly],["JinaCLIPTextModel",bo,E.EncoderOnly],["ClapTextModelWithProjection",wh,E.EncoderOnly],["ClapAudioModelWithProjection",bh,E.EncoderOnly],["DacEncoderModel",im,E.EncoderOnly],["DacDecoderModel",am,E.EncoderOnly],["MimiEncoderModel",tm,E.EncoderOnly],["MimiDecoderModel",rm,E.EncoderOnly],["SnacEncoderModel",um,E.EncoderOnly],["SnacDecoderModel",dm,E.EncoderOnly]];for(const[M,P,D]of rv)y.set(M,D),x.set(P,M),b.set(M,P);const Lm=new Map([["modnet",Yn],["birefnet",Yn],["isnet",Yn],["ben",Yn]]);for(const[M,P]of Lm.entries())P.set(M,["PreTrainedModel",R]),y.set(M,E.EncoderOnly),x.set(R,M),b.set(M,R);class xl extends Pt{}te(xl,"MODEL_CLASS_MAPPINGS",Dm.map(P=>P[0])),te(xl,"BASE_IF_FAIL",!0);class zm extends Pt{}te(zm,"MODEL_CLASS_MAPPINGS",[hm]);class Bm extends Pt{}te(Bm,"MODEL_CLASS_MAPPINGS",[mm]);class Rm extends Pt{}te(Rm,"MODEL_CLASS_MAPPINGS",[Ml]);class jm extends Pt{}te(jm,"MODEL_CLASS_MAPPINGS",[bl]);class Nm extends Pt{}te(Nm,"MODEL_CLASS_MAPPINGS",[cm]);class Vm extends Pt{}te(Vm,"MODEL_CLASS_MAPPINGS",[pm]);class Um extends Pt{}te(Um,"MODEL_CLASS_MAPPINGS",[yl]);class Wm extends Pt{}te(Wm,"MODEL_CLASS_MAPPINGS",[fm]);class Gm extends Pt{}te(Gm,"MODEL_CLASS_MAPPINGS",[_m]);class Km extends Pt{}te(Km,"MODEL_CLASS_MAPPINGS",[vl]);class Hm extends Pt{}te(Hm,"MODEL_CLASS_MAPPINGS",[bm]);class qm extends Pt{}te(qm,"MODEL_CLASS_MAPPINGS",[Yn]);class Xm extends Pt{}te(Xm,"MODEL_CLASS_MAPPINGS",[vm]);class Qm extends Pt{}te(Qm,"MODEL_CLASS_MAPPINGS",[xm]);class Jm extends Pt{}te(Jm,"MODEL_CLASS_MAPPINGS",[Mm]);class Ym extends Pt{}te(Ym,"MODEL_CLASS_MAPPINGS",[ym]);class Zm extends Pt{}te(Zm,"MODEL_CLASS_MAPPINGS",[Tm]);class ef extends Pt{}te(ef,"MODEL_CLASS_MAPPINGS",[Em]);class tf extends Pt{}te(tf,"MODEL_CLASS_MAPPINGS",[Pm]);class rf extends Pt{}te(rf,"MODEL_CLASS_MAPPINGS",[Cm]);class sf extends Pt{}te(sf,"MODEL_CLASS_MAPPINGS",[Sm]);class nf extends Pt{}te(nf,"MODEL_CLASS_MAPPINGS",[ev]);class of extends Pt{}te(of,"MODEL_CLASS_MAPPINGS",[$m]);class af extends Pt{}te(af,"MODEL_CLASS_MAPPINGS",[km]);class lf extends Pt{}te(lf,"MODEL_CLASS_MAPPINGS",[Im]);class uf extends Pt{}te(uf,"MODEL_CLASS_MAPPINGS",[Am]);class df extends Pt{}te(df,"MODEL_CLASS_MAPPINGS",[Fm]);class cf extends Pt{}te(cf,"MODEL_CLASS_MAPPINGS",[Om]);class pf extends Pt{}te(pf,"MODEL_CLASS_MAPPINGS",[gm]);class hf extends Pt{}te(hf,"MODEL_CLASS_MAPPINGS",[wm]);class sv extends pe{constructor({logits:P,past_key_values:D,encoder_outputs:ne,decoder_attentions:ge=null,cross_attentions:_e=null}){super(),this.logits=P,this.past_key_values=D,this.encoder_outputs=ne,this.decoder_attentions=ge,this.cross_attentions=_e}}class mt extends pe{constructor({logits:P,...D}){super(),this.logits=P;const ne=Object.values(D);ne.length>0&&(this.attentions=ne)}}class mf extends pe{constructor({logits:P,embeddings:D}){super(),this.logits=P,this.embeddings=D}}class pr extends pe{constructor({logits:P}){super(),this.logits=P}}class wr extends pe{constructor({logits:P}){super(),this.logits=P}}class Tr extends pe{constructor({start_logits:P,end_logits:D}){super(),this.start_logits=P,this.end_logits=D}}class bn extends pe{constructor({logits:P}){super(),this.logits=P}}class nv extends pe{constructor({logits:P,past_key_values:D}){super(),this.logits=P,this.past_key_values=D}}class ff extends pe{constructor({alphas:P}){super(),this.alphas=P}}class _f extends pe{constructor({waveform:P,spectrogram:D}){super(),this.waveform=P,this.spectrogram=D}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,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 u=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,u={}){const p=await(0,o.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,u),d=p.feature_extractor_type,c=n[d];if(!c)throw new Error(`Unknown feature_extractor_type: '${d}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new c(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(u,p={}){const d=await(0,o.getModelJSON)(u,s.IMAGE_PROCESSOR_NAME,!0,p),c=d.image_processor_type??d.feature_extractor_type;let _=i[c];return _||(c!==void 0&&console.warn(`Image processor type '${c}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),_=n.ImageProcessor),new _(d)}}},"./src/models/auto/processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>u});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 u{static async from_pretrained(d,c={}){const _=await(0,o.getModelJSON)(d,s.IMAGE_PROCESSOR_NAME,!0,c),{image_processor_type:f,feature_extractor_type:v,processor_class:$}=_;if($&&i[$])return i[$].from_pretrained(d,c);if(!f&&!v)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const w={};if(f){const C=a[f];if(!C)throw new Error(`Unknown image_processor_type: '${f}'.`);w.image_processor=new C(_)}if(v){const C=a[v];if(C)w.image_processor=new C(_);else{const E=l[v];if(!E)throw new Error(`Unknown feature_extractor_type: '${v}'.`);w.feature_extractor=new E(_)}}const g={};return new n.Processor(g,w)}}},"./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,u,p){let d;const c=a.length-l;if(c>0)if(u==="rand_trunc"){const _=Math.floor(Math.random()*(c+1));a=a.subarray(_,_+l),d=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${u}" not implemented`);else{if(c<0){let _=new Float64Array(l);if(_.set(a),p==="repeat")for(let f=a.length;f{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 u;const l=(u=this.size)==null?void 0:u.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,c]=this.get_resize_output_image_size(a,{shortest_edge:p});a=await a.resize(d,c,{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 u=await super._call(l),p=[u.pixel_values.dims[0],64,64],d=(0,o.full)(p,1n);return{...u,pixel_mask:d}}post_process_object_detection(...l){return(0,s.post_process_object_detection)(...l)}post_process_panoptic_segmentation(...l){return(0,s.post_process_panoptic_segmentation)(...l)}post_process_instance_segmentation(...l){return(0,s.post_process_instance_segmentation)(...l)}}class i extends n{}},"./src/models/donut/image_processing_donut.js":(e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>n,DonutImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(a,l,u,p={}){const[d,c,_]=l;let f=this.image_mean;Array.isArray(this.image_mean)||(f=new Array(_).fill(f));let v=this.image_std;Array.isArray(v)||(v=new Array(_).fill(f));const $=f.map((w,g)=>-w/v[g]);return super.pad_image(a,l,u,{center:!0,constant_values:$,...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 u=[1,l,a.length/l];return{input_values:new o.Tensor("float32",a,u)}}}},"./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,ImageFeatureExtractor:()=>v.ImageProcessor,MoonshineFeatureExtractor:()=>a.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>l.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>u.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>p.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>c.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>_.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>f.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/moonshine/feature_extraction_moonshine.js"),l=t("./src/models/pyannote/feature_extraction_pyannote.js"),u=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),p=t("./src/models/snac/feature_extraction_snac.js"),d=t("./src/models/speecht5/feature_extraction_speecht5.js"),c=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),_=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),f=t("./src/models/whisper/feature_extraction_whisper.js"),v=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,u){super(l,u);const{tasks_answer_post_processing_type:p,task_prompts_without_inputs:d,task_prompts_with_input:c}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(p??{})),this.task_prompts_without_inputs=new Map(Object.entries(d??{})),this.task_prompts_with_input=new Map(Object.entries(c??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const u=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))u.push(this.task_prompts_without_inputs.get(p));else{for(const[d,c]of this.task_prompts_with_input)if(p.includes(d)){u.push(c.replaceAll("{input}",p).replaceAll(d,""));break}u.length!==l.length&&u.push(p)}return u}post_process_generation(l,u,p){const d=this.tasks_answer_post_processing_type.get(u)??"pure_text";l=l.replaceAll("","").replaceAll("","");let c;switch(d){case"pure_text":c=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const _=d==="ocr"?"quad_boxes":"bboxes",f=l.matchAll(this.regexes[_]),v=[],$=[];for(const[w,g,...C]of f)v.push(g?g.trim():v.at(-1)??""),$.push(C.map((E,y)=>(Number(E)+.5)/this.size_per_bin*p[y%2]));c={labels:v,[_]:$};break;default:throw new Error(`Task "${u}" (of type "${d}") not yet implemented.`)}return{[u]:c}}async _call(l,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const d=await this.image_processor(l,p),c=u?this.tokenizer(u,p):{};return{...d,...c}}}te(i,"tokenizer_class",n.AutoTokenizer),te(i,"image_processor_class",o.AutoImageProcessor)},"./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),u=l.pixel_values.dims,p=(0,o.ones)([u[0],u[2],u[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(u,p){const c=u.dims.at(-1)-1,_=u.tolist();_.fill(!1,0,1),_.fill(!1,c);const f=p.tolist();return _.map((v,$)=>v?$:null).filter(v=>v!==null).map(v=>f[v])}class l extends s.Processor{async _call(p,d,c={}){const _=p?await this.image_processor(p,c):{};return{...d?this.tokenizer(d,c):{},..._}}post_process_grounded_object_detection(p,d,{box_threshold:c=.25,text_threshold:_=.25,target_sizes:f=null}={}){const{logits:v,pred_boxes:$}=p,w=v.dims[0];if(f!==null&&f.length!==w)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const g=v.dims.at(1),C=v.sigmoid(),E=C.max(-1).tolist(),y=$.tolist().map(x=>x.map(S=>(0,i.center_to_corners_format)(S))),b=[];for(let x=0;xj.map((ee,H)=>ee*S[(H+1)%2])));const A=E[x],B=[],K=[],G=[];for(let j=0;j{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[u,p]=a.dims.slice(-2);const d=p/u;return p>=u?(p=Math.ceil(p/l)*l,u=Math.floor(p/d),u=Math.ceil(u/l)*l):(u=Math.ceil(u/l)*l,p=Math.floor(u*d),p=Math.ceil(p/l)*l),{height:u,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:u=!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=[],c=[],_=[];const f=[],v=[];for(const x of p){let S=await Promise.all(x.map(K=>this.preprocess(K)));f.push(...S.map(K=>K.original_size)),v.push(...S.map(K=>K.reshaped_input_size)),S.forEach(K=>K.pixel_values.unsqueeze_(0));const{longest_edge:A}=this.max_image_size;let B;if(l??this.do_image_splitting){let K=new Array(S.length),G=new Array(S.length);B=await Promise.all(S.map(async(j,ee)=>{const H=this.get_resize_for_vision_encoder(j.pixel_values,A),Z=await(0,o.interpolate_4d)(j.pixel_values,{size:[H.height,H.width]}),{frames:X,num_splits_h:oe,num_splits_w:me}=await this.split_image(Z,this.max_image_size);return K[ee]=oe,G[ee]=me,(0,o.cat)(X,0)})),c.push(K),_.push(G)}else{const K=[A,A];B=await Promise.all(S.map(G=>(0,o.interpolate_4d)(G.pixel_values,{size:K}))),c.push(new Array(S.length).fill(0)),_.push(new Array(S.length).fill(0))}d.push((0,o.cat)(B,0))}const $=d.length,[w,g,C,E]=d[0].dims;let y,b;if($===1)y=d[0].unsqueeze_(0),b=(0,o.full)([$,w,C,E],!0);else{const x=Math.max(...d.map(B=>B.dims.at(0)));b=(0,o.full)([$,x,C,E],!0);const S=b.data,A=x*C*E;for(let B=0;B<$;++B){const K=d[B].dims[0];if(Ku||_>p){f=Math.ceil(c/u),v=Math.ceil(_/p);const $=Math.ceil(c/f),w=Math.ceil(_/v);for(let E=0;E{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,c,_,f,v,$){let w="";for(let g=0;g`+v.repeat(d);w+=` +`}return w+=` +${f}${$}`+v.repeat(d)+`${f}`,w}function l(d,c,_,f){return`${c}${f}`+_.repeat(d)+`${c}`}function u(d,c,_,f,v,$){return d===0&&c===0?l(_,f,v,$):a(_,d,c,f,v,$)}class p extends s.Processor{constructor(){super(...arguments);te(this,"fake_image_token","");te(this,"image_token","");te(this,"global_img_token","")}async _call(_,f=null,v={}){v.return_row_col_info??(v.return_row_col_info=!0);let $;f&&($=await this.image_processor(f,v)),Array.isArray(_)||(_=[_]);const w=$.rows??[new Array(_.length).fill(0)],g=$.cols??[new Array(_.length).fill(0)],C=this.config.image_seq_len,E=[],y=[];for(let x=0;x<_.length;++x){const S=_[x],A=w[x],B=g[x];E.push((0,i.count)(S,this.image_token));const K=A.map((ee,H)=>u(ee,B[H],C,this.fake_image_token,this.image_token,this.global_img_token)),G=S.split(this.image_token);if(G.length===0)throw new Error("The image token should be present in the text.");let j=G[0];for(let ee=0;ee{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>o.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>n.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>d.DPTFeatureExtractor,DPTImageProcessor:()=>d.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>u.DetrFeatureExtractor,DetrImageProcessor:()=>u.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>c.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>f.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>v.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>w.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>g.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>C.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>E.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>E.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>y.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>y.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>b.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>b.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>x.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>x.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>S.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>S.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>A.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>A.MobileViTImageProcessor,NougatImageProcessor:()=>B.NougatImageProcessor,OwlViTFeatureExtractor:()=>G.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>G.OwlViTImageProcessor,Owlv2ImageProcessor:()=>K.Owlv2ImageProcessor,Phi3VImageProcessor:()=>j.Phi3VImageProcessor,PvtImageProcessor:()=>ee.PvtImageProcessor,Qwen2VLImageProcessor:()=>H.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Z.RTDetrImageProcessor,SamImageProcessor:()=>X.SamImageProcessor,SegformerFeatureExtractor:()=>oe.SegformerFeatureExtractor,SegformerImageProcessor:()=>oe.SegformerImageProcessor,SiglipImageProcessor:()=>me.SiglipImageProcessor,SmolVLMImageProcessor:()=>ae.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>V.Swin2SRImageProcessor,VLMImageProcessor:()=>$.VLMImageProcessor,ViTFeatureExtractor:()=>F.ViTFeatureExtractor,ViTImageProcessor:()=>F.ViTImageProcessor,VitMatteImageProcessor:()=>W.VitMatteImageProcessor,VitPoseImageProcessor:()=>re.VitPoseImageProcessor,YolosFeatureExtractor:()=>fe.YolosFeatureExtractor,YolosImageProcessor:()=>fe.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"),u=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/donut/image_processing_donut.js"),d=t("./src/models/dpt/image_processing_dpt.js"),c=t("./src/models/efficientnet/image_processing_efficientnet.js"),_=t("./src/models/glpn/image_processing_glpn.js"),f=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),v=t("./src/models/idefics3/image_processing_idefics3.js"),$=t("./src/models/janus/image_processing_janus.js"),w=t("./src/models/jina_clip/image_processing_jina_clip.js"),g=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),C=t("./src/models/mask2former/image_processing_mask2former.js"),E=t("./src/models/maskformer/image_processing_maskformer.js"),y=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),b=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),x=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),S=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),A=t("./src/models/mobilevit/image_processing_mobilevit.js"),B=t("./src/models/nougat/image_processing_nougat.js"),K=t("./src/models/owlv2/image_processing_owlv2.js"),G=t("./src/models/owlvit/image_processing_owlvit.js"),j=t("./src/models/phi3_v/image_processing_phi3_v.js"),ee=t("./src/models/pvt/image_processing_pvt.js"),H=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Z=t("./src/models/rt_detr/image_processing_rt_detr.js"),X=t("./src/models/sam/image_processing_sam.js"),oe=t("./src/models/segformer/image_processing_segformer.js"),me=t("./src/models/siglip/image_processing_siglip.js"),ae=t("./src/models/smolvlm/image_processing_smolvlm.js"),V=t("./src/models/swin2sr/image_processing_swin2sr.js"),F=t("./src/models/vit/image_processing_vit.js"),W=t("./src/models/vitmatte/image_processing_vitmatte.js"),re=t("./src/models/vitpose/image_processing_vitpose.js"),fe=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,u){return super.pad_image(i,a,l,{constant_values:this.constant_values,center:!0,...u})}}},"./src/models/janus/processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>u});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 u extends s.Processor{constructor(d,c){super(d,c),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:c=null,chat_template:_="default"}={}){c?Array.isArray(c)||(c=[c]):c=await Promise.all(d.filter(B=>B.images).flatMap(B=>B.images).map(B=>l.RawImage.read(B)));const f=this.tokenizer,v=f.apply_chat_template(d,{tokenize:!1,add_generation_prompt:!0,chat_template:_}),$=B=>f.encode(B,{add_special_tokens:!1}),w=v.split(this.image_tag),g=w.length-1;if(c.length!==g)throw new Error(`Number of images provided (${c.length}) does not match number of "${this.image_tag}" image tags (${g})`);const[C,E,y]=f.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let b=$(w[0]),x=new Array(b.length).fill(!1);for(let B=1;B0){const B=await this.image_processor(c);return B.pixel_values.unsqueeze_(0),{...A,...B}}return A}}te(u,"image_processor_class",o.AutoImageProcessor),te(u,"tokenizer_class",n.AutoTokenizer),te(u,"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:u,size:p,...d}=i,c=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},_=u==="bicubic"?3:2;super({...d,size:c,resample:_,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,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const d=l?this.tokenizer(l,p):{},c=u?await this.image_processor(u,p):{};return{...d,...c}}}te(i,"tokenizer_class",n.AutoTokenizer),te(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(e,r,t)=>{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[c,_]=a[d],f=this[c].bind(this),[v,$]=p.dims,w=[],g=[],C=p.tolist();for(let y=0;y0?S.reduce((B,K)=>B*K,1):0;g.push(x),w.push(A)}return[f(g),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,c]){const[_,f]=this._decode_helper(p,"char"),[v,$]=this._decode_helper(d,"bpe"),[w,g]=this._decode_helper(c,"wp"),C=[],E=[];for(let y=0;y<_.length;++y){const[b,x]=(0,i.max)([f[y],$[y],g[y]]);C.push([_[y],v[y],w[y]][x]),E.push(b)}return{generated_text:C,scores:E,char_preds:_,bpe_preds:v,wp_preds:w}}static async from_pretrained(...p){const d=await super.from_pretrained(...p),c=await n.AutoTokenizer.from_pretrained("Xenova/gpt2"),_=await n.AutoTokenizer.from_pretrained("Xenova/bert-base-uncased");return d.components={image_processor:d.image_processor,char_tokenizer:d.tokenizer,bpe_tokenizer:c,wp_tokenizer:_},d}async _call(p,d=null){const c=await this.image_processor(p);return d&&(c.labels=this.tokenizer(d).input_ids),c}}te(l,"tokenizer_class",n.AutoTokenizer),te(l,"image_processor_class",o.AutoImageProcessor)},"./src/models/mobilenet_v1/image_processing_mobilenet_v1.js":(e,r,t)=>{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)}}te(i,"tokenizer_class",o.AutoTokenizer),te(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{}te(i,"tokenizer_class",n.AutoTokenizer),te(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(u,p,d,c,_){return`${c.repeat(d*_)}${p}${u} +`}class l extends s.Processor{async _call(p,d=null,c={}){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 _=this.tokenizer.bos_token,f=this.image_processor.config.image_seq_length;let v;d.some(g=>g.includes(i))?v=d.map(g=>{const C=g.replaceAll(i,i.repeat(f)),E=C.lastIndexOf(i),y=E===-1?0:E+i.length;return C.slice(0,y)+_+C.slice(y)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),v=d.map(g=>a(g,_,f,i,p.length)));const $=this.tokenizer(v,c);return{...await this.image_processor(p,c),...$}}}te(l,"tokenizer_class",n.AutoTokenizer),te(l,"image_processor_class",o.AutoImageProcessor),te(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:u}=Math;class p extends s.ImageProcessor{constructor(c){super({...c,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=c.num_crops}calc_num_image_tokens_from_image_size(c,_){const{num_img_tokens:f}=this.config;return l((l(_/n)*l(c/n)+1)*f+1+(l(_/n)+1)*u(f))}get_resize_output_image_size(c,_){const f=this._num_crops,[v,$]=c.size;let w=v/$,g=1;for(;g*Math.ceil(g/w)<=f;)g+=1;g-=1;const C=Math.floor(g*336),E=Math.floor(C/w);return[C,E]}pad_image(c,_,f,v={}){const[$,w]=_,g=n*a($/n),C=n*a(w/n),E=[1,1,1].map((y,b)=>(y-this.image_mean[b])/this.image_std[b]);return super.pad_image(c,_,{width:C,height:g},{center:!0,constant_values:E,...v})}async _call(c,{num_crops:_=null}={}){if(this._num_crops=_??(_=this.config.num_crops),_<4||u(_)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(c)||(c=[c]);const f=c.length,v=await Promise.all(c.map(x=>this.preprocess(x))),$=v.map(x=>x.original_size),w=v.map(x=>x.reshaped_input_size),g=[];for(const{pixel_values:x}of v){x.unsqueeze_(0);const[S,A]=x.dims.slice(-2),B=await(0,o.interpolate_4d)(x,{size:[n,n],mode:"bicubic"});if(_>0){const K=[],G=u(_),j=l(A/G),ee=l(S/G);for(let Z=0;Zx.map(S=>n*a(S/n))),y=new o.Tensor("int64",E.flat(),[f,2]),b=E.map(([x,S])=>this.calc_num_image_tokens_from_image_size(S,x));return{pixel_values:C,original_sizes:$,reshaped_input_sizes:w,image_sizes:y,num_img_tokens:b}}}},"./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:c=!0,truncation:_=!0,num_crops:f=null}={}){Array.isArray(p)||(p=[p]);let v,$;if(d){$=await this.image_processor(d,{num_crops:f});const{num_img_tokens:w}=$,g=p.map((E,y)=>E.split(a).join(i.repeat(w[y])));v=this.tokenizer(g,{padding:c,truncation:_});const C=this.tokenizer.model.convert_tokens_to_ids([i])[0];v.input_ids.map_(E=>E==C?-E:E)}else v=this.tokenizer(p);return{...v,...$}}}te(l,"image_processor_class",o.AutoImageProcessor),te(l,"tokenizer_class",n.AutoTokenizer)},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,GroundingDinoProcessor:()=>o.GroundingDinoProcessor,Idefics3Processor:()=>n.Idefics3Processor,JinaCLIPProcessor:()=>a.JinaCLIPProcessor,MgpstrProcessor:()=>l.MgpstrProcessor,MoonshineProcessor:()=>u.MoonshineProcessor,OwlViTProcessor:()=>p.OwlViTProcessor,PaliGemmaProcessor:()=>c.PaliGemmaProcessor,Phi3VProcessor:()=>d.Phi3VProcessor,PyAnnoteProcessor:()=>_.PyAnnoteProcessor,Qwen2VLProcessor:()=>f.Qwen2VLProcessor,SamProcessor:()=>v.SamProcessor,SmolVLMProcessor:()=>$.SmolVLMProcessor,SpeechT5Processor:()=>w.SpeechT5Processor,UltravoxProcessor:()=>g.UltravoxProcessor,VLChatProcessor:()=>i.VLChatProcessor,Wav2Vec2Processor:()=>C.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>E.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>y.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),o=t("./src/models/grounding_dino/processing_grounding_dino.js"),n=t("./src/models/idefics3/processing_idefics3.js"),i=t("./src/models/janus/processing_janus.js"),a=t("./src/models/jina_clip/processing_jina_clip.js"),l=t("./src/models/mgp_str/processing_mgp_str.js"),u=t("./src/models/moonshine/processing_moonshine.js"),p=t("./src/models/owlvit/processing_owlvit.js"),d=t("./src/models/phi3_v/processing_phi3_v.js"),c=t("./src/models/paligemma/processing_paligemma.js"),_=t("./src/models/pyannote/processing_pyannote.js"),f=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),v=t("./src/models/sam/processing_sam.js"),$=t("./src/models/smolvlm/processing_smolvlm.js"),w=t("./src/models/speecht5/processing_speecht5.js"),g=t("./src/models/ultravox/processing_ultravox.js"),C=t("./src/models/wav2vec2/processing_wav2vec2.js"),E=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),y=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 u=[1,1,l.length];return{input_values:new o.Tensor("float32",l,u)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,u){const p=u/this.samples_to_frames(u)/this.config.sampling_rate,d=[];for(const c of l.tolist()){const _=[];let f=-1;for(let v=0;v({id:v,start:$*p,end:w*p,confidence:g/(w-$)})))}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}}te(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:u,original_sizes:p,reshaped_input_sizes:d}=await super._call(a,...l);let c=u;const{temporal_patch_size:_,merge_size:f,patch_size:v}=this.config;c.dims[0]===1&&(c=(0,o.cat)(Array.from({length:_},()=>c),0));const $=c.dims[0]/_,w=c.dims[1],g=Math.floor(c.dims[2]/v),C=Math.floor(c.dims[3]/v),E=c.view($,_,w,Math.floor(g/f),f,v,Math.floor(C/f),f,v).permute(0,3,6,4,7,2,1,5,8).view($*g*C,w*_*v*v),y=new o.Tensor("int64",[$,g,C],[1,3]);return{pixel_values:E,image_grid_thw:y,original_sizes:p,reshaped_input_sizes:d}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");class i extends s.Processor{async _call(l,u=null,...p){Array.isArray(l)||(l=[l]);let d,c;if(u&&(d=await this.image_processor(u),c=d.image_grid_thw),c){let f=this.image_processor.config.merge_size**2,v=0;const $=c.tolist();l=l.map(w=>{for(;w.includes("<|image_pad|>");){const g=Number($[v++].reduce((C,E)=>C*E,1n));w=w.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(g/f)))}return w.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...d}}}te(i,"image_processor_class",o.AutoImageProcessor),te(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,u,p,d=!1){l=structuredClone(l);let c=(0,o.calculateDimensions)(l);if(c.length===3)d||(c=[1,...c]),l=[l];else if(c.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 _=0;_d!==u.dims[c]))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:u=null,input_labels:p=null,input_boxes:d=null}={}){const c=await super._call(l);if(u&&(c.input_points=this.reshape_input_points(u,c.original_sizes,c.reshaped_input_sizes)),p){if(!c.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");c.input_labels=this.add_input_labels(p,c.input_points)}return d&&(c.input_boxes=this.reshape_input_points(d,c.original_sizes,c.reshaped_input_sizes,!0)),c}async post_process_masks(l,u,p,{mask_threshold:d=0,binarize:c=!0,pad_size:_=null}={}){const f=[];_=_??this.pad_size;const v=[_.height,_.width];for(let $=0;$d&&(y[b]=1);C=new n.Tensor("bool",y,C.dims)}f.push(C)}return f}generate_crop_boxes(l,u,{crop_n_layers:p=0,overlap_ratio:d=512/1500,points_per_crop:c=32,crop_n_points_downscale_factor:_=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)}}te(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 u=this.config.sampling_rate,p=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(u/2),u,null,"kaldi",!0);this.mel_filters=p,this.window=(0,n.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(l,u){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:u,transpose:!0})}async _call(l,{padding:u=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:d=!0,return_attention_mask:c=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let _=await this._extract_fbank_features(l,this.config.max_length);if(d){const[y,b]=_.dims,x=_.data;for(let S=0;S0){const A=new Float32Array(b*(y+S));A.set(x),A.fill(this.config.padding_value,x.length);const B=y+S;_=new o.Tensor(_.type,A,[B,b]),c&&(f=new o.Tensor("int64",new BigInt64Array(B),[1,B]),f.data.fill(1n,0,y))}}const[v,$]=_.dims,w=this.config.stride;if(v%w!==0)throw new Error(`The number of frames (${v}) must be a multiple of the stride (${w}).`);const C=_.view(1,Math.floor(v/w),$*w),E={input_features:C};if(c){const y=C.dims[1],b=new BigInt64Array(y);if(f){const x=f.data;for(let S=1,A=0;S{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)}}te(i,"tokenizer_class",o.AutoTokenizer),te(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,u={}){const[p,d,c]=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,...u})}}},"./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,u=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let d={};if(u){const _=u.length,{input_features:f}=await this.feature_extractor(u,{...p,max_length:_}),v=Math.round(_/this.config.encoder_ds_factor+1e-4),$=1+Math.ceil(v/this.config.stack_factor);d.audio_token_len=[$],d.audio_values=f;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($))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...d}}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",s.AutoFeatureExtractor),te(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 u=await Promise.all(a.map(c=>this.preprocess(c))),p=await Promise.all(l.map(c=>this.preprocess(c,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,o.stack)(u.map((c,_)=>(0,o.cat)([c.pixel_values,p[_].pixel_values],0)),0),original_sizes:u.map(c=>c.original_size),reshaped_input_sizes:u.map(c=>c.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 u=i.tolist(),[p,d,c,_]=i.dims,f=[];for(let v=0;v{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 u=a.reduce((d,c)=>d+c,0)/a.length,p=a.reduce((d,c)=>d+(c-u)**2,0)/a.length;return a.map(d=>(d-u)/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 u=[1,l.length];return{input_values:new o.Tensor("float32",l,u),attention_mask:new o.Tensor("int64",new BigInt64Array(l.length).fill(1n),u)}}}},"./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)}}te(i,"tokenizer_class",s.AutoTokenizer),te(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)}}te(i,"tokenizer_class",s.AutoTokenizer),te(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,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,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 u=l.mean(1).data,p=l.data,[d,c,_]=l.dims;for(let f=0;f{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 u=a.match(/^<\|([a-z]{2})\|>$/);if(u&&(a=u[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 u;super(l),(u=this.config).mel_filters??(u.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 u=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=u.data,d=(0,n.max)(p)[0];for(let c=0;cd?(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);te(this,"return_timestamps",null);te(this,"return_token_timestamps",null);te(this,"num_frames",null);te(this,"alignment_heads",null);te(this,"task",null);te(this,"language",null);te(this,"no_timestamps_token_id",null);te(this,"prompt_ids",null);te(this,"is_multilingual",null);te(this,"lang_to_id",null);te(this,"task_to_id",null);te(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)}}te(i,"tokenizer_class",o.AutoTokenizer),te(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>n,YolosImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),o=t("./src/utils/tensor.js"),n=t("./src/env.js");const i=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV,a=async(u,p,d)=>{const c=await(0,s.createInferenceSession)(new Uint8Array(u),p);let _=Promise.resolve();return async f=>{const v=(0,s.isONNXProxy)(),$=Object.fromEntries(Object.entries(f).map(([g,C])=>[g,(v?C.clone():C).ort_tensor])),w=await(_=i?_.then(()=>c.run($)):c.run($));return Array.isArray(d)?d.map(g=>new o.Tensor(w[g])):new o.Tensor(w[d])}};class l{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=a([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=a([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=a([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=a([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=a([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=a([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=a([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=a([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}te(l,"session_options",{})},"./src/pipelines.js":(e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>G,AutomaticSpeechRecognitionPipeline:()=>ee,BackgroundRemovalPipeline:()=>oe,DepthEstimationPipeline:()=>fe,DocumentQuestionAnsweringPipeline:()=>F,FeatureExtractionPipeline:()=>B,FillMaskPipeline:()=>C,ImageClassificationPipeline:()=>Z,ImageFeatureExtractionPipeline:()=>K,ImageSegmentationPipeline:()=>X,ImageToImagePipeline:()=>re,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>ae,Pipeline:()=>v,QuestionAnsweringPipeline:()=>g,SummarizationPipeline:()=>y,Text2TextGenerationPipeline:()=>E,TextClassificationPipeline:()=>$,TextGenerationPipeline:()=>S,TextToAudioPipeline:()=>W,TokenClassificationPipeline:()=>w,TranslationPipeline:()=>b,ZeroShotAudioClassificationPipeline:()=>j,ZeroShotClassificationPipeline:()=>A,ZeroShotImageClassificationPipeline:()=>me,ZeroShotObjectDetectionPipeline:()=>V,pipeline:()=>$e});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"),u=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),d=t("./src/utils/image.js");async function c(we){return Array.isArray(we)||(we=[we]),await Promise.all(we.map(q=>d.RawImage.read(q)))}async function _(we,q){return Array.isArray(we)||(we=[we]),await Promise.all(we.map(R=>typeof R=="string"||R instanceof URL?(0,u.read_audio)(R,q):R instanceof Float64Array?new Float32Array(R):R))}function f(we,q){q&&(we=we.map(Se=>Se|0));const[R,pe,xe,Me]=we;return{xmin:R,ymin:pe,xmax:xe,ymax:Me}}class v extends i.Callable{constructor({task:q,model:R,tokenizer:pe=null,processor:xe=null}){super(),this.task=q,this.model=R,this.tokenizer=pe,this.processor=xe}async dispose(){await this.model.dispose()}}class $ extends v{constructor(q){super(q)}async _call(q,{top_k:R=1}={}){const pe=this.tokenizer(q,{padding:!0,truncation:!0}),xe=await this.model(pe),Me=this.model.config.problem_type==="multi_label_classification"?Fe=>Fe.sigmoid():Fe=>new p.Tensor("float32",(0,l.softmax)(Fe.data),Fe.dims),Se=this.model.config.id2label,Ae=[];for(const Fe of xe.logits){const ze=Me(Fe),Ve=await(0,p.topk)(ze,R),O=Ve[0].tolist(),z=Ve[1].tolist().map((J,le)=>({label:Se?Se[J]:`LABEL_${J}`,score:O[le]}));R===1?Ae.push(...z):Ae.push(z)}return Array.isArray(q)||R===1?Ae:Ae[0]}}class w extends v{constructor(q){super(q)}async _call(q,{ignore_labels:R=["O"]}={}){const pe=Array.isArray(q),xe=this.tokenizer(pe?q:[q],{padding:!0,truncation:!0}),Se=(await this.model(xe)).logits,Ae=this.model.config.id2label,Fe=[];for(let ze=0;zeIe==this.tokenizer.sep_token_id);Fe[O].map((Ie,Be)=>Ie==1&&(Be===0||Be>z&&ze.findIndex(Xe=>Xe==Y[Be])===-1));const J=Me[O].tolist(),le=Se[O].tolist();for(let Ie=1;IeBe==Y[Ie])!==-1)&&(J[Ie]=-1/0,le[Ie]=-1/0);const ye=(0,l.softmax)(J).map((Ie,Be)=>[Ie,Be]),Ee=(0,l.softmax)(le).map((Ie,Be)=>[Ie,Be]);ye[0][0]=0,Ee[0][0]=0;const ke=(0,a.product)(ye,Ee).filter(Ie=>Ie[0][1]<=Ie[1][1]).map(Ie=>[Ie[0][1],Ie[1][1],Ie[0][0]*Ie[1][0]]).sort((Ie,Be)=>Be[2]-Ie[2]);for(let Ie=0;IeJ==this.tokenizer.mask_token_id);if(ze===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ve=xe[Ae][ze],O=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),R),Y=O[0].tolist(),z=O[1].tolist();Me.push(z.map((J,le)=>{const ye=Fe.slice();return ye[ze]=J,{score:Y[le],token:Number(J),token_str:this.tokenizer.decode([J]),sequence:this.tokenizer.decode(ye,{skip_special_tokens:!0})}}))}return Array.isArray(q)?Me:Me[0]}}class E extends v{constructor(R){super(R);te(this,"_key","generated_text")}async _call(R,pe={}){Array.isArray(R)||(R=[R]),this.model.config.prefix&&(R=R.map(ze=>this.model.config.prefix+ze));const xe=this.model.config.task_specific_params;xe&&xe[this.task]&&xe[this.task].prefix&&(R=R.map(ze=>xe[this.task].prefix+ze));const Me=this.tokenizer,Se={padding:!0,truncation:!0};let Ae;this instanceof b&&"_build_translation_inputs"in Me?Ae=Me._build_translation_inputs(R,Se,pe):Ae=Me(R,Se);const Fe=await this.model.generate({...Ae,...pe});return Me.batch_decode(Fe,{skip_special_tokens:!0}).map(ze=>({[this._key]:ze}))}}class y extends E{constructor(R){super(R);te(this,"_key","summary_text")}}class b extends E{constructor(R){super(R);te(this,"_key","translation_text")}}function x(we){return Array.isArray(we)&&we.every(q=>"role"in q&&"content"in q)}class S extends v{constructor(q){super(q)}async _call(q,R={}){let pe=!1,xe=!1,Me;if(typeof q=="string")Me=q=[q];else if(Array.isArray(q)&&q.every(z=>typeof z=="string"))pe=!0,Me=q;else{if(x(q))q=[q];else if(Array.isArray(q)&&q.every(x))pe=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");xe=!0,Me=q.map(z=>this.tokenizer.apply_chat_template(z,{tokenize:!1,add_generation_prompt:!0}))}const Se=R.add_special_tokens??!1,Ae=xe?!1:R.return_full_text??!0;this.tokenizer.padding_side="left";const Fe=this.tokenizer(Me,{add_special_tokens:Se,padding:!0,truncation:!0}),ze=await this.model.generate({...Fe,...R}),Ve=this.tokenizer.batch_decode(ze,{skip_special_tokens:!0});let O;!Ae&&Fe.input_ids.dims.at(-1)>0&&(O=this.tokenizer.batch_decode(Fe.input_ids,{skip_special_tokens:!0}).map(z=>z.length));const Y=Array.from({length:q.length},z=>[]);for(let z=0;z[R.toLowerCase(),pe])),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,R,{hypothesis_template:pe="This example is {}.",multi_label:xe=!1}={}){const Me=Array.isArray(q);Me||(q=[q]),Array.isArray(R)||(R=[R]);const Se=R.map(ze=>pe.replace("{}",ze)),Ae=xe||R.length===1,Fe=[];for(const ze of q){const Ve=[];for(const z of Se){const J=this.tokenizer(ze,{text_pair:z,padding:!0,truncation:!0}),le=await this.model(J);Ae?Ve.push([le.logits.data[this.contradiction_id],le.logits.data[this.entailment_id]]):Ve.push(le.logits.data[this.entailment_id])}const Y=(Ae?Ve.map(z=>(0,l.softmax)(z)[1]):(0,l.softmax)(Ve)).map((z,J)=>[z,J]).sort((z,J)=>J[0]-z[0]);Fe.push({sequence:ze,labels:Y.map(z=>R[z[1]]),scores:Y.map(z=>z[0])})}return Me?Fe:Fe[0]}}class B extends v{constructor(q){super(q)}async _call(q,{pooling:R="none",normalize:pe=!1,quantize:xe=!1,precision:Me="binary"}={}){const Se=this.tokenizer(q,{padding:!0,truncation:!0}),Ae=await this.model(Se);let Fe=Ae.last_hidden_state??Ae.logits??Ae.token_embeddings;if(R!=="none")if(R==="mean")Fe=(0,p.mean_pooling)(Fe,Se.attention_mask);else if(R==="cls")Fe=Fe.slice(null,0);else throw Error(`Pooling method '${R}' not supported.`);return pe&&(Fe=Fe.normalize(2,-1)),xe&&(Fe=(0,p.quantize_embeddings)(Fe,Me)),Fe}}class K extends v{constructor(q){super(q)}async _call(q,{pool:R=null}={}){const pe=await c(q),{pixel_values:xe}=await this.processor(pe),Me=await this.model({pixel_values:xe});let Se;if(R){if(!("pooler_output"in Me))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Se=Me.pooler_output}else Se=Me.last_hidden_state??Me.logits??Me.image_embeds;return Se}}class G extends v{constructor(q){super(q)}async _call(q,{top_k:R=5}={}){const pe=this.processor.feature_extractor.config.sampling_rate,xe=await _(q,pe),Me=this.model.config.id2label,Se=[];for(const Ae of xe){const Fe=await this.processor(Ae),Ve=(await this.model(Fe)).logits[0],O=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),R),Y=O[0].tolist(),J=O[1].tolist().map((le,ye)=>({label:Me?Me[le]:`LABEL_${le}`,score:Y[ye]}));Se.push(J)}return Array.isArray(q)?Se:Se[0]}}class j extends v{constructor(q){super(q)}async _call(q,R,{hypothesis_template:pe="This is a sound of {}."}={}){const xe=!Array.isArray(q);xe&&(q=[q]);const Me=R.map(Ve=>pe.replace("{}",Ve)),Se=this.tokenizer(Me,{padding:!0,truncation:!0}),Ae=this.processor.feature_extractor.config.sampling_rate,Fe=await _(q,Ae),ze=[];for(const Ve of Fe){const O=await this.processor(Ve),Y=await this.model({...Se,...O}),z=(0,l.softmax)(Y.logits_per_audio.data);ze.push([...z].map((J,le)=>({score:J,label:R[le]})))}return xe?ze[0]:ze}}class ee extends v{constructor(q){super(q)}async _call(q,R={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(q,R);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(q,R);case"moonshine":return this._call_moonshine(q,R);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(q,R){R.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),R.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const pe=!Array.isArray(q);pe&&(q=[q]);const xe=this.processor.feature_extractor.config.sampling_rate,Me=await _(q,xe),Se=[];for(const Ae of Me){const Fe=await this.processor(Ae),Ve=(await this.model(Fe)).logits[0],O=[];for(const z of Ve)O.push((0,l.max)(z.data)[1]);const Y=this.tokenizer.decode(O);Se.push({text:Y})}return pe?Se[0]:Se}async _call_whisper(q,R){const pe=R.return_timestamps??!1,xe=R.chunk_length_s??0,Me=R.force_full_sequences??!1;let Se=R.stride_length_s??null;const Ae={...R};pe==="word"&&(Ae.return_token_timestamps=!0,Ae.return_timestamps=!1);const Fe=!Array.isArray(q);Fe&&(q=[q]);const ze=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ve=this.processor.feature_extractor.config.hop_length,O=this.processor.feature_extractor.config.sampling_rate,Y=await _(q,O),z=[];for(const J of Y){let le=[];if(xe>0){if(Se===null)Se=xe/6;else if(xe<=Se)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const ke=O*xe,Ie=O*Se,Be=ke-2*Ie;let Xe=0;for(;;){const Ge=Xe+ke,lt=J.subarray(Xe,Ge),wt=await this.processor(lt),Gt=Xe===0,Ot=Ge>=J.length;if(le.push({stride:[lt.length,Gt?0:Ie,Ot?0:Ie],input_features:wt.input_features,is_last:Ot}),Ot)break;Xe+=Be}}else le=[{stride:[J.length,0,0],input_features:(await this.processor(J)).input_features,is_last:!0}];for(const ke of le){Ae.num_frames=Math.floor(ke.stride[0]/Ve);const Ie=await this.model.generate({inputs:ke.input_features,...Ae});pe==="word"?(ke.tokens=Ie.sequences.tolist()[0],ke.token_timestamps=Ie.token_timestamps.tolist()[0].map(Be=>(0,l.round)(Be,2))):ke.tokens=Ie[0].tolist(),ke.stride=ke.stride.map(Be=>Be/O)}const[ye,Ee]=this.tokenizer._decode_asr(le,{time_precision:ze,return_timestamps:pe,force_full_sequences:Me});z.push({text:ye,...Ee})}return Fe?z[0]:z}async _call_moonshine(q,R){const pe=!Array.isArray(q);pe&&(q=[q]);const xe=this.processor.feature_extractor.config.sampling_rate,Me=await _(q,xe),Se=[];for(const Ae of Me){const Fe=await this.processor(Ae),ze=Math.floor(Ae.length/xe)*6,Ve=await this.model.generate({max_new_tokens:ze,...R,...Fe}),O=this.processor.batch_decode(Ve,{skip_special_tokens:!0})[0];Se.push({text:O})}return pe?Se[0]:Se}}class H extends v{constructor(q){super(q)}async _call(q,R={}){const pe=Array.isArray(q),xe=await c(q),{pixel_values:Me}=await this.processor(xe),Se=[];for(const Ae of Me){Ae.dims=[1,...Ae.dims];const Fe=await this.model.generate({inputs:Ae,...R}),ze=this.tokenizer.batch_decode(Fe,{skip_special_tokens:!0}).map(Ve=>({generated_text:Ve.trim()}));Se.push(ze)}return pe?Se:Se[0]}}class Z extends v{constructor(q){super(q)}async _call(q,{top_k:R=5}={}){const pe=await c(q),{pixel_values:xe}=await this.processor(pe),Me=await this.model({pixel_values:xe}),Se=this.model.config.id2label,Ae=[];for(const Fe of Me.logits){const ze=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Fe.data),Fe.dims),R),Ve=ze[0].tolist(),Y=ze[1].tolist().map((z,J)=>({label:Se?Se[z]:`LABEL_${z}`,score:Ve[J]}));Ae.push(Y)}return Array.isArray(q)?Ae:Ae[0]}}class X extends v{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:R=.5,mask_threshold:pe=.5,overlap_mask_area_threshold:xe=.8,label_ids_to_fuse:Me=null,target_sizes:Se=null,subtask:Ae=null}={}){if(Array.isArray(q)&&q.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const ze=await c(q),Ve=ze.map(ke=>[ke.height,ke.width]),O=await this.processor(ze),{inputNames:Y,outputNames:z}=this.model.sessions.model;if(!Y.includes("pixel_values")){if(Y.length!==1)throw Error(`Expected a single input name, but got ${Y.length} inputs: ${Y}.`);const ke=Y[0];if(ke in O)throw Error(`Input name ${ke} already exists in the inputs.`);O[ke]=O.pixel_values}const J=await this.model(O);let le=null;if(Ae!==null)le=this.subtasks_mapping[Ae];else if(this.processor.image_processor){for(const[ke,Ie]of Object.entries(this.subtasks_mapping))if(Ie in this.processor.image_processor){le=this.processor.image_processor[Ie].bind(this.processor.image_processor),Ae=ke;break}}const ye=this.model.config.id2label,Ee=[];if(Ae)if(Ae==="panoptic"||Ae==="instance"){const ke=le(J,R,pe,xe,Me,Se??Ve)[0],Ie=ke.segmentation;for(const Be of ke.segments_info){const Xe=new Uint8ClampedArray(Ie.data.length);for(let lt=0;ltwt<-1e-5||wt>1+1e-5)&&Ge.sigmoid_();const lt=await d.RawImage.fromTensor(Ge.mul_(255).to("uint8")).resize(Xe[1],Xe[0]);Ee.push({label:null,score:null,mask:lt})}}return Ee}}class oe extends X{constructor(q){super(q)}async _call(q,R={}){if(Array.isArray(q)&&q.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const xe=await c(q),Me=await super._call(q,R);return xe.map((Ae,Fe)=>{const ze=Ae.clone();return ze.putAlpha(Me[Fe].mask),ze})}}class me extends v{constructor(q){super(q)}async _call(q,R,{hypothesis_template:pe="This is a photo of {}"}={}){const xe=Array.isArray(q),Me=await c(q),Se=R.map(Y=>pe.replace("{}",Y)),Ae=this.tokenizer(Se,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:Fe}=await this.processor(Me),ze=await this.model({...Ae,pixel_values:Fe}),Ve=this.model.config.model_type==="siglip"?Y=>Y.sigmoid().data:Y=>(0,l.softmax)(Y.data),O=[];for(const Y of ze.logits_per_image){const J=[...Ve(Y)].map((le,ye)=>({score:le,label:R[ye]}));J.sort((le,ye)=>ye.score-le.score),O.push(J)}return xe?O:O[0]}}class ae extends v{constructor(q){super(q)}async _call(q,{threshold:R=.9,percentage:pe=!1}={}){const xe=Array.isArray(q);if(xe&&q.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Me=await c(q),Se=pe?null:Me.map(z=>[z.height,z.width]),{pixel_values:Ae,pixel_mask:Fe}=await this.processor(Me),ze=await this.model({pixel_values:Ae,pixel_mask:Fe}),Ve=this.processor.image_processor.post_process_object_detection(ze,R,Se),O=this.model.config.id2label,Y=Ve.map(z=>z.boxes.map((J,le)=>({score:z.scores[le],label:O[z.classes[le]],box:f(J,!pe)})));return xe?Y:Y[0]}}class V extends v{constructor(q){super(q)}async _call(q,R,{threshold:pe=.1,top_k:xe=null,percentage:Me=!1}={}){const Se=Array.isArray(q),Ae=await c(q),Fe=this.tokenizer(R,{padding:!0,truncation:!0}),ze=await this.processor(Ae),Ve=[];for(let O=0;O({score:Ee.scores[Ie],label:Ee.labels[Ie],box:f(ke,!Me)}))}else{const Ee=this.processor.image_processor.post_process_object_detection(le,pe,z,!0)[0];ye=Ee.boxes.map((ke,Ie)=>({score:Ee.scores[Ie],label:R[Ee.classes[Ie]],box:f(ke,!Me)}))}ye.sort((Ee,ke)=>ke.score-Ee.score),xe!==null&&(ye=ye.slice(0,xe)),Ve.push(ye)}return Se?Ve:Ve[0]}}class F extends v{constructor(q){super(q)}async _call(q,R,pe={}){const xe=(await c(q))[0],{pixel_values:Me}=await this.processor(xe),Se=`${R}`,Ae=this.tokenizer(Se,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,Fe=await this.model.generate({inputs:Me,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ae,...pe}),Ve=this.tokenizer.batch_decode(Fe)[0].match(/(.*?)<\/s_answer>/);let O=null;return Ve&&Ve.length>=2&&(O=Ve[1].trim()),[{answer:O}]}}class W extends v{constructor(R){super(R);te(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=R.vocoder??null}async _call(R,{speaker_embeddings:pe=null}={}){return this.processor?this._call_text_to_spectrogram(R,{speaker_embeddings:pe}):this._call_text_to_waveform(R)}async _call_text_to_waveform(R){const pe=this.tokenizer(R,{padding:!0,truncation:!0}),{waveform:xe}=await this.model(pe),Me=this.model.config.sampling_rate;return new u.RawAudio(xe.data,Me)}async _call_text_to_spectrogram(R,{speaker_embeddings:pe}){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 pe=="string"||pe instanceof URL)&&(pe=new Float32Array(await(await fetch(pe)).arrayBuffer())),pe instanceof Float32Array)pe=new p.Tensor("float32",pe,[1,pe.length]);else if(!(pe instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:xe}=this.tokenizer(R,{padding:!0,truncation:!0}),{waveform:Me}=await this.model.generate_speech(xe,pe,{vocoder:this.vocoder}),Se=this.processor.feature_extractor.config.sampling_rate;return new u.RawAudio(Me.data,Se)}}class re extends v{constructor(q){super(q)}async _call(q){const R=await c(q),pe=await this.processor(R),xe=await this.model(pe),Me=[];for(const Se of xe.reconstruction){const Ae=Se.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Me.push(d.RawImage.fromTensor(Ae))}return Me.length>1?Me:Me[0]}}class fe extends v{constructor(q){super(q)}async _call(q){const R=await c(q),pe=await this.processor(R),{predicted_depth:xe}=await this.model(pe),Me=[];for(let Se=0;Se1?Me:Me[0]}}const se=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:$,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:g,model:o.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:C,model:o.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:y,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:b,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:S,model:o.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:A,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:j,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:ee,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:Z,model:o.AutoModelForImageClassification,processor:n.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:X,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:me,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ae,model:o.AutoModelForObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:V,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:re,model:o.AutoModelForImageToImage,processor:n.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:fe,model:o.AutoModelForDepthEstimation,processor:n.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:B,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"}}),ce=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function $e(we,q=null,{progress_callback:R=null,config:pe=null,cache_dir:xe=null,local_files_only:Me=!1,revision:Se="main",device:Ae=null,dtype:Fe=null,subfolder:ze="onnx",use_external_data_format:Ve=null,model_file_name:O=null,session_options:Y={}}={}){we=ce[we]??we;const z=se[we.split("_",1)[0]];if(!z)throw Error(`Unsupported pipeline: ${we}. Must be one of [${Object.keys(se)}]`);q||(q=z.default.model,console.log(`No model specified. Using default model: "${q}".`));const J={progress_callback:R,config:pe,cache_dir:xe,local_files_only:Me,revision:Se,device:Ae,dtype:Fe,subfolder:ze,use_external_data_format:Ve,model_file_name:O,session_options:Y},le=new Map([["tokenizer",z.tokenizer],["model",z.model],["processor",z.processor]]),ye=await Ue(le,q,J);ye.task=we,(0,a.dispatchCallback)(R,{status:"ready",task:we,model:q});const Ee=z.pipeline;return new Ee(ye)}async function Ue(we,q,R){const pe=Object.create(null),xe=[];for(const[Me,Se]of we.entries()){if(!Se)continue;let Ae;Array.isArray(Se)?Ae=new Promise(async(Fe,ze)=>{var O,Y;let Ve;for(const z of Se){if(z===null){Fe(null);return}try{Fe(await z.from_pretrained(q,R));return}catch(J){if((O=J.message)!=null&&O.includes("Unsupported model type"))Ve=J;else if((Y=J.message)!=null&&Y.includes("Could not locate file"))Ve=J;else{ze(J);return}}}ze(Ve)}):Ae=Se.from_pretrained(q,R),pe[Me]=Ae,xe.push(Ae)}await Promise.all(xe);for(const[Me,Se]of Object.entries(pe))pe[Me]=await Se;return pe}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Ir,AutoTokenizer:()=>dn,BartTokenizer:()=>ss,BertTokenizer:()=>Zr,BlenderbotSmallTokenizer:()=>Ms,BlenderbotTokenizer:()=>on,BloomTokenizer:()=>Wr,CLIPTokenizer:()=>tn,CamembertTokenizer:()=>et,CodeGenTokenizer:()=>Dr,CodeLlamaTokenizer:()=>vr,CohereTokenizer:()=>un,ConvBertTokenizer:()=>Xt,DebertaTokenizer:()=>es,DebertaV2Tokenizer:()=>ts,DistilBertTokenizer:()=>Qe,ElectraTokenizer:()=>Or,EsmTokenizer:()=>Zs,FalconTokenizer:()=>fr,GPT2Tokenizer:()=>rs,GPTNeoXTokenizer:()=>zs,GemmaTokenizer:()=>en,Grok1Tokenizer:()=>Gr,HerbertTokenizer:()=>bs,LlamaTokenizer:()=>Ys,M2M100Tokenizer:()=>ur,MBart50Tokenizer:()=>ns,MBartTokenizer:()=>Ur,MPNetTokenizer:()=>Es,MarianTokenizer:()=>sn,MgpstrTokenizer:()=>ys,MobileBertTokenizer:()=>ws,NllbTokenizer:()=>Ps,NougatTokenizer:()=>Bs,PreTrainedTokenizer:()=>at,Qwen2Tokenizer:()=>Ar,RoFormerTokenizer:()=>De,RobertaTokenizer:()=>os,SiglipTokenizer:()=>rn,SpeechT5Tokenizer:()=>an,SqueezeBertTokenizer:()=>Ft,T5Tokenizer:()=>Pr,TokenizerModel:()=>K,VitsTokenizer:()=>ln,Wav2Vec2CTCTokenizer:()=>nn,WhisperTokenizer:()=>_r,XLMRobertaTokenizer:()=>Ts,XLMTokenizer:()=>Bt,is_chinese_char:()=>C});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"),u=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function d(he,k){const N=await Promise.all([(0,n.getModelJSON)(he,"tokenizer.json",!0,k),(0,n.getModelJSON)(he,"tokenizer_config.json",!0,k)]);return k.legacy!==null&&(N[1].legacy=k.legacy),N}function c(he,k){const N=[];let Q=0;for(const ie of he.matchAll(k)){const de=ie[0];Q0&&N.push(de),Q=ie.index+de.length}return Q=19968&&he<=40959||he>=13312&&he<=19903||he>=131072&&he<=173791||he>=173824&&he<=177983||he>=177984&&he<=178207||he>=178208&&he<=183983||he>=63744&&he<=64255||he>=194560&&he<=195103}function E(he,k,N){const Q=[];let ie=0;for(;iethis.tokens_to_ids.get(N)??this.unk_token_id)}convert_ids_to_tokens(k){return k.map(N=>this.vocab[N]??this.unk_token)}}class G extends K{constructor(k){super(k),this.tokens_to_ids=f(k.vocab),this.unk_token_id=this.tokens_to_ids.get(k.unk_token),this.unk_token=k.unk_token,this.max_input_chars_per_word=k.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[N,Q]of this.tokens_to_ids)this.vocab[Q]=N}encode(k){const N=[];for(const Q of k){const ie=[...Q];if(ie.length>this.max_input_chars_per_word){N.push(this.unk_token);continue}let de=!1,ve=0;const je=[];for(;ve0&&(Je=this.config.continuing_subword_prefix+Je),this.tokens_to_ids.has(Je)){We=Je;break}--He}if(We===null){de=!0;break}je.push(We),ve=He}de?N.push(this.unk_token):N.push(...je)}return N}}class j extends K{constructor(k,N){super(k);const Q=k.vocab.length;this.vocab=new Array(Q),this.scores=new Array(Q);for(let ie=0;ie[ie,de])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,i.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(k){const N=k.chars,Q=1;let ie=0;for(;ie{const he=[...Array.from({length:94},(ie,de)=>de+33),...Array.from({length:12},(ie,de)=>de+161),...Array.from({length:82},(ie,de)=>de+174)],k=he.slice();let N=0;for(let ie=0;ie<256;++ie)he.includes(ie)||(he.push(ie),k.push(256+N),N+=1);const Q=k.map(ie=>String.fromCharCode(ie));return Object.fromEntries(he.map((ie,de)=>[ie,Q[de]]))})(),H=(0,o.reverseDictionary)(ee);class Z extends K{constructor(k){super(k),this.tokens_to_ids=f(k.vocab),this.unk_token_id=this.tokens_to_ids.get(k.unk_token),this.unk_token=k.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[Q,ie]of this.tokens_to_ids)this.vocab[ie]=Q;const N=Array.isArray(k.merges[0]);this.merges=N?k.merges:k.merges.map(Q=>Q.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((Q,ie)=>[JSON.stringify(Q),ie])),this.end_of_word_suffix=k.end_of_word_suffix,this.continuing_subword_suffix=k.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(k){if(k.length===0)return[];const N=this.cache.get(k);if(N!==void 0)return N;const Q=Array.from(k);this.end_of_word_suffix&&(Q[Q.length-1]+=this.end_of_word_suffix);let ie=[];if(Q.length>1){const de=new l.PriorityQueue((He,We)=>He.score`<0x${je.toString(16).toUpperCase().padStart(2,"0")}>`);ve.every(je=>this.tokens_to_ids.has(je))?N.push(...ve):N.push(this.unk_token)}else N.push(this.unk_token)}return N}}class X extends K{constructor(k,N){super(k),this.tokens_to_ids=f(N.target_lang?k.vocab[N.target_lang]:k.vocab),this.bos_token=N.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=N.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=N.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[Q,ie]of this.tokens_to_ids)this.vocab[ie]=Q}encode(k){return k}}class oe extends s.Callable{constructor(k){super(),this.config=k}static fromConfig(k){if(k===null)return null;switch(k.type){case"BertNormalizer":return new we(k);case"Precompiled":return new Ot(k);case"Sequence":return new Ue(k);case"Replace":return new me(k);case"NFC":return new V(k);case"NFD":return new F(k);case"NFKC":return new W(k);case"NFKD":return new re(k);case"Strip":return new fe(k);case"StripAccents":return new se(k);case"Lowercase":return new ce(k);case"Prepend":return new $e(k);default:throw new Error(`Unknown Normalizer type: ${k.type}`)}}normalize(k){throw Error("normalize should be implemented in subclass.")}_call(k){return this.normalize(k)}}class me extends oe{normalize(k){const N=_(this.config.pattern);return N===null?k:k.replaceAll(N,this.config.content)}}class ae extends oe{constructor(){super(...arguments);te(this,"form")}normalize(N){return N=N.normalize(this.form),N}}class V extends ae{constructor(){super(...arguments);te(this,"form","NFC")}}class F extends ae{constructor(){super(...arguments);te(this,"form","NFD")}}class W extends ae{constructor(){super(...arguments);te(this,"form","NFKC")}}class re extends ae{constructor(){super(...arguments);te(this,"form","NFKD")}}class fe extends oe{normalize(k){return this.config.strip_left&&this.config.strip_right?k=k.trim():(this.config.strip_left&&(k=k.trimStart()),this.config.strip_right&&(k=k.trimEnd())),k}}class se extends oe{normalize(k){return k=w(k),k}}class ce extends oe{normalize(k){return k=k.toLowerCase(),k}}class $e extends oe{normalize(k){return k=this.config.prepend+k,k}}class Ue extends oe{constructor(k){super(k),this.normalizers=k.normalizers.map(N=>oe.fromConfig(N))}normalize(k){return this.normalizers.reduce((N,Q)=>Q.normalize(N),k)}}class we extends oe{_tokenize_chinese_chars(k){const N=[];for(let Q=0;Qthis.pre_tokenize_text(Q,N)):this.pre_tokenize_text(k,N)).flat()}_call(k,N){return this.pre_tokenize(k,N)}}class R extends q{constructor(k){super(),this.pattern=new RegExp(`[^\\s${b}]+|[${b}]`,"gu")}pre_tokenize_text(k,N){return k.trim().match(this.pattern)||[]}}class pe extends q{constructor(k){super(),this.config=k,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=ee,this.text_encoder=new TextEncoder}pre_tokenize_text(k,N){return this.add_prefix_space&&!k.startsWith(" ")&&(k=" "+k),(this.use_regex?k.match(this.pattern)||[]:[k]).map(ie=>Array.from(this.text_encoder.encode(ie),de=>this.byte_encoder[de]).join(""))}}class xe extends q{constructor(k){super(),this.config=k,this.pattern=_(this.config.pattern,this.config.invert)}pre_tokenize_text(k,N){var Q;return this.pattern===null?[]:this.config.invert?k.match(this.pattern)||[]:((Q=this.config.behavior)==null?void 0:Q.toLowerCase())==="removed"?k.split(this.pattern).filter(ie=>ie):c(k,this.pattern)}}class Me extends q{constructor(k){super(),this.config=k,this.pattern=new RegExp(`[^${b}]+|[${b}]+`,"gu")}pre_tokenize_text(k,N){return k.match(this.pattern)||[]}}class Se extends q{constructor(k){super(),this.config=k;const N=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(N,"gu")}pre_tokenize_text(k,N){return k.match(this.pattern)||[]}}class Ae extends s.Callable{constructor(k){super(),this.config=k}static fromConfig(k){if(k===null)return null;switch(k.type){case"TemplateProcessing":return new Ve(k);case"ByteLevel":return new O(k);case"RobertaProcessing":return new ze(k);case"BertProcessing":return new Fe(k);case"Sequence":return new Y(k);default:throw new Error(`Unknown PostProcessor type: ${k.type}`)}}post_process(k,...N){throw Error("post_process should be implemented in subclass.")}_call(k,...N){return this.post_process(k,...N)}}class Fe extends Ae{constructor(k){super(k),this.cls=k.cls[0],this.sep=k.sep[0]}post_process(k,N=null,{add_special_tokens:Q=!0}={}){Q&&(k=(0,o.mergeArrays)([this.cls],k,[this.sep]));let ie=new Array(k.length).fill(0);if(N!==null){const de=Q&&this instanceof ze?[this.sep]:[],ve=Q?[this.sep]:[];k=(0,o.mergeArrays)(k,de,N,ve),ie=(0,o.mergeArrays)(ie,new Array(N.length+de.length+ve.length).fill(1))}return{tokens:k,token_type_ids:ie}}}class ze extends Fe{}class Ve extends Ae{constructor(k){super(k),this.single=k.single,this.pair=k.pair}post_process(k,N=null,{add_special_tokens:Q=!0}={}){const ie=N===null?this.single:this.pair;let de=[],ve=[];for(const je of ie)"SpecialToken"in je?Q&&(de.push(je.SpecialToken.id),ve.push(je.SpecialToken.type_id)):"Sequence"in je&&(je.Sequence.id==="A"?(de=(0,o.mergeArrays)(de,k),ve=(0,o.mergeArrays)(ve,new Array(k.length).fill(je.Sequence.type_id))):je.Sequence.id==="B"&&(de=(0,o.mergeArrays)(de,N),ve=(0,o.mergeArrays)(ve,new Array(N.length).fill(je.Sequence.type_id))));return{tokens:de,token_type_ids:ve}}}class O extends Ae{post_process(k,N=null){return N&&(k=(0,o.mergeArrays)(k,N)),{tokens:k}}}class Y extends Ae{constructor(k){super(k),this.processors=k.processors.map(N=>Ae.fromConfig(N))}post_process(k,N=null,Q={}){let ie;for(const de of this.processors)if(de instanceof O)k=de.post_process(k).tokens,N&&(N=de.post_process(N).tokens);else{const ve=de.post_process(k,N,Q);k=ve.tokens,ie=ve.token_type_ids}return{tokens:k,token_type_ids:ie}}}class z extends s.Callable{constructor(k){super(),this.config=k,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=k.trim_offsets}static fromConfig(k){if(k===null)return null;switch(k.type){case"WordPiece":return new ke(k);case"Metaspace":return new Gt(k);case"ByteLevel":return new Ie(k);case"Replace":return new J(k);case"ByteFallback":return new le(k);case"Fuse":return new ye(k);case"Strip":return new Ee(k);case"Sequence":return new Xe(k);case"CTC":return new Be(k);case"BPEDecoder":return new Ge(k);default:throw new Error(`Unknown Decoder type: ${k.type}`)}}_call(k){return this.decode(k)}decode(k){return this.decode_chain(k).join("")}decode_chain(k){throw Error("`decode_chain` should be implemented in subclass.")}}class J extends z{decode_chain(k){const N=_(this.config.pattern);return N===null?k:k.map(Q=>Q.replaceAll(N,this.config.content))}}class le extends z{constructor(k){super(k),this.text_decoder=new TextDecoder}decode_chain(k){const N=[];let Q=[];for(const ie of k){let de=null;if(ie.length===6&&ie.startsWith("<0x")&&ie.endsWith(">")){const ve=parseInt(ie.slice(3,5),16);isNaN(ve)||(de=ve)}if(de!==null)Q.push(de);else{if(Q.length>0){const ve=this.text_decoder.decode(Uint8Array.from(Q));N.push(ve),Q=[]}N.push(ie)}}if(Q.length>0){const ie=this.text_decoder.decode(Uint8Array.from(Q));N.push(ie),Q=[]}return N}}class ye extends z{decode_chain(k){return[k.join("")]}}class Ee extends z{constructor(k){super(k),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(k){return k.map(N=>{let Q=0;for(let de=0;de(Q!==0&&(N.startsWith(this.config.prefix)?N=N.replace(this.config.prefix,""):N=" "+N),this.cleanup&&(N=$(N)),N))}}class Ie extends z{constructor(k){super(k),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(k){const N=k.join(""),Q=new Uint8Array([...N].map(de=>this.byte_decoder[de]));return this.text_decoder.decode(Q)}decode_chain(k){const N=[];let Q=[];for(const ie of k)this.added_tokens.find(de=>de.content===ie)!==void 0?(Q.length>0&&(N.push(this.convert_tokens_to_string(Q)),Q=[]),N.push(ie)):Q.push(ie);return Q.length>0&&N.push(this.convert_tokens_to_string(Q)),N}}class Be extends z{constructor(k){super(k),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(k){if(k.length===0)return"";const N=[k[0]];for(let de=1;dede!==this.pad_token).join("");return this.cleanup&&(ie=$(ie).replaceAll(this.word_delimiter_token," ").trim()),ie}decode_chain(k){return[this.convert_tokens_to_string(k)]}}class Xe extends z{constructor(k){super(k),this.decoders=k.decoders.map(N=>z.fromConfig(N))}decode_chain(k){return this.decoders.reduce((N,Q)=>Q.decode_chain(N),k)}}class Ge extends z{constructor(k){super(k),this.suffix=this.config.suffix}decode_chain(k){return k.map((N,Q)=>N.replaceAll(this.suffix,Q===k.length-1?"":" "))}}class lt extends z{decode_chain(k){let N="";for(let Q=1;QQ.normalize("NFKC")).join("~"):k=k.normalize("NFKC"),k}}class lr extends q{constructor(k){super(),this.tokenizers=k.pretokenizers.map(N=>q.fromConfig(N))}pre_tokenize_text(k,N){return this.tokenizers.reduce((Q,ie)=>ie.pre_tokenize(Q,N),[k])}}class Yr extends q{constructor(k){super()}pre_tokenize_text(k,N){return k.match(/\w+|[^\w\s]+/g)||[]}}class gs extends q{constructor(k){super()}pre_tokenize_text(k,N){return y(k)}}class kr extends q{constructor(k){super(),this.config=k,this.pattern=_(this.config.pattern),this.content=this.config.content}pre_tokenize_text(k,N){return this.pattern===null?[k]:[k.replaceAll(this.pattern,this.config.content)]}}const Ds=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function xs(he,k,N,Q){for(const ie of Object.keys(he)){const de=k-he[ie].length,ve=N(ie),je=new Array(de).fill(ve);he[ie]=Q==="right"?(0,o.mergeArrays)(he[ie],je):(0,o.mergeArrays)(je,he[ie])}}function Ls(he,k){for(const N of Object.keys(he))he[N].length=k}class at extends s.Callable{constructor(N,Q){super();te(this,"return_token_type_ids",!1);te(this,"padding_side","right");this._tokenizer_config=Q,this.normalizer=oe.fromConfig(N.normalizer),this.pre_tokenizer=q.fromConfig(N.pre_tokenizer),this.model=K.fromConfig(N.model,Q),this.post_processor=Ae.fromConfig(N.post_processor),this.decoder=z.fromConfig(N.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ie of N.added_tokens){const de=new B(ie);this.added_tokens.push(de),this.model.tokens_to_ids.set(de.content,de.id),this.model.vocab[de.id]=de.content,de.special&&(this.special_tokens.push(de.content),this.all_special_ids.push(de.id))}if(this.additional_special_tokens=Q.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(ie=>ie.content)),this.added_tokens_map=new Map(this.added_tokens.map(ie=>[ie.content,ie])),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=Q.model_max_length,this.remove_space=Q.remove_space,this.clean_up_tokenization_spaces=Q.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=Q.do_lowercase_and_remove_accent??!1,Q.padding_side&&(this.padding_side=Q.padding_side),this.legacy=!1,this.chat_template=Q.chat_template??null,Array.isArray(this.chat_template)){const ie=Object.create(null);for(const{name:de,template:ve}of this.chat_template){if(typeof de!="string"||typeof ve!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ie[de]=ve}this.chat_template=ie}this._compiled_template_cache=new Map}getToken(...N){for(const Q of N){const ie=this._tokenizer_config[Q];if(ie)if(typeof ie=="object"){if(ie.__type==="AddedToken")return ie.content;throw Error(`Unknown token: ${ie}`)}else return ie}return null}static async from_pretrained(N,{progress_callback:Q=null,config:ie=null,cache_dir:de=null,local_files_only:ve=!1,revision:je="main",legacy:He=null}={}){const We=await d(N,{progress_callback:Q,config:ie,cache_dir:de,local_files_only:ve,revision:je,legacy:He});return new this(...We)}_call(N,{text_pair:Q=null,add_special_tokens:ie=!0,padding:de=!1,truncation:ve=null,max_length:je=null,return_tensor:He=!0,return_token_type_ids:We=null}={}){const Je=Array.isArray(N);let dt;if(Je){if(N.length===0)throw Error("text array must be non-empty");if(Q!==null){if(Array.isArray(Q)){if(N.length!==Q.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");dt=N.map((Et,Rt)=>this._encode_plus(Et,{text_pair:Q[Rt],add_special_tokens:ie,return_token_type_ids:We}))}else dt=N.map(Et=>this._encode_plus(Et,{add_special_tokens:ie,return_token_type_ids:We}))}else{if(N==null)throw Error("text may not be null or undefined");if(Array.isArray(Q))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");dt=[this._encode_plus(N,{text_pair:Q,add_special_tokens:ie,return_token_type_ids:We})]}if(je===null?de==="max_length"?je=this.model_max_length:je=(0,i.max)(dt.map(Et=>Et.input_ids.length))[0]:ve||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."),je=Math.min(je,this.model_max_length??1/0),de||ve)for(let Et=0;Etje?ve&&Ls(dt[Et],je):de&&xs(dt[Et],je,Rt=>Rt==="input_ids"?this.pad_token_id:0,this.padding_side));const vt={};if(He){if(!(de&&ve)&&dt.some(Rt=>{var kt;for(const Kt of Object.keys(Rt))if(Rt[Kt].length!==((kt=dt[0][Kt])==null?void 0:kt.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 Et=[dt.length,dt[0].input_ids.length];for(const Rt of Object.keys(dt[0]))vt[Rt]=new a.Tensor("int64",BigInt64Array.from(dt.flatMap(kt=>kt[Rt]).map(BigInt)),Et)}else{for(const Et of Object.keys(dt[0]))vt[Et]=dt.map(Rt=>Rt[Et]);if(!Je)for(const Et of Object.keys(vt))vt[Et]=vt[Et][0]}return vt}_encode_text(N){if(N===null)return null;const Q=this.added_tokens_splitter.split(N);for(let de=0;de0&&(Q[de-1]=Q[de-1].trimEnd()),ve.rstrip&&de{if(de.length===0)return[];if(this.added_tokens_map.has(de))return[de];if(this.remove_space===!0&&(de=de.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(de=g(de)),this.normalizer!==null&&(de=this.normalizer(de)),de.length===0)return[];const je=this.pre_tokenizer!==null?this.pre_tokenizer(de,{section_index:ve}):[de];return this.model(je)})}_encode_plus(N,{text_pair:Q=null,add_special_tokens:ie=!0,return_token_type_ids:de=null}={}){const{tokens:ve,token_type_ids:je}=this._tokenize_helper(N,{pair:Q,add_special_tokens:ie}),He=this.model.convert_tokens_to_ids(ve),We={input_ids:He,attention_mask:new Array(He.length).fill(1)};return(de??this.return_token_type_ids)&&je&&(We.token_type_ids=je),We}_tokenize_helper(N,{pair:Q=null,add_special_tokens:ie=!1}={}){const de=this._encode_text(N),ve=this._encode_text(Q);return this.post_processor?this.post_processor(de,ve,{add_special_tokens:ie}):{tokens:(0,o.mergeArrays)(de??[],ve??[])}}tokenize(N,{pair:Q=null,add_special_tokens:ie=!1}={}){return this._tokenize_helper(N,{pair:Q,add_special_tokens:ie}).tokens}encode(N,{text_pair:Q=null,add_special_tokens:ie=!0,return_token_type_ids:de=null}={}){return this._encode_plus(N,{text_pair:Q,add_special_tokens:ie,return_token_type_ids:de}).input_ids}batch_decode(N,Q={}){return N instanceof a.Tensor&&(N=N.tolist()),N.map(ie=>this.decode(ie,Q))}decode(N,Q={}){if(N instanceof a.Tensor&&(N=v(N)),!Array.isArray(N)||N.length===0||!(0,o.isIntegralNumber)(N[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(N,Q)}decode_single(N,{skip_special_tokens:Q=!1,clean_up_tokenization_spaces:ie=null}){let de=this.model.convert_ids_to_tokens(N);Q&&(de=de.filter(je=>!this.special_tokens.includes(je)));let ve=this.decoder?this.decoder(de):de.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(ve=ve.replaceAll(this.decoder.end_of_word_suffix," "),Q&&(ve=ve.trim())),(ie??this.clean_up_tokenization_spaces)&&(ve=$(ve)),ve}get_chat_template({chat_template:N=null,tools:Q=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ie=this.chat_template;if(N!==null&&Object.hasOwn(ie,N))N=ie[N];else if(N===null)if(Q!==null&&"tool_use"in ie)N=ie.tool_use;else if("default"in ie)N=ie.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(ie).sort()}.`)}else if(N===null)if(this.chat_template)N=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating");return N}apply_chat_template(N,{tools:Q=null,documents:ie=null,chat_template:de=null,add_generation_prompt:ve=!1,tokenize:je=!0,padding:He=!1,truncation:We=!1,max_length:Je=null,return_tensor:dt=!0,return_dict:vt=!1,tokenizer_kwargs:Et={},...Rt}={}){if(de=this.get_chat_template({chat_template:de,tools:Q}),typeof de!="string")throw Error(`chat_template must be a string, but got ${typeof de}`);let kt=this._compiled_template_cache.get(de);kt===void 0&&(kt=new u.Template(de),this._compiled_template_cache.set(de,kt));const Kt=Object.create(null);for(const dr of Ds){const cr=this.getToken(dr);cr&&(Kt[dr]=cr)}const Mr=kt.render({messages:N,add_generation_prompt:ve,tools:Q,documents:ie,...Kt,...Rt});if(je){const dr=this._call(Mr,{add_special_tokens:!1,padding:He,truncation:We,max_length:Je,return_tensor:dt,...Et});return vt?dr:dr.input_ids}return Mr}}class Zr extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Ir extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class ws extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Ft extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class es extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class ts extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class bs extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Xt extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class De extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Qe extends at{}class et extends at{}class Bt extends at{constructor(N,Q){super(N,Q);te(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class Or extends at{constructor(){super(...arguments);te(this,"return_token_type_ids",!0)}}class Pr extends at{}class rs extends at{}class ss extends at{}class Ur extends at{constructor(k,N){super(k,N),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs(k,N,Q){return xr(this,k,N,Q)}}class ns extends Ur{}class os extends at{}class Wr extends at{}const yr="▁";class Ys extends at{constructor(N,Q){super(N,Q);te(this,"padding_side","left");this.legacy=Q.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new wt({replacement:yr,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(N){if(N===null)return null;if(this.legacy||N.length===0)return super._encode_text(N);let Q=super._encode_text(yr+N.replaceAll(yr," "));return Q.length>1&&Q[0]===yr&&this.special_tokens.includes(Q[1])&&(Q=Q.slice(1)),Q}}class vr extends at{}class Ts extends at{}class Es extends at{}class fr extends at{}class zs extends at{}class Zs extends at{}class Ar extends at{}class en extends at{}class Gr extends at{}function xr(he,k,N,Q){if(!("language_codes"in he)||!Array.isArray(he.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in he)||!(he.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in he)||typeof he.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ie=Q.src_lang,de=Q.tgt_lang;if(!he.language_codes.includes(de))throw new Error(`Target language code "${de}" is not valid. Must be one of: {${he.language_codes.join(", ")}}`);if(ie!==void 0){if(!he.language_codes.includes(ie))throw new Error(`Source language code "${ie}" is not valid. Must be one of: {${he.language_codes.join(", ")}}`);for(const ve of he.post_processor.config.single)if("SpecialToken"in ve&&he.languageRegex.test(ve.SpecialToken.id)){ve.SpecialToken.id=he.lang_to_token(ie);break}}return Q.forced_bos_token_id=he.model.convert_tokens_to_ids([he.lang_to_token(de)])[0],he._call(k,N)}class Ps extends at{constructor(k,N){super(k,N),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)),this.lang_to_token=Q=>Q}_build_translation_inputs(k,N,Q){return xr(this,k,N,Q)}}class ur extends at{constructor(k,N){super(k,N),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Q=>this.languageRegex.test(Q)).map(Q=>Q.slice(2,-2)),this.lang_to_token=Q=>`__${Q}__`}_build_translation_inputs(k,N,Q){return xr(this,k,N,Q)}}class _r extends at{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(k,{return_timestamps:N=!1,return_language:Q=!1,time_precision:ie=null,force_full_sequences:de=!0}={}){if(ie===null)throw Error("Must specify time_precision");let ve=null;const je=N==="word";function He(){return{language:ve,timestamp:[null,null],text:""}}const We=[];let Je=He(),dt=0;const vt=this.timestamp_begin,Rt=vt+1500;let kt=[],Kt=[],Mr=!1,dr=null;const cr=new Set(this.all_special_ids);for(const Dt of k){const rr=Dt.tokens,gr=je?Dt.token_timestamps:null;let Hr=null,Lr=vt;if("stride"in Dt){const[or,Vt,Zt]=Dt.stride;if(dt-=Vt,dr=or-Zt,Vt&&(Lr=Vt/ie+vt),Zt)for(let er=rr.length-1;er>=0;--er){const tr=Number(rr[er]);if(tr>=vt){if(Hr!==null&&(tr-vt)*ie=vt&&Vt<=Rt){const Zt=(Vt-vt)*ie+dt,er=(0,i.round)(Zt,2);if(Hr!==null&&Vt>=Hr)Mr=!0;else if(Mr||kt.length>0&&Vt0?(kt.push(Yt),je&&Kt.push(zr)):kt.every(or=>or.length===0)&&(Je=He(),kt=[],Yt=[],Kt=[],zr=[])}if(kt.length>0){if(de&&N)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Dt,rr]=this.findLongestCommonSequence(kt,Kt),gr=this.decode(Dt);Je.text=gr,je&&(Je.words=this.collateWordTimestamps(Dt,rr,ve)),We.push(Je)}let Nt=Object.create(null);const Kr=We.map(Dt=>Dt.text).join("");if(N||Q){for(let Dt=0;Dt0;let je=ve?[]:null,He=ve?N[0]:null;for(let We=1;WeVt===Lr[Zt]&&He[Kr+Zt]<=N[We][gr+Zt]).length:Yt=rr.filter((Vt,Zt)=>Vt===Lr[Zt]).length;const zr=Nt/1e4,or=Yt/Nt+zr;Yt>1&&or>dt&&(dt=or,vt=[Kr,Dt,gr,Hr])}const[Rt,kt,Kt,Mr]=vt,dr=Math.floor((kt+Rt)/2),cr=Math.floor((Mr+Kt)/2);de.push(...Q.slice(0,dr)),Q=Je.slice(cr),ie=Q.length,ve&&(je.push(...He.slice(0,dr)),He=N[We].slice(cr))}return de.push(...Q),ve?(je.push(...He),[de,je]):[de,[]]}collateWordTimestamps(k,N,Q){const[ie,de,ve]=this.combineTokensIntoWords(k,Q),je=[];for(let He=0;He=ie){const je=((ve-ie)*Q).toFixed(2);de.push(`<|${je}|>`),de.push([])}else de[de.length-1].push(ve);return de=de.map(ve=>typeof ve=="string"?ve:super.decode(ve,N)),de.join("")}splitTokensOnUnicode(k){const N=this.decode(k,{decode_with_timestamps:!0}),Q="�",ie=[],de=[],ve=[];let je=[],He=[],We=0;for(let Je=0;Je=this.model.tokens_to_ids.get("<|endoftext|>"),Rt=Je.startsWith(" "),kt=Je.trim(),Kt=He.test(kt);if(Et||Rt||Kt||de.length===0)de.push(Je),ve.push(dt),je.push(vt);else{const Mr=de.length-1;de[Mr]+=Je,ve[Mr].push(...dt),je[Mr].push(...vt)}}return[de,ve,je]}mergePunctuations(k,N,Q,ie,de){const ve=structuredClone(k),je=structuredClone(N),He=structuredClone(Q);let We=ve.length-2,Je=ve.length-1;for(;We>=0;)ve[We].startsWith(" ")&&ie.includes(ve[We].trim())?(ve[Je]=ve[We]+ve[Je],je[Je]=(0,o.mergeArrays)(je[We],je[Je]),He[Je]=(0,o.mergeArrays)(He[We],He[Je]),ve[We]="",je[We]=[],He[We]=[]):Je=We,--We;for(We=0,Je=1;Jedt),je.filter(dt=>dt.length>0),He.filter(dt=>dt.length>0)]}}class Dr extends at{}class tn extends at{}class rn extends at{}class sn extends at{constructor(k,N){super(k,N),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Q=>this.languageRegex.test(Q)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(k){if(k===null)return null;const[N,...Q]=k.trim().split(this.languageRegex);if(Q.length===0)return super._encode_text(N);if(Q.length===2){const[ie,de]=Q;return this.supported_language_codes.includes(ie)||console.warn(`Unsupported language code "${ie}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,o.mergeArrays)([ie],super._encode_text(de))}}}class nn extends at{}class on extends at{}class Ms extends at{}class an extends at{}class Bs extends at{}class ln extends at{constructor(k,N){super(k,N),this.decoder=new lt({})}}class un extends at{}class ys extends at{}class dn{static async from_pretrained(k,{progress_callback:N=null,config:Q=null,cache_dir:ie=null,local_files_only:de=!1,revision:ve="main",legacy:je=null}={}){var vt;const[He,We]=await d(k,{progress_callback:N,config:Q,cache_dir:ie,local_files_only:de,revision:ve,legacy:je}),Je=((vt=We.tokenizer_class)==null?void 0:vt.replace(/Fast$/,""))??"PreTrainedTokenizer";let dt=this.TOKENIZER_CLASS_MAPPING[Je];return dt||(console.warn(`Unknown tokenizer class "${Je}", attempting to construct from base class.`),dt=at),new dt(He,We)}}te(dn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Pr,DistilBertTokenizer:Qe,CamembertTokenizer:et,DebertaTokenizer:es,DebertaV2Tokenizer:ts,BertTokenizer:Zr,HerbertTokenizer:bs,ConvBertTokenizer:Xt,RoFormerTokenizer:De,XLMTokenizer:Bt,ElectraTokenizer:Or,MobileBertTokenizer:ws,SqueezeBertTokenizer:Ft,AlbertTokenizer:Ir,GPT2Tokenizer:rs,BartTokenizer:ss,MBartTokenizer:Ur,MBart50Tokenizer:ns,RobertaTokenizer:os,WhisperTokenizer:_r,CodeGenTokenizer:Dr,CLIPTokenizer:tn,SiglipTokenizer:rn,MarianTokenizer:sn,BloomTokenizer:Wr,NllbTokenizer:Ps,M2M100Tokenizer:ur,LlamaTokenizer:Ys,CodeLlamaTokenizer:vr,XLMRobertaTokenizer:Ts,MPNetTokenizer:Es,FalconTokenizer:fr,GPTNeoXTokenizer:zs,EsmTokenizer:Zs,Wav2Vec2CTCTokenizer:nn,BlenderbotTokenizer:on,BlenderbotSmallTokenizer:Ms,SpeechT5Tokenizer:an,NougatTokenizer:Bs,VitsTokenizer:ln,Qwen2Tokenizer:Ar,GemmaTokenizer:en,Grok1Tokenizer:Gr,CohereTokenizer:un,MgpstrTokenizer:ys,PreTrainedTokenizer:at})},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>G,hamming:()=>c,hanning:()=>d,mel_filter_bank:()=>C,read_audio:()=>u,spectrogram:()=>S,window_function:()=>A});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("?7a2c"),l=t("./src/utils/tensor.js");async function u(j,ee){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)(j)).arrayBuffer(),Z=new AudioContext({sampleRate:ee});typeof ee>"u"&&console.warn(`No sampling rate provided, using default of ${Z.sampleRate}Hz.`);const X=await Z.decodeAudioData(H);let oe;if(X.numberOfChannels===2){const me=Math.sqrt(2),ae=X.getChannelData(0),V=X.getChannelData(1);oe=new Float32Array(ae.length);for(let F=0;F2595*Math.log10(1+j/700),kaldi:j=>1127*Math.log(1+j/700),slaney:(j,ee=1e3,H=15,Z=27/Math.log(6.4))=>j>=ee?H+Math.log(j/ee)*Z:3*j/200};function f(j,ee="htk"){const H=_[ee];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?H(j):j.map(Z=>H(Z))}const v={htk:j=>700*(10**(j/2595)-1),kaldi:j=>700*(Math.exp(j/1127)-1),slaney:(j,ee=1e3,H=15,Z=Math.log(6.4)/27)=>j>=H?ee*Math.exp(Z*(j-H)):200*j/3};function $(j,ee="htk"){const H=v[ee];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?H(j):j.map(Z=>H(Z))}function w(j,ee){const H=Float64Array.from({length:ee.length-1},(me,ae)=>ee[ae+1]-ee[ae]),Z=Array.from({length:j.length},()=>new Array(ee.length));for(let me=0;menew Array(j.length));for(let me=0;mej+Z*oe)}function C(j,ee,H,Z,X,oe=null,me="htk",ae=!1){if(oe!==null&&oe!=="slaney")throw new Error('norm must be one of null or "slaney"');if(j<2)throw new Error(`Require num_frequency_bins: ${j} >= 2`);if(H>Z)throw new Error(`Require min_frequency: ${H} <= max_frequency: ${Z}`);const V=f(H,me),F=f(Z,me),W=g(V,F,ee+2);let re=$(W,me),fe;if(ae){const ce=X/((j-1)*2);fe=f(Float64Array.from({length:j},($e,Ue)=>Ue*ce),me),re=W}else fe=g(0,Math.floor(X/2),j);const se=w(fe,re);if(oe!==null&&oe==="slaney")for(let ce=0;ceX)throw Error(`frame_length (${H}) may not be larger than fft_length (${X})`);if(xe!==H)throw new Error(`Length of the window (${xe}) must equal frame_length (${H})`);if(Z<=0)throw new Error("hop_length must be greater than zero");if(oe===null&&W!==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(me){if(ae!=="reflect")throw new Error(`pad_mode="${ae}" not implemented yet.`);const ye=Math.floor((X-1)/2)+1;j=E(j,ye,ye)}let Me=Math.floor(1+Math.floor((j.length-H)/Z));we!==null&&MeMe?R&&(Fe=q):Fe=Ae=q);const ze=new o.FFT(X),Ve=new Float64Array(X),O=new Float64Array(ze.outputBufferSize),Y=new Float32Array(Se*Fe);for(let ye=0;ye=1;--Ie)Ve[Ie]-=F*Ve[Ie-1];Ve[0]*=1-F}for(let Ie=0;IeMath.pow(ae,.85));break;default:throw new Error(`Unknown window type ${ee}.`)}if(H&&(me=me.subarray(0,j)),Z===null)return me;if(j>Z)throw new Error(`Length of the window (${j}) may not be larger than frame_length (${Z})`);return me}function B(j,ee){let H=44;const Z=new ArrayBuffer(H+j.length*4),X=new DataView(Z);K(X,0,"RIFF"),X.setUint32(4,36+j.length*4,!0),K(X,8,"WAVE"),K(X,12,"fmt "),X.setUint32(16,16,!0),X.setUint16(20,3,!0),X.setUint16(22,1,!0),X.setUint32(24,ee,!0),X.setUint32(28,ee*4,!0),X.setUint16(32,4,!0),X.setUint16(34,32,!0),K(X,36,"data"),X.setUint32(40,j.length*4,!0);for(let oe=0;oe{let oe=await X.arrayBuffer();a.writeFileSync(Z,Buffer.from(oe))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await H(ee,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:()=>u,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.json",u="generation_config.json"},"./src/utils/core.js":(e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>u,calculateReflectOffset:()=>_,count:()=>w,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>$,mergeArrays:()=>d,pick:()=>v,pop:()=>p,product:()=>c,reverseDictionary:()=>o,saveBlob:()=>f});function s(g,C){g&&g(C)}function o(g){return Object.fromEntries(Object.entries(g).map(([C,E])=>[E,C]))}function n(g){return g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(g){var C,E,y;return((y=(E=(C=g==null?void 0:g.prototype)==null?void 0:C.__proto__)==null?void 0:E.constructor)==null?void 0:y.name)==="TypedArray"}function a(g){return Number.isInteger(g)||typeof g=="bigint"}function l(g){return g==null||g===-1}function u(g){const C=[];let E=g;for(;Array.isArray(E);)C.push(E.length),E=E[0];return C}function p(g,C,E=void 0){const y=g[C];if(y!==void 0)return delete g[C],y;if(E===void 0)throw Error(`Key ${C} does not exist in object.`);return E}function d(...g){return Array.prototype.concat.apply([],g)}function c(...g){return g.reduce((C,E)=>C.flatMap(y=>E.map(b=>[y,b])))}function _(g,C){return Math.abs((g+C)%(2*C)-C)}function f(g,C){const E=URL.createObjectURL(C),y=document.createElement("a");y.href=E,y.download=g,y.click(),y.remove(),URL.revokeObjectURL(E)}function v(g,C){return Object.assign({},...C.map(E=>{if(g[E]!==void 0)return{[E]:g[E]}}))}function $(g){let C=0;for(const E of g)++C;return C}function w(g,C){let E=0;for(const y of g)y===C&&++E;return E}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>o,DictionarySplitter:()=>l,LRUCache:()=>u,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(d=(_,f)=>_>f,c=1/0){this._heap=[],this._comparator=d,this._maxSize=c}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 c of d)if(this.size0&&this._swap(0,c),this._heap.pop(),this._siftDown(),d}replace(d){const c=this.peek();return this._heap[0]=d,this._siftDown(),c}_parent(d){return(d+1>>>1)-1}_left(d){return(d<<1)+1}_right(d){return d+1<<1}_greater(d,c){return this._comparator(this._heap[d],this._heap[c])}_swap(d,c){const _=this._heap[d];this._heap[d]=this._heap[c],this._heap[c]=_}_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 f=new a(this.bosTokenId,0,0,0,0),v=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(f.clone()),this.nodes.push(v.clone()),this.beginNodes[this.len].push(v),this.endNodes[0].push(f)}insert(d,c,_,f){const v=this.nodes.length,$=new a(f,v,d,c,_);this.beginNodes[d].push($),this.endNodes[d+c].push($),this.nodes.push($)}viterbi(){const d=this.len;let c=0;for(;c<=d;){if(this.beginNodes[c].length==0)return[];for(let w of this.beginNodes[c]){w.prev=null;let g=0,C=null;for(let E of this.endNodes[c]){const y=E.backtraceScore+w.score;(C===null||y>g)&&(C=E.clone(),g=y)}if(C!==null)w.prev=C,w.backtraceScore=g;else return[]}++c}const _=[],v=this.beginNodes[d][0].prev;if(v===null)return[];let $=v.clone();for(;$.prev!==null;)_.push($.clone()),$=$.clone().prev.clone();return _.reverse(),_}piece(d){return this.chars.slice(d.pos,d.pos+d.length).join("")}tokens(){return this.viterbi().map(c=>this.piece(c))}tokenIds(){return this.viterbi().map(c=>c.tokenId)}}class a{constructor(d,c,_,f,v){this.tokenId=d,this.nodeId=c,this.pos=_,this.length=f,this.score=v,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 _;const c=Object.create(null);for(const f of d){let v=c;for(let $=0;$f&&c.push(d.slice(f,v)),c.push(w),v+=w.length,f=v):++v}return f<_&&c.push(d.slice(f)),c}}class u{constructor(d){this.capacity=d,this.cache=new Map}get(d){if(!this.cache.has(d))return;const c=this.cache.get(d);return this.cache.delete(d),this.cache.set(d,c),c}put(d,c){this.cache.has(d)&&this.cache.delete(d),this.cache.set(d,c),this.cache.size>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 u;return async function(){if(u===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)u=!1;else try{u=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{u=!1}return u}}(),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:()=>_,getModelFile:()=>g,getModelJSON:()=>C});var s=t("?7a2c"),o=t("?a42a"),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 u{constructor(x){if(this.filePath=x,this.headers=new Headers,this.exists=s.existsSync(x),this.exists){this.status=200,this.statusText="OK";let S=s.statSync(x);this.headers.set("content-length",S.size.toString()),this.updateContentType();const A=s.createReadStream(x);this.body=new ReadableStream({start(B){A.on("data",K=>B.enqueue(K)),A.on("end",()=>B.close()),A.on("error",K=>B.error(K))},cancel(){A.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const x=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[x]??"application/octet-stream")}clone(){let x=new u(this.filePath);return x.exists=this.exists,x.status=this.status,x.statusText=this.statusText,x.headers=new Headers(this.headers),x}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const x=await s.promises.readFile(this.filePath);return new Blob([x],{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(b,x=null,S=null){let A;try{A=new URL(b)}catch{return!1}return!(x&&!x.includes(A.protocol)||S&&!S.includes(A.hostname))}const d=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function c(b){return!(!d.test(b)||b.includes("..")||b.includes("--")||b.endsWith(".git")||b.endsWith(".ipynb"))}async function _(b){var x;if(n.env.useFS&&!p(b,["http:","https:","blob:"]))return new u(b.toString());if(typeof process<"u"&&((x=process==null?void 0:process.release)==null?void 0:x.name)==="node"){const S=!!(As!=null&&As.TESTING_REMOTELY),A=n.env.version,B=new Headers;if(B.set("User-Agent",`transformers.js/${A}; is_ci/${S};`),p(b,["http:","https:"],["huggingface.co","hf.co"])){const G=(As==null?void 0:As.HF_TOKEN)??(As==null?void 0:As.HF_ACCESS_TOKEN);G&&B.set("Authorization",`Bearer ${G}`)}return fetch(b,{headers:B})}else return fetch(b)}const f={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 v(b,x,S){if(!S)return null;const A=f[b]??`Error (${b}) occurred while trying to load file`;throw Error(`${A}: "${x}".`)}class ${constructor(x){this.path=x}async match(x){let S=o.join(this.path,x),A=new u(S);if(A.exists)return A}async put(x,S,A=void 0){let B=o.join(this.path,x);try{const K=S.headers.get("Content-Length"),G=parseInt(K??"0");let j=0;await s.promises.mkdir(o.dirname(B),{recursive:!0});const ee=s.createWriteStream(B),H=S.body.getReader();for(;;){const{done:Z,value:X}=await H.read();if(Z)break;await new Promise((me,ae)=>{ee.write(X,V=>{if(V){ae(V);return}me()})}),j+=X.length;const oe=G?j/G*100:0;A==null||A({progress:oe,loaded:j,total:G})}ee.close()}catch(K){try{await s.promises.unlink(B)}catch{}throw K}}}async function w(b,...x){for(let S of x)try{let A=await b.match(S);if(A)return A}catch{continue}}async function g(b,x,S=!0,A={},B=!1){if(!n.env.allowLocalModels){if(A.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)(A.progress_callback,{status:"initiate",name:b,file:x});let K;if(!K&&n.env.useCustomCache){if(!n.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!n.env.customCache.match||!n.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");K=n.env.customCache}if(!K&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{K=await caches.open("transformers-cache")}catch(re){console.warn("An error occurred while opening the browser cache:",re)}}if(!K&&n.env.useFSCache){if(!n.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");K=new $(A.cache_dir??n.env.cacheDir)}const G=A.revision??"main",j=y(b,x),ee=c(b),H=ee?y(n.env.localModelPath,j):j,Z=y(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",b).replaceAll("{revision}",encodeURIComponent(G)),x);let X;const oe=K instanceof $?G==="main"?j:y(b,G,x):Z;let me=!1,ae;K&&(ae=await w(K,H,oe));const V=ae!==void 0;if(ae===void 0){if(n.env.allowLocalModels)if(p(j,["http:","https:"])){if(A.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${j}.`);if(!n.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${j}.`)}else try{ae=await _(H),X=H}catch(fe){console.warn(`Unable to load from local path "${H}": "${fe}"`)}if(ae===void 0||ae.status===404){if(A.local_files_only||!n.env.allowRemoteModels){if(S)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${H}".`);return null}if(!ee)throw Error(`Local file missing at "${H}" and download aborted due to invalid model ID "${b}".`);if(ae=await _(Z),ae.status!==200)return v(ae.status,Z,S);X=oe}me=K&&typeof Response<"u"&&ae instanceof Response&&ae.status===200}(0,i.dispatchCallback)(A.progress_callback,{status:"download",name:b,file:x});let F;if(!(n.apis.IS_NODE_ENV&&B)){let re;A.progress_callback?V&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(re=new Uint8Array(await ae.arrayBuffer()),(0,i.dispatchCallback)(A.progress_callback,{status:"progress",name:b,file:x,progress:100,loaded:re.length,total:re.length})):re=await E(ae,fe=>{(0,i.dispatchCallback)(A.progress_callback,{status:"progress",name:b,file:x,...fe})}):re=new Uint8Array(await ae.arrayBuffer()),F=re}if(me&&X&&await K.match(X)===void 0&&(F?await K.put(X,new Response(F,{headers:ae.headers})).catch(re=>{console.warn(`Unable to add response to browser cache: ${re}.`)}):await K.put(X,ae,A.progress_callback)),(0,i.dispatchCallback)(A.progress_callback,{status:"done",name:b,file:x}),F){if(!n.apis.IS_NODE_ENV&&B)throw new Error("Cannot return path in a browser environment.");return F}if(ae instanceof u)return ae.filePath;const W=await(K==null?void 0:K.match(X));if(W instanceof u)return W.filePath;if(W instanceof Response)return new Uint8Array(await W.arrayBuffer());if(typeof W=="string")return W;throw new Error("Unable to get model file path or buffer.")}async function C(b,x,S=!0,A={}){const B=await g(b,x,S,A,!1);if(B===null)return{};const G=new TextDecoder("utf-8").decode(B);return JSON.parse(G)}async function E(b,x){const S=b.headers.get("Content-Length");S===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let A=parseInt(S??"0"),B=new Uint8Array(A),K=0;const G=b.body.getReader();async function j(){const{done:ee,value:H}=await G.read();if(ee)return;const Z=K+H.length;if(Z>A){A=Z;const oe=new Uint8Array(A);oe.set(B),B=oe}B.set(H,K),K=Z;const X=K/A*100;return x({progress:X,loaded:K,total:A}),j()}return await j(),B}function y(...b){return b=b.map((x,S)=>(S&&(x=x.replace(new RegExp("^/"),"")),S!==b.length-1&&(x=x.replace(new RegExp("/$"),"")),x)),b.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>f,load_image:()=>v});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,u,p;const d=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;if(d)l=($,w)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas($,w)},p=self.createImageBitmap,u=self.ImageData;else if(a)p=async $=>{const g=(await $.metadata()).channels,{data:C,info:E}=await $.rotate().raw().toBuffer({resolveWithObject:!0}),y=new f(new Uint8ClampedArray(C),E.width,E.height,E.channels);return g!==void 0&&g!==E.channels&&y.convert(g),y};else throw new Error("Unable to load image processing library.");const c={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},_=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class f{constructor(w,g,C,E){this.data=w,this.width=g,this.height=C,this.channels=E}get size(){return[this.width,this.height]}static async read(w){if(w instanceof f)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 C=w.getContext("2d").getImageData(0,0,w.width,w.height).data;return new f(C,w.width,w.height,4)}static async fromURL(w){const g=await(0,o.getFile)(w);if(g.status!==200)throw new Error(`Unable to read image from "${w}" (${g.status} ${g.statusText})`);const C=await g.blob();return this.fromBlob(C)}static async fromBlob(w){if(d){const g=await p(w),C=l(g.width,g.height).getContext("2d");return C.drawImage(g,0,0),new this(C.getImageData(0,0,g.width,g.height).data,g.width,g.height,4)}else{const g=a(await w.arrayBuffer());return await p(g)}}static fromTensor(w,g="CHW"){if(w.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${w.dims.length} dimensions.`);if(g==="CHW")w=w.transpose(1,2,0);else if(g!=="HWC")throw new Error(`Unsupported channel format: ${g}`);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 f(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 g=0,C=0;g=0?S=C:B=-C,E>=0?A=E:K=-E,x.drawImage(b,S,A,w,g,B,K,w,g),new f(x.getImageData(0,0,w,g).data,w,g,4).convert(y)}else{let y=this.toSharp();if(C>=0&&E>=0)y=y.extract({left:Math.floor(C),top:Math.floor(E),width:w,height:g});else if(C<=0&&E<=0){const b=Math.floor(-E),x=Math.floor(-C);y=y.extend({top:b,left:x,right:w-this.width-x,bottom:g-this.height-b})}else{let b=[0,0],x=0;E<0?(b[0]=Math.floor(-E),b[1]=g-this.height-b[0]):x=Math.floor(E);let S=[0,0],A=0;C<0?(S[0]=Math.floor(-C),S[1]=w-this.width-S[0]):A=Math.floor(C),y=y.extend({top:b[0],bottom:b[1],left:S[0],right:S[1]}).extract({left:A,top:x,width:w,height:g})}return await p(y)}}async toBlob(w="image/png",g=1){if(!d)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:w,quality:g})}toTensor(w="CHW"){let g=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(w!=="HWC")if(w==="CHW")g=g.permute(2,0,1);else throw new Error(`Unsupported channel format: ${w}`);return g}toCanvas(){if(!d)throw new Error("toCanvas() is only supported in browser environments.");const w=this.clone().rgba(),g=l(w.width,w.height),C=new u(w.data,w.width,w.height);return g.getContext("2d").putImageData(C,0,0),g}split(){const{data:w,width:g,height:C,channels:E}=this,y=w.constructor,b=w.length/E,x=Array.from({length:E},()=>new y(b));for(let S=0;Snew f(S,g,C,1))}_update(w,g,C,E=null){return this.data=w,this.width=g,this.height=C,E!==null&&(this.channels=E),this}clone(){return new f(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 g=w.split(".").pop().toLowerCase(),C=_.get(g)??"image/png",E=await this.toBlob(C);(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 v=f.read.bind(f)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>v,bankers_round:()=>g,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>C,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>u,max:()=>d,medianFilter:()=>$,min:()=>p,permute_data:()=>o,round:()=>w,softmax:()=>n});function s(E,[y,b,x],[S,A],B="bilinear",K=!1){const G=A/x,j=S/b,ee=new E.constructor(S*A*y),H=b*x,Z=S*A;for(let X=0;X=0;--K)S[K]=G,x[K]=y[b[K]],G*=x[K];const A=b.map((K,G)=>S[b.indexOf(G)]),B=new E.constructor(E.length);for(let K=0;K=0;--j)G+=ee%y[j]*A[j],ee=Math.floor(ee/y[j]);B[G]=E[K]}return[B,x]}function n(E){const y=d(E)[0],b=E.map(A=>Math.exp(A-y)),x=b.reduce((A,B)=>A+B,0);return b.map(A=>A/x)}function i(E){const y=d(E)[0];let b=0;for(let A=0;AA-y-x)}function a(E,y){let b=0;for(let x=0;xy+b*b,0))}function p(E){if(E.length===0)throw Error("Array must not be empty");let y=E[0],b=0;for(let x=1;xy&&(y=E[x],b=x);return[y,b]}function c(E){return E>0&&(E&E-1)===0}class _{constructor(y){if(this.size=y|0,this.size<=1||!c(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=y<<1,this.table=new Float64Array(this.size*2);for(let x=0;xx;x<<=1)++b;this._width=b%2===0?b-1:b,this._bitrev=new Int32Array(1<>>S&3)<>>1);for(let S=0;S>>1]=y[S];return x}toComplexArray(y,b){const x=b||this.createComplexArray();for(let S=0;S>>1],x[S+1]=0;return x}transform(y,b){if(y===b)throw new Error("Input and output buffers must be different");this._transform4(y,b,1)}realTransform(y,b){if(y===b)throw new Error("Input and output buffers must be different");this._realTransform4(y,b,1)}inverseTransform(y,b){if(y===b)throw new Error("Input and output buffers must be different");this._transform4(y,b,-1);for(let x=0;x>=2;B>=2;B>>=2){K=S/B<<1;const Z=K>>>2;for(G=0;G>>1,B>>>1)}else for(G=0,j=0;G>>1,B>>>1,x)}const H=this.table;for(B>>=2;B>=2;B>>=2){K=S/B<<1;const X=K>>>1,oe=X>>>1,me=oe>>>1;for(G=0;G>>1;for(let X=2;X>1;++ee){const H=(ee+1-y)**2/2,Z=Math.sqrt(G**2+j**2)**H,X=H*Math.atan2(j,G),oe=2*ee;A[oe]=Z*Math.cos(X),A[oe+1]=Z*Math.sin(X),B[oe]=A[oe],B[oe+1]=-A[oe+1]}this._slicedChirpBuffer=A.subarray(b,x),this._f=new _(S>>1),this._f.transform(this._chirpBuffer,B)}_transform(y,b,x){const S=this._buffer1,A=this._buffer2,B=this._outBuffer1,K=this._outBuffer2,G=this._chirpBuffer,j=this._slicedChirpBuffer,ee=this._a;if(x)for(let H=0;H>1,oe=b[X];S[H]=oe*j[H],S[Z]=oe*j[Z]}else for(let H=0;H=E.length&&(G=2*(E.length-1)-G),x[B++]=E[G]}x.sort(),b[A]=x[S]}return b}function w(E,y){const b=Math.pow(10,y);return Math.round(E*b)/b}function g(E){const y=Math.round(E);return Math.abs(E)%1===.5?y%2===0?y:y-1:y}function C(E){const y=E.length,b=E[0].length,x=[y+1,b+1],S=Array.from({length:x[0]},()=>Array(x[1]).fill(1/0));S[0][0]=0;const A=Array.from({length:x[0]},()=>Array(x[1]).fill(-1));for(let ee=1;ee0||K>0;)switch(G.push(B-1),j.push(K-1),A[B][K]){case 0:--B,--K;break;case 1:--B;break;case 2:--K;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${B}, ${K}]. Please file a bug report.`)}return G.reverse(),j.reverse(),[G,j]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>b,full:()=>j,full_like:()=>ee,interpolate:()=>p,interpolate_4d:()=>d,layer_norm:()=>g,matmul:()=>c,mean:()=>B,mean_pooling:()=>w,ones:()=>H,ones_like:()=>Z,permute:()=>u,quantize_embeddings:()=>ae,rand:()=>me,rfft:()=>_,slice:()=>$,stack:()=>x,std_mean:()=>A,topk:()=>f,zeros:()=>X,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){te(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,re)=>{if(typeof re=="string"){let fe=Number(re);if(Number.isInteger(fe))return W._getitem(fe)}return W[re]},set:(W,re,fe)=>W[re]=fe})}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 re=W.reduce((fe,se)=>fe*se);for(let fe=0;fe0){const fe=re.reduce((se,ce)=>se*ce);return this._subarray(F,fe,re)}else return new a(this.type,[this.data[F]],re)}indexOf(F){const W=this.data;for(let re=0;repe)throw new Error(`Invalid slice: ${q}`);const xe=[Math.max(R,0),Math.min(pe,this.dims[we])];re.push(xe),W.push(xe[1]-xe[0])}else throw new Error(`Invalid slice: ${q}`)}const fe=re.map(([we,q])=>q-we),se=fe.reduce((we,q)=>we*q),ce=this.data,$e=new ce.constructor(se),Ue=this.stride();for(let we=0;we=0;--R){const xe=fe[R];q+=(pe%xe+re[R][0])*Ue[R],pe=Math.floor(pe/xe)}$e[we]=ce[q]}return new a(this.type,$e,W)}permute(...F){return u(this,F)}transpose(...F){return this.permute(...F)}sum(F=null,W=!1){return this.norm(1,F,W)}norm(F="fro",W=null,re=!1){if(F==="fro")F=2;else if(typeof F=="string")throw Error(`Unsupported norm: ${F}`);const fe=this.data,se=(we,q)=>we+q**F;if(W===null){const we=fe.reduce(se,0)**(1/F);return new a(this.type,[we],[])}const[ce,$e,Ue]=S(se,this,W,re);if(F!==1)for(let we=0;we<$e.length;++we)$e[we]=$e[we]**(1/F);return new a(ce,$e,Ue)}normalize_(F=2,W=1){W=y(W,this.dims.length);const re=this.norm(F,W,!0),fe=this.data,se=re.data;for(let ce=0;ce=0;--Ue){const R=this.dims[Ue];if(Ue!==W){const pe=we%R;$e+=pe*q,q*=this.dims[Ue]}we=Math.floor(we/R)}fe[ce]/=se[$e]}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,C(this.dims,F))}squeeze_(F=null){return this.dims=C(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 re=this.dims.slice(0,F),fe=this.dims.slice(F,W+1),se=this.dims.slice(W+1);return this.dims=[...re,fe.reduce((ce,$e)=>ce*$e,1),...se],this}flatten(F=0,W=-1){return this.clone().flatten_(F,W)}view(...F){let W=-1;for(let fe=0;fe$e!==W?se*ce:se,1);F[W]=re.length/fe}return new a(this.type,re,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),re=this.data;for(let fe=0;feMath.min(ce,$e),this,F,W,1/0);return new a(re,fe,se)}max(F=null,W=!1){if(F===null){const ce=(0,s.max)(this.data)[0];return new a(this.type,[ce],[])}const[re,fe,se]=S((ce,$e)=>Math.max(ce,$e),this,F,W,-1/0);return new a(re,fe,se)}argmin(F=null,W=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const re=(0,s.min)(this.data)[1];return new a("int64",[BigInt(re)],[])}argmax(F=null,W=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const re=(0,s.max)(this.data)[1];return new a("int64",[BigInt(re)],[])}to(F){if(this.type===F)return this;if(!i.hasOwnProperty(F))throw new Error(`Unsupported type: ${F}`);let W;const re=["int64","uint64"].includes(this.type),fe=["int64","uint64"].includes(F);return re&&!fe?W=Number:!re&&fe&&(W=BigInt),new a(F,i[F].from(this.data,W),this.dims)}}function l(V,F){const W=V.length,re=F.reduce((se,ce)=>se*ce);if(W!==re)throw Error(`cannot reshape array of size ${W} into shape (${F})`);let fe=V;for(let se=F.length-1;se>=0;se--)fe=fe.reduce((ce,$e)=>{let Ue=ce[ce.length-1];return Ue.lengthnew a("int64",V,[V.length]);async function $(V,F,W,re,fe){return await(await n.TensorOpRegistry.slice)({x:V,s:v(F),e:v(W),a:v(re),t:v(fe??new Array(re.length).fill(1))})}function w(V,F){const W=V.data,re=F.data,fe=[V.dims[0],V.dims[2]],se=new W.constructor(fe[0]*fe[1]),[ce,$e,Ue]=V.dims;let we=0;for(let q=0;qW!==1):typeof F=="number"?V[F]===1&&V.splice(F,1):Array.isArray(F)&&(V=V.filter((W,re)=>W!==1||!F.includes(re))),V}function E(V,F){return F=y(F,V.length+1),V=V.slice(),V.splice(F,0,1),V}function y(V,F,W=null,re=!0){if(V<-F||V>=F){if(re)throw new Error(`IndexError: index ${V} is out of bounds for dimension${W===null?"":" "+W} with size ${F}`);return V<-F?0:F}return V<0&&(V=(V%F+F)%F),V}function b(V,F=0){F=y(F,V[0].dims.length);const W=V[0].dims.slice();W[F]=V.reduce((ce,$e)=>ce+$e.dims[F],0);const re=W.reduce((ce,$e)=>ce*$e,1),fe=new V[0].data.constructor(re),se=V[0].type;if(F===0){let ce=0;for(const $e of V){const Ue=$e.data;fe.set(Ue,ce),ce+=Ue.length}}else{let ce=0;for(let $e=0;$e=0;--pe){const Se=we[pe];let Ae=xe%Se;pe===F&&(Ae+=ce),R+=Ae*Me,Me*=W[pe],xe=Math.floor(xe/Se)}fe[R]=Ue[q]}ce+=we[F]}}return new a(se,fe,W)}function x(V,F=0){return b(V.map(W=>W.unsqueeze(F)),F)}function S(V,F,W=null,re=!1,fe=null){const se=F.data,ce=F.dims;W=y(W,ce.length);const $e=ce.slice();$e[W]=1;const Ue=new se.constructor(se.length/ce[W]);fe!==null&&Ue.fill(fe);for(let we=0;we=0;--R){const Me=ce[R];if(R!==W){const Se=pe%Me;q+=Se*xe,xe*=$e[R]}pe=Math.floor(pe/Me)}Ue[q]=V(Ue[q],se[we],we,q)}return re||$e.splice(W,1),[F.type,Ue,$e]}function A(V,F=null,W=1,re=!1){const fe=V.data,se=V.dims;if(F===null){const xe=fe.reduce((Fe,ze)=>Fe+ze,0)/fe.length,Me=Math.sqrt(fe.reduce((Fe,ze)=>Fe+(ze-xe)**2,0)/(fe.length-W)),Se=new a(V.type,[xe],[]);return[new a(V.type,[Me],[]),Se]}F=y(F,se.length);const ce=B(V,F,re),$e=ce.data,[Ue,we,q]=S((pe,xe,Me,Se)=>pe+(xe-$e[Se])**2,V,F,re);for(let pe=0;pewe+q,0);return new a(V.type,[Ue/fe.length],[])}F=y(F,re.length);const[se,ce,$e]=S((Ue,we)=>Ue+we,V,F,W);if(re[F]!==1)for(let Ue=0;Ue=0;--W)F[W]=re,re*=V[W];return F}function G(V,F,W,re){const fe=V.reduce((se,ce)=>se*ce,1);return new a(W,new re(fe).fill(F),V)}function j(V,F){let W,re;if(typeof F=="number")W="float32",re=Float32Array;else if(typeof F=="bigint")W="int64",re=BigInt64Array;else if(typeof F=="boolean")W="bool",re=Uint8Array;else throw new Error(`Unsupported data type: ${typeof F}`);return G(V,F,W,re)}function ee(V,F){return j(V.dims,F)}function H(V){return G(V,1n,"int64",BigInt64Array)}function Z(V){return H(V.dims)}function X(V){return G(V,0n,"int64",BigInt64Array)}function oe(V){return X(V.dims)}function me(V){const F=V.reduce((W,re)=>W*re,1);return new a("float32",Float32Array.from({length:F},()=>Math.random()),V)}function ae(V,F){if(V.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(V.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",re=W?"int8":"uint8",fe=W?Int8Array:Uint8Array,se=V.data,ce=new fe(se.length/8);for(let $e=0;$e0?1:0,we=Math.floor($e/8),q=$e%8;ce[we]|=Ue<<7-q,W&&q===0&&(ce[we]-=128)}return new a(re,ce,[V.dims[0],V.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(u,p){this.image=u,this.timestamp=p}}class i{constructor(u,p){u.length>0&&u[0]instanceof s.RawImage&&(u=u.map((d,c)=>new n(d,(c+1)/(u.length+1)*p))),this.frames=u,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:u=null,fps:p=null}={}){if(!o.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(u==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const d=[],c=document.createElement("video");if(c.crossOrigin="anonymous",c.muted=!0,typeof l=="string")c.src=l;else if(l instanceof Blob)c.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)c.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(C=>c.onloadedmetadata=C),c.seekable.start(0)===c.seekable.end(0)){const E=await(await fetch(c.src)).blob();c.src=URL.createObjectURL(E),await new Promise(y=>c.onloadedmetadata=y)}const _=c.duration;let f,v;u!=null?(f=u,v=u===1?0:_/(u-1)):(v=1/p,f=Math.floor(_/v));let $=[];for(let C=0;C{c.onseeked=x}),g.drawImage(c,0,0,w.width,w.height);const E=g.getImageData(0,0,w.width,w.height),y=new s.RawImage(E.data,w.width,w.height,4),b=new n(y,C);d.push(b)}return c.remove(),new i(d,_)}}},rb={};function St(e){var r=rb[e];if(r!==void 0)return r.exports;var t=rb[e]={exports:{}};return sT[e](t,t.exports,St),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;St.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);St.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,St.d(o,n),o}})();St.d=(e,r)=>{for(var t in r)St.o(r,t)&&!St.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})};St.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);St.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var m={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/St.r(m),St.d(m,{ASTFeatureExtractor:()=>d.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,AudioClassificationPipeline:()=>r.AudioClassificationPipeline,AutoConfig:()=>o.AutoConfig,AutoFeatureExtractor:()=>c.AutoFeatureExtractor,AutoImageProcessor:()=>v.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:()=>g.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:()=>C.BaseStreamer,BeitFeatureExtractor:()=>f.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:()=>f.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:()=>f.CLIPFeatureExtractor,CLIPImageProcessor:()=>f.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:()=>f.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>d.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>y.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>s.CodeGenTokenizer,CodeLlamaTokenizer:()=>s.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>s.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>s.ConvBertTokenizer,ConvNextFeatureExtractor:()=>f.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>f.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>f.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>f.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:()=>f.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>f.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>r.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>f.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>f.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:()=>f.DonutFeatureExtractor,DonutImageProcessor:()=>f.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>f.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,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:()=>u.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:()=>y.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>y.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>f.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,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>s.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>f.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:()=>f.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>w.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>d.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>_.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>E.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>f.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>w.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>f.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LogitsProcessor:()=>y.LogitsProcessor,LogitsProcessorList:()=>y.LogitsProcessorList,LogitsWarper:()=>y.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,Mask2FormerImageProcessor:()=>f.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>f.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>f.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:()=>y.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>y.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>f.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>f.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>f.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>f.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>f.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>f.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>f.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>f.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>f.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>f.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,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,NllbTokenizer:()=>s.NllbTokenizer,NoBadWordsLogitsProcessor:()=>y.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>y.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>f.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:()=>f.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>f.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>w.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>f.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:()=>f.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:()=>$.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>f.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:()=>f.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>w.Qwen2VLProcessor,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>f.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>n.RawAudio,RawImage:()=>i.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>y.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>s.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>s.RobertaTokenizer,SamImageProcessor:()=>f.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:()=>f.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>f.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>f.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>s.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>f.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:()=>y.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>f.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinForSemanticSegmentation:()=>t.SwinForSemanticSegmentation,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>s.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>y.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>C.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>y.TopKLogitsWarper,TopPLogitsWarper:()=>y.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>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:()=>f.VLMImageProcessor,ViTFeatureExtractor:()=>f.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>f.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:()=>f.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>f.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,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:()=>C.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>y.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>s.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>s.XLMRobertaTokenizer,XLMTokenizer:()=>s.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>f.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>f.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>r.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>r.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>r.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>r.ZeroShotObjectDetectionPipeline,bankers_round:()=>u.bankers_round,cat:()=>l.cat,cos_sim:()=>u.cos_sim,dot:()=>u.dot,dynamic_time_warping:()=>u.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getKeyValueShapes:()=>o.getKeyValueShapes,hamming:()=>n.hamming,hanning:()=>n.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>u.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:()=>u.log_softmax,magnitude:()=>u.magnitude,matmul:()=>l.matmul,max:()=>u.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>u.medianFilter,mel_filter_bank:()=>n.mel_filter_bank,min:()=>u.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>u.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,read_audio:()=>n.read_audio,rfft:()=>l.rfft,round:()=>u.round,slice:()=>l.slice,softmax:()=>u.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=St("./src/env.js"),r=St("./src/pipelines.js"),t=St("./src/models.js"),s=St("./src/tokenizers.js"),o=St("./src/configs.js"),n=St("./src/utils/audio.js"),i=St("./src/utils/image.js"),a=St("./src/utils/video.js"),l=St("./src/utils/tensor.js"),u=St("./src/utils/maths.js"),p=St("./src/base/feature_extraction_utils.js"),d=St("./src/models/feature_extractors.js"),c=St("./src/models/auto/feature_extraction_auto.js"),_=St("./src/base/image_processors_utils.js"),f=St("./src/models/image_processors.js"),v=St("./src/models/auto/image_processing_auto.js"),$=St("./src/base/processing_utils.js"),w=St("./src/models/processors.js"),g=St("./src/models/auto/processing_auto.js"),C=St("./src/generation/streamers.js"),E=St("./src/generation/stopping_criteria.js"),y=St("./src/generation/logits_process.js")})();m.ASTFeatureExtractor;m.ASTForAudioClassification;m.ASTModel;m.ASTPreTrainedModel;m.AlbertForMaskedLM;m.AlbertForQuestionAnswering;m.AlbertForSequenceClassification;m.AlbertModel;m.AlbertPreTrainedModel;m.AlbertTokenizer;m.AudioClassificationPipeline;m.AutoConfig;m.AutoFeatureExtractor;m.AutoImageProcessor;var nT=m.AutoModel;m.AutoModelForAudioClassification;m.AutoModelForAudioFrameClassification;m.AutoModelForAudioTextToText;m.AutoModelForCTC;m.AutoModelForCausalLM;m.AutoModelForDepthEstimation;m.AutoModelForDocumentQuestionAnswering;m.AutoModelForImageClassification;m.AutoModelForImageFeatureExtraction;m.AutoModelForImageMatting;m.AutoModelForImageSegmentation;m.AutoModelForImageTextToText;m.AutoModelForImageToImage;m.AutoModelForMaskGeneration;m.AutoModelForMaskedLM;m.AutoModelForNormalEstimation;m.AutoModelForObjectDetection;m.AutoModelForPoseEstimation;m.AutoModelForQuestionAnswering;m.AutoModelForSemanticSegmentation;m.AutoModelForSeq2SeqLM;m.AutoModelForSequenceClassification;m.AutoModelForSpeechSeq2Seq;m.AutoModelForTextToSpectrogram;m.AutoModelForTextToWaveform;m.AutoModelForTokenClassification;m.AutoModelForUniversalSegmentation;m.AutoModelForVision2Seq;m.AutoModelForXVector;m.AutoModelForZeroShotObjectDetection;var oT=m.AutoProcessor;m.AutoTokenizer;m.AutomaticSpeechRecognitionPipeline;m.BackgroundRemovalPipeline;m.BartForConditionalGeneration;m.BartForSequenceClassification;m.BartModel;m.BartPretrainedModel;m.BartTokenizer;m.BaseModelOutput;m.BaseStreamer;m.BeitFeatureExtractor;m.BeitForImageClassification;m.BeitModel;m.BeitPreTrainedModel;m.BertForMaskedLM;m.BertForQuestionAnswering;m.BertForSequenceClassification;m.BertForTokenClassification;m.BertModel;m.BertPreTrainedModel;m.BertTokenizer;m.BitImageProcessor;m.BlenderbotForConditionalGeneration;m.BlenderbotModel;m.BlenderbotPreTrainedModel;m.BlenderbotSmallForConditionalGeneration;m.BlenderbotSmallModel;m.BlenderbotSmallPreTrainedModel;m.BlenderbotSmallTokenizer;m.BlenderbotTokenizer;m.BloomForCausalLM;m.BloomModel;m.BloomPreTrainedModel;m.BloomTokenizer;m.CLIPFeatureExtractor;m.CLIPImageProcessor;m.CLIPModel;m.CLIPPreTrainedModel;m.CLIPSegForImageSegmentation;m.CLIPSegModel;m.CLIPSegPreTrainedModel;m.CLIPTextModel;m.CLIPTextModelWithProjection;m.CLIPTokenizer;m.CLIPVisionModel;m.CLIPVisionModelWithProjection;m.CamembertForMaskedLM;m.CamembertForQuestionAnswering;m.CamembertForSequenceClassification;m.CamembertForTokenClassification;m.CamembertModel;m.CamembertPreTrainedModel;m.CamembertTokenizer;m.CausalLMOutput;m.CausalLMOutputWithPast;m.ChineseCLIPFeatureExtractor;m.ChineseCLIPModel;m.ChineseCLIPPreTrainedModel;m.ClapAudioModelWithProjection;m.ClapFeatureExtractor;m.ClapModel;m.ClapPreTrainedModel;m.ClapTextModelWithProjection;m.ClassifierFreeGuidanceLogitsProcessor;m.CodeGenForCausalLM;m.CodeGenModel;m.CodeGenPreTrainedModel;m.CodeGenTokenizer;m.CodeLlamaTokenizer;m.CohereForCausalLM;m.CohereModel;m.CoherePreTrainedModel;m.CohereTokenizer;m.ConvBertForMaskedLM;m.ConvBertForQuestionAnswering;m.ConvBertForSequenceClassification;m.ConvBertForTokenClassification;m.ConvBertModel;m.ConvBertPreTrainedModel;m.ConvBertTokenizer;m.ConvNextFeatureExtractor;m.ConvNextForImageClassification;m.ConvNextImageProcessor;m.ConvNextModel;m.ConvNextPreTrainedModel;m.ConvNextV2ForImageClassification;m.ConvNextV2Model;m.ConvNextV2PreTrainedModel;m.DPTFeatureExtractor;m.DPTForDepthEstimation;m.DPTImageProcessor;m.DPTModel;m.DPTPreTrainedModel;m.DacDecoderModel;m.DacDecoderOutput;m.DacEncoderModel;m.DacEncoderOutput;m.DacFeatureExtractor;m.DacModel;m.DacPreTrainedModel;m.DataTypeMap;m.DebertaForMaskedLM;m.DebertaForQuestionAnswering;m.DebertaForSequenceClassification;m.DebertaForTokenClassification;m.DebertaModel;m.DebertaPreTrainedModel;m.DebertaTokenizer;m.DebertaV2ForMaskedLM;m.DebertaV2ForQuestionAnswering;m.DebertaV2ForSequenceClassification;m.DebertaV2ForTokenClassification;m.DebertaV2Model;m.DebertaV2PreTrainedModel;m.DebertaV2Tokenizer;m.DecisionTransformerModel;m.DecisionTransformerPreTrainedModel;m.DeiTFeatureExtractor;m.DeiTForImageClassification;m.DeiTImageProcessor;m.DeiTModel;m.DeiTPreTrainedModel;m.DepthAnythingForDepthEstimation;m.DepthAnythingPreTrainedModel;m.DepthEstimationPipeline;m.DepthProForDepthEstimation;m.DepthProPreTrainedModel;m.DetrFeatureExtractor;m.DetrForObjectDetection;m.DetrForSegmentation;m.DetrImageProcessor;m.DetrModel;m.DetrObjectDetectionOutput;m.DetrPreTrainedModel;m.DetrSegmentationOutput;m.Dinov2ForImageClassification;m.Dinov2Model;m.Dinov2PreTrainedModel;m.Dinov2WithRegistersForImageClassification;m.Dinov2WithRegistersModel;m.Dinov2WithRegistersPreTrainedModel;m.DistilBertForMaskedLM;m.DistilBertForQuestionAnswering;m.DistilBertForSequenceClassification;m.DistilBertForTokenClassification;m.DistilBertModel;m.DistilBertPreTrainedModel;m.DistilBertTokenizer;m.DocumentQuestionAnsweringPipeline;m.DonutFeatureExtractor;m.DonutImageProcessor;m.DonutSwinModel;m.DonutSwinPreTrainedModel;m.EfficientNetForImageClassification;m.EfficientNetImageProcessor;m.EfficientNetModel;m.EfficientNetPreTrainedModel;m.ElectraForMaskedLM;m.ElectraForQuestionAnswering;m.ElectraForSequenceClassification;m.ElectraForTokenClassification;m.ElectraModel;m.ElectraPreTrainedModel;m.ElectraTokenizer;m.EncodecFeatureExtractor;m.EosTokenCriteria;m.EsmForMaskedLM;m.EsmForSequenceClassification;m.EsmForTokenClassification;m.EsmModel;m.EsmPreTrainedModel;m.EsmTokenizer;m.ExaoneForCausalLM;m.ExaoneModel;m.ExaonePreTrainedModel;m.FFT;m.FalconForCausalLM;m.FalconModel;m.FalconPreTrainedModel;m.FalconTokenizer;m.FastViTForImageClassification;m.FastViTModel;m.FastViTPreTrainedModel;m.FeatureExtractionPipeline;m.FeatureExtractor;m.FillMaskPipeline;m.Florence2ForConditionalGeneration;m.Florence2PreTrainedModel;m.Florence2Processor;m.ForcedBOSTokenLogitsProcessor;m.ForcedEOSTokenLogitsProcessor;m.GLPNFeatureExtractor;m.GLPNForDepthEstimation;m.GLPNModel;m.GLPNPreTrainedModel;m.GPT2LMHeadModel;m.GPT2Model;m.GPT2PreTrainedModel;m.GPT2Tokenizer;m.GPTBigCodeForCausalLM;m.GPTBigCodeModel;m.GPTBigCodePreTrainedModel;m.GPTJForCausalLM;m.GPTJModel;m.GPTJPreTrainedModel;m.GPTNeoForCausalLM;m.GPTNeoModel;m.GPTNeoPreTrainedModel;m.GPTNeoXForCausalLM;m.GPTNeoXModel;m.GPTNeoXPreTrainedModel;m.GPTNeoXTokenizer;m.Gemma2ForCausalLM;m.Gemma2Model;m.Gemma2PreTrainedModel;m.Gemma3ForCausalLM;m.Gemma3Model;m.Gemma3PreTrainedModel;m.GemmaForCausalLM;m.GemmaModel;m.GemmaPreTrainedModel;m.GemmaTokenizer;m.GlmForCausalLM;m.GlmModel;m.GlmPreTrainedModel;m.GraniteForCausalLM;m.GraniteModel;m.GranitePreTrainedModel;m.Grok1Tokenizer;m.GroundingDinoForObjectDetection;m.GroundingDinoImageProcessor;m.GroundingDinoPreTrainedModel;m.GroundingDinoProcessor;m.GroupViTModel;m.GroupViTPreTrainedModel;m.HeliumForCausalLM;m.HeliumModel;m.HeliumPreTrainedModel;m.HerbertTokenizer;m.HieraForImageClassification;m.HieraModel;m.HieraPreTrainedModel;m.HubertForCTC;m.HubertForSequenceClassification;m.HubertModel;m.HubertPreTrainedModel;m.IJepaForImageClassification;m.IJepaModel;m.IJepaPreTrainedModel;m.Idefics3ForConditionalGeneration;m.Idefics3ImageProcessor;m.Idefics3PreTrainedModel;m.Idefics3Processor;m.ImageClassificationPipeline;m.ImageFeatureExtractionPipeline;m.ImageFeatureExtractor;m.ImageMattingOutput;m.ImageProcessor;m.ImageSegmentationPipeline;m.ImageToImagePipeline;m.ImageToTextPipeline;m.InterruptableStoppingCriteria;m.JAISLMHeadModel;m.JAISModel;m.JAISPreTrainedModel;m.JinaCLIPImageProcessor;m.JinaCLIPModel;m.JinaCLIPPreTrainedModel;m.JinaCLIPProcessor;m.JinaCLIPTextModel;m.JinaCLIPVisionModel;m.LiteWhisperForConditionalGeneration;m.LlamaForCausalLM;m.LlamaModel;m.LlamaPreTrainedModel;m.LlamaTokenizer;m.LlavaForConditionalGeneration;m.LlavaOnevisionForConditionalGeneration;m.LlavaOnevisionImageProcessor;m.LlavaPreTrainedModel;m.LogitsProcessor;m.LogitsProcessorList;m.LogitsWarper;m.LongT5ForConditionalGeneration;m.LongT5Model;m.LongT5PreTrainedModel;m.M2M100ForConditionalGeneration;m.M2M100Model;m.M2M100PreTrainedModel;m.M2M100Tokenizer;m.MBart50Tokenizer;m.MBartForCausalLM;m.MBartForConditionalGeneration;m.MBartForSequenceClassification;m.MBartModel;m.MBartPreTrainedModel;m.MBartTokenizer;m.MPNetForMaskedLM;m.MPNetForQuestionAnswering;m.MPNetForSequenceClassification;m.MPNetForTokenClassification;m.MPNetModel;m.MPNetPreTrainedModel;m.MPNetTokenizer;m.MT5ForConditionalGeneration;m.MT5Model;m.MT5PreTrainedModel;m.MarianMTModel;m.MarianModel;m.MarianPreTrainedModel;m.MarianTokenizer;m.Mask2FormerImageProcessor;m.MaskFormerFeatureExtractor;m.MaskFormerForInstanceSegmentation;m.MaskFormerImageProcessor;m.MaskFormerModel;m.MaskFormerPreTrainedModel;m.MaskedLMOutput;m.MaxLengthCriteria;m.Metric3DForDepthEstimation;m.Metric3DPreTrainedModel;m.Metric3Dv2ForDepthEstimation;m.Metric3Dv2PreTrainedModel;m.MgpstrForSceneTextRecognition;m.MgpstrModelOutput;m.MgpstrPreTrainedModel;m.MgpstrProcessor;m.MgpstrTokenizer;m.MimiDecoderModel;m.MimiDecoderOutput;m.MimiEncoderModel;m.MimiEncoderOutput;m.MimiModel;m.MimiPreTrainedModel;m.MinLengthLogitsProcessor;m.MinNewTokensLengthLogitsProcessor;m.MistralForCausalLM;m.MistralModel;m.MistralPreTrainedModel;m.MobileBertForMaskedLM;m.MobileBertForQuestionAnswering;m.MobileBertForSequenceClassification;m.MobileBertModel;m.MobileBertPreTrainedModel;m.MobileBertTokenizer;m.MobileLLMForCausalLM;m.MobileLLMModel;m.MobileLLMPreTrainedModel;m.MobileNetV1FeatureExtractor;m.MobileNetV1ForImageClassification;m.MobileNetV1ForSemanticSegmentation;m.MobileNetV1ImageProcessor;m.MobileNetV1Model;m.MobileNetV1PreTrainedModel;m.MobileNetV2FeatureExtractor;m.MobileNetV2ForImageClassification;m.MobileNetV2ForSemanticSegmentation;m.MobileNetV2ImageProcessor;m.MobileNetV2Model;m.MobileNetV2PreTrainedModel;m.MobileNetV3FeatureExtractor;m.MobileNetV3ForImageClassification;m.MobileNetV3ForSemanticSegmentation;m.MobileNetV3ImageProcessor;m.MobileNetV3Model;m.MobileNetV3PreTrainedModel;m.MobileNetV4FeatureExtractor;m.MobileNetV4ForImageClassification;m.MobileNetV4ForSemanticSegmentation;m.MobileNetV4ImageProcessor;m.MobileNetV4Model;m.MobileNetV4PreTrainedModel;m.MobileViTFeatureExtractor;m.MobileViTForImageClassification;m.MobileViTImageProcessor;m.MobileViTModel;m.MobileViTPreTrainedModel;m.MobileViTV2ForImageClassification;m.MobileViTV2Model;m.MobileViTV2PreTrainedModel;m.ModelOutput;m.ModernBertForMaskedLM;m.ModernBertForSequenceClassification;m.ModernBertForTokenClassification;m.ModernBertModel;m.ModernBertPreTrainedModel;m.Moondream1ForConditionalGeneration;m.MoonshineFeatureExtractor;m.MoonshineForConditionalGeneration;m.MoonshineModel;m.MoonshinePreTrainedModel;m.MoonshineProcessor;m.MptForCausalLM;m.MptModel;m.MptPreTrainedModel;m.MultiModalityCausalLM;m.MultiModalityPreTrainedModel;m.MusicgenForCausalLM;m.MusicgenForConditionalGeneration;m.MusicgenModel;m.MusicgenPreTrainedModel;m.NllbTokenizer;m.NoBadWordsLogitsProcessor;m.NoRepeatNGramLogitsProcessor;m.NomicBertModel;m.NomicBertPreTrainedModel;m.NougatImageProcessor;m.NougatTokenizer;m.OPTForCausalLM;m.OPTModel;m.OPTPreTrainedModel;m.ObjectDetectionPipeline;m.Olmo2ForCausalLM;m.Olmo2Model;m.Olmo2PreTrainedModel;m.OlmoForCausalLM;m.OlmoModel;m.OlmoPreTrainedModel;m.OpenELMForCausalLM;m.OpenELMModel;m.OpenELMPreTrainedModel;m.OwlViTFeatureExtractor;m.OwlViTForObjectDetection;m.OwlViTImageProcessor;m.OwlViTModel;m.OwlViTPreTrainedModel;m.OwlViTProcessor;m.Owlv2ForObjectDetection;m.Owlv2ImageProcessor;m.Owlv2Model;m.Owlv2PreTrainedModel;m.PaliGemmaForConditionalGeneration;m.PaliGemmaPreTrainedModel;m.PaliGemmaProcessor;m.PatchTSMixerForPrediction;m.PatchTSMixerModel;m.PatchTSMixerPreTrainedModel;m.PatchTSTForPrediction;m.PatchTSTModel;m.PatchTSTPreTrainedModel;m.Phi3ForCausalLM;m.Phi3Model;m.Phi3PreTrainedModel;m.Phi3VForCausalLM;m.Phi3VImageProcessor;m.Phi3VPreTrainedModel;m.Phi3VProcessor;m.PhiForCausalLM;m.PhiModel;m.PhiPreTrainedModel;m.Pipeline;m.PreTrainedModel;m.PreTrainedTokenizer;m.PretrainedConfig;m.PretrainedMixin;m.Processor;m.PvtForImageClassification;m.PvtImageProcessor;m.PvtModel;m.PvtPreTrainedModel;m.PyAnnoteFeatureExtractor;m.PyAnnoteForAudioFrameClassification;m.PyAnnoteModel;m.PyAnnotePreTrainedModel;m.PyAnnoteProcessor;m.QuestionAnsweringModelOutput;m.QuestionAnsweringPipeline;m.Qwen2ForCausalLM;m.Qwen2Model;m.Qwen2PreTrainedModel;m.Qwen2Tokenizer;m.Qwen2VLForConditionalGeneration;m.Qwen2VLImageProcessor;m.Qwen2VLPreTrainedModel;m.Qwen2VLProcessor;m.RFDetrForObjectDetection;m.RFDetrModel;m.RFDetrObjectDetectionOutput;m.RFDetrPreTrainedModel;m.RTDetrForObjectDetection;m.RTDetrImageProcessor;m.RTDetrModel;m.RTDetrObjectDetectionOutput;m.RTDetrPreTrainedModel;m.RTDetrV2ForObjectDetection;m.RTDetrV2Model;m.RTDetrV2ObjectDetectionOutput;m.RTDetrV2PreTrainedModel;m.RawAudio;var sb=m.RawImage;m.RawVideo;m.RawVideoFrame;m.RepetitionPenaltyLogitsProcessor;m.ResNetForImageClassification;m.ResNetModel;m.ResNetPreTrainedModel;m.RoFormerForMaskedLM;m.RoFormerForQuestionAnswering;m.RoFormerForSequenceClassification;m.RoFormerForTokenClassification;m.RoFormerModel;m.RoFormerPreTrainedModel;m.RoFormerTokenizer;m.RobertaForMaskedLM;m.RobertaForQuestionAnswering;m.RobertaForSequenceClassification;m.RobertaForTokenClassification;m.RobertaModel;m.RobertaPreTrainedModel;m.RobertaTokenizer;m.SamImageProcessor;m.SamImageSegmentationOutput;m.SamModel;m.SamPreTrainedModel;m.SamProcessor;m.SapiensForDepthEstimation;m.SapiensForNormalEstimation;m.SapiensForSemanticSegmentation;m.SapiensPreTrainedModel;m.SeamlessM4TFeatureExtractor;m.SegformerFeatureExtractor;m.SegformerForImageClassification;m.SegformerForSemanticSegmentation;m.SegformerImageProcessor;m.SegformerModel;m.SegformerPreTrainedModel;m.Seq2SeqLMOutput;m.SequenceClassifierOutput;m.SiglipImageProcessor;m.SiglipModel;m.SiglipPreTrainedModel;m.SiglipTextModel;m.SiglipTokenizer;m.SiglipVisionModel;m.SmolVLMForConditionalGeneration;m.SmolVLMImageProcessor;m.SmolVLMProcessor;m.SnacDecoderModel;m.SnacEncoderModel;m.SnacFeatureExtractor;m.SnacModel;m.SnacPreTrainedModel;m.SpeechT5FeatureExtractor;m.SpeechT5ForSpeechToText;m.SpeechT5ForTextToSpeech;m.SpeechT5HifiGan;m.SpeechT5Model;m.SpeechT5PreTrainedModel;m.SpeechT5Processor;m.SpeechT5Tokenizer;m.SqueezeBertForMaskedLM;m.SqueezeBertForQuestionAnswering;m.SqueezeBertForSequenceClassification;m.SqueezeBertModel;m.SqueezeBertPreTrainedModel;m.SqueezeBertTokenizer;m.StableLmForCausalLM;m.StableLmModel;m.StableLmPreTrainedModel;m.Starcoder2ForCausalLM;m.Starcoder2Model;m.Starcoder2PreTrainedModel;m.StoppingCriteria;m.StoppingCriteriaList;m.StyleTextToSpeech2Model;m.StyleTextToSpeech2PreTrainedModel;m.SummarizationPipeline;m.SuppressTokensAtBeginLogitsProcessor;m.Swin2SRForImageSuperResolution;m.Swin2SRImageProcessor;m.Swin2SRModel;m.Swin2SRPreTrainedModel;m.SwinForImageClassification;m.SwinForSemanticSegmentation;m.SwinModel;m.SwinPreTrainedModel;m.T5ForConditionalGeneration;m.T5Model;m.T5PreTrainedModel;m.T5Tokenizer;m.TableTransformerForObjectDetection;m.TableTransformerModel;m.TableTransformerObjectDetectionOutput;m.TableTransformerPreTrainedModel;m.TemperatureLogitsWarper;m.Tensor;m.Text2TextGenerationPipeline;m.TextClassificationPipeline;m.TextGenerationPipeline;m.TextStreamer;m.TextToAudioPipeline;m.TokenClassificationPipeline;m.TokenClassifierOutput;m.TokenizerModel;m.TopKLogitsWarper;m.TopPLogitsWarper;m.TrOCRForCausalLM;m.TrOCRPreTrainedModel;m.TranslationPipeline;m.UltravoxModel;m.UltravoxPreTrainedModel;m.UltravoxProcessor;m.UniSpeechForCTC;m.UniSpeechForSequenceClassification;m.UniSpeechModel;m.UniSpeechPreTrainedModel;m.UniSpeechSatForAudioFrameClassification;m.UniSpeechSatForCTC;m.UniSpeechSatForSequenceClassification;m.UniSpeechSatModel;m.UniSpeechSatPreTrainedModel;m.VLChatProcessor;m.VLMImageProcessor;m.ViTFeatureExtractor;m.ViTForImageClassification;m.ViTImageProcessor;m.ViTMAEModel;m.ViTMAEPreTrainedModel;m.ViTMSNForImageClassification;m.ViTMSNModel;m.ViTMSNPreTrainedModel;m.ViTModel;m.ViTPreTrainedModel;m.VisionEncoderDecoderModel;m.VitMatteForImageMatting;m.VitMatteImageProcessor;m.VitMattePreTrainedModel;m.VitPoseForPoseEstimation;m.VitPoseImageProcessor;m.VitPosePreTrainedModel;m.VitsModel;m.VitsModelOutput;m.VitsPreTrainedModel;m.VitsTokenizer;m.Wav2Vec2BertForCTC;m.Wav2Vec2BertForSequenceClassification;m.Wav2Vec2BertModel;m.Wav2Vec2BertPreTrainedModel;m.Wav2Vec2CTCTokenizer;m.Wav2Vec2FeatureExtractor;m.Wav2Vec2ForAudioFrameClassification;m.Wav2Vec2ForCTC;m.Wav2Vec2ForSequenceClassification;m.Wav2Vec2Model;m.Wav2Vec2PreTrainedModel;m.Wav2Vec2Processor;m.Wav2Vec2ProcessorWithLM;m.WavLMForAudioFrameClassification;m.WavLMForCTC;m.WavLMForSequenceClassification;m.WavLMForXVector;m.WavLMModel;m.WavLMPreTrainedModel;m.WeSpeakerFeatureExtractor;m.WeSpeakerResNetModel;m.WeSpeakerResNetPreTrainedModel;m.WhisperFeatureExtractor;m.WhisperForConditionalGeneration;m.WhisperModel;m.WhisperPreTrainedModel;m.WhisperProcessor;m.WhisperTextStreamer;m.WhisperTimeStampLogitsProcessor;m.WhisperTokenizer;m.XLMForQuestionAnswering;m.XLMForSequenceClassification;m.XLMForTokenClassification;m.XLMModel;m.XLMPreTrainedModel;m.XLMRobertaForMaskedLM;m.XLMRobertaForQuestionAnswering;m.XLMRobertaForSequenceClassification;m.XLMRobertaForTokenClassification;m.XLMRobertaModel;m.XLMRobertaPreTrainedModel;m.XLMRobertaTokenizer;m.XLMTokenizer;m.XLMWithLMHeadModel;m.XVectorOutput;m.YolosFeatureExtractor;m.YolosForObjectDetection;m.YolosImageProcessor;m.YolosModel;m.YolosObjectDetectionOutput;m.YolosPreTrainedModel;m.ZeroShotAudioClassificationPipeline;m.ZeroShotClassificationPipeline;m.ZeroShotImageClassificationPipeline;m.ZeroShotObjectDetectionPipeline;m.bankers_round;m.cat;m.cos_sim;m.dot;m.dynamic_time_warping;var iT=m.env;m.full;m.full_like;m.getKeyValueShapes;m.hamming;m.hanning;m.interpolate;m.interpolate_4d;m.interpolate_data;m.is_chinese_char;m.layer_norm;m.load_image;m.load_video;m.log_softmax;m.magnitude;m.matmul;m.max;m.mean;m.mean_pooling;m.medianFilter;m.mel_filter_bank;m.min;m.ones;m.ones_like;m.permute;m.permute_data;m.pipeline;m.quantize_embeddings;m.rand;m.read_audio;m.rfft;m.round;m.slice;m.softmax;m.spectrogram;m.stack;m.std_mean;m.topk;m.window_function;m.zeros;m.zeros_like;async function aT(){try{if(lT())return{supported:!1,isNode:!0,reason:"",fp16Supported:!1};if(typeof navigator>"u"||!navigator.gpu)return{supported:!1,isNode:!1,reason:"WebGPU is not available (navigator.gpu is undefined)",fp16Supported:!1};const e=await navigator.gpu.requestAdapter();return e?{supported:!0,isNode:!1,reason:"",adapter:e,fp16Supported:e.features.has("shader-f16")}:{supported:!1,isNode:!1,reason:"WebGPU is not supported (no adapter found)",fp16Supported:!1}}catch(e){return{supported:!1,isNode:!1,reason:e instanceof Error?e.toString():String(e),fp16Supported:!1}}}function lT(){return typeof process<"u"&&"versions"in process&&process.versions!=null&&typeof process.versions=="object"&&"node"in process.versions&&process.versions.node!=null}const uT={flex:"","flex-col":"","items-center":"","gap-4":""},dT=["disabled"],cT={"h-full":"","w-full":"",flex:"","gap-2":""},pT={w:"[50%]",border:"2 solid neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-900","min-h":"120",h:"auto","overflow-hidden":"","rounded-lg":""},hT=["src"],mT={w:"[50%]",border:"2 solid neutral-200 dark:neutral-800",bg:"neutral-50 dark:neutral-900","min-h":"120",h:"auto",relative:"","overflow-hidden":"","rounded-lg":""},fT={key:0,bg:"black/50",absolute:"","inset-0":"","z-10":"",flex:"","flex-col":"","items-center":"","justify-center":""},_T={"mb-4":"","text-white":"","font-medium":""},gT={bg:"gray-200/30",w:"70%","h-2":"","overflow-hidden":"","rounded-full":""},wT=["src"],bT={bg:"black/0 group-hover:black/20",absolute:"","inset-0":"",flex:"","items-center":"","justify-center":"","transition-all":"","duration-200":""},MT=["onClick"],yT={key:1,absolute:"","bottom-2":"","right-2":""},ST=pv({__name:"background-remove",setup(e){const r=ks(),t=ks(),s=ks(),o=ks(),n=ks(!1),i=ks(0),a=ks(),l=ks(),u=ks([]),p=hv(()=>u.value.map(f=>URL.createObjectURL(f)));mv(async()=>{try{if(!(await aT()).supported)throw new Error("WebGPU is not supported in this browser.");const f="Xenova/modnet";iT.backends.onnx.wasm.proxy=!1,r.value??(r.value=await nT.from_pretrained(f,{device:"webgpu"})),t.value??(t.value=await oT.from_pretrained(f,{}))}catch(f){s.value=f}o.value=!1});async function d(){if(!r.value||!t.value)return;n.value=!0,i.value=0,a.value=[];const f=p.value.length;for(let v=0;v=a.value.length||!u.value[f])return;const v=u.value[f].name,$=v.substring(0,v.lastIndexOf("."))||v,w=v.substring(v.lastIndexOf("."))||".png",g=`${$}-background-removed${w}`,C=document.createElement("a");C.href=a.value[f],C.download=g,document.body.appendChild(C),C.click(),document.body.removeChild(C)}function _(){!a.value||a.value.length===0||a.value.forEach((f,v)=>{setTimeout(()=>c(v),v*100)})}return(f,v)=>(En(),Tn("div",uT,[Sr("button",{bg:"neutral-100 dark:neutral-800","w-full":"","cursor-pointer":"","rounded-lg":"","px-3":"","py-2":"",disabled:n.value,onClick:d},wf(n.value?"Processing...":"Process"),9,dT),Sr("div",cT,[Sr("div",pT,[(En(!0),Tn(bf,null,Mf(p.value,($,w)=>(En(),Tn("img",{key:w,src:$,"h-full":"","w-full":"","object-cover":""},null,8,hT))),128))]),Sr("div",mT,[n.value?(En(),Tn("div",fT,[Sr("div",_T,wf(i.value)+"% ",1),Sr("div",gT,[Sr("div",{bg:"emerald-500","h-full":"",style:_v({width:`${i.value}%`}),"transition-all":"","duration-200":""},null,4)])])):yf("",!0),(En(!0),Tn(bf,null,Mf(a.value,($,w)=>(En(),Tn("div",{key:w,relative:"",class:"group","h-full":"","w-full":""},[Sr("img",{src:$,"h-full":"","w-full":"","object-cover":""},null,8,wT),Sr("div",bT,[Sr("button",{bg:"emerald-500 hover:emerald-600","rounded-full":"","p-2":"","text-white":"","opacity-0":"","transition-all":"","duration-200":"","group-hover:opacity-100":"",onClick:g=>c(w)},v[1]||(v[1]=[Sr("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[Sr("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"})],-1)]),8,MT)])]))),128)),a.value&&a.value.length>1?(En(),Tn("div",yT,[Sr("button",{bg:"emerald-500 hover:emerald-600","rounded-full":"","p-2":"","text-white":"",onClick:_},v[2]||(v[2]=[Sr("svg",{xmlns:"http://www.w3.org/2000/svg",class:"h-5 w-5",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor"},[Sr("path",{"stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",d:"M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"})],-1)]))])):yf("",!0)])]),fv(gv(cv),{modelValue:u.value,"onUpdate:modelValue":v[0]||(v[0]=$=>u.value=$),"w-full":""},null,8,["modelValue"])]))}});export{ST as default};