(function(){"use strict";const Jo=new Map,on=[],$v=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=Jo.get(e);if(s===void 0)Jo.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 n=on.indexOf(e);n!==-1&&on.splice(n,1);for(let o=0;o{const r=Jo.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}}},Av=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?on:t;let n;const o=[],i=new Set;for(const l of s){const c=await Iv(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&i.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:c}of o)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);const a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?a:Reflect.get(l,c)})]},Fv="1.21.0";let Wu="warning";const cs={wasm:{},webgl:{},webgpu:{},versions:{common:Fv},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}`);Wu=e}},get logLevel(){return Wu}};Object.defineProperty(cs,"logLevel",{enumerable:!0});const Ov=cs,Dv=(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 n,o;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[3]):(n=e.dims[3],o=e.dims[2]);const i=r?.format!==void 0?r.format:"RGB",a=r?.norm;let l,c;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));const p=o*n;let d=0,u=p,f=p*2,_=-1;i==="RGBA"?(d=0,u=p,f=p*2,_=p*3):i==="RGB"?(d=0,u=p,f=p*2):i==="RBG"&&(d=0,f=p,u=p*2);for(let y=0;y{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let n,o,i;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[1],i=e.dims[3]):(n=e.dims[3],o=e.dims[2],i=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r?.norm;let c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));const d=o*n;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const u=4;let f=0,_=1,y=2,I=3,w=0,v=d,k=d*2,T=-1;a==="RGBA"?(w=0,v=d,k=d*2,T=d*3):a==="RGB"?(w=0,v=d,k=d*2):a==="RBG"&&(w=0,k=d,v=d*2),s=t.createImageData(n,o);for(let b=0;b{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,n=r.norm??{mean:255,bias:0};let o,i;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?i=[n.bias,n.bias,n.bias,n.bias]:i=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3);let d=4,u=0,f=1,_=2,y=3,I=0,w=c,v=c*2,k=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,y=-1),l==="RGBA"?k=c*3:l==="RBG"?(I=0,v=c,w=c*2):l==="BGR"&&(v=0,w=c,I=c*2);for(let b=0;b{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,o=typeof e=="string";let i,a=r??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){const p=l();p.width=e.width,p.height=e.height;const d=c(p);if(d!=null){let u=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(u=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=u,a.width=f}else a.tensorFormat="RGBA",a.height=u,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,u).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){const u=l();u.width=d,u.height=p;const f=c(u);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(n){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");const p=l();p.width=e.width,p.height=e.height;const d=c(p);if(d!=null){const u=e.height,f=e.width;return d.drawImage(e,0,0,f,u),i=d.getImageData(0,0,f,u).data,a.height=u,a.width=f,Mi(i,a)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,d)=>{const u=l(),f=c(u);if(!e||!f)return d();const _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{u.width=_.width,u.height=_.height,f.drawImage(_,0,0,u.width,u.height);const y=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(Mi(y.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Mi(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Bv=(e,r)=>{const{width:t,height:s,download:n,dispose:o}=r,i=[1,s,t,4];return new es({location:"texture",type:"float32",texture:e,dims:i,download:n,dispose:o})},Rv=(e,r)=>{const{dataType:t,dims:s,download:n,dispose:o}=r;return new es({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:n,dispose:o})},jv=(e,r)=>{const{dataType:t,dims:s,download:n,dispose:o}=r;return new es({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:n,dispose:o})},Nv=(e,r,t)=>new es({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),An=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Yo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Gu=!1;const Vv=()=>{if(!Gu){Gu=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(An.set("int64",BigInt64Array),Yo.set(BigInt64Array,"int64")),r&&(An.set("uint64",BigUint64Array),Yo.set(BigUint64Array,"uint64")),s?(An.set("float16",t),Yo.set(t,"float16")):An.set("float16",Uint16Array)}},Uv=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new es(e.type,e.data,r);case"cpu-pinned":return new es({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new es({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new es({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new es({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let es=class{constructor(r,t,s){Vv();let n,o;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,n=r.type,o=r.dims,r.location){case"cpu-pinned":{const a=An.get(n);if(!a)throw new TypeError(`unsupported type "${n}" 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(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" 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(n=r,l=s,r==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{const c=An.get(r);if(c===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&c===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${c.name} as data.`);r==="uint64"||r==="int64"?a=c.from(t,BigInt):a=c.from(t)}else if(t instanceof c)a=t;else if(t instanceof Uint8ClampedArray)if(r==="uint8")a=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(r==="float16"&&t instanceof Uint16Array&&c!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${n} tensor's data must be type of ${c}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const c=typeof r[0];if(c==="string")n="string",a=r;else if(c==="boolean")n="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(r instanceof Uint8ClampedArray)n="uint8",a=Uint8Array.from(r);else{const c=Yo.get(r.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);n=c,a=r}if(l===void 0)l=[a.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");o=l,this.cpuData=a,this.dataLocation="cpu"}const i=Uv(o);if(this.cpuData&&i!==this.cpuData.length&&!((n==="uint4"||n==="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=n,this.dims=o,this.size=i}static async fromImage(r,t){return zv(r,t)}static fromTexture(r,t){return Bv(r,t)}static fromGpuBuffer(r,t){return Rv(r,t)}static fromMLTensor(r,t){return jv(r,t)}static fromPinnedBuffer(r,t,s){return Nv(r,t,s)}toDataURL(r){return Dv(this,r)}toImageData(r){return Lv(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 Wv(this,r)}};const Fn=es,Ku=(e,r)=>{(typeof cs.trace>"u"?!cs.wasm.trace:!cs.trace)||console.timeStamp(`${e}::ORT::${r}`)},Hu=(e,r)=>{const t=new Error().stack?.split(/\r\n|\r|\n/g)||[];let s=!1;for(let n=0;n{(typeof cs.trace>"u"?!cs.wasm.trace:!cs.trace)||Hu("BEGIN",e)},bi=e=>{(typeof cs.trace>"u"?!cs.wasm.trace:!cs.trace)||Hu("END",e)};var Gv=Object.freeze({__proto__:null,InferenceSession:class Cv{constructor(r){this.handler=r}async run(r,t,s){wi();const n={};let o={};if(typeof r!="object"||r===null||r instanceof Fn||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 Fn)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(const c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1;const p=Object.getOwnPropertyNames(t);for(const d of this.outputNames)if(p.indexOf(d)!==-1){const u=t[d];(u===null||u instanceof Fn)&&(c=!0,i=!1,n[d]=u)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const c of this.inputNames)if(typeof r[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(i)for(const c of this.outputNames)n[c]=null;const a=await this.handler.run(r,n,o),l={};for(const c in a)if(Object.hasOwnProperty.call(a,c)){const p=a[c];p instanceof Fn?l[c]=p:l[c]=new Fn(p.type,p.data,p.dims)}return bi(),l}async release(){return this.handler.dispose()}static async create(r,t,s,n){wi();let o,i={};if(typeof r=="string"){if(o=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(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){const p=r;let d=0,u=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(u=r.byteLength-d,typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||d+u>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"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.");o=new Uint8Array(p,d,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await Av(i),c=await a.createInferenceSessionHandler(o,l);return bi(),new Cv(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}},TRACE:Ku,TRACE_FUNC_BEGIN:wi,TRACE_FUNC_END:bi,Tensor:Fn,env:Ov,registerBackend:$v});var yi=Object.defineProperty,Kv=Object.getOwnPropertyDescriptor,Hv=Object.getOwnPropertyNames,qv=Object.prototype.hasOwnProperty,Qv=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Ne=(e,r)=>()=>(e&&(r=e(e=0)),r),On=(e,r)=>{for(var t in r)yi(e,t,{get:r[t],enumerable:!0})},Xv=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of Hv(r))!qv.call(e,n)&&n!==t&&yi(e,n,{get:()=>r[n],enumerable:!(s=Kv(r,n))||s.enumerable});return e},lo=e=>Xv(yi({},"__esModule",{value:!0}),e),co,Ws,an,qu,Qu,Xu=Ne(()=>{co=new Map,Ws=[],an=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=co.get(e);if(s===void 0)co.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){let n=Ws.indexOf(e);n!==-1&&Ws.splice(n,1);for(let o=0;o{let r=co.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{let t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},Qu=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Ws:t,n,o=[],i=new Set;for(let l of s){let c=await qu(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&i.add(l))}if(!n)throw new Error(`no available backend found. ERR: ${o.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:c}of o)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${c}`);let a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?a:Reflect.get(l,c)})]}}),Jv=Ne(()=>{Xu()}),Ju,Yv=Ne(()=>{Ju="1.22.0-dev.20250409-89f8206ba4"}),vi,ts,Yu=Ne(()=>{Yv(),vi="warning",ts={wasm:{},webgl:{},webgpu:{},versions:{common:Ju},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);vi=e}},get logLevel(){return vi}},Object.defineProperty(ts,"logLevel",{enumerable:!0})}),Xt,Zv=Ne(()=>{Yu(),Xt=ts}),Zu,ed,ex=Ne(()=>{Zu=(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 n,o;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[3]):(n=e.dims[3],o=e.dims[2]);let i=r?.format!==void 0?r.format:"RGB",a=r?.norm,l,c;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?c=[0,0,0,0]:typeof a.bias=="number"?c=[a.bias,a.bias,a.bias,a.bias]:(c=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(c[3]=a.bias[3]));let p=o*n,d=0,u=p,f=p*2,_=-1;i==="RGBA"?(d=0,u=p,f=p*2,_=p*3):i==="RGB"?(d=0,u=p,f=p*2):i==="RBG"&&(d=0,f=p,u=p*2);for(let y=0;y{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let n,o,i;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[1],i=e.dims[3]):(n=e.dims[3],o=e.dims[2],i=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r?.norm,c,p;l===void 0||l.mean===void 0?c=[255,255,255,255]:typeof l.mean=="number"?c=[l.mean,l.mean,l.mean,l.mean]:(c=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(c[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let d=o*n;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let u=4,f=0,_=1,y=2,I=3,w=0,v=d,k=d*2,T=-1;a==="RGBA"?(w=0,v=d,k=d*2,T=d*3):a==="RGB"?(w=0,v=d,k=d*2):a==="RBG"&&(w=0,k=d,v=d*2),s=t.createImageData(n,o);for(let b=0;b{Ti(),Zo=(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,n=r.norm??{mean:255,bias:0},o,i;typeof n.mean=="number"?o=[n.mean,n.mean,n.mean,n.mean]:o=[n.mean[0],n.mean[1],n.mean[2],n.mean[3]??255],typeof n.bias=="number"?i=[n.bias,n.bias,n.bias,n.bias]:i=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",c=t*s,p=l==="RGBA"?new Float32Array(c*4):new Float32Array(c*3),d=4,u=0,f=1,_=2,y=3,I=0,w=c,v=c*2,k=-1;a==="RGB"&&(d=3,u=0,f=1,_=2,y=-1),l==="RGBA"?k=c*3:l==="RBG"?(I=0,v=c,w=c*2):l==="BGR"&&(v=0,w=c,I=c*2);for(let T=0;T{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,n=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,o=typeof e=="string",i,a=r??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},c=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){let p=l();p.width=e.width,p.height=e.height;let d=c(p);if(d!=null){let u=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(u=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=u,a.width=f}else a.tensorFormat="RGBA",a.height=u,a.width=f;d.drawImage(e,0,0),i=d.getImageData(0,0,f,u).data}else throw new Error("Can not access image data")}else if(s){let p,d;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,d=r.resizedWidth):(p=e.height,d=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=d,r!==void 0){let u=l();u.width=d,u.height=p;let f=c(u);if(f!=null)f.putImageData(e,0,0),i=f.getImageData(0,0,d,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(n){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=e.width,p.height=e.height;let d=c(p);if(d!=null){let u=e.height,f=e.width;return d.drawImage(e,0,0,f,u),i=d.getImageData(0,0,f,u).data,a.height=u,a.width=f,Zo(i,a)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,d)=>{let u=l(),f=c(u);if(!e||!f)return d();let _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{u.width=_.width,u.height=_.height,f.drawImage(_,0,0,u.width,u.height);let y=f.getImageData(0,0,u.width,u.height);a.height=u.height,a.width=u.width,p(Zo(y.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Zo(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},rd=(e,r)=>{let{width:t,height:s,download:n,dispose:o}=r,i=[1,s,t,4];return new qr({location:"texture",type:"float32",texture:e,dims:i,download:n,dispose:o})},sd=(e,r)=>{let{dataType:t,dims:s,download:n,dispose:o}=r;return new qr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:n,dispose:o})},nd=(e,r)=>{let{dataType:t,dims:s,download:n,dispose:o}=r;return new qr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:n,dispose:o})},od=(e,r,t)=>new qr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),ln,uo,xi,ad,rx=Ne(()=>{ln=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),uo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),xi=!1,ad=()=>{if(!xi){xi=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(ln.set("int64",BigInt64Array),uo.set(BigInt64Array,"int64")),r&&(ln.set("uint64",BigUint64Array),uo.set(BigUint64Array,"uint64")),s?(ln.set("float16",t),uo.set(t,"float16")):ln.set("float16",Uint16Array)}}}),id,ld,sx=Ne(()=>{Ti(),id=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`)}}}),qr,Ti=Ne(()=>{ex(),tx(),rx(),sx(),qr=class{constructor(e,r,t){ad();let s,n;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,n=e.dims,e.location){case"cpu-pinned":{let i=ln.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=ln.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?i=l.from(r,BigInt):i=l.from(r)}else if(r instanceof l)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&l!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(a=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",i=e;else if(l==="boolean")s="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(e);else{let l=uo.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,i=e}if(a===void 0)a=[i.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");n=a,this.cpuData=i,this.dataLocation="cpu"}let o=id(n);if(this.cpuData&&o!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=n,this.size=o}static async fromImage(e,r){return td(e,r)}static fromTexture(e,r){return rd(e,r)}static fromGpuBuffer(e,r){return sd(e,r)}static fromMLTensor(e,r){return nd(e,r)}static fromPinnedBuffer(e,r,t){return od(e,r,t)}toDataURL(e){return Zu(this,e)}toImageData(e){return ed(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 ld(this,e)}}}),us,cd=Ne(()=>{Ti(),us=qr}),po,Pi,ds,rs,ud=Ne(()=>{Yu(),po=(e,r)=>{(typeof ts.trace>"u"?!ts.wasm.trace:!ts.trace)||console.timeStamp(`${e}::ORT::${r}`)},Pi=(e,r)=>{let t=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof ts.trace>"u"?!ts.wasm.trace:!ts.trace)||Pi("BEGIN",e)},rs=e=>{(typeof ts.trace>"u"?!ts.wasm.trace:!ts.trace)||Pi("END",e)}}),dd,nx=Ne(()=>{Xu(),cd(),ud(),dd=class Sv{constructor(r){this.handler=r}async run(r,t,s){ds();let n={},o={};if(typeof r!="object"||r===null||r instanceof us||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 us)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let c of t){if(typeof c!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(c)===-1)throw new RangeError(`'fetches' contains invalid output name: ${c}.`);n[c]=null}if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let c=!1,p=Object.getOwnPropertyNames(t);for(let d of this.outputNames)if(p.indexOf(d)!==-1){let u=t[d];(u===null||u instanceof us)&&(c=!0,i=!1,n[d]=u)}if(c){if(typeof s=="object"&&s!==null)o=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else o=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let c of this.inputNames)if(typeof r[c]>"u")throw new Error(`input '${c}' is missing in 'feeds'.`);if(i)for(let c of this.outputNames)n[c]=null;let a=await this.handler.run(r,n,o),l={};for(let c in a)if(Object.hasOwnProperty.call(a,c)){let p=a[c];p instanceof us?l[c]=p:l[c]=new us(p.type,p.data,p.dims)}return rs(),l}async release(){return this.handler.dispose()}static async create(r,t,s,n){ds();let o,i={};if(typeof r=="string"){if(o=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(o=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){let p=r,d=0,u=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(d=t,!Number.isSafeInteger(d))throw new RangeError("'byteOffset' must be an integer.");if(d<0||d>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(u=r.byteLength-d,typeof s=="number"){if(u=s,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||d+u>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-d}].`);if(typeof n=="object"&&n!==null)i=n;else if(typeof n<"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.");o=new Uint8Array(p,d,u)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await Qu(i),c=await a.createInferenceSessionHandler(o,l);return rs(),new Sv(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ei,ox=Ne(()=>{nx(),Ei=dd}),ax=Ne(()=>{}),ix=Ne(()=>{}),lx=Ne(()=>{}),cx=Ne(()=>{}),pd={};On(pd,{InferenceSession:()=>Ei,TRACE:()=>po,TRACE_FUNC_BEGIN:()=>ds,TRACE_FUNC_END:()=>rs,Tensor:()=>us,env:()=>Xt,registerBackend:()=>an});var ps=Ne(()=>{Jv(),Zv(),ox(),cd(),ax(),ix(),ud(),lx(),cx()}),Ci=Ne(()=>{}),md={};On(md,{default:()=>hd});var Si,ki,hd,ux=Ne(()=>{qg(),cn(),zi(),Si="ort-wasm-proxy-worker",ki=globalThis.self?.name===Si,ki&&(self.onmessage=e=>{let{type:r,in:t}=e.data;try{switch(r){case"init-wasm":ji(t.wasm).then(()=>{Zl(t).then(()=>{postMessage({type:r})},s=>{postMessage({type:r,err:s})})},s=>{postMessage({type:r,err:s})});break;case"init-ep":{let{epName:s,env:n}=t;ec(n,s).then(()=>{postMessage({type:r})},o=>{postMessage({type:r,err:o})});break}case"copy-from":{let{buffer:s}=t,n=Ma(s);postMessage({type:r,out:n});break}case"create":{let{model:s,options:n}=t;rc(s,n).then(o=>{postMessage({type:r,out:o})},o=>{postMessage({type:r,err:o})});break}case"release":sc(t),postMessage({type:r});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:i,options:a}=t;oc(s,n,o,i,new Array(i.length).fill(null),a).then(l=>{l.some(c=>c[3]!=="cpu")?postMessage({type:r,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:r,out:l},ic([...o,...l]))},l=>{postMessage({type:r,err:l})});break}case"end-profiling":ac(t),postMessage({type:r});break;default:}}catch(s){postMessage({type:r,err:s})}}),hd=ki?null:e=>new Worker(e??Qr,{type:"module",name:Si})}),_d={};On(_d,{default:()=>fd});var $i,Ii,fd,gd,dx=Ne(()=>{Ii=($i=self.location.href,async function(e={}){var r,t,s=e,n=new Promise((h,E)=>{r=h,t=E}),o=typeof window=="object",i=typeof WorkerGlobalScope<"u",a=i&&self.name?.startsWith("em-pthread");s.mountExternalData=(h,E)=>{h.startsWith("./")&&(h=h.substring(2)),(s.Eb||(s.Eb=new Map)).set(h,E)},s.unmountExternalData=()=>{delete s.Eb};var l=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let c=h=>async(...E)=>{try{if(s.Fb)throw Error("Session already started");let A=s.Fb={dc:E[0],errors:[]},L=await h(...E);if(s.Fb!==A)throw Error("Session mismatch");s.Jb?.flush();let V=A.errors;if(0Ee),0{if(h==="webgpu"){[s.Jb,s.Ub,s.Yb,s.Kb,s.Xb,s.jb,s.Zb,s.ac,s.Vb,s.Wb,s.$b]=E;let A=s.Jb;s.jsepRegisterBuffer=(L,V,ie,Ee)=>A.registerBuffer(L,V,ie,Ee),s.jsepGetBuffer=L=>A.getBuffer(L),s.jsepCreateDownloader=(L,V,ie)=>A.createDownloader(L,V,ie),s.jsepOnCreateSession=L=>{A.onCreateSession(L)},s.jsepOnReleaseSession=L=>{A.onReleaseSession(L)},s.jsepOnRunStart=L=>A.onRunStart(L),s.bc=(L,V)=>{A.upload(L,V)}}else if(h==="webnn"){let A=E[0];[s.nc,s.Nb,s.webnnEnsureTensor,s.Ob,s.webnnDownloadTensor]=E.slice(1),s.webnnReleaseTensorId=s.Nb,s.webnnUploadTensor=s.Ob,s.webnnOnRunStart=L=>A.onRunStart(L),s.webnnOnRunEnd=A.onRunEnd.bind(A),s.webnnRegisterMLContext=(L,V)=>{A.registerMLContext(L,V)},s.webnnOnReleaseSession=L=>{A.onReleaseSession(L)},s.webnnCreateMLTensorDownloader=(L,V)=>A.createMLTensorDownloader(L,V),s.webnnRegisterMLTensor=(L,V,ie,Ee)=>A.registerMLTensor(L,V,ie,Ee),s.webnnCreateMLContext=L=>A.createMLContext(L),s.webnnRegisterMLConstant=(L,V,ie,Ee,Be,Qe)=>A.registerMLConstant(L,V,ie,Ee,Be,s.Eb,Qe),s.webnnRegisterGraphInput=A.registerGraphInput.bind(A),s.webnnIsGraphInput=A.isGraphInput.bind(A),s.webnnCreateTemporaryTensor=A.createTemporaryTensor.bind(A),s.webnnIsInt64Supported=A.isInt64Supported.bind(A)}};let p=()=>{let h=(E,A,L)=>(...V)=>{let ie=Ht,Ee=A?.();V=E(...V);let Be=A?.();return Ee!==Be&&(E=Be,L(Ee),A=L=null),Ht!=ie?new Promise((Qe,it)=>{hr={resolve:Qe,reject:it}}):V};(()=>{for(let E of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])s[E]=h(s[E],()=>s[E],A=>s[E]=A)})(),c!==void 0&&(s._OrtRun=c(s._OrtRun),s._OrtRunWithBinding=c(s._OrtRunWithBinding)),p=void 0};s.asyncInit=()=>{p?.()};var d,u,f=Object.assign({},s),_=(h,E)=>{throw E},y="";(o||i)&&(i?y=self.location.href:typeof document<"u"&&document.currentScript&&(y=document.currentScript.src),$i&&(y=$i),y=y.startsWith("blob:")?"":y.slice(0,y.replace(/[?#].*/,"").lastIndexOf("/")+1),i&&(u=h=>{var E=new XMLHttpRequest;return E.open("GET",h,!1),E.responseType="arraybuffer",E.send(null),new Uint8Array(E.response)}),d=async h=>{if(le(h))return new Promise((A,L)=>{var V=new XMLHttpRequest;V.open("GET",h,!0),V.responseType="arraybuffer",V.onload=()=>{V.status==200||V.status==0&&V.response?A(V.response):L(V.status)},V.onerror=L,V.send(null)});var E=await fetch(h,{credentials:"same-origin"});if(E.ok)return E.arrayBuffer();throw Error(E.status+" : "+E.url)});var I=console.log.bind(console),w=console.error.bind(console),v=I,k=w;Object.assign(s,f),f=null;var T,b,P,x,S,O,F,H,W,B,Y,X,J,re=s.wasmBinary,ne=!1,le=h=>h.startsWith("file://");function pe(){return T.buffer!=x.buffer&&Te(),x}function oe(){return T.buffer!=x.buffer&&Te(),S}function K(){return T.buffer!=x.buffer&&Te(),O}function j(){return T.buffer!=x.buffer&&Te(),F}function D(){return T.buffer!=x.buffer&&Te(),H}function te(){return T.buffer!=x.buffer&&Te(),W}function he(){return T.buffer!=x.buffer&&Te(),B}function Ae(){return T.buffer!=x.buffer&&Te(),J}if(a){let h=function(E){try{var A=E.data,L=A.Bb;if(L==="load"){let V=[];self.onmessage=ie=>V.push(ie),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let ie of V)h(ie);self.onmessage=h};for(let ie of A.Rb)s[ie]&&!s[ie].proxy||(s[ie]=(...Ee)=>{postMessage({Bb:"callHandler",Qb:ie,args:Ee})},ie=="print"&&(v=s[ie]),ie=="printErr"&&(k=s[ie]));T=A.kc,Te(),ke(A.lc)}else if(L==="run"){Qs(A.Ab),En(A.Ab,0,0,1,0,0),Or(),ee(A.Ab),Ve||(xn(),Ve=!0);try{Xs(A.fc,A.Hb)}catch(V){if(V!="unwind")throw V}}else A.target!=="setimmediate"&&(L==="checkMailbox"?Ve&&se():L&&(k(`worker: received unknown command ${L}`),k(A)))}catch(V){throw jo(),V}};var ke,Ve=!1;k=function(...E){E=E.join(" "),console.error(E)},self.alert=function(...E){postMessage({Bb:"alert",text:E.join(" "),ic:Tn()})},self.onunhandledrejection=E=>{throw E.reason||E},self.onmessage=h}function Te(){var h=T.buffer;s.HEAP8=x=new Int8Array(h),s.HEAP16=O=new Int16Array(h),s.HEAPU8=S=new Uint8Array(h),s.HEAPU16=F=new Uint16Array(h),s.HEAP32=H=new Int32Array(h),s.HEAPU32=W=new Uint32Array(h),s.HEAPF32=B=new Float32Array(h),s.HEAPF64=J=new Float64Array(h),s.HEAP64=Y=new BigInt64Array(h),s.HEAPU64=X=new BigUint64Array(h)}function Q(){a?startWorker(s):dt.Ca()}a||(T=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Te());var z,de=0,be=null;function ve(){if(--de==0&&be){var h=be;be=null,h()}}function xe(h){throw k(h="Aborted("+h+")"),ne=!0,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),t(h),h}function Ce(){return{a:{L:fe,Aa:De,b:ar,$:Jr,A:Ts,pa:Ps,X:Es,Z:C,qa:q,na:R,ga:G,ma:Z,J:ce,Y:ye,V:et,oa:ut,W:He,va:Pt,E:Cs,Q:Ss,O:Rs,D:$s,u:Is,r:as,P:Nr,z:Nn,R:ue,ja:$,T:Me,aa:Xe,M:Je,F:Ye,ia:ee,sa:Ke,t:rr,Ba:br,w:bs,o:ls,l:_r,c:ns,n:Ur,j:Ea,v:Ca,p:Sa,f:ka,s:Zs,m:$a,e:Ia,k:Aa,i:Fa,g:Oa,d:en,da:Da,ea:La,fa:$o,ba:Io,ca:Ao,N:Vn,xa:Ba,ua:fc,h:Oo,C:Gn,G:Ra,ta:Fo,x:ja,ra:Na,U:Va,q:za,y:Ua,K:Wa,S:Do,za:Ga,ya:Hn,ka:Os,la:Lo,_:Oe,B:Ka,I:zo,ha:Ha,H:Xn,a:T,wa:Ze}}}var ge={829644:(h,E,A,L,V)=>{if(s===void 0||!s.Eb)return 1;if((h=qt(Number(h>>>0))).startsWith("./")&&(h=h.substring(2)),!(h=s.Eb.get(h)))return 2;if(E=Number(E>>>0),A=Number(A>>>0),L=Number(L>>>0),E+A>h.byteLength)return 3;try{let ie=h.subarray(E,E+A);switch(V){case 0:oe().set(ie,L>>>0);break;case 1:s.mc?s.mc(L,ie):s.bc(L,ie);break;default:return 4}return 0}catch{return 4}},830468:(h,E,A)=>{s.Ob(h,oe().subarray(E>>>0,E+A>>>0))},830532:()=>s.nc(),830574:h=>{s.Nb(h)},830611:()=>{s.Vb()},830642:()=>{s.Wb()},830671:()=>{s.$b()},830696:h=>s.Ub(h),830729:h=>s.Yb(h),830761:(h,E,A)=>{s.Kb(Number(h),Number(E),Number(A),!0)},830824:(h,E,A)=>{s.Kb(Number(h),Number(E),Number(A))},830881:()=>typeof wasmOffsetConverter<"u",830938:h=>{s.jb("Abs",h,void 0)},830989:h=>{s.jb("Neg",h,void 0)},831040:h=>{s.jb("Floor",h,void 0)},831093:h=>{s.jb("Ceil",h,void 0)},831145:h=>{s.jb("Reciprocal",h,void 0)},831203:h=>{s.jb("Sqrt",h,void 0)},831255:h=>{s.jb("Exp",h,void 0)},831306:h=>{s.jb("Erf",h,void 0)},831357:h=>{s.jb("Sigmoid",h,void 0)},831412:(h,E,A)=>{s.jb("HardSigmoid",h,{alpha:E,beta:A})},831491:h=>{s.jb("Log",h,void 0)},831542:h=>{s.jb("Sin",h,void 0)},831593:h=>{s.jb("Cos",h,void 0)},831644:h=>{s.jb("Tan",h,void 0)},831695:h=>{s.jb("Asin",h,void 0)},831747:h=>{s.jb("Acos",h,void 0)},831799:h=>{s.jb("Atan",h,void 0)},831851:h=>{s.jb("Sinh",h,void 0)},831903:h=>{s.jb("Cosh",h,void 0)},831955:h=>{s.jb("Asinh",h,void 0)},832008:h=>{s.jb("Acosh",h,void 0)},832061:h=>{s.jb("Atanh",h,void 0)},832114:h=>{s.jb("Tanh",h,void 0)},832166:h=>{s.jb("Not",h,void 0)},832217:(h,E,A)=>{s.jb("Clip",h,{min:E,max:A})},832286:h=>{s.jb("Clip",h,void 0)},832338:(h,E)=>{s.jb("Elu",h,{alpha:E})},832396:h=>{s.jb("Gelu",h,void 0)},832448:h=>{s.jb("Relu",h,void 0)},832500:(h,E)=>{s.jb("LeakyRelu",h,{alpha:E})},832564:(h,E)=>{s.jb("ThresholdedRelu",h,{alpha:E})},832634:(h,E)=>{s.jb("Cast",h,{to:E})},832692:h=>{s.jb("Add",h,void 0)},832743:h=>{s.jb("Sub",h,void 0)},832794:h=>{s.jb("Mul",h,void 0)},832845:h=>{s.jb("Div",h,void 0)},832896:h=>{s.jb("Pow",h,void 0)},832947:h=>{s.jb("Equal",h,void 0)},833e3:h=>{s.jb("Greater",h,void 0)},833055:h=>{s.jb("GreaterOrEqual",h,void 0)},833117:h=>{s.jb("Less",h,void 0)},833169:h=>{s.jb("LessOrEqual",h,void 0)},833228:(h,E,A,L,V)=>{s.jb("ReduceMean",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833403:(h,E,A,L,V)=>{s.jb("ReduceMax",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833577:(h,E,A,L,V)=>{s.jb("ReduceMin",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833751:(h,E,A,L,V)=>{s.jb("ReduceProd",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},833926:(h,E,A,L,V)=>{s.jb("ReduceSum",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834100:(h,E,A,L,V)=>{s.jb("ReduceL1",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834273:(h,E,A,L,V)=>{s.jb("ReduceL2",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834446:(h,E,A,L,V)=>{s.jb("ReduceLogSum",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834623:(h,E,A,L,V)=>{s.jb("ReduceSumSquare",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834803:(h,E,A,L,V)=>{s.jb("ReduceLogSumExp",h,{keepDims:!!E,noopWithEmptyAxes:!!A,axes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},834983:h=>{s.jb("Where",h,void 0)},835036:(h,E,A)=>{s.jb("Transpose",h,{perm:E?Array.from(D().subarray(Number(E)>>>0,Number(A)>>>0)):[]})},835160:(h,E,A,L)=>{s.jb("DepthToSpace",h,{blocksize:E,mode:qt(A),format:L?"NHWC":"NCHW"})},835293:(h,E,A,L)=>{s.jb("DepthToSpace",h,{blocksize:E,mode:qt(A),format:L?"NHWC":"NCHW"})},835426:(h,E,A,L,V,ie,Ee,Be,Qe,it,vt,Dt,Vt,xr,Us)=>{s.jb("ConvTranspose",h,{format:Qe?"NHWC":"NCHW",autoPad:E,dilations:[A],group:L,kernelShape:[V],pads:[ie,Ee],strides:[Be],wIsConst:()=>!!pe()[it>>>0],outputPadding:vt?Array.from(D().subarray(Number(vt)>>>0,Number(Dt)>>>0)):[],outputShape:Vt?Array.from(D().subarray(Number(Vt)>>>0,Number(xr)>>>0)):[],activation:qt(Us)})},835859:(h,E,A,L,V,ie,Ee,Be,Qe,it,vt,Dt,Vt,xr)=>{s.jb("ConvTranspose",h,{format:Be?"NHWC":"NCHW",autoPad:E,dilations:Array.from(D().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:L,kernelShape:Array.from(D().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(D().subarray(Number(ie)>>>0,4+(Number(ie)>>>0)>>>0)),strides:Array.from(D().subarray(Number(Ee)>>>0,2+(Number(Ee)>>>0)>>>0)),wIsConst:()=>!!pe()[Qe>>>0],outputPadding:it?Array.from(D().subarray(Number(it)>>>0,Number(vt)>>>0)):[],outputShape:Dt?Array.from(D().subarray(Number(Dt)>>>0,Number(Vt)>>>0)):[],activation:qt(xr)})},836520:(h,E,A,L,V,ie,Ee,Be,Qe,it,vt,Dt,Vt,xr,Us)=>{s.jb("ConvTranspose",h,{format:Qe?"NHWC":"NCHW",autoPad:E,dilations:[A],group:L,kernelShape:[V],pads:[ie,Ee],strides:[Be],wIsConst:()=>!!pe()[it>>>0],outputPadding:vt?Array.from(D().subarray(Number(vt)>>>0,Number(Dt)>>>0)):[],outputShape:Vt?Array.from(D().subarray(Number(Vt)>>>0,Number(xr)>>>0)):[],activation:qt(Us)})},836953:(h,E,A,L,V,ie,Ee,Be,Qe,it,vt,Dt,Vt,xr)=>{s.jb("ConvTranspose",h,{format:Be?"NHWC":"NCHW",autoPad:E,dilations:Array.from(D().subarray(Number(A)>>>0,2+(Number(A)>>>0)>>>0)),group:L,kernelShape:Array.from(D().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(D().subarray(Number(ie)>>>0,4+(Number(ie)>>>0)>>>0)),strides:Array.from(D().subarray(Number(Ee)>>>0,2+(Number(Ee)>>>0)>>>0)),wIsConst:()=>!!pe()[Qe>>>0],outputPadding:it?Array.from(D().subarray(Number(it)>>>0,Number(vt)>>>0)):[],outputShape:Dt?Array.from(D().subarray(Number(Dt)>>>0,Number(Vt)>>>0)):[],activation:qt(xr)})},837614:(h,E)=>{s.jb("GlobalAveragePool",h,{format:E?"NHWC":"NCHW"})},837705:(h,E,A,L,V,ie,Ee,Be,Qe,it,vt,Dt,Vt,xr)=>{s.jb("AveragePool",h,{format:xr?"NHWC":"NCHW",auto_pad:E,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Ee)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:it?Array.from(D().subarray(Number(it)>>>0,Number(vt)>>>0)):[],strides:Dt?Array.from(D().subarray(Number(Dt)>>>0,Number(Vt)>>>0)):[]})},838184:(h,E)=>{s.jb("GlobalAveragePool",h,{format:E?"NHWC":"NCHW"})},838275:(h,E,A,L,V,ie,Ee,Be,Qe,it,vt,Dt,Vt,xr)=>{s.jb("AveragePool",h,{format:xr?"NHWC":"NCHW",auto_pad:E,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Ee)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:it?Array.from(D().subarray(Number(it)>>>0,Number(vt)>>>0)):[],strides:Dt?Array.from(D().subarray(Number(Dt)>>>0,Number(Vt)>>>0)):[]})},838754:(h,E)=>{s.jb("GlobalMaxPool",h,{format:E?"NHWC":"NCHW"})},838841:(h,E,A,L,V,ie,Ee,Be,Qe,it,vt,Dt,Vt,xr)=>{s.jb("MaxPool",h,{format:xr?"NHWC":"NCHW",auto_pad:E,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Ee)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:it?Array.from(D().subarray(Number(it)>>>0,Number(vt)>>>0)):[],strides:Dt?Array.from(D().subarray(Number(Dt)>>>0,Number(Vt)>>>0)):[]})},839316:(h,E)=>{s.jb("GlobalMaxPool",h,{format:E?"NHWC":"NCHW"})},839403:(h,E,A,L,V,ie,Ee,Be,Qe,it,vt,Dt,Vt,xr)=>{s.jb("MaxPool",h,{format:xr?"NHWC":"NCHW",auto_pad:E,ceil_mode:A,count_include_pad:L,storage_order:V,dilations:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Ee)>>>0)):[],kernel_shape:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],pads:it?Array.from(D().subarray(Number(it)>>>0,Number(vt)>>>0)):[],strides:Dt?Array.from(D().subarray(Number(Dt)>>>0,Number(Vt)>>>0)):[]})},839878:(h,E,A,L,V)=>{s.jb("Gemm",h,{alpha:E,beta:A,transA:L,transB:V})},839982:h=>{s.jb("MatMul",h,void 0)},840036:(h,E,A,L)=>{s.jb("ArgMax",h,{keepDims:!!E,selectLastIndex:!!A,axis:L})},840144:(h,E,A,L)=>{s.jb("ArgMin",h,{keepDims:!!E,selectLastIndex:!!A,axis:L})},840252:(h,E)=>{s.jb("Softmax",h,{axis:E})},840315:(h,E)=>{s.jb("Concat",h,{axis:E})},840375:(h,E,A,L,V)=>{s.jb("Split",h,{axis:E,numOutputs:A,splitSizes:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},840531:h=>{s.jb("Expand",h,void 0)},840585:(h,E)=>{s.jb("Gather",h,{axis:Number(E)})},840656:(h,E)=>{s.jb("GatherElements",h,{axis:Number(E)})},840735:(h,E)=>{s.jb("GatherND",h,{batch_dims:Number(E)})},840814:(h,E,A,L,V,ie,Ee,Be,Qe,it,vt)=>{s.jb("Resize",h,{antialias:E,axes:A?Array.from(D().subarray(Number(A)>>>0,Number(L)>>>0)):[],coordinateTransformMode:qt(V),cubicCoeffA:ie,excludeOutside:Ee,extrapolationValue:Be,keepAspectRatioPolicy:qt(Qe),mode:qt(it),nearestMode:qt(vt)})},841176:(h,E,A,L,V,ie,Ee)=>{s.jb("Slice",h,{starts:E?Array.from(D().subarray(Number(E)>>>0,Number(A)>>>0)):[],ends:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[],axes:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Ee)>>>0)):[]})},841440:h=>{s.jb("Tile",h,void 0)},841492:(h,E,A)=>{s.jb("InstanceNormalization",h,{epsilon:E,format:A?"NHWC":"NCHW"})},841606:(h,E,A)=>{s.jb("InstanceNormalization",h,{epsilon:E,format:A?"NHWC":"NCHW"})},841720:h=>{s.jb("Range",h,void 0)},841773:(h,E)=>{s.jb("Einsum",h,{equation:qt(E)})},841854:(h,E,A,L,V)=>{s.jb("Pad",h,{mode:E,value:A,pads:L?Array.from(D().subarray(Number(L)>>>0,Number(V)>>>0)):[]})},841997:(h,E,A,L,V,ie)=>{s.jb("BatchNormalization",h,{epsilon:E,momentum:A,spatial:!!V,trainingMode:!!L,format:ie?"NHWC":"NCHW"})},842166:(h,E,A,L,V,ie)=>{s.jb("BatchNormalization",h,{epsilon:E,momentum:A,spatial:!!V,trainingMode:!!L,format:ie?"NHWC":"NCHW"})},842335:(h,E,A)=>{s.jb("CumSum",h,{exclusive:Number(E),reverse:Number(A)})},842432:(h,E,A)=>{s.jb("DequantizeLinear",h,{axis:E,blockSize:A})},842522:(h,E,A,L,V)=>{s.jb("GridSample",h,{align_corners:E,mode:qt(A),padding_mode:qt(L),format:V?"NHWC":"NCHW"})},842692:(h,E,A,L,V)=>{s.jb("GridSample",h,{align_corners:E,mode:qt(A),padding_mode:qt(L),format:V?"NHWC":"NCHW"})},842862:(h,E)=>{s.jb("ScatterND",h,{reduction:qt(E)})},842947:(h,E,A,L,V,ie,Ee,Be,Qe)=>{s.jb("Attention",h,{numHeads:E,isUnidirectional:A,maskFilterValue:L,scale:V,doRotary:ie,qkvHiddenSizes:Ee?Array.from(D().subarray(Number(Be)>>>0,Number(Be)+Ee>>>0)):[],pastPresentShareBuffer:!!Qe})},843219:h=>{s.jb("BiasAdd",h,void 0)},843274:h=>{s.jb("BiasSplitGelu",h,void 0)},843335:h=>{s.jb("FastGelu",h,void 0)},843391:(h,E,A,L,V,ie,Ee,Be,Qe,it,vt,Dt,Vt,xr,Us,Xa)=>{s.jb("Conv",h,{format:Dt?"NHWC":"NCHW",auto_pad:E,dilations:A?Array.from(D().subarray(Number(A)>>>0,Number(L)>>>0)):[],group:V,kernel_shape:ie?Array.from(D().subarray(Number(ie)>>>0,Number(Ee)>>>0)):[],pads:Be?Array.from(D().subarray(Number(Be)>>>0,Number(Qe)>>>0)):[],strides:it?Array.from(D().subarray(Number(it)>>>0,Number(vt)>>>0)):[],w_is_const:()=>!!pe()[Number(Vt)>>>0],activation:qt(xr),activation_params:Us?Array.from(he().subarray(Number(Us)>>>0,Number(Xa)>>>0)):[]})},843975:h=>{s.jb("Gelu",h,void 0)},844027:(h,E,A,L,V,ie,Ee,Be,Qe)=>{s.jb("GroupQueryAttention",h,{numHeads:E,kvNumHeads:A,scale:L,softcap:V,doRotary:ie,rotaryInterleaved:Ee,smoothSoftmax:Be,localWindowSize:Qe})},844244:(h,E,A,L)=>{s.jb("LayerNormalization",h,{axis:E,epsilon:A,simplified:!!L})},844355:(h,E,A,L)=>{s.jb("LayerNormalization",h,{axis:E,epsilon:A,simplified:!!L})},844466:(h,E,A,L,V,ie)=>{s.jb("MatMulNBits",h,{k:E,n:A,accuracyLevel:L,bits:V,blockSize:ie})},844593:(h,E,A,L,V,ie)=>{s.jb("MultiHeadAttention",h,{numHeads:E,isUnidirectional:A,maskFilterValue:L,scale:V,doRotary:ie})},844752:(h,E)=>{s.jb("QuickGelu",h,{alpha:E})},844816:(h,E,A,L,V)=>{s.jb("RotaryEmbedding",h,{interleaved:!!E,numHeads:A,rotaryEmbeddingDim:L,scale:V})},844955:(h,E,A)=>{s.jb("SkipLayerNormalization",h,{epsilon:E,simplified:!!A})},845057:(h,E,A)=>{s.jb("SkipLayerNormalization",h,{epsilon:E,simplified:!!A})},845159:(h,E,A,L)=>{s.jb("GatherBlockQuantized",h,{gatherAxis:E,quantizeAxis:A,blockSize:L})},845280:h=>{s.Zb(h)},845314:(h,E)=>s.ac(Number(h),Number(E),s.Fb.dc,s.Fb.errors)};function De(h,E,A){return Yr(async()=>{await s.Xb(Number(h),Number(E),Number(A))})}function fe(){return typeof wasmOffsetConverter<"u"}class Pe{name="ExitStatus";constructor(E){this.message=`Program terminated with exit(${E})`,this.status=E}}var We=h=>{h.terminate(),h.onmessage=()=>{}},Fe=[],tt=h=>{at.length==0&&(jr(),Bt(at[0]));var E=at.pop();if(!E)return 6;ht.push(E),kt[h.Ab]=E,E.Ab=h.Ab;var A={Bb:"run",fc:h.ec,Hb:h.Hb,Ab:h.Ab};return E.postMessage(A,h.Mb),0},Re=0,rt=(h,E,...A)=>{for(var L=2*A.length,V=eo(),ie=Sn(8*L),Ee=ie>>>3,Be=0;Be>>0]=Qe)}return h=No(h,0,L,ie,E),Cn(V),h};function Ze(h){if(a)return rt(0,1,h);if(P=h,!(0{if(P=h,a)throw je(h),"unwind";Ze(h)},at=[],ht=[],Nt=[],kt={},gr=h=>{var E=h.Ab;delete kt[E],at.push(h),ht.splice(ht.indexOf(h),1),h.Ab=0,Jn(E)};function Or(){Nt.forEach(h=>h())}var Bt=h=>new Promise(E=>{h.onmessage=V=>{var ie=(V=V.data).Bb;if(V.Gb&&V.Gb!=Tn()){var Ee=kt[V.Gb];Ee?Ee.postMessage(V,V.Mb):k(`Internal error! Worker sent a message "${ie}" to target pthread ${V.Gb}, but that thread no longer exists!`)}else ie==="checkMailbox"?se():ie==="spawnThread"?tt(V):ie==="cleanupThread"?gr(kt[V.hc]):ie==="loaded"?(h.loaded=!0,E(h)):ie==="alert"?alert(`Thread ${V.ic}: ${V.text}`):V.target==="setimmediate"?h.postMessage(V):ie==="callHandler"?s[V.Qb](...V.args):ie&&k(`worker sent an unknown command ${ie}`)},h.onerror=V=>{throw k(`worker sent an error! ${V.filename}:${V.lineno}: ${V.message}`),V};var A,L=[];for(A of[])s.propertyIsEnumerable(A)&&L.push(A);h.postMessage({Bb:"load",Rb:L,kc:T,lc:b})});function jr(){var h=new Worker((()=>{let E=URL;return self.location.href>"file:"&&self.location.href<"file;"?new E("ort.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});at.push(h)}var Qs=h=>{Te();var E=te()[h+52>>>2>>>0];h=te()[h+56>>>2>>>0],Uo(E,E-h),Cn(E)},Xs=(h,E)=>{Re=0,h=Wo(h,E),0>>=0);throw E>>>=0,A>>>=0,te()[L.Ib+16>>>2>>>0]=0,te()[L.Ib+4>>>2>>>0]=E,te()[L.Ib+8>>>2>>>0]=A,h}function kr(h,E,A,L){return a?rt(2,1,h,E,A,L):Jr(h,E,A,L)}function Jr(h,E,A,L){if(h>>>=0,A>>>=0,L>>>=0,l===void 0)return 6;var V=[];return a&&V.length===0?kr(h,E>>>=0,A,L):(h={ec:A,Ab:h,Hb:L,Mb:V},a?(h.Bb="spawnThread",postMessage(h,V),0):tt(h))}var Bs=typeof TextDecoder<"u"?new TextDecoder:void 0,ft=(h,E=0,A=NaN)=>{var L=(E>>>=0)+A;for(A=E;h[A]&&!(A>=L);)++A;if(16(V=(240&V)==224?(15&V)<<12|ie<<6|Ee:(7&V)<<18|ie<<12|Ee<<6|63&h[E++])?L+=String.fromCharCode(V):(V-=65536,L+=String.fromCharCode(55296|V>>10,56320|1023&V))}}else L+=String.fromCharCode(V)}return L},qt=(h,E)=>(h>>>=0)?ft(oe(),h,E):"";function Ts(h,E,A){return a?rt(3,1,h,E,A):0}function Ps(h,E){if(a)return rt(4,1,h,E)}var Gr=h=>{for(var E=0,A=0;A=L?E++:2047>=L?E+=2:55296<=L&&57343>=L?(E+=4,++A):E+=3}return E},yt=(h,E,A)=>{var L=oe();if(E>>>=0,0=Ee&&(Ee=65536+((1023&Ee)<<10)|1023&h.charCodeAt(++ie)),127>=Ee){if(E>=A)break;L[E++>>>0]=Ee}else{if(2047>=Ee){if(E+1>=A)break;L[E++>>>0]=192|Ee>>6}else{if(65535>=Ee){if(E+2>=A)break;L[E++>>>0]=224|Ee>>12}else{if(E+3>=A)break;L[E++>>>0]=240|Ee>>18,L[E++>>>0]=128|Ee>>12&63}L[E++>>>0]=128|Ee>>6&63}L[E++>>>0]=128|63&Ee}}L[E>>>0]=0,h=E-V}else h=0;return h};function Es(h,E){if(a)return rt(5,1,h,E)}function C(h,E,A){if(a)return rt(6,1,h,E,A)}function q(h,E,A){return a?rt(7,1,h,E,A):0}function R(h,E){if(a)return rt(8,1,h,E)}function G(h,E,A){if(a)return rt(9,1,h,E,A)}function Z(h,E,A,L){if(a)return rt(10,1,h,E,A,L)}function ce(h,E,A,L){if(a)return rt(11,1,h,E,A,L)}function ye(h,E,A,L){if(a)return rt(12,1,h,E,A,L)}function et(h){if(a)return rt(13,1,h)}function ut(h,E){if(a)return rt(14,1,h,E)}function He(h,E,A){if(a)return rt(15,1,h,E,A)}var Mt,qe,Pt=()=>xe(""),It=h=>{for(var E="";oe()[h>>>0];)E+=Mt[oe()[h++>>>0]];return E},Mr={},pr={};function ir(h,E,A={}){return(function(L,V,ie={}){var Ee=V.name;if(!L)throw new qe(`type "${Ee}" must have a positive integer typeid pointer`);if(pr.hasOwnProperty(L)){if(ie.Sb)return;throw new qe(`Cannot register type '${Ee}' twice`)}pr[L]=V,Mr.hasOwnProperty(L)&&(V=Mr[L],delete Mr[L],V.forEach(Be=>Be()))})(h,E,A)}var Tr=(h,E,A)=>{switch(E){case 1:return A?L=>pe()[L>>>0]:L=>oe()[L>>>0];case 2:return A?L=>K()[L>>>1>>>0]:L=>j()[L>>>1>>>0];case 4:return A?L=>D()[L>>>2>>>0]:L=>te()[L>>>2>>>0];case 8:return A?L=>Y[L>>>3]:L=>X[L>>>3];default:throw new TypeError(`invalid integer width (${E}): ${h}`)}};function Cs(h,E,A){A>>>=0,ir(h>>>=0,{name:E=It(E>>>0),fromWireType:L=>L,toWireType:function(L,V){if(typeof V!="bigint"&&typeof V!="number")throw V=V===null?"null":(L=typeof V)=="object"||L==="array"||L==="function"?V.toString():""+V,new TypeError(`Cannot convert "${V}" to ${this.name}`);return typeof V=="number"&&(V=BigInt(V)),V},Cb:Dr,readValueFromPointer:Tr(E,A,E.indexOf("u")==-1),Db:null})}var Dr=8;function Ss(h,E,A,L){ir(h>>>=0,{name:E=It(E>>>0),fromWireType:function(V){return!!V},toWireType:function(V,ie){return ie?A:L},Cb:Dr,readValueFromPointer:function(V){return this.fromWireType(oe()[V>>>0])},Db:null})}var Lr=[],zr=[];function ns(h){9<(h>>>=0)&&--zr[h+1]==0&&(zr[h]=void 0,Lr.push(h))}var wr=h=>{if(!h)throw new qe("Cannot use deleted val. handle = "+h);return zr[h]},lr=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let E=Lr.pop()||zr.length;return zr[E]=h,zr[E+1]=1,E}};function Kr(h){return this.fromWireType(te()[h>>>2>>>0])}var os={name:"emscripten::val",fromWireType:h=>{var E=wr(h);return ns(h),E},toWireType:(h,E)=>lr(E),Cb:Dr,readValueFromPointer:Kr,Db:null};function Rs(h){return ir(h>>>0,os)}var ks=(h,E)=>{switch(E){case 4:return function(A){return this.fromWireType(he()[A>>>2>>>0])};case 8:return function(A){return this.fromWireType(Ae()[A>>>3>>>0])};default:throw new TypeError(`invalid float width (${E}): ${h}`)}};function $s(h,E,A){A>>>=0,ir(h>>>=0,{name:E=It(E>>>0),fromWireType:L=>L,toWireType:(L,V)=>V,Cb:Dr,readValueFromPointer:ks(E,A),Db:null})}function Is(h,E,A,L,V){if(h>>>=0,A>>>=0,E=It(E>>>0),V===-1&&(V=4294967295),V=Be=>Be,L===0){var ie=32-8*A;V=Be=>Be<>>ie}var Ee=E.includes("unsigned")?function(Be,Qe){return Qe>>>0}:function(Be,Qe){return Qe};ir(h,{name:E,fromWireType:V,toWireType:Ee,Cb:Dr,readValueFromPointer:Tr(E,A,L!==0),Db:null})}function as(h,E,A){function L(ie){var Ee=te()[ie>>>2>>>0];return ie=te()[ie+4>>>2>>>0],new V(pe().buffer,ie,Ee)}var V=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][E];ir(h>>>=0,{name:A=It(A>>>0),fromWireType:L,Cb:Dr,readValueFromPointer:L},{Sb:!0})}function Nr(h,E){ir(h>>>=0,{name:E=It(E>>>0),fromWireType:function(A){for(var L,V=te()[A>>>2>>>0],ie=A+4,Ee=ie,Be=0;Be<=V;++Be){var Qe=ie+Be;Be!=V&&oe()[Qe>>>0]!=0||(Ee=qt(Ee,Qe-Ee),L===void 0?L=Ee:(L+="\0",L+=Ee),Ee=Qe+1)}return Zr(A),L},toWireType:function(A,L){L instanceof ArrayBuffer&&(L=new Uint8Array(L));var V=typeof L=="string";if(!(V||L instanceof Uint8Array||L instanceof Uint8ClampedArray||L instanceof Int8Array))throw new qe("Cannot pass non-string to std::string");var ie=V?Gr(L):L.length,Ee=Pn(4+ie+1),Be=Ee+4;if(te()[Ee>>>2>>>0]=ie,V)yt(L,Be,ie+1);else if(V)for(V=0;V>>0]=Qe}else for(V=0;V>>0]=L[V];return A!==null&&A.push(Zr,Ee),Ee},Cb:Dr,readValueFromPointer:Kr,Db(A){Zr(A)}})}var ze=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Ue=(h,E)=>{for(var A=h>>1,L=A+E/2;!(A>=L)&&j()[A>>>0];)++A;if(32<(A<<=1)-h&&ze)return ze.decode(oe().slice(h,A));for(A="",L=0;!(L>=E/2);++L){var V=K()[h+2*L>>>1>>>0];if(V==0)break;A+=String.fromCharCode(V)}return A},nt=(h,E,A)=>{if(A??=2147483647,2>A)return 0;var L=E;A=(A-=2)<2*h.length?A/2:h.length;for(var V=0;V>>1>>>0]=ie,E+=2}return K()[E>>>1>>>0]=0,E-L},Kt=h=>2*h.length,js=(h,E)=>{for(var A=0,L="";!(A>=E/4);){var V=D()[h+4*A>>>2>>>0];if(V==0)break;++A,65536<=V?(V-=65536,L+=String.fromCharCode(55296|V>>10,56320|1023&V)):L+=String.fromCharCode(V)}return L},As=(h,E,A)=>{if(E>>>=0,A??=2147483647,4>A)return 0;var L=E;A=L+A-4;for(var V=0;V=ie&&(ie=65536+((1023&ie)<<10)|1023&h.charCodeAt(++V)),D()[E>>>2>>>0]=ie,(E+=4)+4>A)break}return D()[E>>>2>>>0]=0,E-L},Ns=h=>{for(var E=0,A=0;A=L&&++A,E+=4}return E};function Nn(h,E,A){if(h>>>=0,E>>>=0,A=It(A>>>=0),E===2)var L=Ue,V=nt,ie=Kt,Ee=Be=>j()[Be>>>1>>>0];else E===4&&(L=js,V=As,ie=Ns,Ee=Be=>te()[Be>>>2>>>0]);ir(h,{name:A,fromWireType:Be=>{for(var Qe,it=te()[Be>>>2>>>0],vt=Be+4,Dt=0;Dt<=it;++Dt){var Vt=Be+4+Dt*E;Dt!=it&&Ee(Vt)!=0||(vt=L(vt,Vt-vt),Qe===void 0?Qe=vt:(Qe+="\0",Qe+=vt),vt=Vt+E)}return Zr(Be),Qe},toWireType:(Be,Qe)=>{if(typeof Qe!="string")throw new qe(`Cannot pass non-string to C++ string type ${A}`);var it=ie(Qe),vt=Pn(4+it+E);return te()[vt>>>2>>>0]=it/E,V(Qe,vt+4,it+E),Be!==null&&Be.push(Zr,vt),vt},Cb:Dr,readValueFromPointer:Kr,Db(Be){Zr(Be)}})}function ue(h,E){ir(h>>>=0,{Tb:!0,name:E=It(E>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function $(h){En(h>>>0,!i,1,!o,131072,!1),Or()}var U=h=>{if(!ne)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(D(),h>>>2,h).value.then(se),h+=128,Atomics.store(D(),h>>>2,1))}var se=()=>{var h=Tn();h&&(ee(h),U(Zn))};function Me(h,E){(h>>>=0)==E>>>0?setTimeout(se):a?postMessage({Gb:h,Bb:"checkMailbox"}):(h=kt[h])&&h.postMessage({Bb:"checkMailbox"})}var $e=[];function Xe(h,E,A,L,V){for(E>>>=0,L/=2,$e.length=L,A=V>>>0>>>3,V=0;V>>0];return(E?ge[E]:Qa[h])(...$e)}var Je=()=>{Re=0};function Ye(h){h>>>=0,a?postMessage({Bb:"cleanupThread",hc:h}):gr(kt[h])}function Ke(h){}var $t=(h,E)=>{var A=pr[h];if(A===void 0)throw h=Ro(h),A=It(h),Zr(h),new qe(`${E} has unknown type ${A}`);return A},Et=(h,E,A)=>{var L=[];return h=h.toWireType(L,A),L.length&&(te()[E>>>2>>>0]=lr(L)),h};function rr(h,E,A){return E>>>=0,A>>>=0,h=wr(h>>>0),E=$t(E,"emval::as"),Et(E,A,h)}function br(h,E){return E>>>=0,h=wr(h>>>0),(E=$t(E,"emval::as")).toWireType(null,h)}var Jt=h=>{try{h()}catch(E){xe(E)}},sr=0,Ht=null,Hr=0,is=[],Pr={},ws={},Yt=0,hr=null,$r=[];function Yr(h){return(function(E){if(!ne){if(sr===0){var A=!1,L=!1;E((V=0)=>{if(!ne&&(Hr=V,A=!0,L)){sr=2,Jt(()=>Ko(Ht)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),V=!1;try{var ie=(function(){var Qe=D()[Ht+8>>>2>>>0];return Qe=dt[ws[Qe]],--Re,Qe()})()}catch(Qe){ie=Qe,V=!0}var Ee=!1;if(!Ht){var Be=hr;Be&&(hr=null,(V?Be.reject:Be.resolve)(ie),Ee=!0)}if(V&&!Ee)throw ie}}),L=!0,A||(sr=1,Ht=(function(){var V=Pn(65548),ie=V+12;te()[V>>>2>>>0]=ie,te()[V+4>>>2>>>0]=ie+65536,ie=is[0];var Ee=Pr[ie];return Ee===void 0&&(Ee=Yt++,Pr[ie]=Ee,ws[Ee]=ie),ie=Ee,D()[V+8>>>2>>>0]=ie,V})(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),Jt(()=>to(Ht)))}else sr===2?(sr=0,Jt(ro),Zr(Ht),Ht=null,$r.forEach(U)):xe(`invalid state: ${sr}`);return Hr}})(E=>{h().then(E)})}function bs(h){return h>>>=0,Yr(async()=>{var E=await wr(h);return lr(E)})}var yr=[];function ls(h,E,A,L){return A>>>=0,L>>>=0,(h=yr[h>>>0])(null,E=wr(E>>>0),A,L)}var vr={},Zt=h=>{var E=vr[h];return E===void 0?It(h):E};function _r(h,E,A,L,V){return A>>>=0,L>>>=0,V>>>=0,(h=yr[h>>>0])(E=wr(E>>>0),E[A=Zt(A)],L,V)}var cr=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Ur(h){return(h>>>=0)==0?lr(cr()):(h=Zt(h),lr(cr()[h]))}var Ys=h=>{var E=yr.length;return yr.push(h),E},Fs=(h,E)=>{for(var A=Array(h),L=0;L>>2>>>0],"parameter "+L);return A},Eo=(h,E)=>Object.defineProperty(E,"name",{value:h});function Ea(h,E,A){var L=(E=Fs(h,E>>>0)).shift();h--;var V=`return function (obj, func, destructorsRef, args) { `,ie=0,Ee=[];A===0&&Ee.push("obj");for(var Be=["retType"],Qe=[L],it=0;itvt.name).join(", ")}) => ${L.name}>`,Ys(Eo(A,h))}function Ca(h){return h=Zt(h>>>0),lr(s[h])}function Sa(h,E){return E>>>=0,h=wr(h>>>0),E=wr(E),lr(h[E])}function ka(h){9<(h>>>=0)&&(zr[h+1]+=1)}function Zs(){return lr([])}function $a(h){h=wr(h>>>0);for(var E=Array(h.length),A=0;A>>0))}function Aa(){return lr({})}function Fa(h){for(var E=wr(h>>>=0);E.length;){var A=E.pop();E.pop()(A)}ns(h)}function Oa(h,E,A){E>>>=0,A>>>=0,h=wr(h>>>0),E=wr(E),A=wr(A),h[E]=A}function en(h,E){return E>>>=0,h=(h=$t(h>>>0,"_emval_take_value")).readValueFromPointer(E),lr(h)}function Da(h,E){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),D()[E>>>2>>>0]=h.getUTCSeconds(),D()[E+4>>>2>>>0]=h.getUTCMinutes(),D()[E+8>>>2>>>0]=h.getUTCHours(),D()[E+12>>>2>>>0]=h.getUTCDate(),D()[E+16>>>2>>>0]=h.getUTCMonth(),D()[E+20>>>2>>>0]=h.getUTCFullYear()-1900,D()[E+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,D()[E+28>>>2>>>0]=h}var Co=h=>h%4==0&&(h%100!=0||h%400==0),So=[0,31,60,91,121,152,182,213,244,274,305,335],ko=[0,31,59,90,120,151,181,212,243,273,304,334];function La(h,E){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),D()[E>>>2>>>0]=h.getSeconds(),D()[E+4>>>2>>>0]=h.getMinutes(),D()[E+8>>>2>>>0]=h.getHours(),D()[E+12>>>2>>>0]=h.getDate(),D()[E+16>>>2>>>0]=h.getMonth(),D()[E+20>>>2>>>0]=h.getFullYear()-1900,D()[E+24>>>2>>>0]=h.getDay();var A=(Co(h.getFullYear())?So:ko)[h.getMonth()]+h.getDate()-1|0;D()[E+28>>>2>>>0]=A,D()[E+36>>>2>>>0]=-60*h.getTimezoneOffset(),A=new Date(h.getFullYear(),6,1).getTimezoneOffset();var L=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(A!=L&&h.getTimezoneOffset()==Math.min(L,A)),D()[E+32>>>2>>>0]=h}function $o(h){h>>>=0;var E=new Date(D()[h+20>>>2>>>0]+1900,D()[h+16>>>2>>>0],D()[h+12>>>2>>>0],D()[h+8>>>2>>>0],D()[h+4>>>2>>>0],D()[h>>>2>>>0],0),A=D()[h+32>>>2>>>0],L=E.getTimezoneOffset(),V=new Date(E.getFullYear(),6,1).getTimezoneOffset(),ie=new Date(E.getFullYear(),0,1).getTimezoneOffset(),Ee=Math.min(ie,V);return 0>A?D()[h+32>>>2>>>0]=+(V!=ie&&Ee==L):0>>2>>>0]=E.getDay(),A=(Co(E.getFullYear())?So:ko)[E.getMonth()]+E.getDate()-1|0,D()[h+28>>>2>>>0]=A,D()[h>>>2>>>0]=E.getSeconds(),D()[h+4>>>2>>>0]=E.getMinutes(),D()[h+8>>>2>>>0]=E.getHours(),D()[h+12>>>2>>>0]=E.getDate(),D()[h+16>>>2>>>0]=E.getMonth(),D()[h+20>>>2>>>0]=E.getYear(),h=E.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function Io(h,E,A,L,V,ie,Ee){return a?rt(16,1,h,E,A,L,V,ie,Ee):-52}function Ao(h,E,A,L,V,ie){if(a)return rt(17,1,h,E,A,L,V,ie)}var Vs={},za=()=>performance.timeOrigin+performance.now();function Vn(h,E){if(a)return rt(18,1,h,E);if(Vs[h]&&(clearTimeout(Vs[h].id),delete Vs[h]),!E)return 0;var A=setTimeout(()=>{delete Vs[h],U(()=>Vo(h,performance.timeOrigin+performance.now()))},E);return Vs[h]={id:A,qc:E},0}function Ba(h,E,A,L){h>>>=0,E>>>=0,A>>>=0,L>>>=0;var V=new Date().getFullYear(),ie=new Date(V,0,1).getTimezoneOffset();V=new Date(V,6,1).getTimezoneOffset();var Ee=Math.max(ie,V);te()[h>>>2>>>0]=60*Ee,D()[E>>>2>>>0]=+(ie!=V),h=(E=Be=>{var Qe=Math.abs(Be);return`UTC${0<=Be?"-":"+"}${String(Math.floor(Qe/60)).padStart(2,"0")}${String(Qe%60).padStart(2,"0")}`})(ie),E=E(V),VDate.now();function fc(h,E,A){return 0<=h&&3>=h?(h===0?h=Date.now():h=performance.timeOrigin+performance.now(),Y[A>>>0>>>3]=BigInt(Math.round(1e6*h)),0):28}var Un=[],Wn=(h,E)=>{Un.length=0;for(var A;A=oe()[h++>>>0];){var L=A!=105;E+=(L&=A!=112)&&E%8?4:0,Un.push(A==112?te()[E>>>2>>>0]:A==106?Y[E>>>3]:A==105?D()[E>>>2>>>0]:Ae()[E>>>3>>>0]),E+=L?8:4}return Un};function Oo(h,E,A){return h>>>=0,E=Wn(E>>>0,A>>>0),ge[h](...E)}function Gn(h,E,A){return h>>>=0,E=Wn(E>>>0,A>>>0),ge[h](...E)}var Ra=()=>{};function ja(h,E){return k(qt(h>>>0,E>>>0))}var Na=()=>{throw Re+=1,"unwind"};function Va(){return 4294901760}var Ua=()=>navigator.hardwareConcurrency;function Wa(){return xe("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Do(h){h>>>=0;var E=oe().length;if(h<=E||4294901760=A;A*=2){var L=E*(1+.2/A);L=Math.min(L,h+100663296);e:{L=(Math.min(4294901760,65536*Math.ceil(Math.max(h,L)/65536))-T.buffer.byteLength+65535)/65536|0;try{T.grow(L),Te();var V=1;break e}catch{}V=void 0}if(V)return!0}return!1}var bn=()=>(xe("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),tn={},Kn=h=>{h.forEach(E=>{bn()})};function Ga(){var h=Error().stack.toString().split(` `);return h[0]=="Error"&&h.shift(),Kn(h),tn.Lb=bn(),tn.cc=h,tn.Lb}function Hn(h,E,A){if(h>>>=0,E>>>=0,tn.Lb==h)var L=tn.cc;else(L=Error().stack.toString().split(` `))[0]=="Error"&&L.shift(),Kn(L);for(var V=3;L[V]&&bn()!=h;)++V;for(h=0;h>>2>>>0]=bn();return h}var yn,qn={},Qn=()=>{if(!yn){var h,E={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(h in qn)qn[h]===void 0?delete E[h]:E[h]=qn[h];var A=[];for(h in E)A.push(`${h}=${E[h]}`);yn=A}return yn};function Os(h,E){if(a)return rt(19,1,h,E);h>>>=0,E>>>=0;var A=0;return Qn().forEach((L,V)=>{var ie=E+A;for(V=te()[h+4*V>>>2>>>0]=ie,ie=0;ie>>0]=L.charCodeAt(ie);pe()[V>>>0]=0,A+=L.length+1}),0}function Lo(h,E){if(a)return rt(20,1,h,E);h>>>=0,E>>>=0;var A=Qn();te()[h>>>2>>>0]=A.length;var L=0;return A.forEach(V=>L+=V.length+1),te()[E>>>2>>>0]=L,0}function Ka(h){return a?rt(21,1,h):52}function zo(h,E,A,L){return a?rt(22,1,h,E,A,L):52}function Ha(h,E,A,L){return a?rt(23,1,h,E,A,L):70}var qa=[null,[],[]];function Xn(h,E,A,L){if(a)return rt(24,1,h,E,A,L);E>>>=0,A>>>=0,L>>>=0;for(var V=0,ie=0;ie>>2>>>0],Be=te()[E+4>>>2>>>0];E+=8;for(var Qe=0;Qe>>0],vt=qa[h];it===0||it===10?((h===1?v:k)(ft(vt)),vt.length=0):vt.push(it)}V+=Be}return te()[L>>>2>>>0]=V,0}a||(function(){for(var h=s.numThreads-1;h--;)jr();Fe.unshift(()=>{de++,(function(E){a?E():Promise.all(at.map(Bt)).then(E)})(()=>ve())})})();for(var Bo=Array(256),vn=0;256>vn;++vn)Bo[vn]=String.fromCharCode(vn);Mt=Bo,qe=s.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},s.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},zr.push(0,1,void 0,1,null,1,!0,1,!1,1),s.count_emval_handles=()=>zr.length/2-5-Lr.length;var dt,Qa=[Ze,je,kr,Ts,Ps,Es,C,q,R,G,Z,ce,ye,et,ut,He,Io,Ao,Vn,Os,Lo,Ka,zo,Ha,Xn];(async function(){function h(L,V){return dt=L.exports,dt=(function(){var ie=dt,Ee={};for(let[Be,Qe]of Object.entries(ie))Ee[Be]=typeof Qe=="function"?(...it)=>{is.push(Be);try{return Qe(...it)}finally{ne||(is.pop(),Ht&&sr===1&&is.length===0&&(sr=0,Re+=1,Jt(Go),typeof Fibers<"u"&&Fibers.rc()))}}:Qe;return Ee})(),dt=(function(){var ie=dt,Ee=Qe=>it=>Qe(it)>>>0,Be=Qe=>()=>Qe()>>>0;return(ie=Object.assign({},ie)).Da=Ee(ie.Da),ie.fb=Be(ie.fb),ie.hb=Ee(ie.hb),ie.tb=Ee(ie.tb),ie.ub=Be(ie.ub),ie.__cxa_get_exception_ptr=Ee(ie.__cxa_get_exception_ptr),ie})(),Nt.push(dt.ib),b=V,ve(),dt}de++;var E=Ce();if(s.instantiateWasm)return new Promise(L=>{s.instantiateWasm(E,(V,ie)=>{h(V,ie),L(V.exports)})});if(a)return new Promise(L=>{ke=V=>{var ie=new WebAssembly.Instance(V,Ce());L(h(ie,V))}});z??=s.locateFile?s.locateFile?s.locateFile("ort-wasm-simd-threaded.jsep.wasm",y):y+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href;try{var A=await(async function(L){var V=z;if(!re&&typeof WebAssembly.instantiateStreaming=="function"&&!le(V))try{var ie=fetch(V,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ie,L)}catch(Ee){k(`wasm streaming compile failed: ${Ee}`),k("falling back to ArrayBuffer instantiation")}return(async function(Ee,Be){try{var Qe=await(async function(it){if(!re)try{var vt=await d(it);return new Uint8Array(vt)}catch{}if(it==z&&re)it=new Uint8Array(re);else{if(!u)throw"both async and sync fetching of the wasm failed";it=u(it)}return it})(Ee);return await WebAssembly.instantiate(Qe,Be)}catch(it){k(`failed to asynchronously prepare wasm: ${it}`),xe(it)}})(V,L)})(E);return h(A.instance,A.module)}catch(L){return t(L),Promise.reject(L)}})();var Ro=h=>(Ro=dt.Da)(h),xn=()=>(xn=dt.Ea)();s._OrtInit=(h,E)=>(s._OrtInit=dt.Fa)(h,E),s._OrtGetLastError=(h,E)=>(s._OrtGetLastError=dt.Ga)(h,E),s._OrtCreateSessionOptions=(h,E,A,L,V,ie,Ee,Be,Qe,it)=>(s._OrtCreateSessionOptions=dt.Ha)(h,E,A,L,V,ie,Ee,Be,Qe,it),s._OrtAppendExecutionProvider=(h,E,A,L,V)=>(s._OrtAppendExecutionProvider=dt.Ia)(h,E,A,L,V),s._OrtAddFreeDimensionOverride=(h,E,A)=>(s._OrtAddFreeDimensionOverride=dt.Ja)(h,E,A),s._OrtAddSessionConfigEntry=(h,E,A)=>(s._OrtAddSessionConfigEntry=dt.Ka)(h,E,A),s._OrtReleaseSessionOptions=h=>(s._OrtReleaseSessionOptions=dt.La)(h),s._OrtCreateSession=(h,E,A)=>(s._OrtCreateSession=dt.Ma)(h,E,A),s._OrtReleaseSession=h=>(s._OrtReleaseSession=dt.Na)(h),s._OrtGetInputOutputCount=(h,E,A)=>(s._OrtGetInputOutputCount=dt.Oa)(h,E,A),s._OrtGetInputOutputMetadata=(h,E,A,L)=>(s._OrtGetInputOutputMetadata=dt.Pa)(h,E,A,L),s._OrtFree=h=>(s._OrtFree=dt.Qa)(h),s._OrtCreateTensor=(h,E,A,L,V,ie)=>(s._OrtCreateTensor=dt.Ra)(h,E,A,L,V,ie),s._OrtGetTensorData=(h,E,A,L,V)=>(s._OrtGetTensorData=dt.Sa)(h,E,A,L,V),s._OrtReleaseTensor=h=>(s._OrtReleaseTensor=dt.Ta)(h),s._OrtCreateRunOptions=(h,E,A,L)=>(s._OrtCreateRunOptions=dt.Ua)(h,E,A,L),s._OrtAddRunConfigEntry=(h,E,A)=>(s._OrtAddRunConfigEntry=dt.Va)(h,E,A),s._OrtReleaseRunOptions=h=>(s._OrtReleaseRunOptions=dt.Wa)(h),s._OrtCreateBinding=h=>(s._OrtCreateBinding=dt.Xa)(h),s._OrtBindInput=(h,E,A)=>(s._OrtBindInput=dt.Ya)(h,E,A),s._OrtBindOutput=(h,E,A,L)=>(s._OrtBindOutput=dt.Za)(h,E,A,L),s._OrtClearBoundOutputs=h=>(s._OrtClearBoundOutputs=dt._a)(h),s._OrtReleaseBinding=h=>(s._OrtReleaseBinding=dt.$a)(h),s._OrtRunWithBinding=(h,E,A,L,V)=>(s._OrtRunWithBinding=dt.ab)(h,E,A,L,V),s._OrtRun=(h,E,A,L,V,ie,Ee,Be)=>(s._OrtRun=dt.bb)(h,E,A,L,V,ie,Ee,Be),s._OrtEndProfiling=h=>(s._OrtEndProfiling=dt.cb)(h),s._JsepOutput=(h,E,A)=>(s._JsepOutput=dt.db)(h,E,A),s._JsepGetNodeName=h=>(s._JsepGetNodeName=dt.eb)(h);var Tn=()=>(Tn=dt.fb)(),Zr=s._free=h=>(Zr=s._free=dt.gb)(h),Pn=s._malloc=h=>(Pn=s._malloc=dt.hb)(h),En=(h,E,A,L,V,ie)=>(En=dt.kb)(h,E,A,L,V,ie),jo=()=>(jo=dt.lb)(),No=(h,E,A,L,V)=>(No=dt.mb)(h,E,A,L,V),Jn=h=>(Jn=dt.nb)(h),Yn=h=>(Yn=dt.ob)(h),Vo=(h,E)=>(Vo=dt.pb)(h,E),Zn=()=>(Zn=dt.qb)(),Uo=(h,E)=>(Uo=dt.rb)(h,E),Cn=h=>(Cn=dt.sb)(h),Sn=h=>(Sn=dt.tb)(h),eo=()=>(eo=dt.ub)(),Wo=s.dynCall_ii=(h,E)=>(Wo=s.dynCall_ii=dt.vb)(h,E),to=h=>(to=dt.wb)(h),Go=()=>(Go=dt.xb)(),Ko=h=>(Ko=dt.yb)(h),ro=()=>(ro=dt.zb)();return s.stackSave=()=>eo(),s.stackRestore=h=>Cn(h),s.stackAlloc=h=>Sn(h),s.setValue=function(h,E,A="i8"){switch(A.endsWith("*")&&(A="*"),A){case"i1":case"i8":pe()[h>>>0]=E;break;case"i16":K()[h>>>1>>>0]=E;break;case"i32":D()[h>>>2>>>0]=E;break;case"i64":Y[h>>>3]=BigInt(E);break;case"float":he()[h>>>2>>>0]=E;break;case"double":Ae()[h>>>3>>>0]=E;break;case"*":te()[h>>>2>>>0]=E;break;default:xe(`invalid type for setValue: ${A}`)}},s.getValue=function(h,E="i8"){switch(E.endsWith("*")&&(E="*"),E){case"i1":case"i8":return pe()[h>>>0];case"i16":return K()[h>>>1>>>0];case"i32":return D()[h>>>2>>>0];case"i64":return Y[h>>>3];case"float":return he()[h>>>2>>>0];case"double":return Ae()[h>>>3>>>0];case"*":return te()[h>>>2>>>0];default:xe(`invalid type for getValue: ${E}`)}},s.UTF8ToString=qt,s.stringToUTF8=yt,s.lengthBytesUTF8=Gr,(function h(){if(0{Ci(),Ai=typeof location>"u"?void 0:location.origin,Fi=self.location.href>"file:"&&self.location.href<"file;",Md=()=>{{if(Fi){let e=URL;return new URL(new e("ort.bundle.min.mjs",self.location.href).href,Ai).href}return self.location.href}},Qr=Md(),wd=()=>{if(Qr&&!Qr.startsWith("blob:"))return Qr.substring(0,Qr.lastIndexOf("/")+1)},ea=(e,r)=>{try{let t=r??Qr;return(t?new URL(e,t):new URL(e)).origin===Ai}catch{return!1}},bd=(e,r)=>{let t=r??Qr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},yd=(e,r)=>`${r??"./"}${e}`,Oi=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},vd=async e=>(await import(e)).default,Di=(ux(),lo(md)).default,xd=async()=>{if(!Qr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ea(Qr))return[void 0,Di()];let e=await Oi(Qr);return[e,Di(e)]},Li=(dx(),lo(_d)).default,Td=async(e,r,t)=>{if(!e&&!r&&Li&&Qr&&ea(Qr))return[void 0,Li];{let s="ort-wasm-simd-threaded.jsep.mjs",n=e??bd(s,r),o=t&&n&&!ea(n,r),i=o?await Oi(n):n??yd(s,r);return[o?i:void 0,await vd(i)]}}}),Bi,ta,mo,Ri,Pd,Ed,Cd,ji,Qt,cn=Ne(()=>{zi(),ta=!1,mo=!1,Ri=!1,Pd=()=>{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}},Ed=()=>{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}},Cd=()=>{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}},ji=async e=>{if(ta)return Promise.resolve();if(mo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ri)throw new Error("previous call to 'initializeWebAssembly()' failed.");mo=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Cd())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Ed())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=Pd();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 n=e.wasmPaths,o=typeof n=="string"?n:void 0,i=n?.mjs,a=i?.href??i,l=n?.wasm,c=l?.href??l,p=e.wasmBinary,[d,u]=await Td(a,o,t>1),f=!1,_=[];if(r>0&&_.push(new Promise(y=>{setTimeout(()=>{f=!0,y()},r)})),_.push(new Promise((y,I)=>{let w={numThreads:t};if(p)w.wasmBinary=p;else if(c||o)w.locateFile=v=>c??o+v;else if(a&&a.indexOf("blob:")!==0)w.locateFile=v=>new URL(v,a).href;else if(d){let v=wd();v&&(w.locateFile=k=>v+k)}u(w).then(v=>{mo=!1,ta=!0,Bi=v,y(),d&&URL.revokeObjectURL(d)},v=>{mo=!1,Ri=!0,I(v)})})),await Promise.race(_),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},Qt=()=>{if(ta&&Bi)return Bi;throw new Error("WebAssembly is not initialized yet.")}}),ms,ra,Gt,Ni=Ne(()=>{cn(),ms=(e,r)=>{let t=Qt(),s=t.lengthBytesUTF8(e)+1,n=t._malloc(s);return t.stringToUTF8(e,n,s),r.push(n),n},ra=(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(([n,o])=>{let i=r?r+n:n;if(typeof o=="object")ra(o,i+".",t,s);else if(typeof o=="string"||typeof o=="number")s(i,o.toString());else if(typeof o=="boolean")s(i,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},Gt=e=>{let r=Qt(),t=r.stackSave();try{let s=r.PTR_SIZE,n=r.stackAlloc(2*s);r._OrtGetLastError(n,n+s);let o=Number(r.getValue(n,s===4?"i32":"i64")),i=r.getValue(n+s,"*"),a=i?r.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${o}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),Sd,px=Ne(()=>{cn(),Ni(),Sd=e=>{let r=Qt(),t=0,s=[],n=e||{};try{if(e?.logSeverityLevel===void 0)n.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)n.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(n.terminate=!1);let o=0;return e?.tag!==void 0&&(o=ms(e.tag,s)),t=r._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),t===0&&Gt("Can't create run options."),e?.extra!==void 0&&ra(e.extra,"",new WeakSet,(i,a)=>{let l=ms(i,s),c=ms(a,s);r._OrtAddRunConfigEntry(t,l,c)!==0&&Gt(`Can't set a run config entry: ${i} - ${a}.`)}),[t,s]}catch(o){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(i=>r._free(i)),o}}}),kd,$d,Id,ho,Ad,Fd,mx=Ne(()=>{cn(),Ni(),kd=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}`)}},$d=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Id=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)},ho=(e,r,t,s)=>{let n=ms(r,s),o=ms(t,s);Qt()._OrtAddSessionConfigEntry(e,n,o)!==0&&Gt(`Can't set a session config entry: ${r} - ${t}.`)},Ad=async(e,r,t)=>{for(let s of r){let n=typeof s=="string"?s:s.name,o=[];switch(n){case"webnn":if(n="WEBNN",typeof s!="string"){let p=s?.deviceType;p&&ho(e,"deviceType",p,t)}break;case"webgpu":if(n="JS",typeof s!="string"){let p=s;if(p?.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);ho(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${n}`)}let i=ms(n,t),a=o.length,l=0,c=0;if(a>0){l=Qt()._malloc(a*Qt().PTR_SIZE),t.push(l),c=Qt()._malloc(a*Qt().PTR_SIZE),t.push(c);for(let p=0;p{let r=Qt(),t=0,s=[],n=e||{};Id(n);try{let o=kd(n.graphOptimizationLevel??"all"),i=$d(n.executionMode??"sequential"),a=typeof n.logId=="string"?ms(n.logId,s):0,l=n.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let c=n.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw new Error(`log verbosity level is not valid: ${c}`);let p=typeof n.optimizedModelFilePath=="string"?ms(n.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,i,!!n.enableProfiling,0,a,l,c,p),t===0&&Gt("Can't create session options."),n.executionProviders&&await Ad(t,n.executionProviders,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);ho(t,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[d,u]of Object.entries(n.freeDimensionOverrides)){if(typeof d!="string")throw new Error(`free dimension override name must be a string: ${d}`);if(typeof u!="number"||!Number.isInteger(u)||u<0)throw new Error(`free dimension override value must be a non-negative integer: ${u}`);let f=ms(d,s);r._OrtAddFreeDimensionOverride(t,f,u)!==0&&Gt(`Can't set a free dimension override: ${d} - ${u}.`)}return n.extra!==void 0&&ra(n.extra,"",new WeakSet,(d,u)=>{ho(t,d,u,s)}),[t,s]}catch(o){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&Gt("Can't release session options."),s.forEach(i=>r._free(i)),o}}}),Dn,Ds,un,Vi,sa,Ui,Wi,Gi,gt=Ne(()=>{Dn=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}`)}},Ds=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}`)}},un=(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((n,o)=>n*o,1);return t>0?Math.ceil(s*t):void 0},Vi=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}`)}},sa=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}`)}},Ui=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Wi=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Gi=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}`)}}}),Ki,Od=Ne(()=>{Ci(),Ki=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 n=r.body.getReader(),o;try{o=new ArrayBuffer(s)}catch(a){if(a instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw a}let i=0;for(;;){let{done:a,value:l}=await n.read();if(a)break;let c=l.byteLength;new Uint8Array(o,i,c).set(l),i+=c}return new Uint8Array(o,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Dd,Ld,zd,Bd,Hi,Rd,Ot,Ls=Ne(()=>{gt(),Dd=["V","I","W","E","F"],Ld=(e,r)=>{console.log(`[${Dd[e]},${new Date().toISOString()}]${r}`)},Hi=(e,r)=>{zd=e,Bd=r},Rd=(e,r)=>{let t=sa(e),s=sa(zd);t>=s&&Ld(t,typeof r=="function"?r():r)},Ot=(...e)=>{Bd&&Rd(...e)}}),jd,Ln,we,na,Nd,Vd,Ud,Tt=Ne(()=>{jd=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},Ln=class{static calcShape(e,r,t=!1){let s=e.length,n=r.length;if(s===0)return r;if(n===0)return e;let o=Math.max(e.length,r.length),i=new Array(o);if(t){if(s<2||n<2)return;let a=jd.calcMatMulShape([e[s-2],e[s-1]],[r[n-2],r[n-1]]);if(a===void 0)return;[i[o-2],i[o-1]]=a}for(let a=t?3:1;a<=o;a++){let l=s-a<0?1:e[s-a],c=n-a<0?1:r[n-a];if(l!==c&&l>1&&c>1)return;let p=Math.max(l,c);if(l&&c)i[o-a]=Math.max(l,c);else{if(p>1)return;i[o-a]=0}}return i}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let n=1;n<=t;n++)if(e[t-n]!==1&&e[t-n]!==r[s-n])return!1;return!0}},we=class gi{static size(r){return gi.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let n=new Array(s),o=s-1;for(;o>=0;){if(r[o]%t===0){n[o]=r[o]/t;break}if(t%r[o]!==0)throw new Error("cannot convert shape");n[o]=1,t/=r[o],o--}for(o--;o>=0;o--)n[o]=r[o];return n}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 gi.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 gi.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let n=1;for(let o=t;o=0;--n)s[n]=s[n+1]*r[n+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((n,o)=>n+t[o]+t[o+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,n)=>s===t[n])}},na=class Xo{static adjustPoolAttributes(r,t,s,n,o,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,n,o,i,a){if(a){if(o.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(n.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{gt(),qi=(e,r)=>new(Vi(r))(e)}),Qi,Xi,Gd,Ji,Kd,Yi,Zi,el,Hd,qd,hx=Ne(()=>{Ls(),Qi=(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),n=new Int32Array(t);for(let o=0;o2147483647n||i<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${o}: ${i}`);n[o]=Number(i)}return r?new Uint8Array(n.buffer):n},Xi=(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),n=BigInt64Array.from(s,BigInt);return r?new Uint8Array(n.buffer):n},Gd=1,Ji=()=>Gd++,Kd=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Yi=(e,r)=>{let t=Kd.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,n)=>s*n)*t/8):0},Zi=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:r,context:t,tensor:s,dataType:n,shape:o,shouldConvertInt64toInt32:i=!1}=e;this.sessionId=r,this.mlContext=t,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.shouldConvertInt64toInt32=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Yi(this.dataType,this.tensorShape)}destroy(){Ot("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=Xi(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,n)=>s===t[n])}setIsInt64ToInt32Converted(e){this.isInt64ToInt32Converted=e}},el=class{constructor(e,r){this.tensorManager=e,this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,r,t,s){let n=r,o=this.tensorManager.getMLContext(e),i=n==="int64"&&!o.opSupportLimits().input.dataTypes.includes("int64");if(i&&(n="int32",Ot("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(o,n,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Yi(n,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,n,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=Qi(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else Ot("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){if(this.activeUpload){let r=this.wrapper?.isInt64ToInt32Converted?Xi(this.activeUpload):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(r):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(r);return}else return r.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32,e):this.wrapper.read(this.wrapper?.shouldConvertInt64toInt32)}},Hd=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=Ji();return this.tensorTrackersById.set(e,new el(this)),e}releaseTensorId(e){let r=this.tensorTrackersById.get(e);r&&(this.tensorTrackersById.delete(e),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(e,r,t,s,n){Ot("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${n}}`);let o=this.tensorTrackersById.get(r);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(e,t,s,n)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){Ot("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${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 n=this.getMLContext(e),o=Ji(),i=new Zi({sessionId:e,context:n,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(o,new el(this,i)),this.externalTensors.add(i),o}async getCachedTensor(e,r,t,s,n,o,i=!1){let a=this.getMLContext(e);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(a,r,t)){Ot("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let d=this.freeTensors.splice(c,1)[0];return d.sessionId=e,d}Ot("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let l=await a.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:n,readable:o});return new Zi({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)}},qd=(...e)=>new Hd(...e)}),oa,Qd,Xd,_x=Ne(()=>{gt(),cn(),Wd(),hx(),Ls(),oa=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Qd=(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((n,o)=>n===s[o]&&e[n]===r[n])},Xd=class{constructor(e){this.tensorManager=qd(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Hi(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Ot("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Ot("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)Ot("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=>Qd(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(n=>n.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Ot("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,n){let o=oa.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,o,s,n)}async createTemporaryTensor(e,r,t){Ot("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=oa.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let n=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,n,s,t,!1);let o=this.temporarySessionTensorIds.get(e);return o?o.push(n):this.temporarySessionTensorIds.set(e,[n]),n}uploadTensor(e,r){if(!Qt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Ot("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 qi(t,r)}}registerMLTensor(e,r,t,s){let n=oa.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.registerTensor(e,r,n,s);return Ot("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(e,r,t,s,n,o,i=!1){if(!o)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let l=o.get(a);if(!l)throw new Error(`File with name ${a} not found in preloaded files.`);if(r+t>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let c=l.slice(r,r+t).buffer,p;switch(n.dataType){case"float32":p=new Float32Array(c);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(c):new Uint16Array(c);break;case"int32":p=new Int32Array(c);break;case"uint32":p=new Uint32Array(c);break;case"int64":i?(p=Qi(new Uint8Array(c),!1),n.dataType="int32"):p=new BigInt64Array(c);break;case"uint64":p=new BigUint64Array(c);break;case"int8":p=new Int8Array(c);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(c);break;default:throw new Error(`Unsupported data type: ${n.dataType} in creating WebNN Constant from external data.`)}return Ot("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(n,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}isInt64Supported(e){return!!this.mlContextBySessionId.get(e)?.opSupportLimits().input.dataTypes.includes("int64")}flush(){}}}),tl=Ne(()=>{}),rl,aa,ia,Jd,Yd,sl,nl,Zd,ep,fx=Ne(()=>{Ls(),tl(),rl=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),aa=[],ia=e=>Math.ceil(Number(e)/16)*16,Jd=e=>{for(let r=0;rYd++,nl=async(e,r,t,s)=>{let n=ia(t),o=e.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(r,0,o,0,n),e.flush(),await o.mapAsync(GPUMapMode.READ);let a=o.getMappedRange();if(s){let l=s();return l.set(new Uint8Array(a,0,t)),l}else return new Uint8Array(a.slice(0,t))}finally{o.destroy()}},Zd=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of rl)aa.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,n=r.byteLength,o=ia(n),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==n)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${n}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:o,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=a.getMappedRange();new Uint8Array(l).set(new Uint8Array(t,s,n)),a.unmap();let c=this.backend.device.createCommandEncoder();c.copyBufferToBuffer(a,0,i.gpuData.buffer,0,o),this.backend.device.queue.submit([c.finish()]),a.destroy(),Ot("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 n=ia(t.originalSize),o=this.backend.getCommandEncoder();this.backend.endComputePass(),o.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,n)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return Ot("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, buffer is the same, skip.`),s;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. Please use the previous external buffer!`)}else s=sl();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),Ot("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Ot("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=Jd(e),s,n=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,o=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(n||o){let a=(n?this.freeBuffers:this.freeUniformBuffers).get(t);a?a.length>0?s=a.pop():s=this.backend.device.createBuffer({size:t,usage:r}):s=this.backend.device.createBuffer({size:t,usage:r})}else s=this.backend.device.createBuffer({size:t,usage:r});let i={id:sl(),type:0,buffer:s};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),Ot("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){return this.storageCache.get(e)?.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 Ot("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,r){let t=this.storageCache.get(Number(e));if(!t)throw new Error("data does not exist");await nl(this.backend,t.gpuData.buffer,t.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let r=rl.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let t=this.freeBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let t=this.freeUniformBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let r of this.buffersPending)e.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let r=this.capturedPendingBuffers.get(e);r&&(r.forEach(t=>{t.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(Ot("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},ep=(...e)=>new Zd(...e)}),tp,Rt,dr=Ne(()=>{tp=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}},Rt=e=>new tp(e)}),zn,la,Sr,Rr,ct,or,ol,Bn,Gs,lt,_o,Ie,ot,rp,al,sp,np,St=Ne(()=>{gt(),Tt(),zn=64,la=(e,r)=>{if(r===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return r>1?`vec${r}`:"f16";case 1:return r>1?`vec${r}`:"f32";case 6:return r>1?`vec${r}`:"i32";case 12:return r>1?`vec${r}`:"u32";case 7:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(r!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},Sr=(e,r=1)=>{let t=la(e,r);return typeof t=="string"?t:t[0]},Rr=(e,r=1)=>{let t=la(e,r);return typeof t=="string"?t:t[1]},ct=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:we.computeStrides(t)})}),r},or=e=>e%4===0?4:e%2===0?2:1,ol=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,Bn=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,Gs=(e,r)=>r===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:r===2?`(${e}.x + ${e}.y)`:r===3?`(${e}.x + ${e}.y + ${e}.z)`:e,lt=(e,r,t,s)=>e.startsWith("uniforms.")&&t>4?typeof r=="string"?s==="f16"?`${e}[(${r}) / 8][(${r}) % 8 / 4][(${r}) % 8 % 4]`:`${e}[(${r}) / 4][(${r}) % 4]`:s==="f16"?`${e}[${Math.floor(r/8)}][${Math.floor(r%8/4)}][${r%8%4}]`:`${e}[${Math.floor(r/4)}][${r%4}]`:t>1?`${e}[${r}]`:e,_o=(e,r,t,s,n)=>{let o=typeof t=="number",i=o?t:t.length,a=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`array`,c=la(r,n),p=typeof c=="string"?c:c[1],d=typeof c=="string"?c:c[0],u={indices:l,value:p,storage:d,tensor:r},f=oe=>typeof oe=="string"?oe:`${oe}u`,_={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},y=o?"uniforms.":"",I=`${y}${e}_shape`,w=`${y}${e}_strides`,v="";for(let oe=0;oe ${u.indices} { var indices: ${u.indices}; var current = offset; ${v} return indices; }`,T=oe=>(_.offsetToIndices=!0,i<2?oe:`o2i_${e}(${oe})`),b=[];if(i>=2)for(let oe=i-1;oe>=0;oe--)b.push(`${lt(w,oe,i)} * (indices[${oe}])`);let P=i<2?"":` fn i2o_${e}(indices: ${u.indices}) -> u32 { return ${b.join("+")}; }`,x=oe=>(_.indicesToOffset=!0,i<2?oe:`i2o_${e}(${oe})`),S=(...oe)=>i===0?"0u":`${u.indices}(${oe.map(f).join(",")})`,O=(oe,K)=>i<2?`${oe}`:`${lt(oe,K,i)}`,F=(oe,K,j)=>i<2?`${oe}=${j};`:`${lt(oe,K,i)}=${j};`,H={},W=(oe,K)=>{_.broadcastedIndicesToOffset=!0;let j=`${K.name}broadcastedIndicesTo${e}Offset`;if(j in H)return`${j}(${oe})`;let D=[];for(let te=i-1;te>=0;te--){let he=K.indicesGet("outputIndices",te+K.rank-i);D.push(`${O(w,te)} * (${he} % ${O(I,te)})`)}return H[j]=`fn ${j}(outputIndices: ${K.type.indices}) -> u32 { return ${D.length>0?D.join("+"):"0u"}; }`,`${j}(${oe})`},B=(oe,K)=>(()=>{if(u.storage===u.value)return`${e}[${oe}]=${K};`;if(u.storage==="vec2"&&u.value==="i32")return`${e}[${oe}]=vec2(u32(${K}), select(0u, 0xFFFFFFFFu, ${K} < 0));`;if(u.storage==="vec2"&&u.value==="u32")return`${e}[${oe}]=vec2(u32(${K}), 0u);`;if(u.storage==="u32"&&u.value==="vec4")return`${e}[${oe}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${K}));`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),Y=oe=>(()=>{if(u.storage===u.value)return`${e}[${oe}]`;if(u.storage==="vec2"&&u.value==="i32")return`i32(${e}[${oe}].x)`;if(u.storage==="vec2"&&u.value==="u32")return`u32(${e}[${oe}].x)`;if(u.storage==="u32"&&u.value==="vec4")return`vec4(bool(${e}[${oe}] & 0xFFu), bool(${e}[${oe}] & 0xFF00u), bool(${e}[${oe}] & 0xFF0000u), bool(${e}[${oe}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${u.storage} and value type ${u.value} yet`)})(),X=i<2?"":` fn get_${e}ByIndices(indices: ${u.indices}) -> ${p} { return ${Y(`i2o_${e}(indices)`)}; }`,J=i<2?"":(()=>{let oe=a.map(j=>`d${j}: u32`).join(", "),K=a.map(j=>`d${j}`).join(", ");return` fn get_${e}(${oe}) -> ${p} { return get_${e}ByIndices(${S(K)}); }`})(),re=(...oe)=>{if(oe.length!==i)throw new Error(`indices length must be ${i}`);let K=oe.map(f).join(",");return i===0?Y("0u"):i===1?Y(K[0]):(_.get=!0,_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}(${K})`)},ne=oe=>i<2?Y(oe):(_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}ByIndices(${oe})`),le=i<2?"":` fn set_${e}ByIndices(indices: ${u.indices}, value: ${p}) { ${B(`i2o_${e}(indices)`,"value")} }`,pe=i<2?"":(()=>{let oe=a.map(j=>`d${j}: u32`).join(", "),K=a.map(j=>`d${j}`).join(", ");return` fn set_${e}(${oe}, value: ${p}) { set_${e}ByIndices(${S(K)}, value); }`})();return{impl:()=>{let oe=[],K=!1;return _.offsetToIndices&&(oe.push(k),K=!0),_.indicesToOffset&&(oe.push(P),K=!0),_.broadcastedIndicesToOffset&&(Object.values(H).forEach(j=>oe.push(j)),K=!0),_.set&&(oe.push(pe),K=!0),_.setByIndices&&(oe.push(le),K=!0),_.get&&(oe.push(J),K=!0),_.getByIndices&&(oe.push(X),K=!0),!o&&K&&oe.unshift(`const ${I} = ${u.indices}(${t.join(",")});`,`const ${w} = ${u.indices}(${we.computeStrides(t).join(",")});`),oe.join(` `)},type:u,offsetToIndices:T,indicesToOffset:x,broadcastedIndicesToOffset:W,indices:S,indicesGet:O,indicesSet:F,set:(...oe)=>{if(oe.length!==i+1)throw new Error(`indices length must be ${i}`);let K=oe[i];if(typeof K!="string")throw new Error("value must be string");let j=oe.slice(0,i).map(f).join(",");return i===0?B("0u",K):i===1?B(j[0],K):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}(${j}, ${K})`)},setByOffset:B,setByIndices:(oe,K)=>i<2?B(oe,K):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}ByIndices(${oe}, ${K});`),get:re,getByOffset:Y,getByIndices:ne,usage:s,name:e,strides:w,shape:I,rank:i}},Ie=(e,r,t,s=1)=>_o(e,r,t,"input",s),ot=(e,r,t,s=1)=>_o(e,r,t,"output",s),rp=(e,r,t)=>_o(e,r,t,"atomicOutput",1),al=(e,r,t,s=1)=>_o(e,r,t,"internal",s),sp=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=zn){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 n=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,o=n?`@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=n?`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(${o}) { ${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 n=s==null||s===1?t:`vec${s}<${t}>`;e.push(`${r}:${n}`)}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])}},np=(e,r)=>new sp(e,r)}),op,il,ap,ip,lp,cp,Xr,up,dp,Ks=Ne(()=>{gt(),Tt(),dr(),St(),op=(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}`)},il=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),ap=(e,r)=>we.sortBasedOnPerm(e,il(e.length,r)),ip=(e,r,t,s)=>{let n=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { var a: ${t.type.indices};`;for(let o=0;o{let t=[],s=[];for(let n=0;n{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,n=il(s,r),o=ap(e.dims,n),i=e.dims,a=o,l=s<2||cp(n,e.dims),c;if(l)return c=_=>{let y=Ie("input",t,i,4),I=ot("output",t,a,4);return` ${_.registerUniform("output_size","u32").declareVariables(y,I)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} output[global_idx] = input[global_idx]; }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let _=we.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64/4)},programUniforms:[{type:12,data:Math.ceil(_/4)}]}},getShaderSource:c};let{newShape:p,newPerm:d}=lp(e.dims,n),u=we.areEqual(d,[2,3,1]),f=we.areEqual(d,[3,1,2]);if(p.length===2||u||f){i=u?[p[0],p[1]*p[2]]:f?[p[0]*p[1],p[2]]:p,a=[i[1],i[0]];let _=16;return c=y=>{let I=Ie("a",t,i.length),w=ot("output",t,a.length);return` ${y.registerUniform("output_size","u32").declareVariables(I,w)} var tile : array, ${_}>; ${y.mainStart([_,_,1])} let stride = (uniforms.output_shape[1] - 1) / ${_} + 1; let workgroup_id_x = workgroup_index % stride; let workgroup_id_y = workgroup_index / stride; let input_col = workgroup_id_y * ${_}u + local_id.x; let input_row = workgroup_id_x * ${_}u + local_id.y; if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { tile[local_id.y][local_id.x] = ${I.getByIndices(`${I.type.indices}(input_row, input_col)`)}; } workgroupBarrier(); let output_col = workgroup_id_x * ${_}u + local_id.x; let output_row = workgroup_id_y * ${_}u + local_id.y; if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { ${w.setByIndices(`${w.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let y=we.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/_),y:Math.ceil(a[0]/_)},programUniforms:[{type:12,data:y},...ct(i,a)]}},getShaderSource:c}}return c=_=>{let y=Ie("a",t,i.length),I=ot("output",t,a.length);return` ${_.registerUniform("output_size","u32").declareVariables(y,I)} ${ip(n,s,y,I)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${I.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${I.setByOffset("global_idx",y.getByIndices("aIndices"))} }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let _=we.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ct(i,a)]}},getShaderSource:c}},up=(e,r)=>{op(e.inputs,r.perm),e.compute(Xr(e.inputs[0],r.perm))},dp=e=>Rt({perm:e.perm})}),pp,mp,hp,_p,fp,gp,Mp,wp,bp,yp,hs,vp,xp,Tp,Pp,Ep,Cp,Sp,kp,$p,Ip,gx=Ne(()=>{gt(),Tt(),St(),cl(),Ks(),pp={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"},mp={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"},hp={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},_p={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},fp=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let o=0;oe[o]);return[t,n]},Mp=(e,r)=>{let t=e.length+r.length,s=[],n=0;for(let o=0;o{for(let t=0;t{let t=[];if(!wp(e,r)){for(let s=0;st.push(s))}return t},yp=(e,r,t,s,n,o,i)=>{let a=t[0].dims,l=we.size(o),c=we.size(i),p=Ie("_A",t[0].dataType,a),d=ot("output",n,o),u=64;l===1&&(u=256);let f=` var aBestValues : array; `,_=y=>` ${y.registerUniform("reduceSize","u32").declareVariables(p,d)} ${f} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${y.mainStart(u)} let outputIndex = global_idx / ${u}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${hp[s]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${u}) { let candidate = f32(${p.getByOffset("offset + k")}); bestValue = ${pp[s]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${u}u); for (var currentSize = reduceSize / 2u; reduceSize > 1u; currentSize = reduceSize / 2u) { let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; bestValue = ${mp[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}(${_p[s]})`}`)}; } }`;return{name:e,shaderCache:{hint:`${r};${u}`,inputDependencies:["type"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:o,dataType:n}],dispatchGroup:{x:l},programUniforms:[{type:12,data:c}]})}},hs=(e,r,t,s)=>{let n=e.inputs.length===1?t:ll(e.inputs,t),o=n.axes;o.length===0&&!n.noopWithEmptyAxes&&(o=e.inputs[0].dims.map((f,_)=>_));let i=we.normalizeAxes(o,e.inputs[0].dims.length),a=i,l=e.inputs[0],c=bp(a,e.inputs[0].dims.length);c.length>0&&(l=e.compute(Xr(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],a=fp(a.length,l.dims.length));let[p,d]=gp(l.dims,a),u=p;n.keepDims&&(u=Mp(p,i)),e.compute(yp(r,n.cacheKey,[l],s,e.inputs[0].dataType,u,d),{inputs:[l]})},vp=(e,r)=>{hs(e,"ReduceMeanShared",r,"mean")},xp=(e,r)=>{hs(e,"ReduceL1Shared",r,"l1")},Tp=(e,r)=>{hs(e,"ReduceL2Shared",r,"l2")},Pp=(e,r)=>{hs(e,"ReduceLogSumExpShared",r,"logSumExp")},Ep=(e,r)=>{hs(e,"ReduceMaxShared",r,"max")},Cp=(e,r)=>{hs(e,"ReduceMinShared",r,"min")},Sp=(e,r)=>{hs(e,"ReduceProdShared",r,"prod")},kp=(e,r)=>{hs(e,"ReduceSumShared",r,"sum")},$p=(e,r)=>{hs(e,"ReduceSumSquareShared",r,"sumSquare")},Ip=(e,r)=>{hs(e,"ReduceLogSumShared",r,"logSum")}}),_s,Ap,ca,ll,fs,Fp,Op,Dp,Lp,zp,Bp,Rp,jp,Np,Vp,gs,Up,Wp,Gp,Kp,Hp,qp,Qp,Xp,Jp,Yp,cl=Ne(()=>{gt(),Tt(),dr(),St(),gx(),_s=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.")},Ap=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],ca=(e,r,t,s,n,o,i=!1,a=!1)=>{let l=[],c=t[0].dims,p=c.length,d=we.normalizeAxes(n,p),u=!a&&d.length===0;c.forEach((y,I)=>{u||d.indexOf(I)>=0?i&&l.push(1):l.push(y)});let f=l.length,_=we.size(l);return{name:e,shaderCache:r,getShaderSource:y=>{let I=[],w=Ie("_A",t[0].dataType,p),v=ot("output",o,f),k=s(w,v,d),T=k[2];for(let b=0,P=0;b=0?(i&&P++,T=`for(var j${b}: u32 = 0; j${b} < ${c[b]}; j${b}++) { ${k[2].includes("last_index")?`let last_index = j${b};`:""} ${w.indicesSet("input_indices",b,`j${b}`)} ${T} }`):(I.push(`${w.indicesSet("input_indices",b,v.indicesGet("output_indices",P))};`),P++);return` ${y.registerUniform("output_size","u32").declareVariables(w,v)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${w.type.indices}; let output_indices = ${v.offsetToIndices("global_idx")}; ${I.join(` `)} ${k[0]} // init ops for reduce max/min ${k[1]} ${T} ${k[3]} ${k.length===4?v.setByOffset("global_idx","value"):k.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:l,dataType:o}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...ct(c,l)]})}},ll=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),Rt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},fs=(e,r,t,s)=>{let n=e.inputs,o=n.length===1?t:ll(n,t);e.compute(ca(r,{hint:o.cacheKey,inputDependencies:["rank"]},[n[0]],o.noopWithEmptyAxes&&o.axes.length===0?Ap:s,o.axes,n[0].dataType,o.keepDims,o.noopWithEmptyAxes),{inputs:[0]})},Fp=(e,r)=>{_s(e.inputs),fs(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},Op=(e,r)=>{_s(e.inputs),fs(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},Dp=(e,r)=>{_s(e.inputs),fs(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);"])},Lp=(e,r)=>{_s(e.inputs),fs(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},zp=(e,r)=>{_s(e.inputs),fs(e,"ReduceMax",r,(t,s,n)=>{let o=[];for(let i=0;i=0||n.length===0)&&o.push(t.indicesSet("input_indices",i,0));return[`${o.join(` `)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},Bp=(e,r)=>{_s(e.inputs),fs(e,"ReduceMean",r,(t,s,n)=>{let o=1;for(let i=0;i=0||n.length===0)&&(o*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${o});`]})},Rp=(e,r)=>{_s(e.inputs),fs(e,"ReduceMin",r,(t,s,n)=>{let o=[];for(let i=0;i=0||n.length===0)&&o.push(`input_indices[${i}] = 0;`);return[`${o.join(` `)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},jp=(e,r)=>{_s(e.inputs),fs(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},Np=(e,r)=>{_s(e.inputs),fs(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},Vp=(e,r)=>{_s(e.inputs),fs(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;`,""])},gs=(e,r,t)=>{if(r.length===0)return t;let s=1,n=1;for(let o=0;o1024},Up=(e,r)=>{gs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Bp(e,r):vp(e,r)},Wp=(e,r)=>{gs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Op(e,r):xp(e,r)},Gp=(e,r)=>{gs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Dp(e,r):Tp(e,r)},Kp=(e,r)=>{gs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Lp(e,r):Pp(e,r)},Hp=(e,r)=>{gs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?zp(e,r):Ep(e,r)},qp=(e,r)=>{gs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Rp(e,r):Cp(e,r)},Qp=(e,r)=>{gs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?jp(e,r):Sp(e,r)},Xp=(e,r)=>{gs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Np(e,r):kp(e,r)},Jp=(e,r)=>{gs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Vp(e,r):$p(e,r)},Yp=(e,r)=>{gs(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Fp(e,r):Ip(e,r)}}),ul,Zp,em,dl,Mx=Ne(()=>{gt(),dr(),cl(),ul=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Zp=(e,r)=>{ul(e.inputs);let t=(s,n,o)=>{let i=[];for(let a=0;a=0||o.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); }`,"",n.setByOffset("global_idx","best_index")]};e.compute(ca("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},em=(e,r)=>{ul(e.inputs);let t=(s,n,o)=>{let i=[];for(let a=0;a=0||o.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); }`,"",n.setByOffset("global_idx","best_index")]};e.compute(ca("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},dl=e=>Rt(e)}),tm,ua,rm,sm,nm,fo,om,am,pl=Ne(()=>{gt(),Tt(),tl(),St(),tm=(e,r)=>{let t=e[0],s=e[1],n=e[2],o=e[3],i=e[4],a=e[5];if(i&&a)throw new Error("Attention cannot have both past and attention_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=t.dims[0],c=t.dims[1],p=t.dims[2];if(n.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(n.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let d=n.dims[0]/3,u=d,f=u;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let k of r.qkvHiddenSizes)if(k%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");d=r.qkvHiddenSizes[0],u=r.qkvHiddenSizes[1],f=r.qkvHiddenSizes[2]}let _=c;if(d!==u)throw new Error("qkv_hidden_sizes first element should be same as the second");if(n.dims[0]!==d+u+f)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let y=0;if(i){if(u!==f)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==u/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(y=i.dims[3])}let I=_+y,w=-1,v=0;if(o)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(a){if(a.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(a.dims[0]!==l||a.dims[1]!==r.numHeads||a.dims[2]!==c||a.dims[3]!==I)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:c,pastSequenceLength:y,kvSequenceLength:_,totalSequenceLength:I,maxSequenceLength:w,inputHiddenSize:p,hiddenSize:d,vHiddenSize:f,headSize:Math.floor(d/r.numHeads),vHeadSize:Math.floor(f/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:v,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ua=(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?.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; `,rm=(e,r,t,s,n,o,i,a)=>{let l=or(i?1:o),c=64,p=o/l;p{let v=ot("x",e.dataType,e.dims,l),k=[v],T=i?Ie("seq_lens",i.dataType,i.dims):void 0;T&&k.push(T);let b=a?Ie("total_sequence_length_input",a.dataType,a.dims):void 0;b&&k.push(b);let P=Rr(e.dataType),x=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${w.registerUniforms(x).declareVariables(...k)} ${w.mainStart([c,1,1])} let batchIdx = workgroup_id.z / uniforms.num_heads; let headIdx = workgroup_id.z % uniforms.num_heads; let sequence_length = uniforms.sequence_length; var total_sequence_length = uniforms.total_sequence_length; ${ua(T,b,!1)} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${c}) * uniforms.total_sequence_length + local_offset; let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; var thread_max_vector = ${_}(-3.402823e+38f); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { thread_max_vector = max(${_}(x[offset + i]), thread_max_vector); } thread_max[local_idx] = ${(()=>{switch(l){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${l}`)}})()}; workgroupBarrier(); var max_value = f32(-3.402823e+38f); for (var i = 0u; i < ${c}; i++) { max_value = max(thread_max[i], max_value); } var sum_vector = ${_}(0); for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { sum_vector += exp(${_}(x[offset + i]) - max_value); } thread_sum[local_idx] = ${(()=>{switch(l){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${l}`)}})()}; workgroupBarrier(); var sum: f32 = 0; for (var i = 0u; i < ${c}; i++) { sum += thread_sum[i]; } if (sum == 0) { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { x[offset + i] = ${v.type.value}(${P}(1.0) / ${P}(seq_causal_length)); } } else { for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { var f32input = ${_}(x[offset + i]); x[offset + i] = ${v.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] = ${v.type.value}(${P}(0)); }`:""}; }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${f};${l}`,inputDependencies:y},getShaderSource:I,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:n,z:r*t},programUniforms:u})}},sm=(e,r,t,s,n,o,i,a,l)=>{let c=i+o.kvSequenceLength,p=[o.batchSize,o.numHeads,o.sequenceLength,c],d=e>1&&s,u=o.kvNumHeads?o.kvNumHeads:o.numHeads,f=d?[o.batchSize,u,c,o.headSize]:void 0,_=o.nReps?o.nReps:1,y=o.scale===0?1/Math.sqrt(o.headSize):o.scale,I=or(o.headSize),w=o.headSize/I,v=12,k={x:Math.ceil(c/v),y:Math.ceil(o.sequenceLength/v),z:o.batchSize*o.numHeads},T=[{type:12,data:o.sequenceLength},{type:12,data:w},{type:12,data:c},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:1,data:y},{type:12,data:i},{type:12,data:o.kvSequenceLength},{type:12,data:_}],b=d&&s&&we.size(s.dims)>0,P=["type","type"];b&&P.push("type"),n&&P.push("type"),a&&P.push("type"),l&&P.push("type");let x=[{dims:p,dataType:r.dataType,gpuDataType:0}];d&&x.push({dims:f,dataType:r.dataType,gpuDataType:0});let S=O=>{let F=Ie("q",r.dataType,r.dims,I),H=Ie("key",t.dataType,t.dims,I),W=[F,H];if(b){let le=Ie("past_key",s.dataType,s.dims,I);W.push(le)}n&&W.push(Ie("attention_bias",n.dataType,n.dims));let B=a?Ie("seq_lens",a.dataType,a.dims):void 0;B&&W.push(B);let Y=l?Ie("total_sequence_length_input",l.dataType,l.dims):void 0;Y&&W.push(Y);let X=ot("output",r.dataType,p),J=[X];d&&J.push(ot("present_key",r.dataType,f,I));let re=Rr(1,I),ne=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${v}u; var tileQ: array<${F.type.storage}, ${v*v}>; var tileK: array<${F.type.storage}, ${v*v}>; ${O.registerUniforms(ne).declareVariables(...W,...J)} ${O.mainStart([v,v,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z % uniforms.num_heads; let kvHeadIdx = ${_===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${_===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let batchIdx = workgroup_id.z / uniforms.num_heads; let m = workgroup_id.y * TILE_SIZE; let n = workgroup_id.x * TILE_SIZE; let sequence_length = uniforms.M; var total_sequence_length = uniforms.N; ${ua(B,Y,!0)} let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; ${b&&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 = ${re}(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; ${b&&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 += ${re}(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(I){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: ${I}`)}})()}; output[outputIdx] = ${X.type.value} (sum * uniforms.alpha) + ${n?"attention_bias[outputIdx]":"0.0"}; } }`};return{name:"AttentionProbs",shaderCache:{hint:`${I};${n!==void 0};${s!==void 0};${e}`,inputDependencies:P},getRunData:()=>({outputs:x,dispatchGroup:k,programUniforms:T}),getShaderSource:S}},nm=(e,r,t,s,n,o,i=void 0,a=void 0)=>{let l=o+n.kvSequenceLength,c=n.nReps?n.nReps:1,p=n.vHiddenSize*c,d=e>1&&s,u=n.kvNumHeads?n.kvNumHeads:n.numHeads,f=d?[n.batchSize,u,l,n.headSize]:void 0,_=[n.batchSize,n.sequenceLength,p],y=12,I={x:Math.ceil(n.vHeadSize/y),y:Math.ceil(n.sequenceLength/y),z:n.batchSize*n.numHeads},w=[{type:12,data:n.sequenceLength},{type:12,data:l},{type:12,data:n.vHeadSize},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:12,data:p},{type:12,data:o},{type:12,data:n.kvSequenceLength},{type:12,data:c}],v=d&&s&&we.size(s.dims)>0,k=["type","type"];v&&k.push("type"),i&&k.push("type"),a&&k.push("type");let T=[{dims:_,dataType:r.dataType,gpuDataType:0}];d&&T.push({dims:f,dataType:r.dataType,gpuDataType:0});let b=P=>{let x=Ie("probs",r.dataType,r.dims),S=Ie("v",t.dataType,t.dims),O=[x,S];v&&O.push(Ie("past_value",s.dataType,s.dims));let F=i?Ie("seq_lens",i.dataType,i.dims):void 0;i&&O.push(F);let H=a?Ie("total_sequence_length_input",a.dataType,a.dims):void 0;a&&O.push(H);let W=[ot("output",r.dataType,_)];d&&W.push(ot("present_value",r.dataType,f));let B=[{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 = ${y}u; var tileQ: array<${x.type.value}, ${y*y}>; var tileV: array<${x.type.value}, ${y*y}>; ${P.registerUniforms(B).declareVariables(...O,...W)} ${P.mainStart([y,y,1])} let headIdx = workgroup_id.z % uniforms.num_heads; let batchIdx = workgroup_id.z / uniforms.num_heads; let kvHeadIdx = ${c===1?"headIdx":"headIdx / uniforms.n_reps"}; let kv_num_heads = ${c===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; let m = global_id.y; let n = global_id.x; let sequence_length = uniforms.M; var total_sequence_length = uniforms.K; ${ua(F,H,!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 ${v&&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; ${v&&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:k},getRunData:()=>({outputs:T,dispatchGroup:I,programUniforms:w}),getShaderSource:b}},fo=(e,r,t,s,n,o,i,a,l,c,p=void 0,d=void 0)=>{let u=Math.min(e.outputCount,1+(i?1:0)+(a?1:0)),f=u>1?c.pastSequenceLength:0,_=f+c.kvSequenceLength,y=l&&we.size(l.dims)>0?l:void 0,I=[r,t];u>1&&i&&we.size(i.dims)>0&&I.push(i),y&&I.push(y),p&&I.push(p),d&&I.push(d);let w=e.compute(sm(u,r,t,i,y,c,f,p,d),{inputs:I,outputs:u>1?[-1,1]:[-1]})[0];e.compute(rm(w,c.batchSize,c.numHeads,f,c.sequenceLength,_,p,d),{inputs:p&&d?[w,p,d]:[w],outputs:[]});let v=[w,s];u>1&&a&&we.size(a.dims)>0&&v.push(a),p&&v.push(p),d&&v.push(d),e.compute(nm(u,w,s,a,c,f,p,d),{inputs:v,outputs:u>1?[0,2]:[0]})},om=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,n=r.inputHiddenSize,o=r.headSize,i=12,a={x:Math.ceil(r.headSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],c=[{type:12,data:s},{type:12,data:n},{type:12,data:o},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:r.hiddenSize},{type:12,data:r.hiddenSize+r.hiddenSize+r.vHiddenSize}],p=d=>{let u=ot("output_q",l[0].dataType,t),f=ot("output_k",l[0].dataType,t),_=ot("output_v",l[0].dataType,t),y=Ie("input",l[0].dataType,l[0].dims),I=Ie("weight",l[1].dataType,l[1].dims),w=Ie("bias",l[2].dataType,l[2].dims),v=y.type.storage,k=[{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<${v}, ${i*i}>; var tileWeightQ: array<${v}, ${i*i}>; var tileWeightK: array<${v}, ${i*i}>; var tileWeightV: array<${v}, ${i*i}>; ${d.registerUniforms(k).declareVariables(y,I,w,u,f,_)} ${d.mainStart([i,i,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = global_id.y; let n = global_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${v}(0); var valueK = ${v}(0); var valueV = ${v}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:a,programUniforms:c}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},am=(e,r)=>{let t=tm(e.inputs,r),[s,n,o]=om(e,t);return fo(e,s,n,o,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),im,lm,cm,um,wx=Ne(()=>{ps(),gt(),Tt(),dr(),St(),im=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,n,o)=>{let i=n.length;if(i!==s.length)throw new Error(`${o}: num dimensions != ${i}`);n.forEach((a,l)=>{if(a!==s[l])throw new Error(`${o}: 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")},lm=(e,r)=>{let{epsilon:t,spatial:s,format:n}=r,o=e[0].dims,i=s?or(o[o.length-1]):1,a=n==="NHWC"&&o.length>1?i:1,l=we.size(o)/i,c=s,p=c?o.length:o,d=Ie("x",e[0].dataType,e[0].dims,i),u=Ie("scale",e[1].dataType,e[1].dims,a),f=Ie("bias",e[2].dataType,e[2].dims,a),_=Ie("inputMean",e[3].dataType,e[3].dims,a),y=Ie("inputVar",e[4].dataType,e[4].dims,a),I=ot("y",e[0].dataType,p,i),w=()=>{let k="";if(s)k=`let cOffset = ${o.length===1?"0u":n==="NHWC"?`outputIndices[${o.length-1}] / ${i}`:"outputIndices[1]"};`;else if(n==="NCHW")k=` ${I.indicesSet("outputIndices","0","0")} let cOffset = ${I.indicesToOffset("outputIndices")};`;else{k=`var cIndices = ${u.type.indices}(0); cIndices[0] = outputIndices[${o.length-1}];`;for(let T=1;T` const epsilon = ${t}; ${k.registerUniform("outputSize","u32").declareVariables(d,u,f,_,y,I)} ${k.mainStart()} ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${I.offsetToIndices(`global_idx * ${i}`)}; ${w()} let scale = ${u.getByOffset("cOffset")}; let bias = ${f.getByOffset("cOffset")}; let inputMean = ${_.getByOffset("cOffset")}; let inputVar = ${y.getByOffset("cOffset")}; let x = ${d.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${I.setByOffset("global_idx","value")} }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${i}`,inputDependencies:c?["rank","type","type","type","type"]:void 0},getShaderSource:v,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c?[{type:12,data:l},...ct(o)]:[{type:12,data:l}]})}},cm=e=>Rt(e),um=(e,r)=>{let{inputs:t,outputCount:s}=e,n=cm({...r,outputCount:s});if(Xt.webgpu.validateInputContent&&im(t,n),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(lm(t,n))}}),dm,pm,mm,bx=Ne(()=>{Tt(),St(),dm=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")},pm=e=>{let r=e[0].dims,t=e[0].dims[2],s=we.size(r)/4,n=e[0].dataType,o=Ie("input",n,r,4),i=Ie("bias",n,[t],4),a=Ie("residual",n,r,4),l=ot("output",n,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:c=>` const channels = ${t}u / 4; ${c.declareVariables(o,i,a,l)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes(s)} let value = ${o.getByOffset("global_idx")} + ${i.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; ${l.setByOffset("global_idx","value")} }`}},mm=e=>{dm(e.inputs),e.compute(pm(e.inputs))}}),hm,zt,_m,fm,gm,Mm,wm,bm,ym,vm,xm,Tm,Pm,Em,Cm,Sm,go,km,da,$m,Im,Am,Fm,Om,Dm,Lm,zm,Bm,Rm,jm,Nm,Vm,Um,Wm,Gm,ml,Km,hl,_l,Hm,qm,Qm,Xm,Jm,Ym,fl=Ne(()=>{gt(),Tt(),dr(),St(),hm=(e,r,t,s,n,o,i)=>{let a=Math.ceil(r/4),l="";typeof n=="string"?l=`${n}(a)`:l=n("a");let c=Ie("inputData",t,[a],4),p=ot("outputData",s,[a],4),d=[{name:"vec_size",type:"u32"}];return i&&d.push(...i),` ${e.registerUniforms(d).declareVariables(c,p)} ${o??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${c.getByOffset("global_idx")}; ${p.setByOffset("global_idx",l)} }`},zt=(e,r,t,s,n,o=e.dataType,i,a)=>{let l=[{type:12,data:Math.ceil(we.size(e.dims)/4)}];return i&&l.push(...i),{name:r,shaderCache:{hint:n,inputDependencies:["type"]},getShaderSource:c=>hm(c,we.size(e.dims),e.dataType,o,t,s,a),getRunData:c=>({outputs:[{dims:e.dims,dataType:o}],dispatchGroup:{x:Math.ceil(we.size(c[0].dims)/64/4)},programUniforms:l})}},_m=e=>{e.compute(zt(e.inputs[0],"Abs","abs"))},fm=e=>{e.compute(zt(e.inputs[0],"Acos","acos"))},gm=e=>{e.compute(zt(e.inputs[0],"Acosh","acosh"))},Mm=e=>{e.compute(zt(e.inputs[0],"Asin","asin"))},wm=e=>{e.compute(zt(e.inputs[0],"Asinh","asinh"))},bm=e=>{e.compute(zt(e.inputs[0],"Atan","atan"))},ym=e=>{e.compute(zt(e.inputs[0],"Atanh","atanh"))},vm=e=>Rt(e),xm=(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(zt(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},Tm=e=>{let r,t,s=e.length>=2&&e[1].data!==0,n=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=n?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=n?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Rt({min:r,max:t})},Pm=(e,r)=>{let t=r||Tm(e.inputs),s=Rr(e.inputs[0].dataType);e.compute(zt(e.inputs[0],"Clip",n=>`clamp(${n}, 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]})},Em=e=>{e.compute(zt(e.inputs[0],"Ceil","ceil"))},Cm=e=>{e.compute(zt(e.inputs[0],"Cos","cos"))},Sm=e=>{e.compute(zt(e.inputs[0],"Cosh","cosh"))},go=e=>Rt(e),km=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(zt(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))},da=(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)); }`,$m=e=>{let r=Rr(e.inputs[0].dataType);e.compute(zt(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,da(r)))},Im=e=>{e.compute(zt(e.inputs[0],"Exp","exp"))},Am=e=>{e.compute(zt(e.inputs[0],"Floor","floor"))},Fm=e=>{let r=Rr(e.inputs[0].dataType);e.compute(zt(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,da(r)))},Om=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(zt(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))},Dm=e=>{e.compute(zt(e.inputs[0],"Not",r=>`!${r}`))},Lm=e=>{e.compute(zt(e.inputs[0],"Neg",r=>`-${r}`))},zm=e=>{e.compute(zt(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},Bm=e=>{let r=Rr(e.inputs[0].dataType);e.compute(zt(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},Rm=e=>{e.compute(zt(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},jm=e=>Rt(e),Nm=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(zt(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))},Vm=e=>{e.compute(zt(e.inputs[0],"Sin","sin"))},Um=e=>{e.compute(zt(e.inputs[0],"Sinh","sinh"))},Wm=e=>{e.compute(zt(e.inputs[0],"Sqrt","sqrt"))},Gm=e=>{e.compute(zt(e.inputs[0],"Tan","tan"))},ml=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Km=e=>{e.compute(zt(e.inputs[0],"Tanh",ml))},hl=(e="f32")=>` const fast_gelu_a: ${e} = 0.5; const fast_gelu_b: ${e} = 0.7978845608028654; const fast_gelu_c: ${e} = 0.035677408136300125; fn tanh_v(v: vec4<${e}>) -> vec4<${e}> { return ${ml("v")}; } `,_l=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Hm=e=>{let r=Rr(e.inputs[0].dataType);e.compute(zt(e.inputs[0],"FastGelu",_l,hl(r),void 0,e.inputs[0].dataType))},qm=(e,r)=>{let t=Rr(e.inputs[0].dataType);return e.compute(zt(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},Qm=e=>{e.compute(zt(e.inputs[0],"Log","log"))},Xm=(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; } `,Jm=e=>`quick_gelu_impl(${e})`,Ym=(e,r)=>{let t=Rr(e.inputs[0].dataType);e.compute(zt(e.inputs[0],"QuickGelu",Jm,Xm(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),Zm,eh,th,yx=Ne(()=>{Tt(),St(),fl(),Zm=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")},eh=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=Ie("input",e[0].dataType,e[0].dims,4),s=Ie("bias",e[0].dataType,[e[0].dims[2]],4),n=ot("output",e[0].dataType,r,4),o=we.size(r)/4,i=Sr(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:a=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${a.declareVariables(t,s,n)} ${da(i)} ${a.mainStart()} ${a.guardAgainstOutOfBoundsWorkgroupSizes(o)} let biasIdx = global_idx % halfChannels; let batchIndex = global_idx / halfChannels; let inputOffset = biasIdx + batchIndex * halfChannels * 2; let valueLeft = input[inputOffset] + bias[biasIdx]; let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${n.setByOffset("global_idx","valueLeft * geluRight")} }`}},th=e=>{Zm(e.inputs),e.compute(eh(e.inputs))}}),rh,sh,Ms,nh,oh,ah,ih,lh,ch,uh,dh,ph,mh,vx=Ne(()=>{gt(),Tt(),St(),rh=(e,r,t,s,n,o,i,a,l,c,p,d)=>{let u,f;typeof a=="string"?u=f=(v,k)=>`${a}((${v}),(${k}))`:typeof a=="function"?u=f=a:(u=a.scalar,f=a.vector);let _=ot("outputData",p,s.length,4),y=Ie("aData",l,r.length,4),I=Ie("bData",c,t.length,4),w;if(n)if(o){let v=we.size(r)===1,k=we.size(t)===1,T=r.length>0&&r[r.length-1]%4===0,b=t.length>0&&t[t.length-1]%4===0;v||k?w=_.setByOffset("global_idx",f(v?`${y.type.value}(${y.getByOffset("0")}.x)`:y.getByOffset("global_idx"),k?`${I.type.value}(${I.getByOffset("0")}.x)`:I.getByOffset("global_idx"))):w=` let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; let offsetA = ${y.broadcastedIndicesToOffset("outputIndices",_)}; let offsetB = ${I.broadcastedIndicesToOffset("outputIndices",_)}; ${_.setByOffset("global_idx",f(i||T?y.getByOffset("offsetA / 4u"):`${y.type.value}(${y.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||b?I.getByOffset("offsetB / 4u"):`${I.type.value}(${I.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else w=_.setByOffset("global_idx",f(y.getByOffset("global_idx"),I.getByOffset("global_idx")));else{if(!o)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let v=(k,T,b="")=>{let P=`aData[indexA${T}][componentA${T}]`,x=`bData[indexB${T}][componentB${T}]`;return` let outputIndices${T} = ${_.offsetToIndices(`global_idx * 4u + ${T}u`)}; let offsetA${T} = ${y.broadcastedIndicesToOffset(`outputIndices${T}`,_)}; let offsetB${T} = ${I.broadcastedIndicesToOffset(`outputIndices${T}`,_)}; let indexA${T} = offsetA${T} / 4u; let indexB${T} = offsetB${T} / 4u; let componentA${T} = offsetA${T} % 4u; let componentB${T} = offsetB${T} % 4u; ${k}[${T}] = ${b}(${u(P,x)}); `};p===9?w=` var data = vec4(0); ${v("data",0,"u32")} ${v("data",1,"u32")} ${v("data",2,"u32")} ${v("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:w=` ${v("outputData[global_idx]",0)} ${v("outputData[global_idx]",1)} ${v("outputData[global_idx]",2)} ${v("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(y,I,_)} ${d??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${w} }`},sh=(e,r,t,s,n,o,i=t.dataType)=>{let a=t.dims.map(y=>Number(y)??1),l=s.dims.map(y=>Number(y)??1),c=!we.areEqual(a,l),p=a,d=we.size(a),u=!1,f=!1,_=[c];if(c){let y=Ln.calcShape(a,l,!1);if(!y)throw new Error("Can't perform binary op on the given tensors");p=y.slice(),d=we.size(p);let I=we.size(a)===1,w=we.size(l)===1,v=a.length>0&&a[a.length-1]%4===0,k=l.length>0&&l[l.length-1]%4===0;_.push(I),_.push(w),_.push(v),_.push(k);let T=1;for(let b=1;by.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:y=>rh(y,a,l,p,u,c,f,n,t.dataType,s.dataType,i,o),getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(d/64/4)},programUniforms:[{type:12,data:Math.ceil(we.size(p)/4)},...ct(a,l,p)]})}},Ms=(e,r,t,s,n,o)=>{e.compute(sh(r,n??"",e.inputs[0],e.inputs[1],t,s,o))},nh=e=>{Ms(e,"Add",(r,t)=>`${r}+${t}`)},oh=e=>{Ms(e,"Div",(r,t)=>`${r}/${t}`)},ah=e=>{Ms(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},ih=e=>{Ms(e,"Mul",(r,t)=>`${r}*${t}`)},lh=e=>{let r=Ie("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Ms(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)); } `)},ch=e=>{Ms(e,"Sub",(r,t)=>`${r}-${t}`)},uh=e=>{Ms(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},dh=e=>{Ms(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},ph=e=>{Ms(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},mh=e=>{Ms(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),hh,_h,fh,gh,Mh,wh,xx=Ne(()=>{gt(),Tt(),dr(),St(),hh=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],n=s.dataType,o=s.dims.length;e.forEach((i,a)=>{if(a!==t){if(i.dataType!==n)throw new Error("input tensors should be one type");if(i.dims.length!==o)throw new Error("input tensors should have the same shape");i.dims.forEach((l,c)=>{if(c!==r&&l!==s.dims[c])throw new Error("non concat dimensions must match")})}})},_h=(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; }`,fh=(e,r)=>{let t=e.length,s=[];for(let n=0;n{let n=we.size(t),o=new Array(e.length),i=new Array(e.length),a=0,l=[],c=[],p=[{type:12,data:n}];for(let y=0;y`uniforms.sizeInConcatAxis${y}`).join(","),_=y=>` ${(()=>{y.registerUniform("outputSize","u32");for(let I=0;I(${f}); ${u} -= sizeInConcatAxis[inputIndex - 1u]; } ${fh(i,d)} }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}),getShaderSource:_}},Mh=(e,r)=>{let t=e.inputs,s=t[0].dims,n=we.normalizeAxis(r.axis,s.length);hh(t,n);let o=s.slice();o[n]=t.reduce((a,l)=>a+(l.dims.length>n?l.dims[n]:0),0);let i=t.filter(a=>we.size(a.dims)>0);e.compute(gh(i,n,o,t[0].dataType),{inputs:i})},wh=e=>Rt({axis:e.axis})}),dn,pn,mn,gl,hn=Ne(()=>{gt(),Tt(),dn=(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}`)}},pn=(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})},mn=(e,r)=>{e.activation==="Clip"?r.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?r.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&r.push({name:"alpha",type:"f32"})},gl=e=>{let r=e?.activation||"";if(r==="HardSigmoid"){let[t,s]=e?.activation_params||[.2,.5];return{activation:r,alpha:t,beta:s}}else if(r==="Clip"){let[t,s]=e?.activation_params||[Vd,Ud];return{activation:r,clipMax:s,clipMin:t}}else if(r==="LeakyRelu"){let[t]=e?.activation_params||[.01];return{activation:r,alpha:t}}return{activation:r}}}),Fr,bh,Ml=Ne(()=>{Fr=(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.`)}},bh=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),yh,Tx=Ne(()=>{yh=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)); } `}),Mo,wl,bl=Ne(()=>{gt(),Tt(),St(),hn(),Mo=(e,r,t,s,n)=>{let o=s-t;return` ${Array.from({length:t}).map((i,a)=>` if (${lt(r.shape,a,r.rank)} != 1) { ${r.indicesSet(e,a,lt(n,a+o,s))} } else { ${r.indicesSet(e,a,0)} }`).join("")} `},wl=(e,r,t,s,n=!1,o)=>{let i=e[0].dims,a=e[1].dims,l=i[i.length-2],c=a[a.length-1],p=i[i.length-1],d=or(c),u=or(p),f=or(l),_=we.size(t)/d/f,y=e.length>2,I=s?s.slice(0,-2):t.slice(0,-2),w=[we.size(I),l,c],v=[{type:12,data:_},{type:12,data:l},{type:12,data:c},{type:12,data:p}];pn(r,v),v.push(...ct(I,i,a)),y&&v.push(...ct(e[2].dims)),v.push(...ct(w));let k=T=>{let b=al("batch_dims",e[0].dataType,I.length),P=Ie("a",e[0].dataType,i.length,u),x=Ie("b",e[1].dataType,a.length,d),S=ot("output",e[0].dataType,w.length,d),O=Sr(S.type.tensor),F=dn(r,S.type.value,O),H=[P,x],W="";if(y){let X=n?d:1;H.push(Ie("bias",e[2].dataType,e[2].dims.length,X)),W=`${n?`value += bias[col / ${X}];`:`value += ${S.type.value}(bias[row + i]);`}`}let B=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];mn(r,B);let Y=()=>{let X=`var a_data: ${P.type.value};`;for(let J=0;J; for (var k: u32 = 0u; k < uniforms.K; k = k + ${u}) { ${Y()} } for (var i = 0u; i < ${f}u; i++) { var value = values[i]; ${W} ${F} 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};${u};${f};${n}`,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:o?o(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:v}),getShaderSource:k}}}),vh,xh,yl,vl,Th,xl,Ph,pa,Tl=Ne(()=>{gt(),Tt(),St(),hn(),bl(),Ml(),vh=(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":""}); `,xh=(e,r)=>e?` let ACached0 = mm_Asub[k * innerElementSize][localRow]; let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; ${r===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} for (var i = 0; i < rowPerThread; i = i + 1) { acc[i] = BCached0 * ACached0[i] + acc[i]; acc[i] = BCached1 * ACached1[i] + acc[i]; acc[i] = BCached2 * ACached2[i] + acc[i]; ${r===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} }`:` for (var i = 0; i < rowPerThread; i = i + 1) { let ACached = mm_Asub[tileRow + i][k]; acc[i] = BCached0 * ACached.x + acc[i]; acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} }`,yl=(e,r,t="f32",s,n=!1,o=32,i=!1,a=32)=>{let l=r[1]*e[1],c=r[0]*e[0],p=n?l:o,d=n?o:l,u=p/r[0],f=o/r[1];if(!((n&&u===4&&e[1]===4||!n&&(u===3||u===4))&&p%r[0]===0&&o%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${n} is true, innerElementSize ${u} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${u} must be 3 or 4. tileAWidth ${p} must be divisible by workgroupSize[0]${r[0]}. tileInner ${o} must be divisible by workgroupSize[1] ${r[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${p/u}>, ${d}>; var mm_Bsub: array, ${c/e[0]}>, ${o}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${u}; const tileInner = ${o}; @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/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; var acc: array, rowPerThread>; // Loop over shared dimension. let tileRowB = localRow * ${f}; for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; ${vh(n,s)} } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) { let inputRow = tileRowB + innerRow; let inputCol = tileCol; mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", batchIndices":""}); } kStart = kStart + tileInner; workgroupBarrier(); // Compute acc values for a single thread. for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${u===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${xh(n,u)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},vl=(e,r)=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart + inputCol${r?", batchIndices":""}); `:` mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRowStart + inputRow, kStart + inputCol${r?", batchIndices":""}); `,Th=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",xl=(e,r,t="f32",s,n=!1,o=32,i=!1,a=32,l=!1)=>{let c=e[1]*r[1],p=e[0]*r[0],d=n?c:o,u=n?o:c;if(!(u%r[1]===0&&d%r[0]===0&&o%r[1]===0))throw new Error(`tileAHight ${u} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${d} must be divisible by workgroupSize[0]${r[0]}, tileInner ${o} must be divisible by workgroupSize[1]${r[1]}`);let f=u/r[1],_=d/r[0],y=o/r[1],I=l?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${c}; let globalColStart = i32(workgroupId.x) * ${p}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${u}; inputRow = inputRow + ${r[1]}) { for (var inputCol = localCol; inputCol < ${d}; inputCol = inputCol + ${r[0]}) { ${vl(n,s)} } } // Load one tile of B into local memory. for (var inputRow = localRow; inputRow < ${o}; 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 = ${n?`mm_Asub[k][localRow + innerRow * ${r[1]}];`:`mm_Asub[localRow + innerRow * ${r[1]}][k];`} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let gRow = globalRowStart + localRow + innerRow * ${r[1]}; for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { let gCol = globalColStart + localCol + innerCol * ${r[0]}; mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); } } `:` let tileRow = i32(localId.y) * rowPerThread; let tileCol = i32(localId.x) * colPerThread; let globalRow = i32(globalId.y) * rowPerThread; let globalCol = i32(globalId.x) * colPerThread; let globalRowStart = i32(workgroupId.y) * ${c}; let tileRowA = i32(localId.y) * ${f}; let tileColA = i32(localId.x) * ${_}; let tileRowB = i32(localId.y) * ${y}; // Loop over shared dimension. for (var t = 0; t < num_tiles; t = t + 1) { // Load one tile of A into local memory. for (var innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${_}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${vl(n,s)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${y}; 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) { ${Th(n)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } } } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { mm_write(batch, globalRow + innerRow, globalCol + innerCol, acc[innerRow][innerCol]); } } `;return` var mm_Asub : array, ${u}>; var mm_Bsub : array, ${o}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const tileInner = ${o}; @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/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; var acc : array, rowPerThread>; ${I} } `},Ph=(e,r,t,s,n=!1)=>{let[o,i,a,l]=s,c=Sr(s[0].type.tensor);return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${o.type.indices}) -> ${Fr(e,c)} { var value = ${Fr(e,c)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { var aIndices: ${i.type.indices}; ${Mo("aIndices",i,i.rank-2,o.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: ${o.type.indices}) -> ${Fr(e,c)} { var value = ${Fr(e,c)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { var bIndices: ${a.type.indices}; ${Mo("bIndices",a,a.rank-2,o.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: ${Fr(e,c)}) { let col = colIn * ${e}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let coords = vec3(batch, row, colIn); ${r?`value = value + ${n?"bias[colIn]":`${Fr(e,c)}(bias[row])`};`:""} ${t} ${l.setByIndices("vec3(coords)","value")} } } `},pa=(e,r,t,s,n=!1,o)=>{let i=e[0].dims,a=e[1].dims,l=i.slice(0,-2),c=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),d=we.size(p),u=i[i.length-2],f=i[i.length-1],_=a[a.length-1],y=f%4===0&&_%4===0,I=u<=8?[4,1,1]:[4,4,1],w=[8,8,1],v=[Math.ceil(_/w[0]/I[0]),Math.ceil(u/w[1]/I[1]),Math.ceil(d/w[2]/I[2])],k=y?4:1,T=[...l,u,f/k],b=T.length,P=[...c,f,_/k],x=P.length,S=[d,u,_/k],O=[{type:6,data:u},{type:6,data:_},{type:6,data:f}];pn(r,O),O.push(...ct(p,T,P));let F=["rank","rank"],H=e.length>2;H&&(O.push(...ct(e[2].dims)),F.push("rank")),O.push(...ct(S));let W=B=>{let Y=p.length,X=al("batchDims",e[0].dataType,Y,1),J=Sr(e[0].dataType),re=Ie("a",e[0].dataType,b,k),ne=Ie("b",e[1].dataType,x,k),le=ot("result",e[0].dataType,S.length,k),pe=[re,ne];if(H){let te=n?k:1;pe.push(Ie("bias",e[2].dataType,e[2].dims.length,te))}let oe=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];mn(r,oe);let K=Sr(le.type.tensor),j=dn(r,le.type.value,K),D=Ph(k,H,j,[X,re,ne,le],n);return` ${B.registerUniforms(oe).registerInternalVariables(X).declareVariables(...pe,le)} ${D} ${y?yl(I,w,J,X):xl(I,w,J,X)} `};return{name:"MatMul",shaderCache:{hint:`${I};${r.activation};${y};${n}`,inputDependencies:F},getRunData:()=>({outputs:[{dims:o?o(t):t,dataType:e[0].dataType}],dispatchGroup:{x:v[0],y:v[1],z:v[2]},programUniforms:O}),getShaderSource:W}}}),Eh,Ch,Px=Ne(()=>{gt(),Ls(),St(),hn(),Ml(),Tx(),Tl(),Eh=(e,r,t,s,n=!1,o,i=4,a=4,l=4,c="f32")=>{let p=O=>{switch(O){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${c}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${O} is not supported.`)}},d=O=>{switch(O){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${O} is not supported.`)}},u=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); `,f=e?` let coords = vec4( batch, row / outWidth, row % outWidth, col); `:` let coords = vec4( batch, row, col / outWidth, col % outWidth); `,_=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",y=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",I=e?"row":"col",w=e?"col":"row",v=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${I} / outWidth; let outCol = ${I} % 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 = ${Fr(i,c)}(0.0); // The bounds checking is always needed since we use it to pad zero for // the 'same' padding type. if (xRow >= 0 && xRow < ${_} && xCol >= 0 && xCol < ${y}) { ${u} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${p(i)} } return resData;`,k=e?r&&s?` let col = colIn * ${i}; ${v}`:` let col = colIn * ${i}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${v} } return ${Fr(i,c)}(0.0);`:s&&t?` let col = colIn * ${i}; ${v}`:` let col = colIn * ${i}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${v} } return ${Fr(i,c)}(0.0);`,T=e?s&&t?d(a):` let col = colIn * ${a}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${d(a)} } return ${Fr(a,c)}(0.0);`:` let col = colIn * ${a}; if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { ${d(a)} } return ${Fr(a,c)}(0.0);`,b=Fr(l,c),P=Fr(e?i:a,c),x=Fr(e?a:i,c),S=dn(o,b,c);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${P} { ${e?k:T} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${x} { ${e?T:k} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${b}) { let col = colIn * ${l}; if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { var value = valueIn; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${f} ${bh(n)} ${S} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Ch=(e,r,t,s,n,o,i,a,l)=>{let c=r.format==="NHWC",p=c?e[0].dims[3]:e[0].dims[1],d=t[0],u=c?t[2]:t[3],f=c?t[1]:t[2],_=c?t[3]:t[1],y=c&&(p%4===0||p%3===0)&&_%4===0,I=c?_:u*f,w=c?u*f:_,v=[8,8,1],k=s<=8?[4,1,1]:[4,4,1],T=[Math.ceil(I/v[0]/k[0]),Math.ceil(w/v[1]/k[1]),Math.ceil(d/v[2]/k[2])];Ot("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${T}`);let b=y?c&&p%4!==0?3:4:1,P=v[1]*k[1],x=v[0]*k[0],S=Math.max(v[0]*b,v[1]),O=s%P===0,F=n%x===0,H=o%S===0,W=y?[b,4,4]:[1,1,1],B=[{type:6,data:s},{type:6,data:n},{type:6,data:o},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];pn(r,B),B.push(...ct(e[0].dims,e[1].dims));let Y=["rank","rank"];i&&(B.push(...ct(e[2].dims)),Y.push("rank")),B.push(...ct(t));let X=J=>{let re=[{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}];mn(r,re);let ne=y?4:1,le=Sr(e[0].dataType),pe=` fn setOutputAtIndex(flatIndex : i32, value : ${y?`vec4<${le}>`:le}) { result[flatIndex] = ${y?`vec4<${le}>`:le}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${y?`vec4<${le}>`:le}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${y?"/ 4":""}, value); }`,oe=Ie("x",e[0].dataType,e[0].dims.length,b===3?1:b),K=Ie("w",e[1].dataType,e[1].dims.length,ne),j=[oe,K],D=ot("result",e[0].dataType,t.length,ne);if(i){let te=Ie("bias",e[2].dataType,e[2].dims.length,ne);j.push(te),pe+=` fn getBiasByOutputCoords(coords : vec4) -> ${y?`vec4<${le}>`:le} { return bias[coords.${c?"w":"y"}${y?"/ 4":""}]; }`}return` ${yh("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 }; ${J.registerUniforms(re).declareVariables(...j,D)} ${pe} ${Eh(c,O,F,H,i,r,W[0],W[1],W[2],le)} ${y?yl(k,v,le,void 0,!c,S):xl(k,v,le,void 0,!c,S,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${b};${y};${O};${F};${H};${P};${x};${S}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:T[0],y:T[1],z:T[2]},programUniforms:B}),getShaderSource:X}}}),Sh,Pl,wo,kh,El,$h,Ih,Ah,Ex=Ne(()=>{gt(),Ls(),Tt(),St(),hn(),Ml(),Sh=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,wo=(e,r)=>r<=1?e:e+(e-1)*(r-1),kh=(e,r,t,s=1)=>{let n=wo(r,s);return Math.floor((e[0]*(t-1)-t+n)/2)},El=(e,r,t,s,n)=>{n==null&&(n=kh(e,r[0],s[0]));let o=[0,0,0,t];for(let i=0;i<3;i++)e[i]+2*n>=r[i]&&(o[i]=Math.trunc((e[i]-r[i]+2*n)/s[i]+1));return o},$h=(e,r,t,s,n,o,i,a,l,c)=>{let p,d,u,f;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let _=El([r,t,s,1],[a,l,c],1,[n,o,i],e);d=_[0],u=_[1],f=_[2]}else if(Array.isArray(e)){if(!e.every((y,I,w)=>y===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 _=El([r,t,s,1],[a,l,c],1,[n,o,i],e[0]);d=_[0],u=_[1],f=_[2]}else if(e==="SAME_UPPER"){d=Math.ceil(r/n),u=Math.ceil(t/o),f=Math.ceil(s/i);let _=(d-1)*n+a-r,y=(u-1)*o+l-t,I=(f-1)*i+c-s,w=Math.floor(_/2),v=_-w,k=Math.floor(y/2),T=y-k,b=Math.floor(I/2),P=I-b;p={top:k,bottom:T,left:b,right:P,front:w,back:v}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:u,outWidth:f}},Ih=(e,r,t,s,n,o=!1,i="channelsLast")=>{let a,l,c,p,d;if(i==="channelsLast")[a,l,c,p,d]=e;else if(i==="channelsFirst")[a,d,l,c,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[u,,f,_,y]=r,[I,w,v]=Pl(t),[k,T,b]=Pl(s),P=wo(f,k),x=wo(_,T),S=wo(y,b),{padInfo:O,outDepth:F,outHeight:H,outWidth:W}=$h(n,l,c,p,I,w,v,P,x,S),B=o?u*d:u,Y=[0,0,0,0,0];return i==="channelsFirst"?Y=[a,B,F,H,W]:i==="channelsLast"&&(Y=[a,F,H,W,B]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:c,inWidth:p,inChannels:d,outDepth:F,outHeight:H,outWidth:W,outChannels:B,padInfo:O,strideDepth:I,strideHeight:w,strideWidth:v,filterDepth:f,filterHeight:_,filterWidth:y,effectiveFilterDepth:P,effectiveFilterHeight:x,effectiveFilterWidth:S,dilationDepth:k,dilationHeight:T,dilationWidth:b,inShape:e,outShape:Y,filterShape:r}},Ah=(e,r,t,s,n,o)=>{let i=o==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((I,w)=>w)},c=[Math.ceil(Sh(l.x.map(I=>t[I]))/a[0]),1,1];Ot("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${c}`);let p=1,d=we.size(t),u=[{type:12,data:d},{type:12,data:s},{type:12,data:n},{type:12,data:r.strides},{type:12,data:r.dilations}];pn(r,u),u.push(...ct(e[0].dims,e[1].dims));let f=["rank","rank"],_=e.length===3;_&&(u.push(...ct(e[2].dims)),f.push("rank")),u.push(...ct(t));let y=I=>{let w=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:n.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];mn(r,w);let v=1,k=Sr(e[0].dataType),T=Ie("x",e[0].dataType,e[0].dims.length,p),b=Ie("W",e[1].dataType,e[1].dims.length,v),P=[T,b],x=ot("result",e[0].dataType,t.length,v),S="";if(_){let H=Ie("bias",e[2].dataType,e[2].dims.length,v);P.push(H),S+=` fn getBiasByOutputCoords(coords : array) -> ${k} { return bias[${i?lt("coords",4,5):lt("coords",1,5)}]; }`}let O=Fr(p,k),F=dn(r,O,k);return` ${S} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${T.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${b.getByIndices("aIndices")}; } ${I.registerUniforms(w).declareVariables(...P,x)} ${I.mainStart()} ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${x.offsetToIndices("global_idx")}; let batch = ${lt("coords",0,T.rank)}; let d2 = ${i?lt("coords",T.rank-1,T.rank):lt("coords",1,T.rank)}; let xFRCCorner = vec3(${i?lt("coords",1,T.rank):lt("coords",2,T.rank)}, ${i?lt("coords",2,T.rank):lt("coords",3,T.rank)}, ${i?lt("coords",3,T.rank):lt("coords",4,T.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${i?lt("uniforms.x_shape",1,T.rank):lt("uniforms.x_shape",2,T.rank)}; let xShapeZ = ${i?lt("uniforms.x_shape",2,T.rank):lt("uniforms.x_shape",3,T.rank)}; let xShapeW = ${i?lt("uniforms.x_shape",3,T.rank):lt("uniforms.x_shape",4,T.rank)}; let xShapeU = ${i?lt("uniforms.x_shape",4,T.rank):lt("uniforms.x_shape",1,T.rank)}; let inputDepthNearestVec4 = (xShapeU / 4) * 4; let inputDepthVec4Remainder = xShapeU % 4; var value = 0.0; for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { let xF = xFCorner + wF * uniforms.dilations[0]; if (xF < 0 || xF >= xShapeY) { continue; } for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { let xR = xRCorner + wR * uniforms.dilations[1]; if (xR < 0 || xR >= xShapeZ) { continue; } for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { let xC = xCCorner + wC * uniforms.dilations[2]; if (xC < 0 || xC >= xShapeW) { continue; } for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { ${i?`let xValues = vec4( getX(batch, xF, xR, xC, d1), getX(batch, xF, xR, xC, d1 + 1), getX(batch, xF, xR, xC, d1 + 2), getX(batch, xF, xR, xC, d1 + 3)); `:`let xValues = vec4( getX(batch, d1, xF, xR, xC), getX(batch, d1 + 1, xF, xR, xC), getX(batch, d1 + 2, xF, xR, xC), getX(batch, d1 + 3, xF, xR, xC)); `} let wValues = vec4( getW(d2, d1, wF, wR, wC), getW(d2, d1 + 1, wF, wR, wC), getW(d2, d1 + 2, wF, wR, wC), getW(d2, d1 + 3, wF, wR, wC)); value += dot(xValues, wValues); } if (inputDepthVec4Remainder == 1) { ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} } else if (inputDepthVec4Remainder == 2) { ${i?`let xValues = vec2( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); `:`let xValues = vec2( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); `} let wValues = vec2( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); value += dot(xValues, wValues); } else if (inputDepthVec4Remainder == 3) { ${i?`let xValues = vec3( getX(batch, xF, xR, xC, inputDepthNearestVec4), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); `:`let xValues = vec3( getX(batch, inputDepthNearestVec4, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); `} let wValues = vec3( getW(d2, inputDepthNearestVec4, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); value += dot(xValues, wValues); } } } } ${_?"value = value + getBiasByOutputCoords(coords)":""}; ${F} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${i};${p};${_}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:c[0],y:c[1],z:c[2]},programUniforms:u}),getShaderSource:y}}}),Fh,Oh,Cx=Ne(()=>{gt(),Tt(),St(),hn(),Fh=(e,r,t,s)=>{let n=e.length>2,o=n?"value += b[output_channel];":"",i=e[0].dims,a=e[1].dims,l=r.format==="NHWC",c=l?t[3]:t[1],p=c/r.group,d=l&&p>=4?or(c):1,u=we.size(t)/d,f=[{type:12,data:u},{type:12,data:r.dilations},{type:12,data:[r.strides[0],r.strides[1]]},{type:12,data:[r.pads[0],r.pads[1]]},{type:12,data:p}];pn(r,f),f.push(...ct(i,[a[0],a[1],a[2],a[3]/d]));let _=n?["rank","rank","rank"]:["rank","rank"];f.push(...ct([t[0],t[1],t[2],t[3]/d]));let y=I=>{let w=ot("output",e[0].dataType,t.length,d),v=Sr(w.type.tensor),k=dn(r,w.type.value,v),T=Ie("x",e[0].dataType,i.length),b=Ie("w",e[1].dataType,a.length,d),P=[T,b];n&&P.push(Ie("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"}];mn(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 = ${T.get("batch","xHeight","xWidth","input_channel")}; let wVal = ${b.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 = ${T.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${b.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal * wVal; } } } `;return` ${I.registerUniforms(x).declareVariables(...P,w)} ${I.mainStart()} ${I.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} ${o} ${k} ${w.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${d}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:y}},Oh=(e,r,t,s)=>{let n=e.length>2,o=or(t[3]),i=or(t[2]),a=we.size(t)/o/i,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/o],c=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/o],p=[t[0],t[1],t[2],t[3]/o],d=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];pn(r,d),d.push(...ct(l,c,p));let u=(i-1)*r.strides[1]+c[1],f=_=>{let y=ot("output",e[0].dataType,p.length,o),I=Sr(y.type.tensor),w=dn(r,y.type.value,I),v=Ie("x",e[0].dataType,l.length,o),k=Ie("w",e[1].dataType,c.length,o),T=[v,k];n&&T.push(Ie("b",e[2].dataType,e[2].dims,o));let b=n?"value += b[output_channel];":"",P=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return mn(r,P),` ${_.registerUniforms(P).declareVariables(...T,y)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let width0 = uniforms.output_shape[3]; let output_channel = global_idx % width0; var index1 = global_idx / width0; let width1 = uniforms.output_shape[2] / ${i}u; let col = (index1 % width1) * ${i}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${v.type.value}, ${u}>; var values: array<${y.type.value}, ${i}>; let input_channel = output_channel; // Use constant instead of uniform can give better performance for w's height/width. for (var w_height: u32 = 0u; w_height < ${c[0]}; w_height++) { let x_height = x_corner.x + i32(w_height); if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { for (var i = 0; i < ${u}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${v.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${v.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) { let w_val = ${k.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]; ${b} ${w} ${y.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${o};${i};${u};${c[0]};${c[1]}`,inputDependencies:n?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:d}),getShaderSource:f}}}),Dh,ma,Lh,ha,Cl,Sl,zh,Bh,kl,Sx=Ne(()=>{Tt(),Px(),Ex(),Tl(),Cx(),hn(),bl(),Ks(),Dh=(e,r,t,s,n,o)=>{let i=e[0],a=e.slice(o?1:2,o?3:4),l=a.length,c=r[0],p=r.slice(2).map((u,f)=>u+(u-1)*(t[f]-1)),d=a.map((u,f)=>u+s[f]+s[f+l]).map((u,f)=>Math.floor((u-p[f]+n[f])/n[f]));return d.splice(0,0,i),d.splice(o?3:1,0,c),d},ma=[2,3,1,0],Lh=(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 n=e[0].dims.length-2;if(r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ha=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=gl(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],n=e.dilations,o=e.group,i=e.kernel_shape,a=e.pads,l=e.strides,c=e.w_is_const();return{autoPad:s,format:t,dilations:n,group:o,kernelShape:i,pads:a,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},Sl=(e,r,t,s)=>{let n=t.format==="NHWC",o=Dh(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,n);if(t.group!==1){let P=[r[0]];if(n){let x=e.kernelCustomData.wT??e.compute(Xr(r[1],ma),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=x),P.push(x)}else P.push(r[1]);r.length===3&&P.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&n&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(Oh(P,t,o,s),{inputs:P}):e.compute(Fh(P,t,o,s),{inputs:P});return}let i=r.length===3,a=r[0].dims[n?1:2],l=r[0].dims[n?2:3],c=r[0].dims[n?3:1],p=r[1].dims[2],d=r[1].dims[3],u=o[n?1:2],f=o[n?2:3],_=o[n?3:1],y=n&&p===a&&d===l&&t.pads[0]===0&&t.pads[1]===0;if(y||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 P=o[0],x,S,O,F=[];if(n){let B=e.kernelCustomData.wT??e.compute(Xr(r[1],ma),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=B),y){let Y=a*l*c;x=r[0].reshape([1,P,Y]),S=B.reshape([1,Y,_]),O=[1,P,_]}else x=r[0].reshape([P,a*l,c]),S=B.reshape([1,c,_]),O=[P,u*f,_];F.push(x),F.push(S)}else x=r[0].reshape([P,c,a*l]),S=r[1].reshape([1,_,c]),O=[P,_,u*f],F.push(S),F.push(x);i&&F.push(r[2]);let H=O[2],W=F[0].dims[F[0].dims.length-1];H<8&&W<8?e.compute(wl(F,t,o,O,n,s),{inputs:F}):e.compute(pa(F,t,o,O,n,s),{inputs:F});return}let I=!0,w=e.kernelCustomData.wT??e.compute(Xr(r[1],ma),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=w);let v=[r[0],w];i&&v.push(r[2]);let k=n?u*f:_,T=n?_:u*f,b=p*d*c;e.compute(Ch(v,t,o,k,T,b,i,I,s),{inputs:v})},zh=(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 n=[0,r.pads[0],0,r.pads[1]],o=[1].concat(r.strides),i=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=ha({...r,pads:n,strides:o,dilations:i,kernelShape:a},s);Sl(e,s,l,c=>t?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},Bh=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",n=ha(t,r),o=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=Ih(r[0].dims,r[1].dims,t.strides,t.dilations,o,!1,s);e.compute(Ah(r,n,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},kl=(e,r)=>{if(Lh(e.inputs,r),e.inputs[0].dims.length===3)zh(e,r);else if(e.inputs[0].dims.length===5)Bh(e,e.inputs,r);else{let t=ha(r,e.inputs);Sl(e,e.inputs,t)}}}),Rh,kx=Ne(()=>{gt(),Ls(),Tt(),St(),Rh=(e,r,t)=>{let s=e.length>2,n=r.outputShape,o=r.format==="NHWC",i=r.group,a=e[1].dims,l=a[2]/i,c=a[3],p=o?or(l):1,d=o&&c===1&&l>=4,u=d?Math.floor(l/4)*4:Math.floor(l/p)*p,f=l-u,_=o?or(c):1,y=o?c===1?p:_:1,I=we.size(n)/_,w=[Math.ceil(I/64),1,1];Ot("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${w}`);let v=["rank","rank"],k=[r.strides[0],r.strides[1]],T=[r.kernelShape[o?1:2],r.kernelShape[o?2:3]],b=[r.dilations[0],r.dilations[1]],P=[T[0]+(r.dilations[0]<=1?0:(r.kernelShape[o?1:2]-1)*(r.dilations[0]-1)),T[1]+(r.dilations[1]<=1?0:(r.kernelShape[o?2:3]-1)*(r.dilations[1]-1))],x=[P[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),P[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],S=[{type:12,data:I},{type:12,data:k},{type:12,data:T},{type:12,data:b},{type:12,data:P},{type:6,data:x},{type:12,data:u},{type:12,data:l},{type:12,data:c},...ct(e[0].dims,e[1].dims)];s&&(S.push(...ct(e[2].dims)),v.push("rank")),S.push(...ct(n));let O=F=>{let H=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:k.length},{name:"filter_dims",type:"u32",length:T.length},{name:"dilations",type:"u32",length:T.length},{name:"effective_filter_dims",type:"u32",length:P.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"}],W=Sr(e[0].dataType),B=o?1:2,Y=o?2:3,X=o?3:1,J=Ie("W",e[1].dataType,e[1].dims.length,y),re=Ie("Dy",e[0].dataType,e[0].dims.length,p),ne=[re,J];s&&ne.push(Ie("bias",e[2].dataType,[n[X]].length,_));let le=ot("result",e[0].dataType,n.length,_),pe=()=>{let j="";if(d)p===4?j+=` let xValue = ${re.getByOffset("x_offset")}; let wValue = ${J.getByOffset("w_offset")}; dotProd = dotProd + dot(xValue, wValue); x_offset += 1u; w_offset += 1u;`:p===2?j+=` dotProd = dotProd + dot(vec4<${W}>(${re.getByOffset("x_offset")}, ${re.getByOffset("x_offset + 1u")}), vec4<${W}>(${J.getByOffset("w_offset")}, ${J.getByOffset("w_offset + 1u")})); x_offset += 2u; w_offset += 2u;`:p===1&&(j+=` dotProd = dotProd + dot(vec4<${W}>(${re.getByOffset("x_offset")}, ${re.getByOffset("x_offset + 1u")}, ${re.getByOffset("x_offset + 2u")}, ${re.getByOffset("x_offset + 3u")}), vec4<${W}>(${J.getByOffset("w_offset")}, ${J.getByOffset("w_offset + 1u")}, ${J.getByOffset("w_offset + 2u")}, ${J.getByOffset("w_offset + 3u")})); x_offset += 4u; w_offset += 4u;`);else if(j+=` let xValue = ${o?re.getByOffset(`${re.indicesToOffset(`${re.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):re.get("batch","inputChannel","idyR","idyC")}; `,p===1)j+=` let w_offset = ${J.indicesToOffset(`${J.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; let wValue = ${J.getByOffset(`w_offset / ${y}`)}; dotProd = dotProd + xValue * wValue;`;else for(let D=0;D{if(f===0)return"";if(!d)throw new Error(`packInputAs4 ${d} is not true.`);let j="";if(p===1){j+="dotProd = dotProd";for(let D=0;D(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 = ${le.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 = (${W}(dyRCorner) + ${W}(wR)) / ${W}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${W}(uniforms.Dy_shape[${B}]) || 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 = (${W}(dyCCorner) + ${W}(wC)) / ${W}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${W}(uniforms.Dy_shape[${Y}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; ${d?` var x_offset = ${re.indicesToOffset(`${re.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; var w_offset = ${J.indicesToOffset(`${J.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${y}; `:""} for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${d?4:p}) { ${pe()} inputChannel = inputChannel + ${d?4:p}; } ${oe()} wC = wC + uniforms.strides.y - 1; } wR = wR + uniforms.strides[0] - 1; } let value = dotProd${s?` + bias[d1 / ${_}]`:""}; ${le.setByOffset("global_idx","value")}; `;return` ${F.registerUniforms(H).declareVariables(...ne,le)} ${F.mainStart()} ${F.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${K}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${y}${_}${d}${f}`,inputDependencies:v},getRunData:()=>({dispatchGroup:{x:w[0],y:w[1],z:w[2]},outputs:[{dims:t?t(n):n,dataType:e[0].dataType}],programUniforms:S}),getShaderSource:O}}}),jh,Nh,Vh,$l,Uh,Wh,Il,Gh,Kh,$x=Ne(()=>{kx(),hn(),Ks(),jh=(e,r,t,s,n,o)=>(e-1)*r+t+(s-1)*n+1-o,Nh=(e,r,t,s,n)=>{let o=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=o,t[n]=e-o):r==="SAME_LOWER"&&(t[s]=e-o,t[n]=o)},Vh=(e,r,t,s,n,o,i,a,l,c)=>{let p=e.length-2,d=c.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((d,u)=>d*u,1)===0){t.length=0;for(let d=2;dd+u,0)===0){let d=r[0].dims.length-2;l=new Array(d).fill(1)}let c=e.strides.slice();if(c.reduce((d,u)=>d+u,0)===0){let d=r[0].dims.length-2;c=new Array(d).fill(1)}Vh(a,t,l,e.autoPad,e.group,n,c,s,i,o);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:n,outputPadding:i,outputShape:o,dilations:l,strides:c}),p},Uh=e=>{let r=gl(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],n=e.dilations,o=e.group,i=e.kernelShape,a=e.pads,l=e.strides,c=e.wIsConst(),p=e.outputPadding,d=e.outputShape;return{autoPad:s,format:t,dilations:n,group:o,kernelShape:i,outputPadding:p,outputShape:d,pads:a,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},Wh=(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 n=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==n))throw new Error("invalid bias");let o=e[0].dims.length-2;if(r.dilations.reduce((i,a)=>i+a,0)>0&&r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.reduce((i,a)=>i+a,0)>0&&r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.reduce((i,a)=>i+a,0)>0&&r.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(r.outputPadding.length!==o&&r.outputPadding.length!==0)throw new Error(`output_padding should be ${o}D`);if(r.kernelShape.reduce((i,a)=>i+a,0)>0&&r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(r.outputShape.length!==0&&r.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},Il=(e,r,t,s)=>{let n=e.kernelCustomData.wT??e.compute(Xr(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=n);let o=[r[0],n];r.length===3&&o.push(r[2]),e.compute(Rh(o,t,s),{inputs:o})},Gh=(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 n=r.kernelShape;(n.length===0||n[0]===0)&&(n=[e.inputs[1].dims[2]]);let o=r.dilations;(o.length===0||o[0]===0)&&(o=[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),o=[1].concat(o),n=[1].concat(n);let l=r.outputPadding;l=[0].concat(l);let c=$l({...r,pads:a,strides:i,dilations:o,kernelShape:n,outputPadding:l},s);Il(e,s,c,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Kh=(e,r)=>{if(Wh(e.inputs,r),e.inputs[0].dims.length===3)Gh(e,r);else{let t=$l(r,e.inputs);Il(e,e.inputs,t)}}}),Hh,qh,Qh,Ix=Ne(()=>{gt(),Tt(),dr(),St(),Hh=(e,r,t,s)=>{let n=we.size(r),o=r.length,i=Ie("input",e,o),a=ot("output",e,o),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),c=we.normalizeAxis(l,o),p=d=>{let u=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,f=lt("uniforms.input_shape","uniforms.axis",o),_=s.reverse?u+(s.exclusive?" + 1":""):"0",y=s.reverse?f:u+(s.exclusive?"":" + 1");return` ${d.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,a)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${a.offsetToIndices("global_idx")}; var sum = ${a.type.value}(0); let first : i32 = ${_}; let last : i32 = ${y}; 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(n/64)},programUniforms:[{type:12,data:n},{type:12,data:c},...ct(r,r)]}),getShaderSource:p}},qh=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,n=e.inputs[1];e.compute(Hh(s,t,n,r),{inputs:[0]})},Qh=e=>{let r=e.exclusive===1,t=e.reverse===1;return Rt({exclusive:r,reverse:t})}}),Xh,Jh,Yh,Zh,e_,Ax=Ne(()=>{gt(),Tt(),dr(),St(),Xh=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.")},Jh=(e,r,t,s)=>{let n=[];n.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { var a: ${t.type.indices};`);for(let o=0;o{let t,s,n,o,i,a,l=r.format==="NHWC",c=r.blocksize,p=r.mode==="DCR";l?([t,s,n,o]=e.dims,i=p?[t,s,n,c,c,o/c**2]:[t,s,n,o/c**2,c,c],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,n,o]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=p?[t,c,c,o/c**2,s,n]:[t,o/c**2,c,c,s,n],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let d=e.reshape(i),u=d.dims.length,f=e.dataType,_=Ie("a",f,u),y=ot("output",f,u),I=w=>` ${w.registerUniform("output_size","u32").declareVariables(_,y)} ${Jh(a,u,_,y)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${y.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${y.setByOffset("global_idx",_.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:w=>{let v=l?[t,s*c,n*c,o/c**2]:[t,o/c**2,s*c,n*c],k=we.size(v),T=d.dims,b=we.sortBasedOnPerm(T,a);return{outputs:[{dims:v,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:[{type:12,data:k},...ct(T,b)]}},getShaderSource:I}},Zh=(e,r)=>{Xh(e.inputs),e.compute(Yh(e.inputs[0],r))},e_=e=>Rt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),_a,bo,Al,t_,r_,s_,n_,Fl,o_,a_,i_,Fx=Ne(()=>{gt(),Tt(),dr(),St(),_a="[a-zA-Z]|\\.\\.\\.",bo="("+_a+")+",Al="^"+bo+"$",t_="("+bo+",)*"+bo,r_="^"+t_+"$",s_=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)}},n_=class{constructor(e,r){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(r_)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,o)=>{let i=e[o].dims.slice();if(!n.match(RegExp(Al)))throw new Error("Invalid LHS term");let a=this.processTerm(n,!0,i,o);this.lhs.push(a)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,o])=>o.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(bo)))throw new Error("Invalid RHS");s.match(RegExp(_a,"g"))?.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(n);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.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 n=t.length,o=!1,i=[],a=0;if(!e.match(RegExp(Al))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(_a,"g")),c=new s_(s);return l?.forEach((p,d)=>{if(p==="..."){if(o)throw new Error("Only one ellipsis is allowed per input term");o=!0;let u=n-l.length+1;if(u<0)throw new Error("Ellipsis out of bounds");if(i=t.slice(a,a+u),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let f=0;fe+"_max",o_=(e,r,t,s)=>{let n=e.map(c=>c.length).map((c,p)=>Ie(`input${p}`,r,c)),o=we.size(s),i=ot("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(c=>!t.rhs.symbolToIndices.has(c)),l=c=>{let p=[],d="var prod = 1.0;",u="var sum = 0.0;",f="sum += prod;",_=[],y=[],I=[],w=[],v=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((T,b)=>{if(t.rhs.symbolToIndices.has(b)){let P=t.rhs.symbolToIndices.get(b)?.[0];P!==void 0&&t.lhs.forEach((x,S)=>{if(T.inputIndices.includes(S)){let O=x.symbolToIndices.get(b);if(O===void 0)throw new Error("Invalid symbol error");O.forEach(F=>{p.push(`${n[S].indicesSet(`input${S}Indices`,F,i.indicesGet("outputIndices",P))}`)})}})}else t.lhs.forEach((P,x)=>{if(T.inputIndices.includes(x)){let S=P.symbolToIndices.get(b);if(S===void 0)throw new Error("Invalid symbol error");S.forEach(O=>{_.push(`${n[x].indicesSet(`input${x}Indices`,O,`${b}`)}`)}),w.push(`prod *= ${n[x].getByIndices(`input${x}Indices`)};`)}}),y.push(`for(var ${b}: u32 = 0; ${b} < uniforms.${Fl(b)}; ${b}++) {`),I.push("}")});let k=v?[...p,`let sum = ${n.map((T,b)=>T.getByIndices(`input${b}Indices`)).join(" * ")};`]:[...p,u,...y,..._,d,...w,f,...I];return` ${c.registerUniforms(a.map(T=>({name:`${Fl(T)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...n,i)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${i.offsetToIndices("global_idx")}; ${n.map((T,b)=>`var input${b}Indices: ${n[b].type.indices};`).join(` `)} ${k.join(` `)}; ${i.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let c=a.filter(d=>t.symbolToInfo.has(d)).map(d=>({type:12,data:t.symbolToInfo.get(d)?.dimValue||0}));c.push({type:12,data:o});let p=e.map((d,u)=>[...ct(d)]).reduce((d,u)=>d.concat(u),c);return p.push(...ct(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}},getShaderSource:l}},a_=(e,r)=>{let t=new n_(e.inputs,r.equation),s=t.outputDims,n=e.inputs.map((o,i)=>o.dims);e.compute(o_(n,e.inputs[0].dataType,t,s))},i_=e=>{let r=e.equation.replace(/\s+/g,"");return Rt({equation:r})}}),l_,Ol,c_,u_,d_,Ox=Ne(()=>{gt(),Tt(),St(),l_=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 n=0;ne.length>r.length?Ol(e,r):Ol(r,e),u_=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=c_(r,t),n=e[0].dataType,o=n===9||we.size(r)===1,i=n===9||r.length>0&&r[r.length-1]%4===0?4:1,a=o||s.length>0&&s[s.length-1]%4===0?4:1,l=Math.ceil(we.size(s)/a),c=d=>{let u=Ie("input",n,r.length,i),f=ot("output",n,s.length,a),_;if(n===9){let y=(I,w,v="")=>` let outputIndices${w} = ${f.offsetToIndices(`outputOffset + ${w}u`)}; let offset${w} = ${u.broadcastedIndicesToOffset(`outputIndices${w}`,f)}; let index${w} = offset${w} / 4u; let component${w} = offset${w} % 4u; ${I}[${w}] = ${v}(${u.getByOffset(`index${w}`)}[component${w}]); `;_=` let outputOffset = global_idx * ${a}; var data = vec4(0); ${y("data",0,"u32")} ${y("data",1,"u32")} ${y("data",2,"u32")} ${y("data",3,"u32")} ${f.setByOffset("global_idx","data")} }`}else _=` let outputIndices = ${f.offsetToIndices(`global_idx * ${a}`)}; let inputOffset = ${u.broadcastedIndicesToOffset("outputIndices",f)}; let data = ${f.type.value}(${u.getByOffset(`inputOffset / ${i}`)}); ${f.setByOffset("global_idx","data")} }`;return` ${d.registerUniform("vec_size","u32").declareVariables(u,f)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${_}`},p=[{type:12,data:l},...ct(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${i}${a}`,inputDependencies:["rank"]},getShaderSource:c,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},d_=e=>{l_(e.inputs),e.compute(u_(e.inputs),{inputs:[0]})}}),p_,m_,Dx=Ne(()=>{gt(),Tt(),St(),fl(),p_=e=>{let r=e[0].dataType,t=we.size(e[0].dims),s=we.size(e[1].dims),n=s%4===0,o=i=>{let a=Ie("x",r,[1],4),l=Ie("bias",r,[1],4),c=ot("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],d=f=>` let bias${f}_offset: u32 = (global_idx * 4 + ${f}) % uniforms.bias_size; let bias${f} = ${l.getByOffset(`bias${f}_offset / 4`)}[bias${f}_offset % 4];`,u=n?` let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${d(0)}${d(1)}${d(2)}${d(3)} let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(p).declareVariables(a,l,c)} ${hl(Rr(r))} ${i.mainStart(zn)} ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${a.getByOffset("global_idx")}; ${u} let x_in = x + bias; ${c.setByOffset("global_idx",_l("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${n}`,inputDependencies:["type","type"]},getShaderSource:o,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/zn/4)}})}},m_=e=>{e.inputs.length<2||we.size(e.inputs[1].dims)===0?Hm(e):e.compute(p_(e.inputs))}}),h_,__,f_,g_,Lx=Ne(()=>{gt(),Tt(),dr(),St(),h_=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},__=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t.length,o=we.normalizeAxis(r.axis,n),i=t.slice(0);i.splice(o,1,...s);let a=t[o],l=e[0].dataType===9?4:1,c=Math.ceil(we.size(i)/l),p=[{type:12,data:c},{type:6,data:a},{type:12,data:o},...ct(e[0].dims,e[1].dims,i)],d=u=>{let f=Ie("data",e[0].dataType,e[0].dims.length,l),_=Ie("inputIndices",e[1].dataType,e[1].dims.length),y=ot("output",e[0].dataType,i.length,l),I=v=>{let k=s.length,T=`var indicesIndices${v} = ${_.type.indices}(0);`;for(let b=0;b1?`indicesIndices${v}[${b}]`:`indicesIndices${v}`} = ${i.length>1?`outputIndices${v}[uniforms.axis + ${b}]`:`outputIndices${v}`};`;T+=` var idx${v} = ${_.getByIndices(`indicesIndices${v}`)}; if (idx${v} < 0) { idx${v} = idx${v} + uniforms.axisDimLimit; } var dataIndices${v} : ${f.type.indices}; `;for(let b=0,P=0;b1?`dataIndices${v}[${b}]`:`dataIndices${v}`} = u32(idx${v});`,P+=k):(T+=`${n>1?`dataIndices${v}[${b}]`:`dataIndices${v}`} = ${i.length>1?`outputIndices${v}[${P}]`:`outputIndices${v}`};`,P++);return T},w;if(e[0].dataType===9){let v=(k,T,b="")=>` let outputIndices${T} = ${y.offsetToIndices(`outputOffset + ${T}u`)}; ${I(T)}; let offset${T} = ${f.indicesToOffset(`dataIndices${T}`)}; let index${T} = offset${T} / 4u; let component${T} = offset${T} % 4u; ${k}[${T}] = ${b}(${f.getByOffset(`index${T}`)}[component${T}]); `;w=` let outputOffset = global_idx * ${l}; var value = vec4(0); ${v("value",0,"u32")} ${v("value",1,"u32")} ${v("value",2,"u32")} ${v("value",3,"u32")} ${y.setByOffset("global_idx","value")} `}else w=` let outputIndices = ${y.offsetToIndices("global_idx")}; ${I("")}; let value = ${f.getByIndices("dataIndices")}; ${y.setByOffset("global_idx","value")}; `;return` ${u.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(f,_,y)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${w} }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:d}},f_=e=>Rt({axis:e.axis}),g_=(e,r)=>{let t=e.inputs;h_(t),e.compute(__(e.inputs,r))}}),M_,w_,b_,zx=Ne(()=>{gt(),Tt(),St(),M_=(e,r,t,s,n,o,i,a,l)=>{let c=[{type:12,data:o},{type:12,data:s},{type:12,data:n},{type:12,data:t},{type:12,data:i},{type:12,data:a},{type:12,data:l}],p=[o];c.push(...ct(r.dims,p));let d=u=>{let f=Ie("indices_data",r.dataType,r.dims.length),_=ot("input_slice_offsets_data",12,1,1),y=[f,_],I=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:n.length},{name:"sizes_from_slice_dims_data",type:"u32",length:t.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` ${u.registerUniforms(I).declareVariables(...y)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let batch_idx = global_idx / uniforms.num_slices_per_batch; let base_offset = batch_idx * uniforms.input_batch_stride; let slice_indices_base_offset = global_idx * uniforms.num_slice_dims; var relative_slice_offset = 0; for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) { var index = i32(indices_data[dim_idx + slice_indices_base_offset].x); let input_dim_idx = uniforms.batch_dims + dim_idx; if (index < 0) { ${n.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:`${n.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:c}),getShaderSource:d},{inputs:[r],outputs:[-1]})[0]},w_=(e,r)=>{let t=e.inputs,s=t[0].dims,n=t[0].dataType,o=t[1].dims,i=o[o.length-1],a=we.sizeToDimension(o,o.length-1),l=we.sizeFromDimension(s,r.batchDims+i),c=we.sizeToDimension(s,r.batchDims),p=we.sizeFromDimension(s,r.batchDims),d=a/c,u=new Array(i),f=l;for(let T=0;Ts.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let I=o.slice(0,-1).concat(s.slice(y)),w=we.size(I),v=[{type:12,data:w},{type:12,data:l},...ct(t[0].dims,_.dims,I)],k=T=>{let b=Ie("data",t[0].dataType,t[0].dims.length),P=Ie("slice_offsets",12,_.dims.length),x=ot("output",t[0].dataType,I.length);return` ${T.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(b,P,x)} ${T.mainStart()} ${T.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:I,dataType:n}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:v}),getShaderSource:k},{inputs:[t[0],_]})},b_=e=>({batchDims:e.batch_dims,cacheKey:""})}),y_,v_,x_,T_,Bx=Ne(()=>{gt(),Tt(),dr(),St(),y_=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=we.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,n=e[0],o=e[2],i=e.length===4?e[3]:void 0;if(o.dims.length!==n.dims.length||!n.dims.map((a,l)=>l===t?Math.ceil(a/s)===o.dims[l]:a===o.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!==n.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==o.dims.length||!i.dims.map((a,l)=>a===o.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.")}},v_=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t.length,o=we.normalizeAxis(r.gatherAxis,n),i=we.normalizeAxis(r.quantizeAxis,n),a=t.slice(0);a.splice(o,1,...s);let l=we.size(a),c=e[2].dataType,p=e[0].dataType===22,d=[{type:12,data:l},{type:12,data:i},{type:12,data:o},{type:12,data:r.blockSize},...ct(...e.map((f,_)=>f.dims),a)],u=f=>{let _=Ie("data",e[0].dataType,e[0].dims.length),y=Ie("inputIndices",e[1].dataType,e[1].dims.length),I=Ie("scales",e[2].dataType,e[2].dims.length),w=e.length>3?Ie("zeroPoint",e[3].dataType,e[3].dims.length):void 0,v=ot("output",c,a.length),k=[_,y,I];w&&k.push(w);let T=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${f.registerUniforms(T).declareVariables(...k,v)} ${f.mainStart()} let output_indices = ${v.offsetToIndices("global_idx")}; var indices_indices = ${y.type.indices}(0); ${s.length>1?` for (var i: u32 = 0; i < ${s.length}; i++) { let index = ${v.indicesGet("output_indices","uniforms.gather_axis + i")}; ${y.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${v.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${_.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${v.indicesGet("output_indices","i")}; ${_.indicesSet("data_indices","i","index")}; } var index_from_indices = ${y.getByIndices("indices_indices")}; if (index_from_indices < 0) { index_from_indices += ${t[o]}; } ${_.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; for (var i = uniforms.gather_axis + 1; i < ${a.length}; i++) { let index = ${v.indicesGet("output_indices",`i + ${s.length} - 1`)}; ${_.indicesSet("data_indices","i","index")}; } let data_offset = ${_.indicesToOffset("data_indices")}; let data_index = data_offset % 8; // Convert 4-bit packed data to 8-bit packed data. let packed_4bit_quantized_data = ${_.getByOffset("data_offset / 8")}; let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; let quantized_data_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); let quantized_data = quantized_data_vec[data_index / 2]; var scale_indices = data_indices; let quantize_axis_index = ${I.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; ${I.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; var scale = ${I.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 = ${Rr(c)}(quantized_data - zero_point) * scale; ${v.setByOffset("global_idx","dequantized_data")}; }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((f,_)=>_!==1).map(f=>f.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(f,_)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:c}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:u}},x_=(e,r)=>{let t=e.inputs;y_(t,r),e.compute(v_(e.inputs,r))},T_=e=>Rt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),P_,E_,C_,S_,Rx=Ne(()=>{gt(),Tt(),dr(),St(),P_=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and indices input tensors be of same rank.`)},E_=(e,r)=>{let t=e[0].dims,s=e[0].dataType,n=t.length,o=e[1].dims,i=e[1].dataType,a=we.normalizeAxis(r.axis,n),l=t[a],c=o.slice(0),p=we.size(c),d=Ie("input",s,n),u=Ie("indicesInput",i,o.length),f=ot("output",s,c.length),_=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return _.push(...ct(t,o,c)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:_}),getShaderSource:y=>` ${y.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(d,u,f)} ${y.mainStart()} ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${f.offsetToIndices("global_idx")}; var idx = ${u.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${d.type.indices}(outputIndices); ${d.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${d.getByIndices("inputIndices")}; ${f.setByOffset("global_idx","value")}; }`}},C_=e=>Rt({axis:e.axis}),S_=(e,r)=>{let t=e.inputs;P_(t),e.compute(E_(e.inputs,r))}}),k_,$_,I_,A_,jx=Ne(()=>{gt(),Tt(),St(),k_=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")},$_=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[n,o,i]=Nd.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[n,o];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,c=Math.ceil(o/l),p=Math.ceil(n/l),d=!0,u=we.size(a),f=[{type:12,data:d?c:u},{type:12,data:n},{type:12,data:o},{type:12,data:i},{type:1,data:r.alpha},{type:1,data:r.beta}],_=["type","type"];e.length===3&&(f.push(...ct(e[2].dims)),_.push("rank")),f.push(...ct(a));let y=w=>{let v="";r.transA&&r.transB?v="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?v="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?v="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(v="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let k=r.alpha===1?"":"value *= uniforms.alpha;",T=Ie("a",e[0].dataType,e[0].dims),b=Ie("b",e[1].dataType,e[1].dims),P=T.type.value,x=null,S=[T,b];e.length===3&&(x=Ie("c",e[2].dataType,e[2].dims.length),S.push(x));let O=ot("output",e[0].dataType,a.length);S.push(O);let F=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` ${w.registerUniforms(F).declareVariables(...S)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${P}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${v} } ${k} ${x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",O)}; value += ${P}(uniforms.beta) * ${x.getByOffset("cOffset")};`:""} output[global_idx] = value; }`},I=w=>{let v=Ie("a",e[0].dataType,e[0].dims),k=Ie("b",e[1].dataType,e[1].dims),T=null,b=[v,k];e.length===3&&(T=Ie("c",e[2].dataType,e[2].dims.length),b.push(T));let P=ot("output",e[0].dataType,a.length);b.push(P);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="",O="";r.transA&&r.transB?(O=` var col = tile_row_start + local_id.x; var row = k_start + local_id.y; if (col < uniforms.M && row < uniforms.K) { tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; } else { tile_a[local_id.y][local_id.x] = ${v.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] = ${k.type.value}(0); } `,S="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(O=` var col = tile_row_start + local_id.x; var row = k_start + local_id.y; if (col < uniforms.M && row < uniforms.K) { tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; } else { tile_a[local_id.y][local_id.x] = ${v.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] = ${k.type.value}(0); } `,S="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(O=` var col = k_start + local_id.x; var row = tile_row_start + local_id.y; if (col < uniforms.K && row < uniforms.M) { tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; } else { tile_a[local_id.y][local_id.x] = ${v.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] = ${k.type.value}(0); } `,S="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(O=` var col = k_start + local_id.x; var row = tile_row_start + local_id.y; if (col < uniforms.K && row < uniforms.M) { tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; } else { tile_a[local_id.y][local_id.x] = ${v.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] = ${k.type.value}(0); } `,S="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let F=r.alpha===1?"":"value *= uniforms.alpha;";return` ${w.registerUniforms(x).declareVariables(...b)} 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 = ${P.type.value}(0); for (var t: u32 = 0u; t < num_tiles; t++) { ${O} k_start = k_start + ${l}; workgroupBarrier(); for (var k: u32 = 0u; k < ${l}; k++) { ${S} } workgroupBarrier(); } ${F} let m = tile_row_start + local_id.y; let n = tile_col_start + local_id.x; ${T!=null?`let cOffset = ${T.broadcastedIndicesToOffset("vec2(m, n)",P)}; value += ${P.type.value}(uniforms.beta) * ${T.getByOffset("cOffset")};`:""} if (m < uniforms.M && n < uniforms.N) { output[m * uniforms.N + n] = value; } }`};return d?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:c*p},programUniforms:f}),getShaderSource:I}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:y}},I_=e=>{let r=e.transA,t=e.transB,s=e.alpha,n=e.beta;return{transA:r,transB:t,alpha:s,beta:n,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},A_=(e,r)=>{k_(e.inputs),e.compute($_(e.inputs,r))}}),xs,zs,_n,fn,F_,O_,D_,L_,z_,B_,R_,j_,N_,V_,Nx=Ne(()=>{gt(),Tt(),dr(),St(),[xs,zs,_n,fn]=[0,1,2,3],F_=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")},O_=` 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; } `,D_=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; } `,L_=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)); `} } `,z_=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); }`:""} `,B_=(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[${xs}] = batch; indices[${zs}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` if (r >= 0 && r < H && c >=0 && c < W) { indices[${_n}] = u32(r); indices[${fn}] = u32(c); } else { return ${r}(0); } `;case"border":return` indices[${_n}] = u32(clamp(r, 0, H - 1)); indices[${fn}] = u32(clamp(c, 0, W - 1)); `;case"reflection":return` indices[${_n}] = gs_reflect(r, border[1], border[3]); indices[${fn}] = gs_reflect(c, border[0], border[2]); `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` return ${e.getByIndices("indices")}; } `,R_=(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[${xs}], indices[${zs}], 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[${xs}], indices[${zs}], border); let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${xs}], indices[${zs}], border); let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${xs}], indices[${zs}], border); let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${xs}], indices[${zs}], 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[${xs}], indices[${zs}], 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")}`,j_=(e,r)=>{let t=Ie("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],n=Ie("grid",e[1].dataType,s.length,2),o=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];r.format==="NHWC"&&(o=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[xs,zs,_n,fn]=[0,3,1,2]);let i=ot("output",e[0].dataType,o.length),a=t.type.value,l=we.size(o),c=[{type:12,data:l},...ct(e[0].dims,s,o)],p=d=>` ${d.registerUniform("output_size","u32").declareVariables(t,n,i)} ${O_} ${D_(a)} ${L_(r)} ${z_(r)} ${B_(t,a,r)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let H_in = i32(uniforms.x_shape[${_n}]); let W_in = i32(uniforms.x_shape[${fn}]); ${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[${xs}], indices[${_n}], indices[${fn}]); let nxy = ${n.getByIndices("grid_indices")}; var x = gs_denormalize(f32(nxy[0]), W_in); var y = gs_denormalize(f32(nxy[1]), H_in); ${R_(i,a,r)} }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:d=>{let u=we.size(o);return{outputs:[{dims:o,dataType:d[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:c}},getShaderSource:p}},N_=(e,r)=>{F_(e.inputs),e.compute(j_(e.inputs,r))},V_=e=>Rt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Vr,U_,W_,Dl,G_,yo,K_,H_=Ne(()=>{gt(),Tt(),dr(),tl(),pl(),St(),Ks(),Vr=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,U_=(e,r)=>{let t=e[0],s=Vr(e,1),n=Vr(e,2),o=Vr(e,3),i=Vr(e,4),a=Vr(e,5),l=Vr(e,6),c=Vr(e,7);if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let p=t.dims[0],d=t.dims[1],u=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],f=d,_=0,y=0,I=Math.floor(u/r.numHeads);if(l&&c&&we.size(l.dims)&&we.size(c.dims)){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==p||l.dims[1]!==r.numHeads||l.dims[3]!==I)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(c.dims[0]!==p||c.dims[1]!==r.numHeads||c.dims[3]!==I)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==c.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(c.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');_=l.dims[2],y=l.dims[2]}else if(l&&we.size(l.dims)||c&&we.size(c.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(s&&we.size(s.dims)>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(s.dims[2]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');w=2,f=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==I)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(n)throw new Error('Expect "value" be none when "key" has packed kv format.');w=5,f=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==I)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');w=0,f=s.dims[2]}}else{if(t.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(t.dims[2]!==r.numHeads||t.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}if(o&&we.size(o.dims)>0){if(o.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 v=_+f,k=0;if(i&&we.size(i.dims)>0){k=8;let x=i.dims;throw x.length===1?x[0]===p?k=1:x[0]===3*p+2&&(k=3):x.length===2&&x[0]===p&&x[1]===v&&(k=5),k===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let T=!1,b=u;if(n&&we.size(n.dims)>0){if(n.dims.length!==3&&n.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==n.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(n.dims.length===3){if(f!==n.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');b=n.dims[2]}else{if(f!==n.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');b=n.dims[1]*n.dims[3],T=!0}}let P=!1;if(i&&we.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(a&&we.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]!==v)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:d,pastSequenceLength:_,kvSequenceLength:f,totalSequenceLength:v,maxSequenceLength:y,inputHiddenSize:0,hiddenSize:u,vHiddenSize:b,headSize:I,vHeadSize:Math.floor(b/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:k,scale:r.scale,broadcastResPosBias:P,passPastInKv:T,qkvFormat:w}},W_=e=>Rt({...e}),Dl=Rt({perm:[0,2,1,3]}),G_=(e,r,t,s,n,o,i)=>{let a=[s,n,o],l=we.size(a),c=[{type:12,data:l},{type:12,data:i},{type:12,data:o}],p=d=>{let u=ot("qkv_with_bias",r.dataType,a),f=Ie("qkv",r.dataType,a),_=Ie("bias",t.dataType,a),y=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${d.registerUniforms(y).declareVariables(f,_,u)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},yo=(e,r,t,s,n,o,i,a)=>{let l=o;if(i&&we.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=G_(e,o,i,r,s,t*n,a),l=l.reshape([r,s,t,n]),t===1||s===1?l:e.compute(Xr(l,Dl.perm),{inputs:[l],outputs:[-1]})[0]}else return o.dims.length===3&&(l=o.reshape([r,s,t,n])),t===1||s===1?l:e.compute(Xr(l,Dl.perm),{inputs:[l],outputs:[-1]})[0]},K_=(e,r)=>{let t=U_(e.inputs,r),s=e.inputs[0],n=Vr(e.inputs,1),o=Vr(e.inputs,2),i=Vr(e.inputs,3),a=Vr(e.inputs,4),l=Vr(e.inputs,5),c=Vr(e.inputs,6),p=Vr(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if(n?.dims.length===5)throw new Error("Packed KV is not implemented");let d=n&&o&&n.dims.length===4&&o.dims.length===4,u=yo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(d)return fo(e,u,n,o,a,void 0,c,p,l,t);if(!n||!o)throw new Error("key and value must be provided");let f=yo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,n,i,t.hiddenSize),_=yo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,o,i,2*t.hiddenSize);fo(e,u,f,_,a,void 0,c,p,l,t)}}),q_,Q_,X_,J_,Ll,Y_,Z_,ef=Ne(()=>{gt(),Tt(),dr(),St(),q_=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Q_=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(n=>t.push(Number(n))),s=t.length),Rt({numOutputs:s,axis:r.axis,splitSizes:t})},X_=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${lt("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,J_=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=we.size(t),n=e[0].dataType,o=we.normalizeAxis(r.axis,t.length),i=new Array(r.numOutputs),a=Ie("input",n,t.length),l=new Array(r.numOutputs),c=[],p=[],d=0,u=[{type:12,data:s}];for(let _=0;_` ${_.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...i)} ${X_(l.length)} ${J_(i)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${a.offsetToIndices("global_idx")}; var index = ${a.indicesGet("indices",o)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${lt("uniforms.size_in_split_axis","output_number - 1u",l.length)}; ${a.indicesSet("indices",o,"index")}; } writeBufferData(output_number, indices, global_idx); }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:f,getRunData:()=>({outputs:c,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:u})}},Y_=(e,r)=>{q_(e.inputs);let t=e.inputs.length===1?r:Q_(e.inputs,r);e.compute(Ll(e.inputs,t),{inputs:[0]})},Z_=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 Rt({axis:r,numOutputs:s,splitSizes:t})}}),tf,fa,rf,sf=Ne(()=>{gt(),Tt(),dr(),St(),tf=(e,r)=>{let[t,s,n,o]=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(!we.areEqual(s.dims,[])&&!we.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(n.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(!we.areEqual(n.dims,o.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],c=t.dims[t.dims.length-2],p=n.dims[0],d=we.sizeFromDimension(t.dims,1)/c,u=a===0?n.dims[1]*2:d/i;if(a>u)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(l!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(c!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(u/2!==n.dims[1]&&a/2!==n.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${n.dims[1]}`);if(c>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},fa=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:n,scale:o}=r,i=e[0].dims[0],a=we.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],c=a/l,p=e[2].dims[1],d=n===0?p*2:c/s,u=new Array(i,l,c/d,d-p),f=we.computeStrides(u),_=[{type:1,data:o},{type:12,data:u},{type:12,data:f},...e[0].dims.length===3?new Array({type:12,data:[a,c,d,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,d,l*d,1]}):[],...ct(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],y=I=>{let w=Ie("input",e[0].dataType,e[0].dims.length),v=Ie("position_ids",e[1].dataType,e[1].dims.length),k=Ie("cos_cache",e[2].dataType,e[2].dims.length),T=Ie("sin_cache",e[3].dataType,e[3].dims.length),b=ot("output",e[0].dataType,e[0].dims.length);return I.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:u.length},{name:"global_strides",type:"u32",length:f.length},{name:"input_output_strides",type:"u32",length:f.length}]),` ${I.declareVariables(w,v,k,T,b)} ${I.mainStart(zn)} let half_rotary_emb_dim = uniforms.${k.name}_shape[1]; let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; let size = uniforms.global_shape[0] * uniforms.global_strides[0]; ${I.guardAgainstOutOfBoundsWorkgroupSizes("size")} if (bsnh[3] < half_rotary_emb_dim) { let position_ids_idx = ${v.broadcastedIndicesToOffset("bsnh.xy",ot("",v.type.tensor,2))}; let position_id = u32(${v.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")} * ${k.get("position_id","bsnh[3]")} - ${w.getByOffset("j")} * ${T.get("position_id","bsnh[3]")}; ${b.setByOffset("i","re")} let im = ${w.getByOffset("i")} * ${T.get("position_id","bsnh[3]")} + ${w.getByOffset("j")} * ${k.get("position_id","bsnh[3]")}; ${b.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${b.setByOffset("k",w.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:Rt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:y,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(we.size(u)/zn)},programUniforms:_})}},rf=(e,r)=>{tf(e.inputs,r),e.compute(fa(e.inputs,r))}}),nf,of,zl,af,lf,Vx=Ne(()=>{dr(),gt(),pl(),H_(),ef(),Ks(),sf(),St(),nf=(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],n=e[2],o=e[3],i=e[4];if(r.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(r.localWindowSize!==-1)throw new Error("Local attention is not supported");if(r.softcap!==0)throw new Error("Softcap is not supported");if(r.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(r.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let a=!1,l=t.dims[0],c=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],d=c,u=0,f=!s||s.dims.length===0,_=Math.floor(f?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);f&&(p=_*r.numHeads);let y=o&&o.dims.length!==0,I=i&&i.dims.length!==0;if(y&&o.dims.length===4&&o.dims[0]===l&&o.dims[1]!==r.kvNumHeads&&o.dims[2]===r.kvNumHeads&&o.dims[3]===_)throw new Error("BSNH pastKey/pastValue is not supported");if(y&&I){if(o.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');u=o.dims[2]}else if(y||I)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w=1;if(s&&s.dims.length>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(t.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');d=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(n)throw new Error('Expect "value" be none when "key" has packed kv format.');d=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');d=s.dims[2]}}else{if(t.dims.length!==3&&t.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(t.dims.length===5&&(t.dims[2]!==r.numHeads||t.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}let v=0,k=!1,T=r.kvNumHeads?_*r.kvNumHeads:p;if(n&&n.dims.length>0){if(n.dims.length!==3&&n.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==n.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(n.dims.length===3){if(d!==n.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');T=n.dims[2]}else{if(d!==n.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');T=n.dims[1]*n.dims[3],k=!0}}let b=e.length>4?e[5]:void 0;if(b&&b.dims.length!==1&&b.dims[0]!==l)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:l,sequenceLength:c,pastSequenceLength:u,kvSequenceLength:d,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:T,headSize:_,vHeadSize:Math.floor(T/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:v,scale:r.scale,broadcastResPosBias:!1,passPastInKv:k,qkvFormat:w}},of=Rt({perm:[0,2,1,3]}),zl=(e,r,t)=>{let s=r,n=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,n,t.headSize]),s=e.compute(Xr(s,of.perm),{inputs:[s],outputs:[-1]})[0]),s},af=(e,r,t,s)=>{let n=7,o=["type","type"],i=[e*r],a=e*r,l=[{type:12,data:a},{type:12,data:r},{type:12,data:e}],c=p=>{let d=Ie("seq_lens",t.dataType,t.dims),u=Ie("total_seq_lens",s.dataType,s.dims),f=ot("pos_ids",n,i),_=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` ${p.registerUniforms(_).declareVariables(d,u,f)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let total_sequence_length = u32(${u.getByOffset("0")}); let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length; let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length; let batch_idx = global_idx / uniforms.sequence_length; let sequence_idx = i32(global_idx % uniforms.sequence_length); var pos_id: i32 = 0; let seqlen = ${d.getByOffset("batch_idx")}; let total_seqlen = seqlen + 1; if (is_first_prompt) { if (sequence_idx < total_seqlen) { pos_id = sequence_idx; } else { pos_id = 1; } ${f.setByOffset("global_idx","pos_id")} } else if (is_subsequent_prompt) { let past_seqlen = total_seqlen - i32(uniforms.sequence_length); if (past_seqlen + sequence_idx < total_seqlen) { pos_id = past_seqlen + sequence_idx; } else { pos_id = 1; } ${f.setByOffset("global_idx","pos_id")} } else if (global_idx < uniforms.batch_size) { ${f.setByOffset("global_idx","seqlen")} }; } `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${r}`,inputDependencies:o},getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:c}},lf=(e,r)=>{let t=nf(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],n=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,o=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,i=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,c=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,d=Rt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[u,f,_]=!n&&!o?e.compute(Ll([s],d),{inputs:[s],outputs:[-1,-1,-1]}):[s,n,o],y,I;if(r.doRotary){let T=e.compute(af(t.batchSize,t.sequenceLength,l,c),{inputs:[l,c],outputs:[-1]})[0],b=e.inputs[7],P=e.inputs[8],x=Rt({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),S=[u,T,b,P],O=[-1];y=e.compute(fa(S,x),{inputs:S,outputs:O})[0],S.splice(0,1,f);let F=Rt({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});I=e.compute(fa(S,F),{inputs:S,outputs:O})[0]}let w=yo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?y:u,void 0,0),v=zl(e,r.doRotary?I:f,t),k=zl(e,_,t);fo(e,w,v,k,void 0,void 0,i,a,void 0,t,l,c)}}),Bl,cf,uf,df,Ux=Ne(()=>{gt(),Tt(),Ks(),St(),Bl=(e,r,t,s,n,o,i,a)=>{let l=or(o),c=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,d=n*i,u=64;d===1&&(u=256);let f=[n,i,o/l],_=[n,i,2],y=["rank","type","type"],I=[];I.push(...ct(f,_));let w=v=>{let k=Ie("x",r.dataType,3,l),T=Ie("scale",t.dataType,t.dims),b=Ie("bias",s.dataType,s.dims),P=ot("output",1,3,2),x=[k,T,b,P];return` var workgroup_shared : array<${p}, ${u}>; const workgroup_size = ${u}u; ${v.declareVariables(...x)} ${v.mainStart(u)} let batch = workgroup_index / uniforms.x_shape[1]; let channel = workgroup_index % uniforms.x_shape[1]; let hight = uniforms.x_shape[2]; // initialize workgroup memory var sum = ${c}(0); var squared_sum = ${c}(0); for (var h = local_idx; h < hight; h += workgroup_size) { let value = ${c}(${k.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 = ${Gs("workgroup_shared[0][0]",l)} / f32(hight * ${l}); let squared_sum_final = ${Gs("workgroup_shared[0][1]",l)} / f32(hight * ${l}); let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${a})); let channel_scale = inv_std_dev * f32(scale[channel]); let channel_shift = f32(bias[channel]) - sum_final * channel_scale; output[workgroup_index] = vec2f(channel_scale, channel_shift); } }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${a};${u}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:_,dataType:1}],dispatchGroup:{x:d},programUniforms:I}),getShaderSource:w},{inputs:[r,t,s],outputs:[-1]})[0]},cf=(e,r,t)=>{let s=r[0].dims,n=s,o=2,i=s[0],a=s[1],l=we.sizeFromDimension(s,o),c=or(l),p=we.size(n)/c,d=Bl(e,r[0],r[1],r[2],i,l,a,t.epsilon),u=[i,a,l/c],f=[i,a],_=["type","none"],y=I=>{let w=Ie("x",r[0].dataType,u.length,c),v=Ie("scale_shift",1,f.length,2),k=ot("output",r[0].dataType,u.length,c),T=[w,v,k];return` ${I.registerUniform("output_size","u32").declareVariables(...T)} ${I.mainStart()} ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${k.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${v.getByIndices("vec2(batch, channel)")}; let value = ${w.getByOffset("global_idx")} * ${k.type.value}(scale_shift.x) + ${k.type.value}(scale_shift.y); ${k.setByOffset("global_idx","value")}; }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${c}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:n,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...ct(u,f,u)]}),getShaderSource:y},{inputs:[r[0],d]})},uf=(e,r,t)=>{let s=r[0].dims,n=s,o=s[0],i=s[s.length-1],a=we.sizeFromDimension(s,1)/i,l=or(i),c=we.size(n)/l,p=[{type:12,data:a},{type:12,data:Math.floor(i/l)}],d=["type","type"],u=!1,f=[0,s.length-1];for(let w=0;ws[f[v]])),y=Bl(e,_,r[1],r[2],o,a,i,t.epsilon),I=w=>{let v=Sr(r[0].dataType),k=l===1?"vec2f":`mat${l}x2f`,T=x=>{let S=x===0?"x":"y",O=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${v}(${O}(scale.${S}))`;case 2:return`vec2<${v}>(${O}(scale[0].${S}, scale[1].${S}))`;case 4:return`vec4<${v}>(${O}(scale[0].${S}, scale[1].${S}, scale[2].${S}, scale[3].${S}))`;default:throw new Error(`Not supported compoents ${l}`)}},b=Ie("input",r[0].dataType,r[0].dims,l),P=ot("output",r[0].dataType,n,l);return` @group(0) @binding(0) var input : array<${b.type.storage}>; @group(0) @binding(1) var scale_input : array<${k}>; @group(0) @binding(2) var output : array<${P.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], ${T(0)}, ${T(1)}); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:n,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:I},{inputs:[r[0],y]})},df=(e,r)=>{r.format==="NHWC"?uf(e,e.inputs,r):cf(e,e.inputs,r)}}),pf,mf,hf,Wx=Ne(()=>{gt(),Tt(),St(),pf=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},mf=(e,r,t)=>{let s=r.simplified,n=e[0].dims,o=e[1],i=!s&&e[2],a=n,l=we.normalizeAxis(r.axis,n.length),c=we.sizeToDimension(n,l),p=we.sizeFromDimension(n,l),d=we.size(o.dims),u=i?we.size(i.dims):0;if(d!==p||i&&u!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. Size of scale and bias (if provided) must match this. Got scale size of ${d} and bias size of ${u}`);let f=[];for(let b=0;b1,v=t>2,k=b=>{let P=Sr(e[0].dataType),x=[Ie("x",e[0].dataType,e[0].dims,_),Ie("scale",o.dataType,o.dims,_)];i&&x.push(Ie("bias",i.dataType,i.dims,_)),x.push(ot("output",e[0].dataType,a,_)),w&&x.push(ot("mean_data_output",1,f)),v&&x.push(ot("inv_std_output",1,f));let S=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${b.registerUniforms(S).declareVariables(...x)} ${b.mainStart()} ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${ol("f32",_)}; var mean_square_vector = ${ol("f32",_)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Bn(P,_,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Gs("mean_vector",_)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Gs("mean_square_vector",_)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${Bn(P,_,"x[j + offset]")}; let f32scale = ${Bn(P,_,"scale[j]")}; output[j + offset] = ${x[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale ${i?`+ ${Bn(P,_,"bias[j]")}`:""} ); } ${w?"mean_data_output[global_idx] = mean":""}; ${v?"inv_std_output[global_idx] = inv_std_dev":""}; }`},T=[{dims:a,dataType:e[0].dataType}];return w&&T.push({dims:f,dataType:1}),v&&T.push({dims:f,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${t};${s}`,inputDependencies:y},getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:I}),getShaderSource:k}},hf=(e,r)=>{pf(e.inputs),e.compute(mf(e.inputs,r,e.outputCount))}}),_f,ff,Gx=Ne(()=>{Tt(),bl(),Tl(),_f=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.")},ff=e=>{_f(e.inputs);let r=Ln.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(wl(e.inputs,{activation:""},r));else{let n=r[r.length-2],o=we.size(e.inputs[0].dims.slice(0,-2)),i=we.size(e.inputs[1].dims.slice(0,-2));if(o!==1&&n===1&&i===1){let a=e.inputs[0].reshape([1,o,s]),l=e.inputs[1].reshape([1,s,t]),c=[1,o,t],p=[a,l];e.compute(pa(p,{activation:""},r,c),{inputs:p})}else e.compute(pa(e.inputs,{activation:""},r))}}}),gf,Mf,wf,bf,yf,Kx=Ne(()=>{gt(),Tt(),dr(),St(),gf=(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 n=Math.floor((r.k+r.blockSize-1)/r.blockSize),o=r.blockSize/8*r.bits,i=e[1];if(!we.areEqual(i.dims,[r.n,n,o]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(we.size(a)!==r.n*n)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,c=r.bits>4?r.n*n:r.n*Math.floor((n+1)/2);if(we.size(l)!==c)throw new Error("zeroPoints input size error.")}},Mf=(e,r)=>{let t=e[0].dims,s=t.length,n=t[s-2],o=r.k,i=r.n,a=t.slice(0,s-2),l=we.size(a),c=e[1].dims[2]/4,p=e[0].dataType,d=or(r.k),u=or(c),f=or(i),_=a.concat([n,i]),y=n>1&&i/f%2===0?2:1,I=we.size(_)/f/y,w=64,v=[],k=[l,n,o/d],T=we.convertShape(e[1].dims).slice();T.splice(-1,1,c/u),v.push(...ct(k)),v.push(...ct(T)),v.push(...ct(e[2].dims)),e.length===4&&v.push(...ct(we.convertShape(e[3].dims)));let b=[l,n,i/f];v.push(...ct(b));let P=x=>{let S=k.length,O=Ie("a",e[0].dataType,S,d),F=Ie("b",12,T.length,u),H=Ie("scales",e[2].dataType,e[2].dims.length),W=[O,F,H],B=e.length===4?Ie("zero_points",12,e[3].dims.length):void 0;B&&W.push(B);let Y=b.length,X=ot("output",e[0].dataType,Y,f),J=Sr(e[0].dataType),re=(()=>{switch(d){case 1:return`array<${J}, 8>`;case 2:return`mat4x2<${J}>`;case 4:return`mat2x4<${J}>`;default:throw new Error(`${d}-component is not supported.`)}})(),ne=()=>{let oe=` // reuse a data var input_offset = ${O.indicesToOffset(`${O.type.indices}(batch, row, word_offset)`)}; var a_data: ${re}; for (var j: u32 = 0; j < ${8/d}; j++) { a_data[j] = ${O.getByOffset("input_offset")}; input_offset++; } `;for(let K=0;K> 4) & b_mask); b_quantized_values = ${re}(${Array.from({length:4},(j,D)=>`${J}(b_value_lower[${D}]), ${J}(b_value_upper[${D}])`).join(", ")}); b_dequantized_values = ${d===1?`${re}(${Array.from({length:8},(j,D)=>`(b_quantized_values[${D}] - ${B?`zero_point${K}`:"zero_point"}) * scale${K}`).join(", ")});`:`(b_quantized_values - ${re}(${Array(8).fill(`${B?`zero_point${K}`:"zero_point"}`).join(",")})) * scale${K};`}; workgroup_shared[local_id.x * ${y} + ${Math.floor(K/f)}]${f>1?`[${K%f}]`:""} += ${Array.from({length:8/d},(j,D)=>`${d===1?`a_data[${D}] * b_dequantized_values[${D}]`:`dot(a_data[${D}], b_dequantized_values[${D}])`}`).join(" + ")}; `;return oe},le=()=>{let oe=` var col_index = col * ${f}; ${B?` 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 = ${J}(8);`} `;for(let K=0;K> 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 = ${B.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${K} = ${J}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return oe},pe=()=>{let oe=`col_index = col * ${f};`;for(let K=0;K; var b_value_upper: vec4; var b_quantized_values: ${re}; var b_dequantized_values: ${re};`,oe};return` var workgroup_shared: array<${X.type.value}, ${y*w}>; ${x.declareVariables(...W,X)} ${x.mainStart([w,1,1])} let output_indices = ${X.offsetToIndices(`(global_idx / ${w}) * ${y}`)}; 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}; ${le()} for (var word: u32 = 0; word < ${c}; word += ${u}) { ${pe()} for (var i: u32 = 0; i < ${u}; i++) { ${ne()} word_offset += ${8/d}; } } } workgroupBarrier(); if (local_id.x < ${y}) { var output_value: ${X.type.value} = ${X.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 += ${y}; } ${X.setByIndices(`${X.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${d};${u};${f};${y};${w}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:I},programUniforms:v}),getShaderSource:P}},wf=(e,r)=>{let t=e[0].dims,s=t.length,n=t[s-2],o=r.k,i=r.n,a=t.slice(0,s-2),l=we.size(a),c=e[1].dims[2]/4,p=e[0].dataType,d=or(r.k),u=or(c),f=a.concat([n,i]),_=128,y=i%8===0?8:i%4===0?4:1,I=_/y,w=I*u*8,v=w/d,k=w/r.blockSize,T=we.size(f)/y,b=[],P=[l,n,o/d],x=we.convertShape(e[1].dims).slice();x.splice(-1,1,c/u),b.push(...ct(P)),b.push(...ct(x)),b.push(...ct(e[2].dims)),e.length===4&&b.push(...ct(we.convertShape(e[3].dims)));let S=[l,n,i];b.push(...ct(S));let O=F=>{let H=P.length,W=Ie("a",e[0].dataType,H,d),B=Ie("b",12,x.length,u),Y=Ie("scales",e[2].dataType,e[2].dims.length),X=[W,B,Y],J=e.length===4?Ie("zero_points",12,e[3].dims.length):void 0;J&&X.push(J);let re=S.length,ne=ot("output",e[0].dataType,re),le=Sr(e[0].dataType),pe=()=>{switch(d){case 1:return` let a_data0 = vec4<${le}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${le}>(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<${le}>(sub_a[word_offset], sub_a[word_offset + 1]); let a_data1 = vec4<${le}>(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<${W.type.value}, ${v}>; var inter_results: array, ${y}>; ${F.declareVariables(...X,ne)} ${F.mainStart([I,y,1])} let output_indices = ${ne.offsetToIndices(`workgroup_index * ${y}`)}; 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) / ${k} + 1; // Loop over shared dimension. for (var tile: u32 = 0; tile < num_tiles; tile += 1) { let a_col_start = tile * ${v}; // load one tile A data into shared memory. for (var a_offset = local_idx; a_offset < ${v}; a_offset += ${_}) { let a_col = a_col_start + a_offset; if (a_col < uniforms.a_shape[2]) { sub_a[a_offset] = ${W.getByIndices(`${W.type.indices}(batch, row, a_col)`)}; } else { sub_a[a_offset] = ${W.type.value}(0); } } workgroupBarrier(); // each thread process one block let b_row = col + local_id.y; let block = tile * ${k} + local_id.x; ${J?` 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 = ${J.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point = ${le}((zero_point_word) & 0xFu);`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${le}(8);`} let scale = ${Y.getByOffset("b_row * n_blocks_per_col + block")}; let b_data = ${B.getByIndices(`${B.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${r.blockSize/d}; for (var i: u32 = 0; i < ${u}; i++) { ${pe()} let b_value = ${u===1?"b_data":"b_data[i]"}; let b_value_lower = unpack4xU8(b_value & 0x0F0F0F0Fu); let b_value_upper = unpack4xU8((b_value >> 4) & 0x0F0F0F0Fu); let b_quantized_values = mat2x4<${le}>(${Array.from({length:4},(oe,K)=>`${le}(b_value_lower[${K}]), ${le}(b_value_upper[${K}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${le}>(${Array(8).fill("zero_point").join(",")})) * scale; inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(oe,K)=>`${`dot(a_data${K}, b_dequantized_values[${K}])`}`).join(" + ")}; word_offset += ${8/d}; } workgroupBarrier(); } if (local_idx < ${y}) { var output_value: ${ne.type.value} = ${ne.type.value}(0); for (var b = 0u; b < ${I}; b++) { output_value += inter_results[local_idx][b]; } if (col + local_idx < uniforms.output_shape[2]) { ${ne.setByIndices(`${ne.type.indices}(batch, row, col + local_idx)`,"output_value")} } } }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${d};${u};${I};${y}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:T},programUniforms:b}),getShaderSource:O}},bf=(e,r)=>{gf(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(wf(e.inputs,r)):e.compute(Mf(e.inputs,r))},yf=e=>Rt(e)}),vf,xf,Tf,Pf,Ef,Cf,Sf,kf,$f,Hx=Ne(()=>{gt(),Tt(),St(),vf=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].")}},xf=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${lt("uniforms.pads",n,t)}; if (k < 0) { break; } if (k >= i32(${lt("uniforms.x_shape",n,r)})) { break; } offset += k * i32(${lt("uniforms.x_strides",n,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]; } `},Tf=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${lt("uniforms.pads",n,t)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${lt("uniforms.x_shape",n,r)}) - 1); k = k % _2n_1; if(k >= i32(${lt("uniforms.x_shape",n,r)})) { k = _2n_1 - k; } } offset += k * i32(${lt("uniforms.x_strides",n,r)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},Pf=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${lt("uniforms.pads",n,t)}; if (k < 0) { k = 0; } if (k >= i32(${lt("uniforms.x_shape",n,r)})) { k = i32(${lt("uniforms.x_shape",n,r)}) - 1; } offset += k * i32(${lt("uniforms.x_strides",n,r)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},Ef=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${lt("uniforms.pads",n,t)}; if (k < 0) { k += i32(${lt("uniforms.x_shape",n,r)}]); } if (k >= i32(${lt("uniforms.x_shape",n,r)})) { k -= i32(${lt("uniforms.x_shape",n,r)}); } offset += k * i32(${lt("uniforms.x_strides",n,r)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},Cf=(e,r,t)=>{switch(t.mode){case 0:return xf(e,r,t.pads.length);case 1:return Tf(e,r,t.pads.length);case 2:return Pf(e,r,t.pads.length);case 3:return Ef(e,r,t.pads.length);default:throw new Error("Invalid mode")}},Sf=(e,r)=>{let t=we.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,n=we.size(t),o=[{type:12,data:n},{type:6,data:r.pads}],i=e.length>=3&&e[2].data;r.mode===0&&o.push({type:i?e[2].dataType:1,data:r.value}),o.push(...ct(e[0].dims,t));let a=["rank"],l=c=>{let p=ot("output",e[0].dataType,t.length),d=Ie("x",e[0].dataType,s.length),u=d.type.value,f=Cf(p,s.length,r),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&_.push({name:"constant_value",type:i?u:"f32"}),` ${c.registerUniforms(_).declareVariables(d,p)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${p.offsetToIndices("global_idx")}; var value = ${u}(0); ${f} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${i}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(we.size(t)/64)},programUniforms:o}),getShaderSource:l}},kf=(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,n=e[0].dims.length,o=new Int32Array(2*n).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;lo[Number(l)]=Number(a));let i=[];return o.forEach(a=>i.push(a)),{mode:r.mode,value:s,pads:i}}else return r},$f=(e,r)=>{vf(e.inputs);let t=kf(e.inputs,r);e.compute(Sf(e.inputs,t),{inputs:[0]})}}),vo,Rl,jl,Nl,Vl,If,Af,Ul,Wl,Ff,Of,Gl,Df,Lf,Kl,zf,Bf,Rf,jf,qx=Ne(()=>{ps(),gt(),Tt(),St(),vo=e=>{if(Xt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Rl=(e,r,t)=>{let s=r.format==="NHWC",n=e.dims.slice();s&&n.splice(1,0,n.pop());let o=Object.hasOwnProperty.call(r,"dilations"),i=r.kernelShape.slice(),a=r.strides.slice(),l=o?r.dilations.slice():[],c=r.pads.slice();na.adjustPoolAttributes(t,n,i,a,l,c);let p=na.computePoolOutputShape(t,n,a,l,i,c,r.autoPad),d=Object.assign({},r);o?Object.assign(d,{kernelShape:i,strides:a,pads:c,dilations:l,cacheKey:r.cacheKey}):Object.assign(d,{kernelShape:i,strides:a,pads:c,cacheKey:r.cacheKey});let u=p.slice();return u.push(u.splice(1,1)[0]),[d,s?u:p]},jl=(e,r)=>{let t=r.format==="NHWC",s=we.size(e),n=we.size(r.kernelShape),o=[{type:12,data:s},{type:12,data:n}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let a=r.kernelShape[r.kernelShape.length-1],l=r.strides[r.strides.length-1],c=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],d=!!(c+p);o.push({type:12,data:a},{type:12,data:l},{type:12,data:c},{type:12,data:p}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let u=!1;if(r.kernelShape.length===2){let f=r.kernelShape[r.kernelShape.length-2],_=r.strides[r.strides.length-2],y=r.pads[r.pads.length/2-2],I=r.pads[r.pads.length-2];u=!!(y+I),o.push({type:12,data:f},{type:12,data:_},{type:12,data:y},{type:12,data:I}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[o,i,!0,d,u]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=we.computeStrides(r.kernelShape);o.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),i.push({name:"kernelStrides",type:"u32",length:a.length},{name:"pads",type:"u32",length:r.pads.length},{name:"strides",type:"u32",length:r.strides.length});let l=r.pads.reduce((c,p)=>c+p);return[o,i,!!l,!1,!1]}},Nl=(e,r,t,s,n,o,i,a,l,c,p,d)=>{let u=n.format==="NHWC",f=r.type.value,_=ot("output",r.type.tensor,s);if(n.kernelShape.length<=2){let y="",I="",w="",v=t-(u?2:1);if(p?y=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${v}] < 0 || xIndices[${v}] >= uniforms.x_shape[${v}]) { pad++; continue; } let x_val = x[${r.indicesToOffset("xIndices")}]; ${o} }`:y=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${v}] = indices[${v}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${r.indicesToOffset("xIndices")}]; ${o} }`,n.kernelShape.length===2){let k=t-(u?3:2);d?I=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${k}] = indices[${k}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${k}] < 0 || xIndices[${k}] >= uniforms.x_shape[${k}]) { pad += i32(uniforms.kw); continue; } `:I=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${k}] = indices[${k}] * uniforms.sh - uniforms.phStart + j; `,w=` } `}return` ${e.registerUniforms(l).declareVariables(r,_)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${_.offsetToIndices("global_idx")}; var xIndices = ${_.offsetToIndices("global_idx")}; var value = ${f}(${a}); var pad = 0; ${I} ${y} ${w} ${i} output[global_idx] = value; }`}else{if(u)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let y=n.kernelShape.length,I=n.pads.length,w="";return c?w=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${r.indicesToOffset("xIndices")}]; ${o} }`:w=` } let x_val = x[${r.indicesToOffset("xIndices")}]; ${o} `,` ${e.registerUniforms(l).declareVariables(r,_)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let indices = ${_.offsetToIndices("global_idx")}; var xIndices = ${_.offsetToIndices("global_idx")}; var offsets: array; var value = ${f}(${a}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${y-1}u; j++) { offsets[j] = offset / ${lt("uniforms.kernelStrides","j",y)}; offset -= offsets[j] * ${lt("uniforms.kernelStrides","j",y)}; } offsets[${y-1}] = offset; isPad = false; for (var j = ${t-y}u; j < ${t}u; j++) { xIndices[j] = indices[j] * ${lt("uniforms.strides",`j - ${t-y}u`,y)} + offsets[j - ${t-y}u] - ${lt("uniforms.pads","j - 2u",I)}; ${w} } ${i} output[global_idx] = value; }`}},Vl=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,If=e=>`${Vl(e)};${e.countIncludePad}`,Af=e=>`${Vl(e)};${e.storageOrder};${e.dilations}`,Ul=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Wl=(e,r,t,s)=>{let[n,o]=Rl(r,s,t),i=Ie("x",r.dataType,r.dims.length),a=i.type.value,l="value += x_val;",c="";n.countIncludePad?c+=`value /= ${a}(uniforms.kernelSize);`:c+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,d,u,f,_]=jl(o,n);p.push(...ct(r.dims,o));let y=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${u};${f};${_}`,inputDependencies:y},getRunData:()=>({outputs:[{dims:o,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(we.size(o)/64)},programUniforms:p}),getShaderSource:I=>Nl(I,i,r.dims.length,o.length,n,l,c,0,d,u,f,_)}},Ff=e=>{let r=e.count_include_pad!==0,t=Ul(e);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:r,...t,cacheKey:""};return{...s,cacheKey:If(s)}},Of=(e,r)=>{vo(e.inputs),e.compute(Wl("AveragePool",e.inputs[0],!1,r))},Gl={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Df=e=>{let r=e.format;return{format:r,...Gl,cacheKey:r}},Lf=(e,r)=>{vo(e.inputs),e.compute(Wl("GlobalAveragePool",e.inputs[0],!0,r))},Kl=(e,r,t,s)=>{let[n,o]=Rl(r,s,t),i=` value = max(x_val, value); `,a="",l=Ie("x",r.dataType,r.dims.length),c=["rank"],[p,d,u,f,_]=jl(o,n);return p.push(...ct(r.dims,o)),{name:e,shaderCache:{hint:`${s.cacheKey};${u};${f};${_}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:o,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(we.size(o)/64)},programUniforms:p}),getShaderSource:y=>Nl(y,l,r.dims.length,o.length,n,i,a,r.dataType===10?-65504:-1e5,d,u,f,_)}},zf=(e,r)=>{vo(e.inputs),e.compute(Kl("MaxPool",e.inputs[0],!1,r))},Bf=e=>{let r=e.storage_order,t=e.dilations,s=Ul(e);if(r!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let n={storageOrder:r,dilations:t,...s,cacheKey:""};return{...n,cacheKey:Af(n)}},Rf=e=>{let r=e.format;return{format:r,...Gl,cacheKey:r}},jf=(e,r)=>{vo(e.inputs),e.compute(Kl("GlobalMaxPool",e.inputs[0],!0,r))}}),Nf,Vf,Uf,Wf,Qx=Ne(()=>{gt(),Tt(),dr(),St(),Nf=(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((n,o)=>o===r.axis||n===e[0].dims[o]).reduce((n,o)=>n&&o,!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)].")}},Vf=(e,r)=>{let t=we.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,n=s===3,o=e[0].dims,i=e[1].dataType,a=we.size(o),l=s===3||s===2,c=l?[Math.ceil(we.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,d=e.length>2?e[2]:void 0,u=d?l?[Math.ceil(we.size(d.dims)/4)]:d.dims:void 0,f=p.length===0||p.length===1&&p[0]===1,_=f===!1&&p.length===1,y=or(a),I=f&&(!l||y===4),w=I?y:1,v=I&&!l?y:1,k=Ie("input",l?12:s,c.length,v),T=Ie("scale",i,p.length),b=d?Ie("zero_point",l?12:s,u.length):void 0,P=ot("output",i,o.length,w),x=[k,T];b&&x.push(b);let S=[c,p];d&&S.push(u);let O=[{type:12,data:a/w},{type:12,data:t},{type:12,data:r.blockSize},...ct(...S,o)],F=H=>{let W=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${H.registerUniforms(W).declareVariables(...x,P)} ${H.mainStart()} ${H.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${P.offsetToIndices("global_idx")}; // Set input x ${l?` let input = ${k.getByOffset("global_idx / 4")}; let x_vec = ${n?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${w===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${k.getByOffset("global_idx")};`}; // Set scale input ${f?`let scale_value= ${T.getByOffset("0")}`:_?` let scale_index = ${P.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${T.getByOffset("scale_index")};`:` var scale_indices: ${T.type.indices} = output_indices; let index = ${T.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${T.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${T.getByIndices("scale_indices")};`}; // Set zero-point input ${b?f?l?` let zero_point_input = ${b.getByOffset("0")}; let zero_point_vec = ${n?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${b.getByOffset("0")}`:_?l?` let zero_point_index = ${P.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${b.getByOffset("zero_point_index / 4")}; let zero_point_vec = ${n?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_index % 4]`:` let zero_point_index = ${P.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${b.getByOffset("zero_point_index")};`:l?` let zero_point_offset = ${T.indicesToOffset("scale_indices")}; let zero_point_input = ${b.getByOffset("zero_point_offset / 4")}; let zero_point_vec = ${n?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${b.getByIndices("scale_indices")};`:`let zero_point_value = ${l?n?"i32":"u32":k.type.value}(0);`}; // Compute and write output ${P.setByOffset("global_idx",`${P.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:b?["rank","rank","rank"]:["rank","rank"]},getShaderSource:F,getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(a/w/64),y:1,z:1},programUniforms:O})}},Uf=(e,r)=>{Nf(e.inputs,r),e.compute(Vf(e.inputs,r))},Wf=e=>Rt({axis:e.axis,blockSize:e.blockSize})}),Gf,Kf,Hf,Xx=Ne(()=>{ps(),gt(),St(),Gf=(e,r,t)=>{let s=e===r,n=er&&t>0;if(s||n||o)throw new Error("Range these inputs' contents are invalid.")},Kf=(e,r,t,s)=>{let n=Math.abs(Math.ceil((r-e)/t)),o=[n],i=n,a=[{type:12,data:i},{type:s,data:e},{type:s,data:t},...ct(o)],l=c=>{let p=ot("output",s,o.length),d=p.type.value,u=[{name:"outputSize",type:"u32"},{name:"start",type:d},{name:"delta",type:d}];return` ${c.registerUniforms(u).declareVariables(p)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${d}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:o,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:a})}},Hf=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]),Xt.webgpu.validateInputContent&&Gf(r,t,s),e.compute(Kf(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),qf,Hl,ql,Qf,Xf,Jf,Jx=Ne(()=>{gt(),Tt(),dr(),St(),qf=(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 n=`{ var oldValue = 0; loop { let newValueF32 =`,o=`; 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}));`:` ${n}bitcast<${s}>(oldValue) + (${t})${o}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` ${n}max(bitcast(oldValue), (${t}))${o}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${n}min(bitcast<${s}>(oldValue), (${t}))${o}`;case"mul":return`${n}(bitcast<${s}>(oldValue) * (${t}))${o}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Hl=(e,r)=>`${e===1?` let element_count_dim = uniforms.output_strides; let dim_value = uniforms.output_shape;`:` let element_count_dim = uniforms.output_strides[${r?"i - indices_start":"i"}]; let dim_value = uniforms.output_shape[${r?"i - indices_start":"i"} + uniforms.last_index_dimension];`} if (index >= 0) { if (index >= i32(dim_value)) { index = i32(dim_value - 1); } } else { if (index < -i32(dim_value)) { index = 0; } else { index += i32(dim_value); } } data_offset += u32((u32(index) * element_count_dim));`,ql=(e,r,t)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { let value = updates[uniforms.num_updates_elements * ${t?"global_idx":"idx"} + i]; ${qf(e.reduction,"output[data_offset + i]","value",r)} }`,Qf=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t,o=1,i=Math.ceil(we.size(s)/o),a=s[s.length-1],l=we.sizeFromDimension(t,a),c=we.sizeFromDimension(s,0)/a,p=[{type:12,data:i},{type:12,data:a},{type:12,data:l},...ct(e[1].dims,e[2].dims,n)],d=u=>{let f=Ie("indices",e[1].dataType,e[1].dims.length),_=Ie("updates",e[2].dataType,e[2].dims.length,o),y=r.reduction!=="none"&&r.reduction!==""?rp("output",e[0].dataType,n.length):ot("output",e[0].dataType,n.length,o);return` ${u.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(f,_,y)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var hasDuplicates = false; if (${r.reduction==="none"}) { for (var i = 0; i < ${c}; i = i + 1) { for (var j = i + 1; j < ${c}; j = j + 1) { var index_i = i32(indices[i].x); var index_j = i32(indices[j].x); if (index_i == index_j) { hasDuplicates = true; break; } } if (hasDuplicates) { break; } } } if (${r.reduction==="none"} && hasDuplicates) { if (global_idx != 0u) { return; } // Process each index-update pair individually when duplicates exist for (var idx = 0u; idx < ${c}u; idx++) { var data_offset = 0u; for (var i = 0u; i < uniforms.last_index_dimension; i++) { var index = i32(indices[idx * uniforms.last_index_dimension + i].x); ${Hl(t.length,!1)} } ${ql(r,y.type.value,!1)} } return; } var data_offset = 0u; var indices_start = uniforms.last_index_dimension * global_idx; var indices_end = indices_start + uniforms.last_index_dimension; for (var i = indices_start; i < indices_end; i++) { var index = i32(indices[i].x); ${Hl(t.length,!0)} } ${ql(r,y.type.value,!0)} }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:d}},Xf=e=>Rt({reduction:e.reduction}),Jf=(e,r)=>{e.compute(Qf(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Yf,Zf,eg,Ql,tg,rg,sg,ng,og,ag,ig,lg,Xl,cg,ug,dg,pg,mg,hg,_g,Yx=Ne(()=>{gt(),Tt(),dr(),St(),Yf=(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")}},Zf=(e,r,t)=>{r.every(n=>n>=0&&n{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((n,o)=>s[n]=e[o]),s},eg=(e,r,t,s,n,o)=>{let[i,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(p=>o.push(p));else if(r.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(a>0&&e.length>a&&e[a].dims.length===1&&e[a].dims[0]>0){if(e[a].getFloat32Array().forEach(p=>s.push(p)),s.length!==0&&s.length!==c&&t>=18&&s.length!==r.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Yf(s,r),r.axes.length>0&&Zf(s,r.axes,c).forEach((p,d)=>s[d]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>n.push(Number(p))),n.length!==0&&n.length!==c&&t>=18&&n.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(n.length!==0&&n.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 n<"u"&&s.length>0&&n.length>c)throw new Error("Resize requires only of scales or sizes to be specified")},Ql=(e,r,t,s)=>` // The whole part and the fractional part are calculated separately due to inaccuracy of floating // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an // offset-by-one error later in floor(). let big = (${e}) * (${r}); let whole = ${s}(big / (${t})); let fract = ${s}(big % (${t})) / ${s}(${t}); return whole + fract; `,tg=(e,r)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${r} { `+(()=>{switch(e){case"asymmetric":return` if (xScale < 1.0 || floor(xScale) != xScale) { return ${r}(xResized) / ${r}(xScale); } else { ${Ql("xResized","lengthOriginal","lengthResized",r)} } `;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5; } else { return 0.0; }`;case"tf_half_pixel_for_nn":return`return (${r}(xResized) + 0.5) / ${r}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { ${Ql("xResized","lengthOriginal - 1","lengthResized - 1",r)} }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${r}(roiStart) * ${r}(lengthOriginal - 1) + (${r}(xResized) * ${r}(roiEnd - roiStart) * ${r}(lengthOriginal - 1)) / ${r}(lengthResized - 1); } else { return 0.5 * ${r}(roiStart + roiEnd) * ${r}(lengthOriginal - 1); }`;case"half_pixel_symmetric":return`const outputWidth = ${r}xScale * ${r}(lengthResized); const adjustment = ${r}(lengthResized) / outputWidth; const center = ${r}(lengthOriginal) / 2; const offset = center * (1 - adjustment); return offset + ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;case"half_pixel":return`return ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",rg=(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); }";default:if(r<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",sg=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),n=e.length===0?s:e.slice();return r.length>0?(r.forEach((o,i)=>{s[o]=n[i],s[i+t]=n[r.length+i]}),s):n},ng=(e,r,t,s)=>{let n=[];if(t.length>0)if(s.length>0){if(e.forEach(o=>n.push(o)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((o,i)=>n[o]=t[i])}else t.forEach(o=>n.push(o));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");n=e.map((o,i)=>Math.round(o*r[i]))}return n},og=(e,r,t)=>{let s=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(o=>r[o]),Number.MAX_VALUE):Math.min(...r,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(o=>r[o]),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 n=e.slice();return t.axes.length>0?(t.axes.forEach(o=>r[o]=s),t.axes.forEach(o=>n[o]=Math.round(e[o]*r[o]))):(r.fill(s,0,r.length),n.forEach((o,i)=>n[i]=Math.round(o*r[i]))),n},ag=(e,r,t,s,n)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${t.length}> { var original_indices: array<${e.type.value}, ${t.length}>; for (var i:u32 = 0; i < ${t.length}; i++) { var output_index = ${e.indicesGet("output_indices","i")}; var scale = ${lt("uniforms.scales","i",s)}; var roi_low = ${lt("uniforms.roi","i",n)}; var roi_hi = ${lt("uniforms.roi",`i + ${r.length}`,n)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${lt("uniforms.input_shape","i",r.length)}; var output_shape_i = ${lt("uniforms.output_shape","i",t.length)}; original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); } } return original_indices; }`,ig=(e,r,t,s,n,o,i)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${s.length}; i++) { var output_index = ${r.indicesGet("output_indices","i")}; var input_index: u32; var scale = ${lt("uniforms.scales","i",n)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${lt("uniforms.roi","i",o)}; var roi_hi = ${lt("uniforms.roi",`i + ${t.length}`,o)}; var input_shape_i = ${lt("uniforms.input_shape","i",t.length)}; var output_shape_i = ${lt("uniforms.output_shape","i",s.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${i} || (original_idx >= 0 && original_idx < ${r.type.value}(input_shape_i))) { if (original_idx < 0) { input_index = 0; } else if (original_idx > ${r.type.value}(input_shape_i - 1)) { input_index = input_shape_i - 1; } else { input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); } } else { input_index = u32(original_idx); } } ${e.indicesSet("input_indices","i","input_index")} } return input_indices; }`,lg=(e,r)=>` fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { for (var i:u32 = 0; i < ${r.length}; i++) { var input_index = ${e.indicesGet("input_indices","i")}; if (input_index < 0 || input_index >= ${lt("uniforms.input_shape","i",r.length)}) { return false; } } return true; }`,Xl=(e,r,t,s)=>e.rank>s?` ${e.indicesSet("input_indices",r,"channel")}; ${e.indicesSet("input_indices",t,"batch")}; `:"",cg=(e,r,t,s,n)=>{let[o,i,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],c=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${c} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",i,`max(0, min(row, ${t[i]} - 1))`)}; ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; ${Xl(e,l,o,2)} return ${e.getByIndices("input_indices")}; } fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${c} { var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); var row:${c} = originalIndices[${i}]; var col:${c} = originalIndices[${a}]; ${s?`if (row < 0 || row > (${t[i]} - 1) || col < 0 || col > (${t[a]} - 1)) { return ${n}; }`:""}; 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[${o}])`:"0"}; var x11: ${c} = getInputValue(batch, channel, row1, col1); var x12: ${c} = getInputValue(batch, channel, row1, col2); var x21: ${c} = getInputValue(batch, channel, row2, col1); var x22: ${c} = getInputValue(batch, channel, row2, col2); var dx1: ${c} = abs(row - ${c}(row1)); var dx2: ${c} = abs(${c}(row2) - row); var dy1: ${c} = abs(col - ${c}(col1)); var dy2: ${c} = abs(${c}(col2) - col); if (row1 == row2) { dx1 = 0.5; dx2 = 0.5; } if (col1 == col2) { dy1 = 0.5; dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); }`},ug=(e,r,t,s,n,o,i,a,l,c)=>{let p=t.length===2,[d,u]=p?[0,1]:[2,3],f=e.type.value,_=y=>{let I=y===d?"row":"col";return` fn ${I}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${f} { var output_index = ${r.indicesGet("output_indices",y)}; var originalIdx: ${f} = getOriginalCoordinateFromResizedCoordinate(output_index, ${n[y]}, ${s[y]}, ${t[y]}, ${o[y]}, ${o[y]} + ${t.length}); var fractOriginalIdx: ${f} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${a} && (originalIdx < 0 || originalIdx > (${t[y]} - 1))) { return ${l}; } var data: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); for (var i: i32 = -1; i < 3; i++) { var ${I}: ${f} = originalIdx + ${f}(i); if (${I} < 0 || ${I} >= ${t[y]}) { ${c?`coefs[i + 1] = 0.0; continue;`:a?`return ${l};`:`${I} = max(0, min(${I}, ${t[y]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",y,`u32(${I})`)}; data[i + 1] = ${y===d?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${_(d)}; ${_(u)}; fn getCubicInterpolationCoefs(s: ${f}) -> array<${f}, 4> { var absS = abs(s); var coeffs: array<${f}, 4> = array<${f}, 4>(0.0, 0.0, 0.0, 0.0); var oneMinusAbsS: ${f} = 1.0 - absS; var twoMinusAbsS: ${f} = 2.0 - absS; var onePlusAbsS: ${f} = 1.0 + absS; coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; return coeffs; } fn cubicInterpolation1D(x: array<${f}, 4>, coefs: array<${f}, 4>) -> ${f} { var coefsSum: ${f} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; } fn bicubicInterpolation(output_indices: ${r.type.indices}) -> ${f} { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } `},dg=(e,r,t,s,n)=>{let[o,i,a,l,c]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${p} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",i,`max(0, min(depth, ${t[i]} - 1))`)}; ${e.indicesSet("input_indices",a,`max(0, min(height, ${t[a]} - 1))`)}; ${e.indicesSet("input_indices",l,`max(0, min(width, ${t[l]} - 1))`)}; ${Xl(e,c,o,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 ${n}; }`:""}; depth = max(0, min(depth, ${t[i]} - 1)); height = max(0, min(height, ${t[a]} - 1)); width = max(0, min(width, ${t[l]} - 1)); var depth1: u32 = u32(depth); var height1: u32 = u32(height); var width1: u32 = u32(width); var depth2: u32 = u32(depth + 1); var height2: u32 = u32(height + 1); var width2: u32 = u32(width + 1); var channel: u32 = ${t.length>3?`u32(originalIndices[${c}])`:"0"}; var batch: u32 = ${t.length>3?`u32(originalIndices[${o}])`:"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); }`},pg=(e,r,t,s,n,o)=>{let i=e.dims,a=sg(o,r.axes,i.length),l=ng(i,s,n,r.axes),c=s.slice();s.length===0&&(c=i.map((v,k)=>v===0?1:l[k]/v),r.keepAspectRatioPolicy!=="stretch"&&(l=og(i,c,r)));let p=ot("output",e.dataType,l.length),d=Ie("input",e.dataType,i.length),u=we.size(l),f=i.length===l.length&&i.every((v,k)=>v===l[k]),_=r.coordinateTransformMode==="tf_crop_and_resize",y=r.extrapolationValue,I=d.type.value,w=v=>` ${f?"":` ${tg(r.coordinateTransformMode,I)}; ${(()=>{switch(r.mode){case"nearest":return` ${lg(d,i)}; ${rg(r.nearestMode,t,I)}; ${ig(d,p,i,l,c.length,a.length,_)}; `;case"linear":return` ${ag(p,i,l,c.length,a.length)}; ${(()=>{if(i.length===2||i.length===4)return`${cg(d,p,i,_,y)}`;if(i.length===3||i.length===5)return`${dg(d,p,i,_,y)}`;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`${ug(d,p,i,l,c,a,r.cubicCoeffA,_,r.extrapolationValue,r.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${v.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",a.length).declareVariables(d,p)} ${v.mainStart()} ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${f?"output[global_idx] = input[global_idx];":` let output_indices = ${p.offsetToIndices("global_idx")}; var input_indices: ${d.type.indices}; ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${d.getByIndices("input_indices")}; } else { output[global_idx] = ${r.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${r.mode}`)}})()}; `} }`;return{name:"Resize",shaderCache:{hint:`${r.cacheKey}|${t}|${c.length>0?r.mode==="cubic"?c:c.length:""}|${n.length>0?n:""}|${a.length>0?a:""}|${f}|${r.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:1,data:c},{type:1,data:a},...ct(i,l)]})}},mg=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},hg=(e,r)=>{let t=[],s=[],n=[],o=mg(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");eg(e.inputs,r,o,t,s,n),e.compute(pg(e.inputs[0],r,o,t,s,n),{inputs:[0]})},_g=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,n=e.cubicCoeffA,o=e.excludeOutside!==0,i=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return Rt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:n,excludeOutside:o,extrapolationValue:i,keepAspectRatioPolicy:a,mode:l,nearestMode:c})}}),fg,gg,Mg,Zx=Ne(()=>{gt(),Tt(),St(),fg=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 n=r.dims[r.dims.length-1],o=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==n)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==o)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]!==n)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]!==n)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]!==n)throw new Error("Bias must have the same hidden size as input")}},gg=(e,r,t,s)=>{let n=r.simplified,o=e[0].dims,i=we.size(o),a=o,l=i,c=o.slice(-1)[0],p=s?o.slice(0,-1).concat(1):[],d=!n&&e.length>3,u=e.length>4,f=s&&t>1,_=s&&t>2,y=t>3,I=64,w=or(c),v=[{type:12,data:l},{type:12,data:w},{type:12,data:c},{type:1,data:r.epsilon}],k=b=>{let P=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],x=[Ie("x",e[0].dataType,e[0].dims,w),Ie("skip",e[1].dataType,e[1].dims,w),Ie("gamma",e[2].dataType,e[2].dims,w)];d&&x.push(Ie("beta",e[3].dataType,e[3].dims,w)),u&&x.push(Ie("bias",e[4].dataType,e[4].dims,w)),x.push(ot("output",e[0].dataType,a,w)),f&&x.push(ot("mean_output",1,p)),_&&x.push(ot("inv_std_output",1,p)),y&&x.push(ot("input_skip_bias_sum",e[0].dataType,a,w));let S=Sr(e[0].dataType),O=Sr(1,w);return` ${b.registerUniforms(P).declareVariables(...x)} var sum_shared : array<${O}, ${I}>; var sum_squared_shared : array<${O}, ${I}>; ${b.mainStart([I,1,1])} let ix = local_id.x; let iy = global_id.x / ${I}; let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; var stride = hidden_size_vectorized / ${I}; let offset = ix * stride + iy * hidden_size_vectorized; let offset1d = stride * ix; if (ix == ${I-1}) { stride = hidden_size_vectorized - stride * ix; } for (var i: u32 = 0; i < stride; i++) { let skip_value = skip[offset + i]; let bias_value = ${u?"bias[offset1d + i]":S+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${y?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${Bn(S,w,"value")}; sum_shared[ix] += f32_value; sum_squared_shared[ix] += f32_value * f32_value; } workgroupBarrier(); var reduce_size : u32 = ${I}; 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 = ${Gs("sum",w)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Gs("square_sum",w)} / f32(uniforms.hidden_size) ${n?"":"- mean * mean"} + uniforms.epsilon); ${f?"mean_output[global_idx] = mean;":""} ${_?"inv_std_output[global_idx] = inv_std_dev;":""} for (var i: u32 = 0; i < stride; i++) { output[offset + i] = (output[offset + i] ${n?"":`- ${S}(mean)`}) * ${S}(inv_std_dev) * gamma[offset1d + i] ${d?"+ beta[offset1d + i]":""}; } }`},T=[{dims:a,dataType:e[0].dataType}];return t>1&&T.push({dims:p,dataType:1}),t>2&&T.push({dims:p,dataType:1}),t>3&&T.push({dims:o,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${w};${f};${_};${y}`,inputDependencies:e.map((b,P)=>"type")},getShaderSource:k,getRunData:()=>({outputs:T,dispatchGroup:{x:Math.ceil(l/c)},programUniforms:v})}},Mg=(e,r)=>{fg(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(gg(e.inputs,r,e.outputCount,!1),{outputs:t})}}),wg,xo,bg,Jl,yg,vg,xg,Tg,eT=Ne(()=>{gt(),Tt(),dr(),St(),wg=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");if(r.axes.length!==0){if(r.axes.length!==r.starts.length||r.axes.length!==r.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(r.starts.length!==r.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((t,s)=>{if(e[s+1].dataType!==6&&e[s+1].dataType!==7)throw new Error(`Input ${s} must be an array of int32 or int64`)})},xo=(e,r)=>{let t=[];if(e.length>r)if(e[r].dataType===7)e[r].getBigInt64Array().forEach(s=>t.push(Number(s)));else if(e[r].dataType===6)e[r].getInt32Array().forEach(s=>t.push(Number(s)));else throw new Error(`Input ${r} must be an array of int32 or int64`);return t},bg=(e,r)=>{if(e.length>1){let t=xo(e,1),s=xo(e,2),n=xo(e,3);return n.length===0&&(n=[...Array(e[0].dims.length).keys()]),Rt({starts:t,ends:s,axes:n})}else return r},Jl=(e,r,t,s,n)=>{let o=e;return e<0&&(o+=t[s[r]]),n[r]<0?Math.max(0,Math.min(o,t[s[r]]-1)):Math.max(0,Math.min(o,t[s[r]]))},yg=(e,r,t)=>`fn calculateInputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${t.length}; i >= 0; i--) { let input_shape_i = ${lt("uniforms.input_shape","i",t.length)}; let steps_i = ${lt("uniforms.steps","i",t.length)}; let signs_i = ${lt("uniforms.signs","i",t.length)}; let starts_i = ${lt("uniforms.starts","i",t.length)}; var output_index = ${r.indicesGet("output_indices","i")}; var input_index = output_index * steps_i + starts_i + carry; carry = input_index / input_shape_i; input_index = input_index % input_shape_i; if (signs_i < 0) { input_index = input_shape_i - input_index - 1u + starts_i; } ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; }`,vg=(e,r)=>{let t=e[0].dims,s=we.size(t),n=r.axes.length>0?we.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],o=xo(e,4);o.forEach(w=>w!==0||(()=>{throw new Error("step cannot be 0")})),o.length===0&&(o=Array(n.length).fill(1));let i=r.starts.map((w,v)=>Jl(w,v,t,n,o)),a=r.ends.map((w,v)=>Jl(w,v,t,n,o));if(n.length!==i.length||n.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(n.length!==t.length)for(let w=0;wMath.sign(w));o.forEach((w,v,k)=>{if(w<0){let T=(a[v]-i[v])/w,b=i[v],P=b+T*o[v];i[v]=P,a[v]=b,k[v]=-w}});let c=t.slice(0);n.forEach((w,v)=>{c[w]=Math.ceil((a[w]-i[w])/o[w])});let p={dims:c,dataType:e[0].dataType},d=ot("output",e[0].dataType,c.length),u=Ie("input",e[0].dataType,e[0].dims.length),f=we.size(c),_=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:o.length}],y=[{type:12,data:f},{type:12,data:i},{type:6,data:l},{type:12,data:o},...ct(e[0].dims,c)],I=w=>` ${w.registerUniforms(_).declareVariables(u,d)} ${yg(u,d,t)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${d.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${d.setByOffset("global_idx",u.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${o.length}`,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:y})}},xg=(e,r)=>{wg(e.inputs,r);let t=bg(e.inputs,r);e.compute(vg(e.inputs,t),{inputs:[0]})},Tg=e=>{let r=e.starts,t=e.ends,s=e.axes;return Rt({starts:r,ends:t,axes:s})}}),Pg,Eg,Cg,Sg,tT=Ne(()=>{gt(),Tt(),dr(),Ks(),St(),Pg=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Eg=(e,r)=>{let t=e.inputs[0],s=t.dims,n=we.size(s),o=s.length,i=we.normalizeAxis(r.axis,o),a=iS),c[i]=o-1,c[o-1]=i,l=e.compute(Xr(t,c),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,d=p[o-1],u=n/d,f=or(d),_=d/f,y=64;u===1&&(y=256);let I=(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=Ie("x",l.dataType,l.dims,f),v=ot("result",l.dataType,l.dims,f),k=w.type.value,T=Sr(l.dataType)==="f32"?`var threadMax = ${k}(-3.402823e+38f);`:`var threadMax = ${k}(-65504.0h);`,b=x=>` var rowMaxShared : ${k}; var rowSumShared : ${k}; var threadShared : array<${k}, ${y}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${k} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${k}) { let index = row * row_stride + col; result[index] = value; } ${x.registerUniform("packedCols","i32").declareVariables(w,v)} ${x.mainStart(y)} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${y}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${T} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${k}(${I("threadShared[0]",f)}); } workgroupBarrier(); // find the rows sum var threadSum = ${k}(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 = ${k}(${Gs("threadShared[0]",f)}); } workgroupBarrier(); // calculate final value for each element in the row for (var col = lindex; col < cols; col += wg) { let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; setValue(row, col, row_stride, value); } }`,P=e.compute({name:"Softmax",shaderCache:{hint:`${f};${y}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:u},programUniforms:[{type:6,data:_}]}),getShaderSource:b},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(Xr(P,c),{inputs:[P]})},Cg=(e,r)=>{Pg(e.inputs),Eg(e,r)},Sg=e=>Rt({axis:e.axis})}),Yl,kg,$g,Ig,Ag,rT=Ne(()=>{gt(),Tt(),St(),Yl=e=>Array.from(e.getBigInt64Array(),Number),kg=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Yl(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},$g=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Yl(e[1]),n=$g(t,s),o=we.size(n),i=e[0].dataType,a=Ie("input",i,t.length),l=ot("output",i,n.length),c=p=>` const inputShape = ${a.indices(...t)}; ${p.registerUniform("output_size","u32").declareVariables(a,l)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${l.offsetToIndices("global_idx")}; var input_indices: ${a.type.indices}; for (var i = 0; i < ${t.length}; i++) { let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i; ${a.indicesSet("input_indices","i","input_dim_value")} } ${l.setByOffset("global_idx",a.getByIndices("input_indices"))} }`;return{name:"Tile",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},...ct(e[0].dims,n)]}),getShaderSource:c}},Ag=e=>{kg(e.inputs),e.compute(Ig(e.inputs),{inputs:[0]})}}),Fg,Og,Dg,sT=Ne(()=>{gt(),Tt(),St(),Fg=(e,r,t,s,n)=>{let o=ot("output_data",n,t.length,4),i=Ie("a_data",r[1].dataType,r[1].dims.length,4),a=Ie("b_data",r[2].dataType,r[2].dims.length,4),l=Ie("c_data",r[0].dataType,r[0].dims.length,4),c,p=(d,u,f)=>`select(${u}, ${d}, ${f})`;if(!s)c=o.setByOffset("global_idx",p(i.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let d=(u,f,_="")=>{let y=`a_data[index_a${f}][component_a${f}]`,I=`b_data[index_b${f}][component_b${f}]`,w=`bool(c_data[index_c${f}] & (0xffu << (component_c${f} * 8)))`;return` let output_indices${f} = ${o.offsetToIndices(`global_idx * 4u + ${f}u`)}; let offset_a${f} = ${i.broadcastedIndicesToOffset(`output_indices${f}`,o)}; let offset_b${f} = ${a.broadcastedIndicesToOffset(`output_indices${f}`,o)}; let offset_c${f} = ${l.broadcastedIndicesToOffset(`output_indices${f}`,o)}; let index_a${f} = offset_a${f} / 4u; let index_b${f} = offset_b${f} / 4u; let index_c${f} = offset_c${f} / 4u; let component_a${f} = offset_a${f} % 4u; let component_b${f} = offset_b${f} % 4u; let component_c${f} = offset_c${f} % 4u; ${u}[${f}] = ${_}(${p(y,I,w)}); `};n===9?c=` var data = vec4(0); ${d("data",0,"u32")} ${d("data",1,"u32")} ${d("data",2,"u32")} ${d("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=` ${d("output_data[global_idx]",0)} ${d("output_data[global_idx]",1)} ${d("output_data[global_idx]",2)} ${d("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(l,i,a,o)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${c} }`},Og=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,n=e[1].dataType,o=!(we.areEqual(r,t)&&we.areEqual(t,s)),i=r,a=we.size(r);if(o){let c=Ln.calcShape(Ln.calcShape(r,t,!1),s,!1);if(!c)throw new Error("Can't perform where op on the given tensors");i=c,a=we.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>Fg(c,e,i,o,n),getRunData:()=>({outputs:[{dims:i,dataType:n}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...ct(s,r,t,i)]})}},Dg=e=>{e.compute(Og(e.inputs))}}),Lg,nT=Ne(()=>{Mx(),pl(),wx(),bx(),yx(),vx(),xx(),Sx(),$x(),Ix(),Ax(),Fx(),Ox(),Dx(),Lx(),zx(),Bx(),Rx(),jx(),Nx(),Vx(),Ux(),Wx(),Gx(),Kx(),H_(),Hx(),qx(),Qx(),Xx(),Jx(),cl(),Yx(),sf(),Zx(),eT(),tT(),ef(),rT(),Ks(),fl(),sT(),Lg=new Map([["Abs",[_m]],["Acos",[fm]],["Acosh",[gm]],["Add",[nh]],["ArgMax",[em,dl]],["ArgMin",[Zp,dl]],["Asin",[Mm]],["Asinh",[wm]],["Atan",[bm]],["Atanh",[ym]],["Attention",[am]],["AveragePool",[Of,Ff]],["BatchNormalization",[um]],["BiasAdd",[mm]],["BiasSplitGelu",[th]],["Cast",[xm,vm]],["Ceil",[Em]],["Clip",[Pm]],["Concat",[Mh,wh]],["Conv",[kl,Cl]],["ConvTranspose",[Kh,Uh]],["Cos",[Cm]],["Cosh",[Sm]],["CumSum",[qh,Qh]],["DepthToSpace",[Zh,e_]],["DequantizeLinear",[Uf,Wf]],["Div",[oh]],["Einsum",[a_,i_]],["Elu",[km,go]],["Equal",[ah]],["Erf",[$m]],["Exp",[Im]],["Expand",[d_]],["FastGelu",[m_]],["Floor",[Am]],["FusedConv",[kl,Cl]],["Gather",[g_,f_]],["GatherElements",[S_,C_]],["GatherBlockQuantized",[x_,T_]],["GatherND",[w_,b_]],["Gelu",[Fm]],["Gemm",[A_,I_]],["GlobalAveragePool",[Lf,Df]],["GlobalMaxPool",[jf,Rf]],["Greater",[uh]],["GreaterOrEqual",[ph]],["GridSample",[N_,V_]],["GroupQueryAttention",[lf]],["HardSigmoid",[Nm,jm]],["InstanceNormalization",[df]],["LayerNormalization",[hf]],["LeakyRelu",[Om,go]],["Less",[dh]],["LessOrEqual",[mh]],["Log",[Qm]],["MatMul",[ff]],["MatMulNBits",[bf,yf]],["MaxPool",[zf,Bf]],["Mul",[ih]],["MultiHeadAttention",[K_,W_]],["Neg",[Lm]],["Not",[Dm]],["Pad",[$f]],["Pow",[lh]],["QuickGelu",[Ym,go]],["Range",[Hf]],["Reciprocal",[zm]],["ReduceMin",[qp]],["ReduceMean",[Up]],["ReduceMax",[Hp]],["ReduceSum",[Xp]],["ReduceProd",[Qp]],["ReduceL1",[Wp]],["ReduceL2",[Gp]],["ReduceLogSum",[Yp]],["ReduceLogSumExp",[Kp]],["ReduceSumSquare",[Jp]],["Relu",[Bm]],["Resize",[hg,_g]],["RotaryEmbedding",[rf]],["ScatterND",[Jf,Xf]],["Sigmoid",[Rm]],["Sin",[Vm]],["Sinh",[Um]],["Slice",[xg,Tg]],["SkipLayerNormalization",[Mg]],["Split",[Y_,Z_]],["Sqrt",[Wm]],["Softmax",[Cg,Sg]],["Sub",[ch]],["Tan",[Gm]],["Tanh",[Km]],["ThresholdedRelu",[qm,go]],["Tile",[Ag]],["Transpose",[up,dp]],["Where",[Dg]]])}),zg,oT=Ne(()=>{ps(),Ls(),St(),zg=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,n){ds(e.programInfo.name);let o=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let c of r)a.push({binding:a.length,resource:{buffer:c.buffer}});for(let c of t)a.push({binding:a.length,resource:{buffer:c.buffer}});n&&a.push({binding:a.length,resource:n});let l=o.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let c={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(c)}i.setPipeline(e.computePipeline),i.setBindGroup(0,l),i.dispatchWorkgroups(...s),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),rs(e.programInfo.name)}dispose(){}build(e,r){ds(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(c=>{t.features.has(c.feature)&&s.push(`enable ${c.extension};`)});let n=np(r,this.backend.device.limits),o=e.getShaderSource(n),i=`${s.join(` `)} ${n.additionalImplementations} ${o}`,a=t.createShaderModule({code:i,label:e.name});Ot("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return rs(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:n.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,n=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=n&&t<=n&&s<=n)return[r,t,s];let o=r*t*s,i=Math.ceil(Math.sqrt(o));if(i>n){if(i=Math.ceil(Math.cbrt(o)),i>n)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),Bg={};On(Bg,{WebGpuBackend:()=>Vg});var Rg,jg,Ng,Vg,aT=Ne(()=>{ps(),gt(),Ls(),Wd(),fx(),nT(),oT(),Rg=(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{let s=e.name;return e.shaderCache?.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${Rg(r,e.shaderCache?.inputDependencies??new Array(r.length).fill("dims"))}`,s},Ng=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Vg=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},n=o=>r.features.has(o)&&t.push(o)&&!0;n("chromium-experimental-timestamp-query-inside-passes")||n("timestamp-query"),n("shader-f16"),n("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new Ng(r.info||await r.requestAdapterInfo()),this.gpuDataManager=ep(this),this.programManager=new zg(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Hi(e.logLevel,!!e.debug),this.device.onuncapturederror=o=>{o.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${o.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;ds(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let s=0;s"u"&&(this.queryTimeBase=u);let _=Number(u-this.queryTimeBase),y=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(_)||!Number.isSafeInteger(y))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:p.map(I=>({dims:I.dims,dataType:Ds(I.dataType)})),outputsMetadata:d.map(I=>({dims:I.dims,dataType:Ds(I.dataType)})),kernelId:o,kernelType:a,kernelName:l,programName:c,startTime:_,endTime:y});else{let I="";p.forEach((v,k)=>{I+=`input[${k}]: [${v.dims}] | ${Ds(v.dataType)}, `});let w="";d.forEach((v,k)=>{w+=`output[${k}]: [${v.dims}] | ${Ds(v.dataType)}, `}),console.log(`[profiling] kernel "${o}|${a}|${l}|${c}" ${I}${w}execution time: ${y-_} ns`)}po("GPU",`${c}::${u}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),rs()}run(e,r,t,s,n,o){ds(e.name);let i=[];for(let v=0;vk):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let d=[],u=[];for(let v=0;v=o)throw new Error(`Invalid output index: ${p[v]}`);if(p[v]===-3)continue;let k=p[v]===-1,T=p[v]===-2,b=k||T?n(a[v].dataType,a[v].dims):s(p[v],a[v].dataType,a[v].dims);if(d.push(b),b.data===0)continue;let P=this.gpuDataManager.get(b.data);if(!P)throw new Error(`no GPU data for output: ${b.data}`);if(k&&this.temporaryData.push(P),T){let x=this.kernelPersistentData.get(this.currentKernelId);x||(x=[],this.kernelPersistentData.set(this.currentKernelId,x)),x.push(P)}u.push(P)}if(i.length!==r.length||u.length!==d.length){if(u.length===0)return rs(e.name),d;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let f;if(c){let v=0,k=[];c.forEach(x=>{let S=typeof x.data=="number"?[x.data]:x.data;if(S.length===0)return;let O=x.type===10?2:4,F,H;x.type===10?(H=S.length>4?16:S.length>2?8:S.length*O,F=S.length>4?16:O*S.length):(H=S.length<=2?S.length*O:16,F=16),v=Math.ceil(v/H)*H,k.push(v);let W=x.type===10?8:4;v+=S.length>4?Math.ceil(S.length/W)*F:S.length*O});let T=16;v=Math.ceil(v/T)*T;let b=new ArrayBuffer(v);c.forEach((x,S)=>{let O=k[S],F=typeof x.data=="number"?[x.data]:x.data;if(x.type===6)new Int32Array(b,O,F.length).set(F);else if(x.type===12)new Uint32Array(b,O,F.length).set(F);else if(x.type===10)new Uint16Array(b,O,F.length).set(F);else if(x.type===1)new Float32Array(b,O,F.length).set(F);else throw new Error(`Unsupported uniform type: ${Ds(x.type)}`)});let P=this.gpuDataManager.create(v,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(P.buffer,0,b,0,v),this.gpuDataManager.release(P.id),f={offset:0,size:v,buffer:P.buffer}}let _=this.programManager.normalizeDispatchGroupSize(l),y=_[1]===1&&_[2]===1,I=jg(e,r,y),w=this.programManager.getArtifact(I);if(w||(w=this.programManager.build(e,_),this.programManager.setArtifact(I,w),Ot("info",()=>`[artifact] key: ${I}, programName: ${e.name}`)),c&&w.uniformVariablesInfo){if(c.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${c.length} in program "${w.programInfo.name}".`);for(let v=0;v`[ProgramManager] run "${e.name}" (key=${I}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let v={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:r,outputTensorViews:d};this.pendingKernels.push(v),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(v)}return this.programManager.run(w,i,u,_,f),rs(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 n=Lg.get(e);if(!n)throw new Error(`kernel not implemented: ${e}`);let o={kernelType:e,kernelName:s,kernelEntry:n[0],attributes:[n[1],t]};this.kernels.set(r,o)}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 n=s.kernelType,o=s.kernelName,i=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${n}] ${o}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),Ot("info",()=>`[WebGPU] Start to run kernel "[${n}] ${o}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(r,a[1]),0}catch(c){return t.push(Promise.resolve(`[WebGPU] Kernel "[${n}] ${o}" failed. ${c}`)),1}finally{l&&t.push(this.device.popErrorScope().then(c=>c?`GPU validation error for kernel "[${n}] ${o}": ${c.message}`:null));for(let c of this.temporaryData)this.gpuDataManager.release(c.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let n=this.sessionExternalDataMapping.get(e);n||(n=new Map,this.sessionExternalDataMapping.set(e,n));let o=n.get(r),i=this.gpuDataManager.registerExternalBuffer(t,s,o);return n.set(r,[i,t]),i}unregisterBuffers(e){let r=this.sessionExternalDataMapping.get(e);r&&(r.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let r=this.gpuDataManager.get(e);if(!r)throw new Error(`no GPU data for buffer: ${e}`);return r.buffer}createDownloader(e,r,t){return async()=>{let s=await nl(this,e,r);return qi(s.buffer,t)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.mode==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){Ot("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(){Ot("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Ot("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()}}}),Ug={};On(Ug,{init:()=>Gg});var ga,Wg,Gg,iT=Ne(()=>{gt(),Ls(),Tt(),_x(),ga=class kv{constructor(r,t,s,n){this.module=r,this.dataType=t,this.data=s,this.dims=n}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=we.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=we.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=we.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=we.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(we.size(r)!==we.size(this.dims))throw new Error("Invalid new shape");return new kv(this.module,this.dataType,this.data,r)}},Wg=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,n=t/e.PTR_SIZE,o=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*n++,o));let i=Number(e.getValue(s*n++,o));this.outputCount=Number(e.getValue(s*n++,o)),this.customDataOffset=Number(e.getValue(s*n++,"*")),this.customDataSize=Number(e.getValue(s*n++,o));let a=[];for(let l=0;ltypeof i=="number"?this.inputs[i]:i)??this.inputs,s=r?.outputs??[],n=(i,a,l)=>new ga(this.module,a,this.output(i,l),l),o=(i,a)=>{let l=un(i,a);if(!l)throw new Error(`Unsupported data type: ${i}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new ga(this.module,i,c,a)};return this.backend.run(e,t,s,n,o,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,n=s===4?"i32":"i64",o=this.module.stackAlloc((1+r.length)*s);this.module.setValue(o,r.length,n);for(let i=0;i{let n=r.jsepInit;if(!n)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let o=(aT(),lo(Bg)).WebGpuBackend,i=new o;await i.initialize(t,s),n("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,c,p=!1)=>{if(p)Ot("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(c)}`),i.memcpy(Number(a),Number(l));else{Ot("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(c)}`);let d=r.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(c));i.upload(Number(l),d)}},async(a,l,c)=>{Ot("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${c}`),await i.download(Number(a),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+c)>>>0))},(a,l,c)=>i.createKernel(a,Number(l),c,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,c,p)=>{Ot("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${a}, contextDataOffset=${l}`);let d=new Wg(r,i,Number(l));return i.computeKernel(Number(a),d,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let o=new Xd(t);n("webnn",[o,()=>o.reserveTensorId(),i=>o.releaseTensorId(i),async(i,a,l,c,p)=>o.ensureTensor(i,a,l,c,p),(i,a)=>{o.uploadTensor(i,a)},async(i,a)=>o.downloadTensor(i,a)])}}}),Kg,Zl,ec,Hs,Hg,tc,Ma,rc,sc,nc,oc,ac,ic,qg=Ne(()=>{px(),mx(),gt(),cn(),Ni(),Od(),Kg=(e,r)=>{Qt()._OrtInit(e,r)!==0&&Gt("Can't initialize onnxruntime.")},Zl=async e=>{Kg(e.wasm.numThreads,sa(e.logLevel))},ec=async(e,r)=>{Qt().asyncInit?.();{let t=(iT(),lo(Ug)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let s=e.webgpu.adapter;if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let n=e.webgpu.powerPreference;if(n!==void 0&&n!=="low-power"&&n!=="high-performance")throw new Error(`Invalid powerPreference setting: "${n}"`);let o=e.webgpu.forceFallbackAdapter;if(o!==void 0&&typeof o!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${o}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:n,forceFallbackAdapter:o}),!s)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await t("webgpu",Qt(),e,s)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await t("webnn",Qt(),e)}}},Hs=new Map,Hg=e=>{let r=Qt(),t=r.stackSave();try{let s=r.PTR_SIZE,n=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,n,n+s)!==0&&Gt("Can't get session input/output count.");let o=s===4?"i32":"i64";return[Number(r.getValue(n,o)),Number(r.getValue(n+s,o))]}finally{r.stackRestore(t)}},tc=(e,r)=>{let t=Qt(),s=t.stackSave(),n=0;try{let o=t.PTR_SIZE,i=t.stackAlloc(2*o);t._OrtGetInputOutputMetadata(e,r,i,i+o)!==0&&Gt("Can't get session input/output metadata.");let a=Number(t.getValue(i,"*"));n=Number(t.getValue(i+o,"*"));let l=t.HEAP32[n/4];if(l===0)return[a,0];let c=t.HEAPU32[n/4+1],p=[];for(let d=0;d{let r=Qt(),t=r._malloc(e.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return r.HEAPU8.set(e,t),[t,e.byteLength]},rc=async(e,r)=>{let t,s,n=Qt();Array.isArray(e)?[t,s]=e:e.buffer===n.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=Ma(e);let o=0,i=0,a=0,l=[],c=[],p=[];try{if([i,l]=await Fd(r),r?.externalData&&n.mountExternalData){let T=[];for(let b of r.externalData){let P=typeof b=="string"?b:b.path;T.push(Ki(typeof b=="string"?b:b.data).then(x=>{n.mountExternalData(P,x)}))}await Promise.all(T)}for(let T of r?.executionProviders??[])if((typeof T=="string"?T:T.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof T!="string"){let b=T,P=b?.context,x=b?.gpuDevice,S=b?.deviceType,O=b?.powerPreference;P?n.currentContext=P:x?n.currentContext=await n.webnnCreateMLContext(x):n.currentContext=await n.webnnCreateMLContext({deviceType:S,powerPreference:O})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(t,s,i),n.webgpuOnCreateSession?.(o),o===0&&Gt("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[d,u]=Hg(o),f=!!r?.enableGraphCapture,_=[],y=[],I=[],w=[],v=[];for(let T=0;TT==="gpu-buffer"||T==="ml-tensor")&&(a=n._OrtCreateBinding(o),a===0&&Gt("Can't create IO binding."),k={handle:a,outputPreferredLocations:v,outputPreferredLocationsEncoded:v.map(T=>Gi(T))}),Hs.set(o,[o,c,p,k,f,!1]),[o,_,y,I,w]}catch(d){throw c.forEach(u=>n._OrtFree(u)),p.forEach(u=>n._OrtFree(u)),a!==0&&n._OrtReleaseBinding(a)!==0&&Gt("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&Gt("Can't release session."),d}finally{n._free(t),i!==0&&n._OrtReleaseSessionOptions(i)!==0&&Gt("Can't release session options."),l.forEach(d=>n._free(d)),n.unmountExternalData?.()}},sc=e=>{let r=Qt(),t=Hs.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,n,o,i,a]=t;i&&(a&&r._OrtClearBoundOutputs(i.handle)!==0&&Gt("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&Gt("Can't release IO binding.")),r.jsepOnReleaseSession?.(e),r.webnnOnReleaseSession?.(e),r.webgpuOnReleaseSession?.(e),n.forEach(l=>r._OrtFree(l)),o.forEach(l=>r._OrtFree(l)),r._OrtReleaseSession(s)!==0&&Gt("Can't release session."),Hs.delete(e)},nc=async(e,r,t,s,n,o,i=!1)=>{if(!e){r.push(0);return}let a=Qt(),l=a.PTR_SIZE,c=e[0],p=e[1],d=e[3],u=d,f,_;if(c==="string"&&(d==="gpu-buffer"||d==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&d!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(d==="gpu-buffer"){let w=e[2].gpuBuffer;_=un(Dn(c),p);{let v=a.jsepRegisterBuffer;if(!v)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');f=v(s,o,w,_)}}else if(d==="ml-tensor"){let w=e[2].mlTensor;_=un(Dn(c),p);let v=a.webnnRegisterMLTensor;if(!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');f=v(s,w,Dn(c),p)}else{let w=e[2];if(Array.isArray(w)){_=l*w.length,f=a._malloc(_),t.push(f);for(let v=0;va.setValue(I+k*l,v,l===4?"i32":"i64"));let w=a._OrtCreateTensor(Dn(c),f,_,I,p.length,Gi(u));w===0&&Gt(`Can't create tensor for input/output. session=${s}, index=${o}.`),r.push(w)}finally{a.stackRestore(y)}},oc=async(e,r,t,s,n,o)=>{let i=Qt(),a=i.PTR_SIZE,l=Hs.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],p=l[1],d=l[2],u=l[3],f=l[4],_=l[5],y=r.length,I=s.length,w=0,v=[],k=[],T=[],b=[],P=i.stackSave(),x=i.stackAlloc(y*a),S=i.stackAlloc(y*a),O=i.stackAlloc(I*a),F=i.stackAlloc(I*a);try{[w,v]=Sd(o);for(let B=0;BAe*ke,1);ne=Ds(oe);let he=u?.outputPreferredLocations[s[B]];if(ne==="string"){if(he==="gpu-buffer"||he==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Ae=[];for(let ke=0;ke0){let Ae=i.jsepGetBuffer;if(!Ae)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ke=Ae(le),Ve=un(oe,te);if(Ve===void 0||!Ui(ne))throw new Error(`Unsupported data type: ${ne}`);re=!0,W.push([ne,D,{gpuBuffer:ke,download:i.jsepCreateDownloader(ke,Ve,ne),dispose:()=>{i._OrtReleaseTensor(Y)!==0&&Gt("Can't release tensor.")}},"gpu-buffer"])}else if(he==="ml-tensor"&&te>0){let Ae=i.webnnEnsureTensor,ke=i.webnnIsInt64Supported;if(!Ae||!ke)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(un(oe,te)===void 0||!Wi(ne))throw new Error(`Unsupported data type: ${ne}`);if(ne==="int64"&&!ke(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let Ve=await Ae(e,le,oe,D,!1);re=!0,W.push([ne,D,{mlTensor:Ve,download:i.webnnCreateMLTensorDownloader(le,ne),dispose:()=>{i.webnnReleaseTensorId(le),i._OrtReleaseTensor(Y)}},"ml-tensor"])}else{let Ae=Vi(ne),ke=new Ae(te);new Uint8Array(ke.buffer,ke.byteOffset,ke.byteLength).set(i.HEAPU8.subarray(le,le+ke.byteLength)),W.push([ne,D,ke,"cpu"])}}finally{i.stackRestore(X),ne==="string"&&le&&i._free(le),re||i._OrtReleaseTensor(Y),i.webnnOnRunEnd?.(c)}}return u&&!f&&(i._OrtClearBoundOutputs(u.handle)!==0&&Gt("Can't clear bound outputs."),Hs.set(e,[c,p,d,u,f,!1])),W}finally{i.stackRestore(P),k.forEach(H=>i._OrtReleaseTensor(H)),T.forEach(H=>i._OrtReleaseTensor(H)),b.forEach(H=>i._free(H)),w!==0&&i._OrtReleaseRunOptions(w),v.forEach(H=>i._free(H))}},ac=e=>{let r=Qt(),t=Hs.get(e);if(!t)throw new Error("invalid session id");let s=t[0],n=r._OrtEndProfiling(s);n===0&&Gt("Can't get an profile file name."),r._OrtFree(n)},ic=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),qs,ss,Rn,To,Po,wa,lc,ba,gn,Mn,Qg,Xg,Jg,Yg,Zg,eM,tM,rM,sM=Ne(()=>{ps(),qg(),cn(),zi(),qs=()=>!!Xt.wasm.proxy&&typeof document<"u",Rn=!1,To=!1,Po=!1,ba=new Map,gn=(e,r)=>{let t=ba.get(e);t?t.push(r):ba.set(e,[r])},Mn=()=>{if(Rn||!To||Po||!ss)throw new Error("worker not ready")},Qg=e=>{switch(e.data.type){case"init-wasm":Rn=!1,e.data.err?(Po=!0,lc[1](e.data.err)):(To=!0,lc[0]()),wa&&(URL.revokeObjectURL(wa),wa=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=ba.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},Xg=async()=>{if(!To){if(Rn)throw new Error("multiple calls to 'initWasm()' detected.");if(Po)throw new Error("previous call to 'initWasm()' failed.");if(Rn=!0,qs())return new Promise((e,r)=>{ss?.terminate(),xd().then(([t,s])=>{try{ss=s,ss.onerror=o=>r(o),ss.onmessage=Qg,lc=[e,r];let n={type:"init-wasm",in:Xt};!n.in.wasm.wasmPaths&&(t||Fi)&&(n.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href}),ss.postMessage(n),wa=t}catch(n){r(n)}},r)});try{await ji(Xt.wasm),await Zl(Xt),To=!0}catch(e){throw Po=!0,e}finally{Rn=!1}}},Jg=async e=>{if(qs())return Mn(),new Promise((r,t)=>{gn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Xt}};ss.postMessage(s)});await ec(Xt,e)},Yg=async e=>qs()?(Mn(),new Promise((r,t)=>{gn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};ss.postMessage(s,[e.buffer])})):Ma(e),Zg=async(e,r)=>{if(qs()){if(r?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Mn(),new Promise((t,s)=>{gn("create",[t,s]);let n={type:"create",in:{model:e,options:{...r}}},o=[];e instanceof Uint8Array&&o.push(e.buffer),ss.postMessage(n,o)})}else return rc(e,r)},eM=async e=>{if(qs())return Mn(),new Promise((r,t)=>{gn("release",[r,t]);let s={type:"release",in:e};ss.postMessage(s)});sc(e)},tM=async(e,r,t,s,n,o)=>{if(qs()){if(t.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return Mn(),new Promise((i,a)=>{gn("run",[i,a]);let l=t,c={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:o}};ss.postMessage(c,ic(l))})}else return oc(e,r,t,s,n,o)},rM=async e=>{if(qs())return Mn(),new Promise((r,t)=>{gn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};ss.postMessage(s)});ac(e)}}),cc,nM,oM,lT=Ne(()=>{ps(),sM(),gt(),Ci(),Od(),cc=(e,r)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${r()}`)}},nM=e=>{switch(e[3]){case"cpu":return new us(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!Ui(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:n}=e[2];return us.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:n})}case"ml-tensor":{let r=e[0];if(!Wi(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:n}=e[2];return us.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},oM=class{async fetchModelAndCopyToWasmMemory(e){return Yg(await Ki(e))}async loadModel(e,r){ds();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Zg(t,r),rs()}async dispose(){return eM(this.sessionId)}async run(e,r,t){ds();let s=[],n=[];Object.entries(e).forEach(d=>{let u=d[0],f=d[1],_=this.inputNames.indexOf(u);if(_===-1)throw new Error(`invalid input '${u}'`);s.push(f),n.push(_)});let o=[],i=[];Object.entries(r).forEach(d=>{let u=d[0],f=d[1],_=this.outputNames.indexOf(u);if(_===-1)throw new Error(`invalid output '${u}'`);o.push(f),i.push(_)});let a=s.map((d,u)=>cc(d,()=>`input "${this.inputNames[n[u]]}"`)),l=o.map((d,u)=>d?cc(d,()=>`output "${this.outputNames[i[u]]}"`):null),c=await tM(this.sessionId,n,a,i,l,t),p={};for(let d=0;ddc,initializeFlags:()=>uc,wasmBackend:()=>iM});var uc,dc,iM,cT=Ne(()=>{ps(),sM(),lT(),uc=()=>{(typeof Xt.wasm.initTimeout!="number"||Xt.wasm.initTimeout<0)&&(Xt.wasm.initTimeout=0);let e=Xt.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.`),Xt.wasm.simd=!1),typeof Xt.wasm.proxy!="boolean"&&(Xt.wasm.proxy=!1),typeof Xt.wasm.trace!="boolean"&&(Xt.wasm.trace=!1),typeof Xt.wasm.numThreads!="number"||!Number.isInteger(Xt.wasm.numThreads)||Xt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Xt.wasm.numThreads=1;else{let r=typeof navigator>"u"?Qv("node:os").cpus().length:navigator.hardwareConcurrency;Xt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},dc=class{async init(e){uc(),await Xg(),await Jg(e)}async createInferenceSessionHandler(e,r){let t=new oM;return await t.loadModel(e,r),t}},iM=new dc});ps(),ps(),ps();var uT="1.22.0-dev.20250409-89f8206ba4",dT=pd;{let e=(cT(),lo(aM)).wasmBackend;an("webgpu",e,5),an("webnn",e,5),an("cpu",e,10),an("wasm",e,10)}Object.defineProperty(Xt.versions,"web",{value:uT,enumerable:!0});var pT=Object.freeze({__proto__:null,get InferenceSession(){return Ei},get TRACE(){return po},get TRACE_FUNC_BEGIN(){return ds},get TRACE_FUNC_END(){return rs},get Tensor(){return us},default:dT,get env(){return Xt},get registerBackend(){return an}}),pc={},mT={"onnxruntime-common":(e=>{e.exports=Gv}),"onnxruntime-web":(e=>{e.exports=pT}),"?2ce3":(()=>{}),"?7992":(()=>{}),"?5af5":(()=>{}),"?2b25":(()=>{}),"?db59":(()=>{}),"?383f":(()=>{}),"?fa4b":(()=>{}),"./node_modules/@huggingface/jinja/dist/index.js":((e,r,t)=>{t.r(r),t.d(r,{Environment:()=>at,Interpreter:()=>gr,Template:()=>Es,parse:()=>Ae,tokenize:()=>d});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),n=class{constructor(C,q){this.value=C,this.type=q}};function o(C){return/\w/.test(C)}function i(C){return/[0-9]/.test(C)}function a(C){return/\s/.test(C)}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.AdditiveBinaryOperator],["*",s.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],c=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function p(C,q={}){return C.endsWith(` `)&&(C=C.slice(0,-1)),q.lstrip_blocks&&(C=C.replace(/^[ \t]*({[#%-])/gm,"$1")),q.trim_blocks&&(C=C.replace(/([#%-]})\n/g,"$1")),C.replace(/{%\s*(end)?generation\s*%}/gs,"")}function d(C,q={}){const R=[],G=p(C,q);let Z=0,ce=0;const ye=He=>{let Mt="";for(;He(G[Z]);){if(G[Z]==="\\"){if(++Z,Z>=G.length)throw new SyntaxError("Unexpected end of input");const qe=G[Z++],Pt=c.get(qe);if(Pt===void 0)throw new SyntaxError(`Unexpected escaped character: ${qe}`);Mt+=Pt;continue}if(Mt+=G[Z++],Z>=G.length)throw new SyntaxError("Unexpected end of input")}return Mt},et=()=>{const He=R.at(-1);He&&He.type===s.Text&&(He.value=He.value.trimEnd(),He.value===""&&R.pop())},ut=()=>{for(;Z0){R.push(new n(qe,s.Text));continue}}if(G[Z]==="{"&&G[Z+1]==="#"){Z+=2;const qe=G[Z]==="-";qe&&++Z;let Pt="";for(;G[Z]!=="#"||G[Z+1]!=="}";){if(Z+2>=G.length)throw new SyntaxError("Missing end of comment tag");Pt+=G[Z++]}const It=Pt.endsWith("-");It&&(Pt=Pt.slice(0,-1)),qe&&et(),R.push(new n(Pt,s.Comment)),Z+=2,It&&ut();continue}if(G.slice(Z,Z+3)==="{%-"){et(),R.push(new n("{%",s.OpenStatement)),Z+=3;continue}if(G.slice(Z,Z+3)==="{{-"){et(),R.push(new n("{{",s.OpenExpression)),ce=0,Z+=3;continue}if(ye(a),G.slice(Z,Z+3)==="-%}"){R.push(new n("%}",s.CloseStatement)),Z+=3,ut();continue}if(G.slice(Z,Z+3)==="-}}"){R.push(new n("}}",s.CloseExpression)),Z+=3,ut();continue}const Mt=G[Z];if(Mt==="-"||Mt==="+"){const qe=R.at(-1)?.type;if(qe===s.Text||qe===void 0)throw new SyntaxError(`Unexpected character: ${Mt}`);switch(qe){case s.Identifier:case s.NumericLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++Z;const Pt=ye(i);R.push(new n(`${Mt}${Pt}`,Pt.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[qe,Pt]of l){if(qe==="}}"&&ce>0)continue;if(G.slice(Z,Z+qe.length)===qe){R.push(new n(qe,Pt)),Pt===s.OpenExpression?ce=0:Pt===s.OpenCurlyBracket?++ce:Pt===s.CloseCurlyBracket&&--ce,Z+=qe.length;continue e}}if(Mt==="'"||Mt==='"'){++Z;const qe=ye(Pt=>Pt!==Mt);R.push(new n(qe,s.StringLiteral)),++Z;continue}if(i(Mt)){let qe=ye(i);if(G[Z]==="."&&i(G[Z+1])){++Z;const Pt=ye(i);qe=`${qe}.${Pt}`}R.push(new n(qe,s.NumericLiteral));continue}if(o(Mt)){const qe=ye(o);R.push(new n(qe,s.Identifier));continue}throw new SyntaxError(`Unexpected character: ${Mt}`)}return R}var u=class{type="Statement"},f=class extends u{constructor(C){super(),this.body=C}type="Program"},_=class extends u{constructor(C,q,R){super(),this.test=C,this.body=q,this.alternate=R}type="If"},y=class extends u{constructor(C,q,R,G){super(),this.loopvar=C,this.iterable=q,this.body=R,this.defaultBlock=G}type="For"},I=class extends u{type="Break"},w=class extends u{type="Continue"},v=class extends u{constructor(C,q,R){super(),this.assignee=C,this.value=q,this.body=R}type="Set"},k=class extends u{constructor(C,q,R){super(),this.name=C,this.args=q,this.body=R}type="Macro"},T=class extends u{constructor(C){super(),this.value=C}type="Comment"},b=class extends u{type="Expression"},P=class extends b{constructor(C,q,R){super(),this.object=C,this.property=q,this.computed=R}type="MemberExpression"},x=class extends b{constructor(C,q){super(),this.callee=C,this.args=q}type="CallExpression"},S=class extends b{constructor(C){super(),this.value=C}type="Identifier"},O=class extends b{constructor(C){super(),this.value=C}type="Literal"},F=class extends O{type="IntegerLiteral"},H=class extends O{type="FloatLiteral"},W=class extends O{type="StringLiteral"},B=class extends O{type="ArrayLiteral"},Y=class extends O{type="TupleLiteral"},X=class extends O{type="ObjectLiteral"},J=class extends b{constructor(C,q,R){super(),this.operator=C,this.left=q,this.right=R}type="BinaryExpression"},re=class extends b{constructor(C,q){super(),this.operand=C,this.filter=q}type="FilterExpression"},ne=class extends u{constructor(C,q){super(),this.filter=C,this.body=q}type="FilterStatement"},le=class extends b{constructor(C,q){super(),this.lhs=C,this.test=q}type="SelectExpression"},pe=class extends b{constructor(C,q,R){super(),this.operand=C,this.negate=q,this.test=R}type="TestExpression"},oe=class extends b{constructor(C,q){super(),this.operator=C,this.argument=q}type="UnaryExpression"},K=class extends b{constructor(C=void 0,q=void 0,R=void 0){super(),this.start=C,this.stop=q,this.step=R}type="SliceExpression"},j=class extends b{constructor(C,q){super(),this.key=C,this.value=q}type="KeywordArgumentExpression"},D=class extends b{constructor(C){super(),this.argument=C}type="SpreadExpression"},te=class extends u{constructor(C,q,R){super(),this.call=C,this.callerArgs=q,this.body=R}type="CallStatement"},he=class extends b{constructor(C,q,R){super(),this.condition=C,this.trueExpr=q,this.falseExpr=R}type="Ternary"};function Ae(C){const q=new f([]);let R=0;function G(ze,Ue){const nt=C[R++];if(!nt||nt.type!==ze)throw new Error(`Parser Error: ${Ue}. ${nt.type} !== ${ze}.`);return nt}function Z(ze){if(!ut(ze))throw new SyntaxError(`Expected ${ze}`);++R}function ce(){switch(C[R].type){case s.Comment:return new T(C[R++].value);case s.Text:return He();case s.OpenStatement:return Mt();case s.OpenExpression:return qe();default:throw new SyntaxError(`Unexpected token type: ${C[R].type}`)}}function ye(...ze){return R+ze.length<=C.length&&ze.every((Ue,nt)=>Ue===C[R+nt].type)}function et(...ze){return C[R]?.type===s.OpenStatement&&C[R+1]?.type===s.Identifier&&ze.includes(C[R+1]?.value)}function ut(...ze){return R+ze.length<=C.length&&ze.every((Ue,nt)=>C[R+nt].type==="Identifier"&&Ue===C[R+nt].value)}function He(){return new W(G(s.Text,"Expected text token").value)}function Mt(){if(G(s.OpenStatement,"Expected opening statement token"),C[R].type!==s.Identifier)throw new SyntaxError(`Unknown statement, got ${C[R].type}`);const ze=C[R].value;let Ue;switch(ze){case"set":++R,Ue=Pt();break;case"if":++R,Ue=It(),G(s.OpenStatement,"Expected {% token"),Z("endif"),G(s.CloseStatement,"Expected %} token");break;case"macro":++R,Ue=Mr(),G(s.OpenStatement,"Expected {% token"),Z("endmacro"),G(s.CloseStatement,"Expected %} token");break;case"for":++R,Ue=ir(),G(s.OpenStatement,"Expected {% token"),Z("endfor"),G(s.CloseStatement,"Expected %} token");break;case"call":{++R;let nt=null;ye(s.OpenParen)&&(nt=Kr());const Kt=Nr();if(Kt.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const js=Kr();G(s.CloseStatement,"Expected closing statement token");const As=[];for(;!et("endcall");)As.push(ce());G(s.OpenStatement,"Expected '{%'"),Z("endcall"),G(s.CloseStatement,"Expected closing statement token");const Ns=new x(Kt,js);Ue=new te(Ns,nt,As);break}case"break":++R,G(s.CloseStatement,"Expected closing statement token"),Ue=new I;break;case"continue":++R,G(s.CloseStatement,"Expected closing statement token"),Ue=new w;break;case"filter":{++R;let nt=Nr();nt instanceof S&&ye(s.OpenParen)&&(nt=lr(nt)),G(s.CloseStatement,"Expected closing statement token");const Kt=[];for(;!et("endfilter");)Kt.push(ce());G(s.OpenStatement,"Expected '{%'"),Z("endfilter"),G(s.CloseStatement,"Expected '%}'"),Ue=new ne(nt,Kt);break}default:throw new SyntaxError(`Unknown statement type: ${ze}`)}return Ue}function qe(){G(s.OpenExpression,"Expected opening expression token");const ze=Tr();return G(s.CloseExpression,"Expected closing expression token"),ze}function Pt(){const ze=pr();let Ue=null;const nt=[];if(ye(s.Equals))++R,Ue=pr();else{for(G(s.CloseStatement,"Expected %} token");!et("endset");)nt.push(ce());G(s.OpenStatement,"Expected {% token"),Z("endset")}return G(s.CloseStatement,"Expected closing statement token"),new v(ze,Ue,nt)}function It(){const ze=Tr();G(s.CloseStatement,"Expected closing statement token");const Ue=[],nt=[];for(;!et("elif","else","endif");)Ue.push(ce());if(et("elif")){++R,++R;const Kt=It();nt.push(Kt)}else if(et("else"))for(++R,++R,G(s.CloseStatement,"Expected closing statement token");!et("endif");)nt.push(ce());return new _(ze,Ue,nt)}function Mr(){const ze=Nr();if(ze.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const Ue=Kr();G(s.CloseStatement,"Expected closing statement token");const nt=[];for(;!et("endmacro");)nt.push(ce());return new k(ze,Ue,nt)}function pr(ze=!1){const Ue=ze?Nr:Tr,nt=[Ue()],Kt=ye(s.Comma);for(;Kt&&(++R,nt.push(Ue()),!!ye(s.Comma)););return Kt?new Y(nt):nt[0]}function ir(){const ze=pr(!0);if(!(ze instanceof S||ze instanceof Y))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${ze.type} instead`);if(!ut("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++R;const Ue=Tr();G(s.CloseStatement,"Expected closing statement token");const nt=[];for(;!et("endfor","else");)nt.push(ce());const Kt=[];if(et("else"))for(++R,++R,G(s.CloseStatement,"Expected closing statement token");!et("endfor");)Kt.push(ce());return new y(ze,Ue,nt,Kt)}function Tr(){return Cs()}function Cs(){const ze=Dr();if(ut("if")){++R;const Ue=Dr();if(ut("else")){++R;const nt=Cs();return new he(Ue,ze,nt)}else return new le(ze,Ue)}return ze}function Dr(){let ze=Ss();for(;ut("or");){const Ue=C[R];++R;const nt=Ss();ze=new J(Ue,ze,nt)}return ze}function Ss(){let ze=Lr();for(;ut("and");){const Ue=C[R];++R;const nt=Lr();ze=new J(Ue,ze,nt)}return ze}function Lr(){let ze;for(;ut("not");){const Ue=C[R];++R;const nt=Lr();ze=new oe(Ue,nt)}return ze??zr()}function zr(){let ze=ns();for(;;){let Ue;if(ut("not","in"))Ue=new n("not in",s.Identifier),R+=2;else if(ut("in"))Ue=C[R++];else if(ye(s.ComparisonBinaryOperator))Ue=C[R++];else break;const nt=ns();ze=new J(Ue,ze,nt)}return ze}function ns(){let ze=$s();for(;ye(s.AdditiveBinaryOperator);){const Ue=C[R];++R;const nt=$s();ze=new J(Ue,ze,nt)}return ze}function wr(){const ze=ks(Nr());return ye(s.OpenParen)?lr(ze):ze}function lr(ze){let Ue=new x(ze,Kr());return Ue=ks(Ue),ye(s.OpenParen)&&(Ue=lr(Ue)),Ue}function Kr(){G(s.OpenParen,"Expected opening parenthesis for arguments list");const ze=os();return G(s.CloseParen,"Expected closing parenthesis for arguments list"),ze}function os(){const ze=[];for(;!ye(s.CloseParen);){let Ue;if(C[R].type===s.MultiplicativeBinaryOperator&&C[R].value==="*"){++R;const nt=Tr();Ue=new D(nt)}else if(Ue=Tr(),ye(s.Equals)){if(++R,!(Ue instanceof S))throw new SyntaxError("Expected identifier for keyword argument");const nt=Tr();Ue=new j(Ue,nt)}ze.push(Ue),ye(s.Comma)&&++R}return ze}function Rs(){const ze=[];let Ue=!1;for(;!ye(s.CloseSquareBracket);)ye(s.Colon)?(ze.push(void 0),++R,Ue=!0):(ze.push(Tr()),ye(s.Colon)&&(++R,Ue=!0));if(ze.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(Ue){if(ze.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new K(...ze)}return ze[0]}function ks(ze){for(;ye(s.Dot)||ye(s.OpenSquareBracket);){const Ue=C[R];++R;let nt;const Kt=Ue.type===s.OpenSquareBracket;if(Kt)nt=Rs(),G(s.CloseSquareBracket,"Expected closing square bracket");else if(nt=Nr(),nt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");ze=new P(ze,nt,Kt)}return ze}function $s(){let ze=Is();for(;ye(s.MultiplicativeBinaryOperator);){const Ue=C[R++],nt=Is();ze=new J(Ue,ze,nt)}return ze}function Is(){let ze=as();for(;ut("is");){++R;const Ue=ut("not");Ue&&++R;const nt=Nr();if(!(nt instanceof S))throw new SyntaxError("Expected identifier for the test");ze=new pe(ze,Ue,nt)}return ze}function as(){let ze=wr();for(;ye(s.Pipe);){++R;let Ue=Nr();if(!(Ue instanceof S))throw new SyntaxError("Expected identifier for the filter");ye(s.OpenParen)&&(Ue=lr(Ue)),ze=new re(ze,Ue)}return ze}function Nr(){const ze=C[R++];switch(ze.type){case s.NumericLiteral:{const Ue=ze.value;return Ue.includes(".")?new H(Number(Ue)):new F(Number(Ue))}case s.StringLiteral:{let Ue=ze.value;for(;ye(s.StringLiteral);)Ue+=C[R++].value;return new W(Ue)}case s.Identifier:return new S(ze.value);case s.OpenParen:{const Ue=pr();return G(s.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),Ue}case s.OpenSquareBracket:{const Ue=[];for(;!ye(s.CloseSquareBracket);)Ue.push(Tr()),ye(s.Comma)&&++R;return++R,new B(Ue)}case s.OpenCurlyBracket:{const Ue=new Map;for(;!ye(s.CloseCurlyBracket);){const nt=Tr();G(s.Colon,"Expected colon between key and value in object literal");const Kt=Tr();Ue.set(nt,Kt),ye(s.Comma)&&++R}return++R,new X(Ue)}default:throw new SyntaxError(`Unexpected token: ${ze.type}`)}}for(;R=0?(q=(q??=0)<0?Math.max(C.length+q,0):Math.min(q,C.length),R=(R??=C.length)<0?Math.max(C.length+R,0):Math.min(R,C.length)):(q=(q??=C.length-1)<0?Math.max(C.length+q,-1):Math.min(q,C.length-1),R=(R??=-1)<-1?Math.max(C.length+R,-1):Math.min(R,C.length-1));const ce=[];for(let ye=q;Z*yeq.toUpperCase())}function Q(C){return z(new Date,C)}function z(C,q){const R=new Intl.DateTimeFormat(void 0,{month:"long"}),G=new Intl.DateTimeFormat(void 0,{month:"short"}),Z=ce=>ce<10?"0"+ce:ce.toString();return q.replace(/%[YmdbBHM%]/g,ce=>{switch(ce){case"%Y":return C.getFullYear().toString();case"%m":return Z(C.getMonth()+1);case"%d":return Z(C.getDate());case"%b":return G.format(C);case"%B":return R.format(C);case"%H":return Z(C.getHours());case"%M":return Z(C.getMinutes());case"%%":return"%";default:return ce}})}function de(C){return C.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function be(C,q,R,G){if(G===0)return C;let Z=G==null||G<0?1/0:G;const ce=q.length===0?new RegExp("(?=)","gu"):new RegExp(de(q),"gu");return C.replaceAll(ce,ye=>Z>0?(--Z,R):ye)}var ve=class extends Error{},xe=class extends Error{},Ce=class{type="RuntimeValue";value;builtins=new Map;constructor(C=void 0){this.value=C}__bool__(){return new Pe(!!this.value)}toString(){return String(this.value)}},ge=class extends Ce{type="IntegerValue"},De=class extends Ce{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},fe=class extends Ce{type="StringValue";builtins=new Map([["upper",new Ze(()=>new fe(this.value.toUpperCase()))],["lower",new Ze(()=>new fe(this.value.toLowerCase()))],["strip",new Ze(()=>new fe(this.value.trim()))],["title",new Ze(()=>new fe(Te(this.value)))],["capitalize",new Ze(()=>new fe(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new ge(this.value.length)],["rstrip",new Ze(()=>new fe(this.value.trimEnd()))],["lstrip",new Ze(()=>new fe(this.value.trimStart()))],["startswith",new Ze(C=>{if(C.length===0)throw new Error("startswith() requires at least one argument");const q=C[0];if(q instanceof fe)return new Pe(this.value.startsWith(q.value));if(q instanceof Re){for(const R of q.value){if(!(R instanceof fe))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(R.value))return new Pe(!0)}return new Pe(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new Ze(C=>{if(C.length===0)throw new Error("endswith() requires at least one argument");const q=C[0];if(q instanceof fe)return new Pe(this.value.endsWith(q.value));if(q instanceof Re){for(const R of q.value){if(!(R instanceof fe))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(R.value))return new Pe(!0)}return new Pe(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new Ze(C=>{const q=C[0]??new je;if(!(q instanceof fe||q instanceof je))throw new Error("sep argument must be a string or null");const R=C[1]??new ge(-1);if(!(R instanceof ge))throw new Error("maxsplit argument must be a number");let G=[];if(q instanceof je){const Z=this.value.trimStart();for(const{0:ce,index:ye}of Z.matchAll(/\S+/g)){if(R.value!==-1&&G.length>=R.value&&ye!==void 0){G.push(ce+Z.slice(ye+ce.length));break}G.push(ce)}}else{if(q.value==="")throw new Error("empty separator");G=this.value.split(q.value),R.value!==-1&&G.length>R.value&&G.push(G.splice(R.value).join(q.value))}return new Re(G.map(Z=>new fe(Z)))})],["replace",new Ze(C=>{if(C.length<2)throw new Error("replace() requires at least two arguments");const q=C[0],R=C[1];if(!(q instanceof fe&&R instanceof fe))throw new Error("replace() arguments must be strings");let G;if(C.length>2?C[2].type==="KeywordArgumentsValue"?G=C[2].value.get("count")??new je:G=C[2]:G=new je,!(G instanceof ge||G instanceof je))throw new Error("replace() count argument must be a number or null");return new fe(be(this.value,q.value,R.value,G.value))})]])},Pe=class extends Ce{type="BooleanValue"};function We(C,q,R,G=!0){const Z=R??0;switch(C.type){case"NullValue":return"null";case"UndefinedValue":return G?"null":"undefined";case"IntegerValue":case"FloatValue":case"StringValue":case"BooleanValue":return JSON.stringify(C.value);case"ArrayValue":case"ObjectValue":{const ce=q?" ".repeat(q):"",ye=` `+ce.repeat(Z),et=ye+ce;if(C.type==="ArrayValue"){const ut=C.value.map(He=>We(He,q,Z+1,G));return q?`[${et}${ut.join(`,${et}`)}${ye}]`:`[${ut.join(", ")}]`}else{const ut=Array.from(C.value.entries()).map(([He,Mt])=>{const qe=`"${He}": ${We(Mt,q,Z+1,G)}`;return q?`${et}${qe}`:qe});return q?`{${ut.join(",")}${ye}}`:`{${ut.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${C.type}`)}}var Fe=class extends Ce{type="ObjectValue";__bool__(){return new Pe(this.value.size>0)}builtins=new Map([["get",new Ze(([C,q])=>{if(!(C instanceof fe))throw new Error(`Object key must be a string: got ${C.type}`);return this.value.get(C.value)??q??new je})],["items",new Ze(()=>this.items())],["keys",new Ze(()=>this.keys())],["values",new Ze(()=>this.values())],["dictsort",new Ze(C=>{let q=new Map;const R=C.filter(et=>et instanceof tt?(q=et.value,!1):!0),G=R.at(0)??q.get("case_sensitive")??new Pe(!1);if(!(G instanceof Pe))throw new Error("case_sensitive must be a boolean");const Z=R.at(1)??q.get("by")??new fe("key");if(!(Z instanceof fe))throw new Error("by must be a string");if(!["key","value"].includes(Z.value))throw new Error("by must be either 'key' or 'value'");const ce=R.at(2)??q.get("reverse")??new Pe(!1);if(!(ce instanceof Pe))throw new Error("reverse must be a boolean");const ye=Array.from(this.value.entries()).map(([et,ut])=>new Re([new fe(et),ut])).sort((et,ut)=>{const He=Z.value==="key"?0:1,Mt=et.value[He],qe=ut.value[He],Pt=kt(Mt,qe,G.value);return ce.value?-Pt:Pt});return new Re(ye)})]]);items(){return new Re(Array.from(this.value.entries()).map(([C,q])=>new Re([new fe(C),q])))}keys(){return new Re(Array.from(this.value.keys()).map(C=>new fe(C)))}values(){return new Re(Array.from(this.value.values()))}toString(){return We(this,null,0,!1)}},tt=class extends Fe{type="KeywordArgumentsValue"},Re=class extends Ce{type="ArrayValue";builtins=new Map([["length",new ge(this.value.length)]]);__bool__(){return new Pe(this.value.length>0)}toString(){return We(this,null,0,!1)}},rt=class extends Re{type="TupleValue"},Ze=class extends Ce{type="FunctionValue"},je=class extends Ce{type="NullValue"},Oe=class extends Ce{type="UndefinedValue"},at=class{constructor(C){this.parent=C}variables=new Map([["namespace",new Ze(C=>{if(C.length===0)return new Fe(new Map);if(C.length!==1||!(C[0]instanceof Fe))throw new Error("`namespace` expects either zero arguments or a single object argument");return C[0]})]]);tests=new Map([["boolean",C=>C.type==="BooleanValue"],["callable",C=>C instanceof Ze],["odd",C=>{if(!(C instanceof ge))throw new Error(`cannot odd on ${C.type}`);return C.value%2!==0}],["even",C=>{if(!(C instanceof ge))throw new Error(`cannot even on ${C.type}`);return C.value%2===0}],["false",C=>C.type==="BooleanValue"&&!C.value],["true",C=>C.type==="BooleanValue"&&C.value],["none",C=>C.type==="NullValue"],["string",C=>C.type==="StringValue"],["number",C=>C instanceof ge||C instanceof De],["integer",C=>C instanceof ge],["iterable",C=>C.type==="ArrayValue"||C.type==="StringValue"],["mapping",C=>C.type==="ObjectValue"],["lower",C=>{const q=C.value;return C.type==="StringValue"&&q===q.toLowerCase()}],["upper",C=>{const q=C.value;return C.type==="StringValue"&&q===q.toUpperCase()}],["none",C=>C.type==="NullValue"],["defined",C=>C.type!=="UndefinedValue"],["undefined",C=>C.type==="UndefinedValue"],["equalto",(C,q)=>C.value===q.value],["eq",(C,q)=>C.value===q.value]]);set(C,q){return this.declareVariable(C,Or(q))}declareVariable(C,q){if(this.variables.has(C))throw new SyntaxError(`Variable already declared: ${C}`);return this.variables.set(C,q),q}setVariable(C,q){return this.variables.set(C,q),q}resolve(C){if(this.variables.has(C))return this;if(this.parent)return this.parent.resolve(C);throw new Error(`Unknown variable: ${C}`)}lookupVariable(C){try{return this.resolve(C).variables.get(C)??new Oe}catch{return new Oe}}};function ht(C){C.set("false",!1),C.set("true",!0),C.set("none",null),C.set("raise_exception",q=>{throw new Error(q)}),C.set("range",ke),C.set("strftime_now",Q),C.set("True",!0),C.set("False",!1),C.set("None",null)}function Nt(C,q){const R=q.split(".");let G=C;for(const Z of R)if(G instanceof Fe)G=G.value.get(Z)??new Oe;else if(G instanceof Re){const ce=parseInt(Z,10);if(!isNaN(ce)&&ce>=0&&cece instanceof ge||ce instanceof De||ce instanceof Pe,Z=ce=>ce instanceof Pe?ce.value?1:0:ce.value;if(G(C)&&G(q)){const ce=Z(C),ye=Z(q);return ceye?1:0}if(C.type!==q.type)throw new Error(`Cannot compare different types: ${C.type} and ${q.type}`);if(C.type==="StringValue"){let ce=C.value,ye=q.value;return R||(ce=ce.toLowerCase(),ye=ye.toLowerCase()),ceye?1:0}else throw new Error(`Cannot compare type: ${C.type}`)}var gr=class{global;constructor(C){this.global=C??new at}run(C){return this.evaluate(C,this.global)}evaluateBinaryExpression(C,q){const R=this.evaluate(C.left,q);switch(C.operator.value){case"and":return R.__bool__().value?this.evaluate(C.right,q):R;case"or":return R.__bool__().value?R:this.evaluate(C.right,q)}const G=this.evaluate(C.right,q);switch(C.operator.value){case"==":return new Pe(R.value==G.value);case"!=":return new Pe(R.value!=G.value)}if(R instanceof Oe||G instanceof Oe){if(G instanceof Oe&&["in","not in"].includes(C.operator.value))return new Pe(C.operator.value==="not in");throw new Error(`Cannot perform operation ${C.operator.value} on undefined values`)}else{if(R instanceof je||G instanceof je)throw new Error("Cannot perform operation on null values");if(C.operator.value==="~")return new fe(R.value.toString()+G.value.toString());if((R instanceof ge||R instanceof De)&&(G instanceof ge||G instanceof De)){const Z=R.value,ce=G.value;switch(C.operator.value){case"+":case"-":case"*":{const ye=C.operator.value==="+"?Z+ce:C.operator.value==="-"?Z-ce:Z*ce;return R instanceof De||G instanceof De?new De(ye):new ge(ye)}case"/":return new De(Z/ce);case"%":{const ye=Z%ce;return R instanceof De||G instanceof De?new De(ye):new ge(ye)}case"<":return new Pe(Z":return new Pe(Z>ce);case">=":return new Pe(Z>=ce);case"<=":return new Pe(Z<=ce)}}else if(R instanceof Re&&G instanceof Re){if(C.operator.value==="+")return new Re(R.value.concat(G.value))}else if(G instanceof Re){const Z=G.value.find(ce=>ce.value===R.value)!==void 0;switch(C.operator.value){case"in":return new Pe(Z);case"not in":return new Pe(!Z)}}}if((R instanceof fe||G instanceof fe)&&C.operator.value==="+")return new fe(R.value.toString()+G.value.toString());if(R instanceof fe&&G instanceof fe)switch(C.operator.value){case"in":return new Pe(G.value.includes(R.value));case"not in":return new Pe(!G.value.includes(R.value))}if(R instanceof fe&&G instanceof Fe)switch(C.operator.value){case"in":return new Pe(G.value.has(R.value));case"not in":return new Pe(!G.value.has(R.value))}throw new SyntaxError(`Unknown operator "${C.operator.value}" between ${R.type} and ${G.type}`)}evaluateArguments(C,q){const R=[],G=new Map;for(const Z of C)if(Z.type==="SpreadExpression"){const ce=Z,ye=this.evaluate(ce.argument,q);if(!(ye instanceof Re))throw new Error(`Cannot unpack non-iterable type: ${ye.type}`);for(const et of ye.value)R.push(et)}else if(Z.type==="KeywordArgumentExpression"){const ce=Z;G.set(ce.key.value,this.evaluate(ce.value,q))}else{if(G.size>0)throw new Error("Positional arguments must come before keyword arguments");R.push(this.evaluate(Z,q))}return[R,G]}applyFilter(C,q,R){if(q.type==="Identifier"){const G=q;if(G.value==="tojson")return new fe(We(C));if(C instanceof Re)switch(G.value){case"list":return C;case"first":return C.value[0];case"last":return C.value[C.value.length-1];case"length":return new ge(C.value.length);case"reverse":return new Re(C.value.slice().reverse());case"sort":return new Re(C.value.slice().sort((Z,ce)=>kt(Z,ce,!1)));case"join":return new fe(C.value.map(Z=>Z.value).join(""));case"string":return new fe(We(C,null,0,!1));case"unique":{const Z=new Set,ce=[];for(const ye of C.value)Z.has(ye.value)||(Z.add(ye.value),ce.push(ye));return new Re(ce)}default:throw new Error(`Unknown ArrayValue filter: ${G.value}`)}else if(C instanceof fe)switch(G.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const Z=C.builtins.get(G.value);if(Z instanceof Ze)return Z.value([],R);if(Z instanceof ge)return Z;throw new Error(`Unknown StringValue filter: ${G.value}`)}case"trim":return new fe(C.value.trim());case"indent":return new fe(C.value.split(` `).map((Z,ce)=>ce===0||Z.length===0?Z:" "+Z).join(` `));case"join":case"string":return C;case"int":{const Z=parseInt(C.value,10);return new ge(isNaN(Z)?0:Z)}case"float":{const Z=parseFloat(C.value);return new De(isNaN(Z)?0:Z)}default:throw new Error(`Unknown StringValue filter: ${G.value}`)}else if(C instanceof ge||C instanceof De)switch(G.value){case"abs":return C instanceof ge?new ge(Math.abs(C.value)):new De(Math.abs(C.value));case"int":return new ge(Math.floor(C.value));case"float":return new De(C.value);default:throw new Error(`Unknown NumericValue filter: ${G.value}`)}else if(C instanceof Fe)switch(G.value){case"items":return new Re(Array.from(C.value.entries()).map(([Z,ce])=>new Re([new fe(Z),ce])));case"length":return new ge(C.value.size);default:{const Z=C.builtins.get(G.value);if(Z)return Z instanceof Ze?Z.value([],R):Z;throw new Error(`Unknown ObjectValue filter: ${G.value}`)}}else if(C instanceof Pe)switch(G.value){case"bool":return new Pe(C.value);case"int":return new ge(C.value?1:0);case"float":return new De(C.value?1:0);case"string":return new fe(C.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${G.value}`)}throw new Error(`Cannot apply filter "${G.value}" to type: ${C.type}`)}else if(q.type==="CallExpression"){const G=q;if(G.callee.type!=="Identifier")throw new Error(`Unknown filter: ${G.callee.type}`);const Z=G.callee.value;if(Z==="tojson"){const[,ce]=this.evaluateArguments(G.args,R),ye=ce.get("indent")??new je;if(!(ye instanceof ge||ye instanceof je))throw new Error("If set, indent must be a number");return new fe(We(C,ye.value))}else if(Z==="join"){let ce;if(C instanceof fe)ce=Array.from(C.value);else if(C instanceof Re)ce=C.value.map(He=>He.value);else throw new Error(`Cannot apply filter "${Z}" to type: ${C.type}`);const[ye,et]=this.evaluateArguments(G.args,R),ut=ye.at(0)??et.get("separator")??new fe("");if(!(ut instanceof fe))throw new Error("separator must be a string");return new fe(ce.join(ut.value))}else if(Z==="int"||Z==="float"){const[ce,ye]=this.evaluateArguments(G.args,R),et=ce.at(0)??ye.get("default")??(Z==="int"?new ge(0):new De(0));if(C instanceof fe){const ut=Z==="int"?parseInt(C.value,10):parseFloat(C.value);return isNaN(ut)?et:Z==="int"?new ge(ut):new De(ut)}else{if(C instanceof ge||C instanceof De)return C;if(C instanceof Pe)return Z==="int"?new ge(C.value?1:0):new De(C.value?1:0);throw new Error(`Cannot apply filter "${Z}" to type: ${C.type}`)}}else if(Z==="default"){const[ce,ye]=this.evaluateArguments(G.args,R),et=ce[0]??new fe(""),ut=ce[1]??ye.get("boolean")??new Pe(!1);if(!(ut instanceof Pe))throw new Error("`default` filter flag must be a boolean");return C instanceof Oe||ut.value&&!C.__bool__().value?et:C}if(C instanceof Re){switch(Z){case"sort":{const[ce,ye]=this.evaluateArguments(G.args,R),et=ce.at(0)??ye.get("reverse")??new Pe(!1);if(!(et instanceof Pe))throw new Error("reverse must be a boolean");const ut=ce.at(1)??ye.get("case_sensitive")??new Pe(!1);if(!(ut instanceof Pe))throw new Error("case_sensitive must be a boolean");const He=ce.at(2)??ye.get("attribute")??new je;if(!(He instanceof fe||He instanceof ge||He instanceof je))throw new Error("attribute must be a string, integer, or null");const Mt=qe=>{if(He instanceof je)return qe;const Pt=He instanceof ge?String(He.value):He.value;return Nt(qe,Pt)};return new Re(C.value.slice().sort((qe,Pt)=>{const It=Mt(qe),Mr=Mt(Pt),pr=kt(It,Mr,ut.value);return et.value?-pr:pr}))}case"selectattr":case"rejectattr":{const ce=Z==="selectattr";if(C.value.some(qe=>!(qe instanceof Fe)))throw new Error(`\`${Z}\` can only be applied to array of objects`);if(G.args.some(qe=>qe.type!=="StringLiteral"))throw new Error(`arguments of \`${Z}\` must be strings`);const[ye,et,ut]=G.args.map(qe=>this.evaluate(qe,R));let He;if(et){const qe=R.tests.get(et.value);if(!qe)throw new Error(`Unknown test: ${et.value}`);He=qe}else He=(...qe)=>qe[0].__bool__().value;const Mt=C.value.filter(qe=>{const Pt=qe.value.get(ye.value),It=Pt?He(Pt,ut):!1;return ce?It:!It});return new Re(Mt)}case"map":{const[,ce]=this.evaluateArguments(G.args,R);if(ce.has("attribute")){const ye=ce.get("attribute");if(!(ye instanceof fe))throw new Error("attribute must be a string");const et=ce.get("default"),ut=C.value.map(He=>{if(!(He instanceof Fe))throw new Error("items in map must be an object");const Mt=Nt(He,ye.value);return Mt instanceof Oe?et??new Oe:Mt});return new Re(ut)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${Z}`)}else if(C instanceof fe){switch(Z){case"indent":{const[ce,ye]=this.evaluateArguments(G.args,R),et=ce.at(0)??ye.get("width")??new ge(4);if(!(et instanceof ge))throw new Error("width must be a number");const ut=ce.at(1)??ye.get("first")??new Pe(!1),He=ce.at(2)??ye.get("blank")??new Pe(!1),Mt=C.value.split(` `),qe=" ".repeat(et.value),Pt=Mt.map((It,Mr)=>!ut.value&&Mr===0||!He.value&&It.length===0?It:qe+It);return new fe(Pt.join(` `))}case"replace":{const ce=C.builtins.get("replace");if(!(ce instanceof Ze))throw new Error("replace filter not available");const[ye,et]=this.evaluateArguments(G.args,R);return ce.value([...ye,new tt(et)],R)}}throw new Error(`Unknown StringValue filter: ${Z}`)}else if(C instanceof Fe){const ce=C.builtins.get(Z);if(ce&&ce instanceof Ze){const[ye,et]=this.evaluateArguments(G.args,R);return et.size>0&&ye.push(new tt(et)),ce.value(ye,R)}throw new Error(`Unknown ObjectValue filter: ${Z}`)}else throw new Error(`Cannot apply filter "${Z}" to type: ${C.type}`)}throw new Error(`Unknown filter: ${q.type}`)}evaluateFilterExpression(C,q){const R=this.evaluate(C.operand,q);return this.applyFilter(R,C.filter,q)}evaluateTestExpression(C,q){const R=this.evaluate(C.operand,q),G=q.tests.get(C.test.value);if(!G)throw new Error(`Unknown test: ${C.test.value}`);const Z=G(R);return new Pe(C.negate?!Z:Z)}evaluateSelectExpression(C,q){return this.evaluate(C.test,q).__bool__().value?this.evaluate(C.lhs,q):new Oe}evaluateUnaryExpression(C,q){const R=this.evaluate(C.argument,q);if(C.operator.value==="not")return new Pe(!R.value);throw new SyntaxError(`Unknown operator: ${C.operator.value}`)}evaluateTernaryExpression(C,q){return this.evaluate(C.condition,q).__bool__().value?this.evaluate(C.trueExpr,q):this.evaluate(C.falseExpr,q)}evalProgram(C,q){return this.evaluateBlock(C.body,q)}evaluateBlock(C,q){let R="";for(const G of C){const Z=this.evaluate(G,q);Z.type!=="NullValue"&&Z.type!=="UndefinedValue"&&(R+=Z.toString())}return new fe(R)}evaluateIdentifier(C,q){return q.lookupVariable(C.value)}evaluateCallExpression(C,q){const[R,G]=this.evaluateArguments(C.args,q);G.size>0&&R.push(new tt(G));const Z=this.evaluate(C.callee,q);if(Z.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${Z.type}`);return Z.value(R,q)}evaluateSliceExpression(C,q,R){if(!(C instanceof Re||C instanceof fe))throw new Error("Slice object must be an array or string");const G=this.evaluate(q.start,R),Z=this.evaluate(q.stop,R),ce=this.evaluate(q.step,R);if(!(G instanceof ge||G instanceof Oe))throw new Error("Slice start must be numeric or undefined");if(!(Z instanceof ge||Z instanceof Oe))throw new Error("Slice stop must be numeric or undefined");if(!(ce instanceof ge||ce instanceof Oe))throw new Error("Slice step must be numeric or undefined");return C instanceof Re?new Re(Ve(C.value,G.value,Z.value,ce.value)):new fe(Ve(Array.from(C.value),G.value,Z.value,ce.value).join(""))}evaluateMemberExpression(C,q){const R=this.evaluate(C.object,q);let G;if(C.computed){if(C.property.type==="SliceExpression")return this.evaluateSliceExpression(R,C.property,q);G=this.evaluate(C.property,q)}else G=new fe(C.property.value);let Z;if(R instanceof Fe){if(!(G instanceof fe))throw new Error(`Cannot access property with non-string: got ${G.type}`);Z=R.value.get(G.value)??R.builtins.get(G.value)}else if(R instanceof Re||R instanceof fe)if(G instanceof ge)Z=R.value.at(G.value),R instanceof fe&&(Z=new fe(R.value.at(G.value)));else if(G instanceof fe)Z=R.builtins.get(G.value);else throw new Error(`Cannot access property with non-string/non-number: got ${G.type}`);else{if(!(G instanceof fe))throw new Error(`Cannot access property with non-string: got ${G.type}`);Z=R.builtins.get(G.value)}return Z instanceof Ce?Z:new Oe}evaluateSet(C,q){const R=C.value?this.evaluate(C.value,q):this.evaluateBlock(C.body,q);if(C.assignee.type==="Identifier"){const G=C.assignee.value;q.setVariable(G,R)}else if(C.assignee.type==="TupleLiteral"){const G=C.assignee;if(!(R instanceof Re))throw new Error(`Cannot unpack non-iterable type in set: ${R.type}`);const Z=R.value;if(Z.length!==G.value.length)throw new Error(`Too ${G.value.length>Z.length?"few":"many"} items to unpack in set`);for(let ce=0;ceIt.setVariable(C.loopvar.value,qe);else if(C.loopvar.type==="TupleLiteral"){const It=C.loopvar;if(qe.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${qe.type}`);const Mr=qe;if(It.value.length!==Mr.value.length)throw new Error(`Too ${It.value.length>Mr.value.length?"few":"many"} items to unpack`);Pt=pr=>{for(let ir=0;ir0?ce[He-1]:new Oe],["nextitem",He{const Z=new at(G);R=R.slice();let ce;R.at(-1)?.type==="KeywordArgumentsValue"&&(ce=R.pop());for(let ye=0;ye{const He=new at(ut);if(C.callerArgs)for(let Mt=0;Mtthis.evaluate(R,q)));case"TupleLiteral":return new rt(C.value.map(R=>this.evaluate(R,q)));case"ObjectLiteral":{const R=new Map;for(const[G,Z]of C.value){const ce=this.evaluate(G,q);if(!(ce instanceof fe))throw new Error(`Object keys must be strings: got ${ce.type}`);R.set(ce.value,this.evaluate(Z,q))}return new Fe(R)}case"Identifier":return this.evaluateIdentifier(C,q);case"CallExpression":return this.evaluateCallExpression(C,q);case"MemberExpression":return this.evaluateMemberExpression(C,q);case"UnaryExpression":return this.evaluateUnaryExpression(C,q);case"BinaryExpression":return this.evaluateBinaryExpression(C,q);case"FilterExpression":return this.evaluateFilterExpression(C,q);case"FilterStatement":return this.evaluateFilterStatement(C,q);case"TestExpression":return this.evaluateTestExpression(C,q);case"SelectExpression":return this.evaluateSelectExpression(C,q);case"Ternary":return this.evaluateTernaryExpression(C,q);case"Comment":return new je;default:throw new SyntaxError(`Unknown node type: ${C.type}`)}}};function Or(C){switch(typeof C){case"number":return Number.isInteger(C)?new ge(C):new De(C);case"string":return new fe(C);case"boolean":return new Pe(C);case"undefined":return new Oe;case"object":return C===null?new je:Array.isArray(C)?new Re(C.map(Or)):new Fe(new Map(Object.entries(C).map(([q,R])=>[q,Or(R)])));case"function":return new Ze((q,R)=>{const G=C(...q.map(Z=>Z.value))??null;return Or(G)});default:throw new Error(`Cannot convert to runtime value: ${C}`)}}var Bt=` `,jr="{%- ",Qs=" -%}";function Xs(C){switch(C.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return C.operator.value==="and"?1:C.operator.value==="in"||C.operator.value==="not in"?2:0}return 0}function Js(C,q=" "){const R=typeof q=="number"?" ".repeat(q):q;return kr(C.body,0,R).replace(/\n$/,"")}function ar(...C){return jr+C.join(" ")+Qs}function kr(C,q,R){return C.map(G=>Jr(G,q,R)).join(Bt)}function Jr(C,q,R){const G=R.repeat(q);switch(C.type){case"Program":return kr(C.body,q,R);case"If":return Bs(C,q,R);case"For":return ft(C,q,R);case"Set":return qt(C,q,R);case"Macro":return Ts(C,q,R);case"Break":return G+ar("break");case"Continue":return G+ar("continue");case"CallStatement":return Ps(C,q,R);case"FilterStatement":return Gr(C,q,R);case"Comment":return G+"{# "+C.value+" #}";default:return G+"{{- "+yt(C)+" -}}"}}function Bs(C,q,R){const G=R.repeat(q),Z=[];let ce=C;for(;ce&&(Z.push({test:ce.test,body:ce.body}),ce.alternate.length===1&&ce.alternate[0].type==="If");)ce=ce.alternate[0];let ye=G+ar("if",yt(Z[0].test))+Bt+kr(Z[0].body,q+1,R);for(let et=1;et0&&(ye+=Bt+G+ar("else")+Bt+kr(ce.alternate,q+1,R)),ye+=Bt+G+ar("endif"),ye}function ft(C,q,R){const G=R.repeat(q);let Z="";if(C.iterable.type==="SelectExpression"){const ye=C.iterable;Z=`${yt(ye.lhs)} if ${yt(ye.test)}`}else Z=yt(C.iterable);let ce=G+ar("for",yt(C.loopvar),"in",Z)+Bt+kr(C.body,q+1,R);return C.defaultBlock.length>0&&(ce+=Bt+G+ar("else")+Bt+kr(C.defaultBlock,q+1,R)),ce+=Bt+G+ar("endfor"),ce}function qt(C,q,R){const G=R.repeat(q),Z=yt(C.assignee),ce=C.value?yt(C.value):"",ye=G+ar("set",`${Z}${C.value?" = "+ce:""}`);return C.body.length===0?ye:ye+Bt+kr(C.body,q+1,R)+Bt+G+ar("endset")}function Ts(C,q,R){const G=R.repeat(q),Z=C.args.map(yt).join(", ");return G+ar("macro",`${C.name.value}(${Z})`)+Bt+kr(C.body,q+1,R)+Bt+G+ar("endmacro")}function Ps(C,q,R){const G=R.repeat(q),Z=C.callerArgs&&C.callerArgs.length>0?`(${C.callerArgs.map(yt).join(", ")})`:"",ce=yt(C.call);let ye=G+ar(`call${Z}`,ce)+Bt;return ye+=kr(C.body,q+1,R)+Bt,ye+=G+ar("endcall"),ye}function Gr(C,q,R){const G=R.repeat(q),Z=C.filter.type==="Identifier"?C.filter.value:yt(C.filter);let ce=G+ar("filter",Z)+Bt;return ce+=kr(C.body,q+1,R)+Bt,ce+=G+ar("endfilter"),ce}function yt(C,q=-1){switch(C.type){case"SpreadExpression":return`*${yt(C.argument)}`;case"Identifier":return C.value;case"IntegerLiteral":return`${C.value}`;case"FloatLiteral":return`${C.value}`;case"StringLiteral":return JSON.stringify(C.value);case"BinaryExpression":{const R=C,G=Xs(R),Z=yt(R.left,G),ce=yt(R.right,G+1),ye=`${Z} ${R.operator.value} ${ce}`;return G`${yt(G)}: ${yt(Z)}`).join(", ")}}`;case"SliceExpression":{const R=C,G=R.start?yt(R.start):"",Z=R.stop?yt(R.stop):"",ce=R.step?`:${yt(R.step)}`:"";return`${G}:${Z}${ce}`}case"KeywordArgumentExpression":{const R=C;return`${R.key.value}=${yt(R.value)}`}case"Ternary":{const R=C,G=`${yt(R.trueExpr)} if ${yt(R.condition,0)} else ${yt(R.falseExpr)}`;return q>-1?`(${G})`:G}default:throw new Error(`Unknown expression type: ${C.type}`)}}var Es=class{parsed;constructor(C){const q=d(C,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Ae(q)}render(C){const q=new at;if(ht(q),C)for(const[Z,ce]of Object.entries(C))q.set(Z,ce);return new gr(q).run(this.parsed).value}format(C){return Js(this.parsed,C?.indent||" ")}}}),"./src/backends/onnx.js":((e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>I,deviceToExecutionProviders:()=>_,isONNXProxy:()=>P,isONNXTensor:()=>T,runInferenceSession:()=>k});var n=t("./src/env.js"),o=t("?2ce3"),i=t("onnxruntime-web"),a=t("onnxruntime-common");const l=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),c=[];let p,d;const u=Symbol.for("onnxruntime");if(u in globalThis)d=globalThis[u];else if(n.apis.IS_NODE_ENV){switch(d=o??(s||(s=t.t(o,2))),process.platform){case"win32":c.push("dml");break;case"linux":process.arch==="x64"&&c.push("cuda");break}c.push("cpu"),p=["cpu"]}else d=i,n.apis.IS_WEBNN_AVAILABLE&&c.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),n.apis.IS_WEBGPU_AVAILABLE&&c.push("webgpu"),c.push("wasm"),p=["wasm"];const f=d.InferenceSession;function _(x=null){if(!x)return p;switch(x){case"auto":return c;case"gpu":return c.filter(S=>["webgpu","cuda","dml","webnn-gpu"].includes(S))}if(c.includes(x))return[l[x]??x];throw new Error(`Unsupported device: "${x}". Should be one of: ${c.join(", ")}.`)}let y=null;async function I(x,S,O){y&&await y;const F=f.create(x,S);y??=F;const H=await F;return H.config=O,H}let w=Promise.resolve();const v=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;async function k(x,S){const O=()=>x.run(S);return await(v?w=w.then(O):O())}function T(x){return x instanceof d.Tensor}const b=d?.env;b?.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!b.wasm.wasmPaths&&(b.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${n.env.version}/dist/`),b.wasm.proxy=!1),b?.webgpu&&(b.webgpu.powerPreference="high-performance");function P(){return b?.wasm?.proxy}n.env.backends.onnx=b}),"./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"),n=t("./src/utils/generic.js"),o=t("./src/utils/hub.js");class i extends n.Callable{constructor(c){super(),this.config=c}static async from_pretrained(c,p={}){const d=await(0,o.getModelJSON)(c,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(d)}}function a(l,c){if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${c} expects input to be a Float32Array or a Float64Array, but got ${l?.constructor?.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:()=>T,center_to_corners_format:()=>d,post_process_instance_segmentation:()=>k,post_process_object_detection:()=>u,post_process_panoptic_segmentation:()=>v,post_process_semantic_segmentation:()=>f});var s=t("./src/utils/generic.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");t("./src/utils/image.js");var i=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function c(b,P,x=0,S=null){const O=b/P;let F=(0,o.bankers_round)(O)*P;return S!==null&&F>S&&(F=Math.floor(O)*P),FP&&K.push(D)}else{let D=(0,o.max)(oe.data)[1];if(D===B-1||(j=(0,o.softmax)(oe.data),j[D]he*J[(Ae+1)%2])),re.boxes.push(te),re.classes.push(D),re.scores.push(j[D])}}Y.push(re)}return Y}function f(b,P=null){const x=b.logits,S=x.dims[0];if(P!==null&&P.length!==S)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const O=[];for(let F=0;FJ[K]&&(J[K]=oe[K],re[K]=pe)}const ne=new Array(W.dims[0]);for(let pe=0;pepe!==void 0);O.push({segmentation:X,labels:le})}return O}function _(b,P,x,S){const O=[],F=[],H=[];for(let W=0;Wx&&(O.push(Y),F.push(re),H.push(X))}return[O,F,H]}function y(b,P,x,S=.5,O=.8){const F=[];let H=0,W=0;const B=P[x].data;for(let X=0;X=S&&++W;let Y=H>0&&W>0;return Y&&(Y=H/W>O),[Y,F]}function I(b,P,x,S,O,F=null,H=null){const[W,B]=H??b[0].dims,Y=new n.Tensor("int32",new Int32Array(W*B),[W,B]),X=[];if(H!==null)for(let pe=0;pere[j]&&(J[j]=pe,re[j]=K[j])}let ne=0;const le=Y.data;for(let pe=0;pe200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(b,P)/Math.min(b,P)}`);let F=Math.round(b/x)*x,H=Math.round(P/x)*x;if(F*H>O){const W=Math.sqrt(b*P/O);F=Math.floor(b/W/x)*x,H=Math.floor(P/W/x)*x}else if(F*HF?Y=Math.floor(F*B/O):F>O&&(B=Math.floor(O*Y/F)),await P.resize(Y,B,{resample:S}))}async crop_margin(P,x=200){const S=P.clone().grayscale(),O=(0,o.min)(S.data)[0],H=(0,o.max)(S.data)[0]-O;if(H===0)return P;const W=x/255;let B=S.width,Y=S.height,X=0,J=0;const re=S.data;for(let ne=0;nethis.preprocess(F)));return{pixel_values:(0,n.stack)(S.map(F=>F.pixel_values),0),original_sizes:S.map(F=>F.original_size),reshaped_input_sizes:S.map(F=>F.reshaped_input_size)}}static async from_pretrained(P,x={}){const S=await(0,a.getModelJSON)(P,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"),n=t("./src/utils/generic.js"),o=t("./src/utils/hub.js");class i extends n.Callable{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(l,c,p){super(),this.config=l,this.components=c,this.chat_template=p}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(l,c={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,chat_template:this.chat_template??void 0,...c})}batch_decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...l)}decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...l)}async _call(l,...c){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...c);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,c={}){const[p,d,u]=await Promise.all([this.uses_processor_config?(0,o.getModelJSON)(l,s.PROCESSOR_NAME,!0,c):{},Promise.all(this.classes.filter(f=>f in this).map(async f=>{const _=await this[f].from_pretrained(l,c);return[f.replace(/_class$/,""),_]})).then(Object.fromEntries),this.uses_chat_template_file?(0,o.getModelText)(l,s.CHAT_TEMPLATE_NAME,!0,c):null]);return new this(p,d,u)}}}),"./src/configs.js":((e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>p,PretrainedConfig:()=>c,getCacheShapes:()=>a});var s=t("./src/utils/core.js"),n=t("./src/utils/hub.js");async function o(d,u){return await(0,n.getModelJSON)(d,"config.json",!0,u)}function i(d){const u={};let f={};switch(d.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"voxtral":case"smolvlm":case"gemma3n":case"mistral3":f=i(d.text_config);break;case"moondream1":f=i(d.phi_config);break;case"musicgen":f=i(d.decoder);break;case"multi_modality":f=i(d.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":u.num_heads="num_attention_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size";break;case"llama":case"llama4_text":case"nanochat":case"arcee":case"lfm2":case"smollm3":case"olmo":case"olmo2":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size",u.num_attention_heads="num_attention_heads",u.dim_kv="head_dim";break;case"qwen3":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"glm":case"helium":case"ernie4_5":case"ministral":case"ministral3":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.dim_kv="head_dim";break;case"openelm":u.num_heads="num_kv_heads",u.num_layers="num_transformer_layers",u.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":u.num_heads="num_heads",u.num_layers="num_layers",u.hidden_size="hidden_size";break;case"bloom":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="hidden_size";break;case"mpt":u.num_heads="n_heads",u.num_layers="n_layers",u.hidden_size="d_model";break;case"exaone":u.num_heads="num_key_value_heads",u.num_layers="num_layers",u.dim_kv="head_dim",u.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":u.num_decoder_layers="num_decoder_layers",u.num_decoder_heads="num_heads",u.decoder_dim_kv="d_kv",u.num_encoder_layers="num_layers",u.num_encoder_heads="num_heads",u.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="d_model",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="d_model";break;case"speecht5":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="hidden_size",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="hidden_size";break;case"trocr":u.num_encoder_layers=u.num_decoder_layers="decoder_layers",u.num_encoder_heads=u.num_decoder_heads="decoder_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="d_model";break;case"musicgen_decoder":u.num_encoder_layers=u.num_decoder_layers="num_hidden_layers",u.num_encoder_heads=u.num_decoder_heads="num_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"moonshine":u.num_decoder_layers="decoder_num_hidden_layers",u.num_decoder_heads="decoder_num_key_value_heads",u.num_encoder_layers="encoder_num_hidden_layers",u.num_encoder_heads="encoder_num_key_value_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const y=i(d.decoder),I="num_decoder_layers"in y,w=(0,s.pick)(d,["model_type","is_encoder_decoder"]);return I?(w.num_decoder_layers=y.num_decoder_layers,w.num_decoder_heads=y.num_decoder_heads,w.decoder_hidden_size=y.decoder_hidden_size,w.num_encoder_layers=y.num_encoder_layers,w.num_encoder_heads=y.num_encoder_heads,w.encoder_hidden_size=y.encoder_hidden_size):(w.num_layers=y.num_layers,w.num_heads=y.num_heads,w.hidden_size=y.hidden_size),w}const _={...f,...(0,s.pick)(d,["model_type","multi_query","is_encoder_decoder"])};for(const y in u)_[y]=d[u[y]];return _}function a(d,u){if(d.model_type==="lfm2"){const f=u?.prefix??"past_key_values",_=f==="present"?"present":"past",y={},{layer_types:I,num_attention_heads:w,num_key_value_heads:v,hidden_size:k,conv_L_cache:T}=d,b=k/w,P=u?.batch_size??1;for(let x=0;x{t.r(r),t.d(r,{apis:()=>w,env:()=>x});var s=t("?db59"),n=t("?383f"),o=t("?fa4b");const i="3.8.1",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),c=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,d=typeof navigator<"u"&&"ml"in navigator,u=typeof process<"u",f=u&&process?.release?.name==="node",_=!S(s),y=!S(n),I=typeof globalThis.Deno<"u",w=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:c,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:d,IS_PROCESS_AVAILABLE:u,IS_NODE_ENV:f,IS_FS_AVAILABLE:_,IS_PATH_AVAILABLE:y}),v=_&&y;let k="./";if(v){const O=Object({url:self.location.href}).url;O?k=n.dirname(n.dirname(o.fileURLToPath(O))):typeof __dirname<"u"&&(k=n.dirname(__dirname))}const T=v?n.join(k,"/.cache/"):null,b="/models/",P=v?n.join(k,b):b,x={version:i,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:P,useFS:_,useBrowserCache:c&&!I,useFSCache:_,cacheDir:T,useCustomCache:!1,customCache:null};function S(O){return Object.keys(O).length===0}}),"./src/generation/configuration_utils.js":((e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>n});var s=t("./src/utils/core.js");class n{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(i){Object.assign(this,(0,s.pick)(i,Object.getOwnPropertyNames(this)))}}}),"./src/generation/logits_process.js":((e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>w,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>c,LogitsProcessor:()=>o,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>_,MinNewTokensLengthLogitsProcessor:()=>y,NoBadWordsLogitsProcessor:()=>I,NoRepeatNGramLogitsProcessor:()=>u,RepetitionPenaltyLogitsProcessor:()=>f,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>v,TopKLogitsWarper:()=>T,TopPLogitsWarper:()=>k,WhisperTimeStampLogitsProcessor:()=>d});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var n=t("./src/utils/maths.js");class o extends s.Callable{_call(P,x){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(P,x){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(P){this.processors.push(P)}extend(P){this.processors.push(...P)}_call(P,x){let S=x;for(const O of this.processors)S=O(P,S);return S}[Symbol.iterator](){return this.processors.values()}}class l extends o{constructor(P){super(),this.bos_token_id=P}_call(P,x){for(let S=0;S=1&&F[F.length-1]>=this.timestamp_begin,W=F.length<2||F[F.length-2]>=this.timestamp_begin;if(H&&(W?O.subarray(this.timestamp_begin).fill(-1/0):O.subarray(0,this.eos_token_id).fill(-1/0)),P[S].length===this.begin_index&&this.max_initial_timestamp_index!==null){const J=this.timestamp_begin+this.max_initial_timestamp_index;O.subarray(J+1).fill(-1/0)}const B=(0,n.log_softmax)(O),Y=Math.log(B.subarray(this.timestamp_begin).map(Math.exp).reduce((J,re)=>J+re)),X=(0,n.max)(B.subarray(0,this.timestamp_begin))[0];Y>X&&O.subarray(0,this.timestamp_begin).fill(-1/0)}return x}}class u extends o{constructor(P){super(),this.no_repeat_ngram_size=P}getNgrams(P){const x=P.length,S=[];for(let F=0;F1 to use the classifier free guidance processor, got guidance scale ${P}.`);this.guidance_scale=P}_call(P,x){if(x.dims[0]!==2*P.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 ${P.length} for the input ids.`);const S=P.length,O=x.slice([0,S],null),F=x.slice([S,x.dims[0]],null);for(let H=0;H1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${P}`);if(!Number.isInteger(S)||S<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${S}`);this.top_p=P,this.filter_value=x,this.min_tokens_to_keep=S}}class T extends i{constructor(P,{filter_value:x=-1/0,min_tokens_to_keep:S=1}={}){if(super(),!Number.isInteger(P)||P<0)throw new Error(`\`top_k\` must be a positive integer, but is ${P}`);this.top_k=Math.max(P,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"),n=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class i extends s.Callable{constructor(d){super(),this.generation_config=d}async _call(d){return this.sample(d)}async sample(d){throw Error("sample should be implemented in subclasses.")}getLogits(d,u){let f=d.dims.at(-1),_=d.data;if(u===-1)_=_.slice(-f);else{let y=u*f;_=_.slice(y,y+f)}return _}randomSelect(d){let u=0;for(let _=0;_1)return new c(d);if(d.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${d.num_return_sequences}.`);return new a(d)}}class a extends i{async sample(d){const u=(0,o.max)(d.data)[1];return[[BigInt(u),0]]}}class l extends i{async sample(d){let u=d.dims.at(-1);this.generation_config.top_k>0&&(u=Math.min(this.generation_config.top_k,u));const[f,_]=await(0,n.topk)(d,u),y=(0,o.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},()=>{const I=this.randomSelect(y);return[_.data[I],Math.log(y[I])]})}}class c extends i{async sample(d){let u=d.dims.at(-1);this.generation_config.top_k>0&&(u=Math.min(this.generation_config.top_k,u));const[f,_]=await(0,n.topk)(d,u),y=(0,o.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},(I,w)=>[_.data[w],Math.log(y[w])])}}}),"./src/generation/stopping_criteria.js":((e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>i,StoppingCriteria:()=>n,StoppingCriteriaList:()=>o});var s=t("./src/utils/generic.js");class n extends s.Callable{_call(p,d){throw Error("StoppingCriteria needs to be subclassed")}}class o extends s.Callable{constructor(){super(),this.criteria=[]}push(p){this.criteria.push(p)}extend(p){p instanceof o?p=p.criteria:p instanceof n&&(p=[p]),this.criteria.push(...p)}_call(p,d){const u=new Array(p.length).fill(!1);for(const f of this.criteria){const _=f(p,d);for(let y=0;yd.length>=this.max_length)}}class a extends n{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,d){return p.map(u=>{const f=u.at(-1);return this.eos_token_id.some(_=>f==_)})}}class l extends n{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,d){return new Array(p.length).fill(this.interrupted)}}}),"./src/generation/streamers.js":((e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>i,TextStreamer:()=>l,WhisperTextStreamer:()=>c});var s=t("./src/utils/core.js"),n=t("./src/tokenizers.js"),o=t("./src/env.js");class i{put(d){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const a=o.apis.IS_PROCESS_AVAILABLE?p=>process.stdout.write(p):p=>console.log(p);class l extends i{constructor(d,{skip_prompt:u=!1,callback_function:f=null,token_callback_function:_=null,skip_special_tokens:y=!0,decode_kwargs:I={},...w}={}){super(),this.tokenizer=d,this.skip_prompt=u,this.callback_function=f??a,this.token_callback_function=_,this.decode_kwargs={skip_special_tokens:y,...I,...w},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(d){if(d.length>1)throw Error("TextStreamer only supports batch size of 1");const u=this.next_tokens_are_prompt;if(u&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const f=d[0];this.token_callback_function?.(f),this.token_cache=(0,s.mergeArrays)(this.token_cache,f);const _=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let y;u||_.endsWith(` `)?(y=_.slice(this.print_len),this.token_cache=[],this.print_len=0):_.length>0&&(0,n.is_chinese_char)(_.charCodeAt(_.length-1))?(y=_.slice(this.print_len),this.print_len+=y.length):(y=_.slice(this.print_len,_.lastIndexOf(" ")+1),this.print_len+=y.length),this.on_finalized_text(y,!1)}end(){let d;this.token_cache.length>0?(d=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):d="",this.next_tokens_are_prompt=!0,this.on_finalized_text(d,!0)}on_finalized_text(d,u){d.length>0&&this.callback_function?.(d),u&&this.callback_function===a&&o.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.(` `)}}class c extends l{constructor(d,{skip_prompt:u=!1,callback_function:f=null,token_callback_function:_=null,on_chunk_start:y=null,on_chunk_end:I=null,on_finalize:w=null,time_precision:v=.02,skip_special_tokens:k=!0,decode_kwargs:T={}}={}){super(d,{skip_prompt:u,skip_special_tokens:k,callback_function:f,token_callback_function:_,decode_kwargs:T}),this.timestamp_begin=d.timestamp_begin,this.on_chunk_start=y,this.on_chunk_end=I,this.on_finalize=w,this.time_precision=v,this.waiting_for_timestamp=!1}put(d){if(d.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const u=d[0];if(u.length===1){const f=Number(u[0])-this.timestamp_begin;if(f>=0){const _=f*this.time_precision;this.waiting_for_timestamp?this.on_chunk_end?.(_):this.on_chunk_start?.(_),this.waiting_for_timestamp=!this.waiting_for_timestamp,this.token_callback_function?.(u);return}}return super.put(d)}end(){super.end(),this.on_finalize?.()}}}),"./src/models.js":((e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>Ao,ASTModel:()=>Io,ASTPreTrainedModel:()=>$o,AlbertForMaskedLM:()=>Ke,AlbertForQuestionAnswering:()=>Ye,AlbertForSequenceClassification:()=>Je,AlbertModel:()=>Xe,AlbertPreTrainedModel:()=>$e,ArceeForCausalLM:()=>bM,ArceeModel:()=>wM,ArceePreTrainedModel:()=>gc,AutoModel:()=>VT,AutoModelForAudioClassification:()=>iP,AutoModelForAudioFrameClassification:()=>cP,AutoModelForAudioTextToText:()=>MP,AutoModelForCTC:()=>aP,AutoModelForCausalLM:()=>QT,AutoModelForDepthEstimation:()=>mP,AutoModelForDocumentQuestionAnswering:()=>uP,AutoModelForImageClassification:()=>ZT,AutoModelForImageFeatureExtraction:()=>fP,AutoModelForImageMatting:()=>dP,AutoModelForImageSegmentation:()=>eP,AutoModelForImageTextToText:()=>gP,AutoModelForImageToImage:()=>pP,AutoModelForMaskGeneration:()=>oP,AutoModelForMaskedLM:()=>XT,AutoModelForNormalEstimation:()=>hP,AutoModelForObjectDetection:()=>sP,AutoModelForPoseEstimation:()=>_P,AutoModelForQuestionAnswering:()=>JT,AutoModelForSemanticSegmentation:()=>tP,AutoModelForSeq2SeqLM:()=>GT,AutoModelForSequenceClassification:()=>UT,AutoModelForSpeechSeq2Seq:()=>KT,AutoModelForTextToSpectrogram:()=>HT,AutoModelForTextToWaveform:()=>qT,AutoModelForTokenClassification:()=>WT,AutoModelForUniversalSegmentation:()=>rP,AutoModelForVision2Seq:()=>YT,AutoModelForXVector:()=>lP,AutoModelForZeroShotObjectDetection:()=>nP,BartForConditionalGeneration:()=>Yt,BartForSequenceClassification:()=>hr,BartModel:()=>ws,BartPretrainedModel:()=>Pr,BaseModelOutput:()=>be,BeitForImageClassification:()=>Vw,BeitModel:()=>Nw,BeitPreTrainedModel:()=>Xc,BertForMaskedLM:()=>Ce,BertForQuestionAnswering:()=>fe,BertForSequenceClassification:()=>ge,BertForTokenClassification:()=>De,BertModel:()=>xe,BertPreTrainedModel:()=>ve,BlenderbotForConditionalGeneration:()=>_r,BlenderbotModel:()=>Zt,BlenderbotPreTrainedModel:()=>vr,BlenderbotSmallForConditionalGeneration:()=>Ys,BlenderbotSmallModel:()=>Ur,BlenderbotSmallPreTrainedModel:()=>cr,BloomForCausalLM:()=>uw,BloomModel:()=>cw,BloomPreTrainedModel:()=>Bc,CLIPModel:()=>Lo,CLIPPreTrainedModel:()=>Os,CLIPSegForImageSegmentation:()=>No,CLIPSegModel:()=>jo,CLIPSegPreTrainedModel:()=>En,CLIPTextModel:()=>Ka,CLIPTextModelWithProjection:()=>zo,CLIPVisionModel:()=>Ha,CLIPVisionModelWithProjection:()=>qa,CamembertForMaskedLM:()=>ce,CamembertForQuestionAnswering:()=>ut,CamembertForSequenceClassification:()=>ye,CamembertForTokenClassification:()=>et,CamembertModel:()=>Z,CamembertPreTrainedModel:()=>G,CausalLMOutput:()=>sn,CausalLMOutputWithPast:()=>bP,ChineseCLIPModel:()=>Ro,ChineseCLIPPreTrainedModel:()=>Qa,ClapAudioModelWithProjection:()=>o0,ClapModel:()=>s0,ClapPreTrainedModel:()=>ni,ClapTextModelWithProjection:()=>n0,CodeGenForCausalLM:()=>Be,CodeGenModel:()=>Ee,CodeGenPreTrainedModel:()=>ie,CohereForCausalLM:()=>VM,CohereModel:()=>NM,CoherePreTrainedModel:()=>Sc,ConvBertForMaskedLM:()=>ft,ConvBertForQuestionAnswering:()=>Ps,ConvBertForSequenceClassification:()=>qt,ConvBertForTokenClassification:()=>Ts,ConvBertModel:()=>Bs,ConvBertPreTrainedModel:()=>Jr,ConvNextForImageClassification:()=>Lb,ConvNextModel:()=>Db,ConvNextPreTrainedModel:()=>du,ConvNextV2ForImageClassification:()=>Bb,ConvNextV2Model:()=>zb,ConvNextV2PreTrainedModel:()=>pu,DFineForObjectDetection:()=>tb,DFineModel:()=>eb,DFinePreTrainedModel:()=>ru,DINOv3ConvNextModel:()=>Kb,DINOv3ConvNextPreTrainedModel:()=>Gb,DINOv3ViTModel:()=>Wb,DINOv3ViTPreTrainedModel:()=>Ub,DPTForDepthEstimation:()=>gb,DPTModel:()=>fb,DPTPreTrainedModel:()=>lu,DacDecoderModel:()=>H0,DacDecoderOutput:()=>W0,DacEncoderModel:()=>K0,DacEncoderOutput:()=>U0,DacModel:()=>G0,DacPreTrainedModel:()=>di,DebertaForMaskedLM:()=>qe,DebertaForQuestionAnswering:()=>Mr,DebertaForSequenceClassification:()=>Pt,DebertaForTokenClassification:()=>It,DebertaModel:()=>Mt,DebertaPreTrainedModel:()=>He,DebertaV2ForMaskedLM:()=>Tr,DebertaV2ForQuestionAnswering:()=>Ss,DebertaV2ForSequenceClassification:()=>Cs,DebertaV2ForTokenClassification:()=>Dr,DebertaV2Model:()=>ir,DebertaV2PreTrainedModel:()=>pr,DecisionTransformerModel:()=>E0,DecisionTransformerPreTrainedModel:()=>P0,DeiTForImageClassification:()=>ab,DeiTModel:()=>ob,DeiTPreTrainedModel:()=>nu,DepthAnythingForDepthEstimation:()=>wb,DepthAnythingPreTrainedModel:()=>Mb,DepthProForDepthEstimation:()=>Tb,DepthProPreTrainedModel:()=>xb,DetrForObjectDetection:()=>Ww,DetrForSegmentation:()=>Jc,DetrModel:()=>Uw,DetrObjectDetectionOutput:()=>Yc,DetrPreTrainedModel:()=>Ja,DetrSegmentationOutput:()=>Gw,Dinov2ForImageClassification:()=>jb,Dinov2Model:()=>Rb,Dinov2PreTrainedModel:()=>mu,Dinov2WithRegistersForImageClassification:()=>Vb,Dinov2WithRegistersModel:()=>Nb,Dinov2WithRegistersPreTrainedModel:()=>hu,DistilBertForMaskedLM:()=>Kr,DistilBertForQuestionAnswering:()=>lr,DistilBertForSequenceClassification:()=>ns,DistilBertForTokenClassification:()=>wr,DistilBertModel:()=>zr,DistilBertPreTrainedModel:()=>Lr,DonutSwinModel:()=>Ob,DonutSwinPreTrainedModel:()=>Fb,EdgeTamModel:()=>sy,EfficientNetForImageClassification:()=>p0,EfficientNetModel:()=>d0,EfficientNetPreTrainedModel:()=>Su,ElectraForMaskedLM:()=>Es,ElectraForQuestionAnswering:()=>R,ElectraForSequenceClassification:()=>C,ElectraForTokenClassification:()=>q,ElectraModel:()=>yt,ElectraPreTrainedModel:()=>Gr,Ernie4_5ForCausalLM:()=>Yy,Ernie4_5Model:()=>Jy,Ernie4_5PreTrainedModel:()=>xu,EsmForMaskedLM:()=>ks,EsmForSequenceClassification:()=>$s,EsmForTokenClassification:()=>Is,EsmModel:()=>Rs,EsmPreTrainedModel:()=>os,ExaoneForCausalLM:()=>$M,ExaoneModel:()=>kM,ExaonePreTrainedModel:()=>vc,FalconForCausalLM:()=>r0,FalconModel:()=>t0,FalconPreTrainedModel:()=>Pu,FastViTForImageClassification:()=>$w,FastViTModel:()=>kw,FastViTPreTrainedModel:()=>Gc,Florence2ForConditionalGeneration:()=>Va,Florence2PreTrainedModel:()=>Na,GLPNForDepthEstimation:()=>Ab,GLPNModel:()=>Ib,GLPNPreTrainedModel:()=>uu,GPT2LMHeadModel:()=>Vo,GPT2Model:()=>Yn,GPT2PreTrainedModel:()=>Jn,GPTBigCodeForCausalLM:()=>V,GPTBigCodeModel:()=>L,GPTBigCodePreTrainedModel:()=>A,GPTJForCausalLM:()=>E,GPTJModel:()=>h,GPTJPreTrainedModel:()=>ro,GPTNeoForCausalLM:()=>Wo,GPTNeoModel:()=>eo,GPTNeoPreTrainedModel:()=>Sn,GPTNeoXForCausalLM:()=>Ko,GPTNeoXModel:()=>Go,GPTNeoXPreTrainedModel:()=>to,Gemma2ForCausalLM:()=>KM,Gemma2Model:()=>GM,Gemma2PreTrainedModel:()=>$c,Gemma3ForCausalLM:()=>XM,Gemma3Model:()=>QM,Gemma3PreTrainedModel:()=>Ac,Gemma3nForConditionalGeneration:()=>Kn,Gemma3nPreTrainedModel:()=>tn,GemmaForCausalLM:()=>WM,GemmaModel:()=>UM,GemmaPreTrainedModel:()=>kc,GlmForCausalLM:()=>SM,GlmModel:()=>CM,GlmPreTrainedModel:()=>yc,GraniteForCausalLM:()=>BM,GraniteModel:()=>zM,GraniteMoeHybridForCausalLM:()=>jM,GraniteMoeHybridModel:()=>RM,GraniteMoeHybridPreTrainedModel:()=>Cc,GranitePreTrainedModel:()=>Ec,GroundingDinoForObjectDetection:()=>qb,GroundingDinoPreTrainedModel:()=>Hb,GroupViTModel:()=>Sw,GroupViTPreTrainedModel:()=>Cw,HeliumForCausalLM:()=>EM,HeliumModel:()=>PM,HeliumPreTrainedModel:()=>bc,HieraForImageClassification:()=>lb,HieraModel:()=>ib,HieraPreTrainedModel:()=>ou,HubertForCTC:()=>$y,HubertForSequenceClassification:()=>Iy,HubertModel:()=>ky,HubertPreTrainedModel:()=>kT,IJepaForImageClassification:()=>Mw,IJepaModel:()=>gw,IJepaPreTrainedModel:()=>Vc,Idefics3ForConditionalGeneration:()=>Hn,Idefics3PreTrainedModel:()=>Ga,ImageMattingOutput:()=>Tv,JAISLMHeadModel:()=>Cn,JAISModel:()=>Uo,JAISPreTrainedModel:()=>Zn,JinaCLIPModel:()=>Tn,JinaCLIPPreTrainedModel:()=>xn,JinaCLIPTextModel:()=>Zr,JinaCLIPVisionModel:()=>Pn,Lfm2ForCausalLM:()=>vM,Lfm2Model:()=>yM,Lfm2PreTrainedModel:()=>Mc,LiteWhisperForConditionalGeneration:()=>Ba,Llama4ForCausalLM:()=>Vt,Llama4PreTrainedModel:()=>Dt,LlamaForCausalLM:()=>vt,LlamaModel:()=>it,LlamaPreTrainedModel:()=>Qe,LlavaForConditionalGeneration:()=>Gn,LlavaOnevisionForConditionalGeneration:()=>Ra,LlavaPreTrainedModel:()=>Oo,LlavaQwen2ForCausalLM:()=>Do,LongT5ForConditionalGeneration:()=>sr,LongT5Model:()=>Jt,LongT5PreTrainedModel:()=>br,M2M100ForConditionalGeneration:()=>ly,M2M100Model:()=>iy,M2M100PreTrainedModel:()=>gu,MBartForCausalLM:()=>ls,MBartForConditionalGeneration:()=>bs,MBartForSequenceClassification:()=>yr,MBartModel:()=>Yr,MBartPreTrainedModel:()=>$r,MPNetForMaskedLM:()=>As,MPNetForQuestionAnswering:()=>ue,MPNetForSequenceClassification:()=>Ns,MPNetForTokenClassification:()=>Nn,MPNetModel:()=>js,MPNetPreTrainedModel:()=>Kt,MT5ForConditionalGeneration:()=>is,MT5Model:()=>Hr,MT5PreTrainedModel:()=>Ht,MarianMTModel:()=>ay,MarianModel:()=>oy,MarianPreTrainedModel:()=>fu,MaskFormerForInstanceSegmentation:()=>$b,MaskFormerModel:()=>kb,MaskFormerPreTrainedModel:()=>cu,MaskedLMOutput:()=>Ir,Metric3DForDepthEstimation:()=>Eb,Metric3DPreTrainedModel:()=>Pb,Metric3Dv2ForDepthEstimation:()=>Sb,Metric3Dv2PreTrainedModel:()=>Cb,MgpstrForSceneTextRecognition:()=>I0,MgpstrModelOutput:()=>k0,MgpstrPreTrainedModel:()=>$0,MimiDecoderModel:()=>V0,MimiDecoderOutput:()=>R0,MimiEncoderModel:()=>N0,MimiEncoderOutput:()=>B0,MimiModel:()=>j0,MimiPreTrainedModel:()=>ui,Ministral3ForCausalLM:()=>Xy,Ministral3Model:()=>Qy,Ministral3PreTrainedModel:()=>vu,MinistralForCausalLM:()=>qy,MinistralModel:()=>Hy,MinistralPreTrainedModel:()=>yu,Mistral3ForConditionalGeneration:()=>bn,MistralForCausalLM:()=>Ky,MistralModel:()=>Gy,MistralPreTrainedModel:()=>bu,MobileBertForMaskedLM:()=>ze,MobileBertForQuestionAnswering:()=>nt,MobileBertForSequenceClassification:()=>Ue,MobileBertModel:()=>Nr,MobileBertPreTrainedModel:()=>as,MobileLLMForCausalLM:()=>AM,MobileLLMModel:()=>IM,MobileLLMPreTrainedModel:()=>xc,MobileNetV1ForImageClassification:()=>h0,MobileNetV1ForSemanticSegmentation:()=>_0,MobileNetV1Model:()=>m0,MobileNetV1PreTrainedModel:()=>ai,MobileNetV2ForImageClassification:()=>g0,MobileNetV2ForSemanticSegmentation:()=>M0,MobileNetV2Model:()=>f0,MobileNetV2PreTrainedModel:()=>ii,MobileNetV3ForImageClassification:()=>b0,MobileNetV3ForSemanticSegmentation:()=>y0,MobileNetV3Model:()=>w0,MobileNetV3PreTrainedModel:()=>li,MobileNetV4ForImageClassification:()=>x0,MobileNetV4ForSemanticSegmentation:()=>T0,MobileNetV4Model:()=>v0,MobileNetV4PreTrainedModel:()=>ci,MobileViTForImageClassification:()=>Ow,MobileViTModel:()=>Fw,MobileViTPreTrainedModel:()=>Kc,MobileViTV2ForImageClassification:()=>Lw,MobileViTV2Model:()=>Dw,MobileViTV2PreTrainedModel:()=>Hc,ModelOutput:()=>de,ModernBertDecoderForCausalLM:()=>gr,ModernBertDecoderModel:()=>kt,ModernBertDecoderPreTrainedModel:()=>Nt,ModernBertForMaskedLM:()=>Oe,ModernBertForSequenceClassification:()=>at,ModernBertForTokenClassification:()=>ht,ModernBertModel:()=>je,ModernBertPreTrainedModel:()=>Ze,Moondream1ForConditionalGeneration:()=>ja,MoonshineForConditionalGeneration:()=>Un,MoonshineModel:()=>fc,MoonshinePreTrainedModel:()=>Fo,MptForCausalLM:()=>pw,MptModel:()=>dw,MptPreTrainedModel:()=>Rc,MultiModalityCausalLM:()=>S0,MultiModalityPreTrainedModel:()=>C0,MusicgenForCausalLM:()=>FT,MusicgenForConditionalGeneration:()=>$u,MusicgenModel:()=>AT,MusicgenPreTrainedModel:()=>ku,NanoChatForCausalLM:()=>Xa,NanoChatModel:()=>Us,NanoChatPreTrainedModel:()=>xr,NeoBertForMaskedLM:()=>Fe,NeoBertForQuestionAnswering:()=>rt,NeoBertForSequenceClassification:()=>tt,NeoBertForTokenClassification:()=>Re,NeoBertModel:()=>We,NeoBertPreTrainedModel:()=>Pe,NomicBertModel:()=>Bt,NomicBertPreTrainedModel:()=>Or,OPTForCausalLM:()=>hw,OPTModel:()=>mw,OPTPreTrainedModel:()=>jc,Olmo2ForCausalLM:()=>LM,Olmo2Model:()=>DM,Olmo2PreTrainedModel:()=>Pc,OlmoForCausalLM:()=>OM,OlmoModel:()=>FM,OlmoPreTrainedModel:()=>Tc,OpenELMForCausalLM:()=>YM,OpenELMModel:()=>JM,OpenELMPreTrainedModel:()=>Fc,OwlViTForObjectDetection:()=>Bw,OwlViTModel:()=>zw,OwlViTPreTrainedModel:()=>qc,Owlv2ForObjectDetection:()=>jw,Owlv2Model:()=>Rw,Owlv2PreTrainedModel:()=>Qc,PaliGemmaForConditionalGeneration:()=>Wa,PaliGemmaPreTrainedModel:()=>Ua,ParakeetForCTC:()=>hy,ParakeetPreTrainedModel:()=>my,PatchTSMixerForPrediction:()=>D0,PatchTSMixerModel:()=>O0,PatchTSMixerPreTrainedModel:()=>Au,PatchTSTForPrediction:()=>F0,PatchTSTModel:()=>A0,PatchTSTPreTrainedModel:()=>Iu,Phi3ForCausalLM:()=>lw,Phi3Model:()=>iw,Phi3PreTrainedModel:()=>zc,Phi3VForCausalLM:()=>Qn,Phi3VPreTrainedModel:()=>qn,PhiForCausalLM:()=>aw,PhiModel:()=>ow,PhiPreTrainedModel:()=>Lc,PreTrainedModel:()=>z,PretrainedMixin:()=>Ut,PvtForImageClassification:()=>vw,PvtModel:()=>yw,PvtPreTrainedModel:()=>Uc,PyAnnoteForAudioFrameClassification:()=>fy,PyAnnoteModel:()=>_y,PyAnnotePreTrainedModel:()=>Mu,QuestionAnsweringModelOutput:()=>Br,Qwen2ForCausalLM:()=>ew,Qwen2Model:()=>ZM,Qwen2PreTrainedModel:()=>Oc,Qwen2VLForConditionalGeneration:()=>nw,Qwen2VLPreTrainedModel:()=>sw,Qwen3ForCausalLM:()=>rw,Qwen3Model:()=>tw,Qwen3PreTrainedModel:()=>Dc,RFDetrForObjectDetection:()=>Yw,RFDetrModel:()=>Jw,RFDetrObjectDetectionOutput:()=>Zw,RFDetrPreTrainedModel:()=>tu,RTDetrForObjectDetection:()=>Hw,RTDetrModel:()=>Kw,RTDetrObjectDetectionOutput:()=>Ho,RTDetrPreTrainedModel:()=>Zc,RTDetrV2ForObjectDetection:()=>Qw,RTDetrV2Model:()=>qw,RTDetrV2ObjectDetectionOutput:()=>Xw,RTDetrV2PreTrainedModel:()=>eu,ResNetForImageClassification:()=>ub,ResNetModel:()=>cb,ResNetPreTrainedModel:()=>au,RoFormerForMaskedLM:()=>Xs,RoFormerForQuestionAnswering:()=>kr,RoFormerForSequenceClassification:()=>Js,RoFormerForTokenClassification:()=>ar,RoFormerModel:()=>Qs,RoFormerPreTrainedModel:()=>jr,RobertaForMaskedLM:()=>Ea,RobertaForQuestionAnswering:()=>ka,RobertaForSequenceClassification:()=>Ca,RobertaForTokenClassification:()=>Sa,RobertaModel:()=>Eo,RobertaPreTrainedModel:()=>Fs,Sam2ImageSegmentationOutput:()=>ty,Sam2Model:()=>ei,Sam2PreTrainedModel:()=>ry,Sam3TrackerModel:()=>ny,SamImageSegmentationOutput:()=>ey,SamModel:()=>Zb,SamPreTrainedModel:()=>Yb,SapiensForDepthEstimation:()=>yb,SapiensForNormalEstimation:()=>vb,SapiensForSemanticSegmentation:()=>bb,SapiensPreTrainedModel:()=>Za,SegformerForImageClassification:()=>i0,SegformerForSemanticSegmentation:()=>l0,SegformerModel:()=>IT,SegformerPreTrainedModel:()=>oi,Seq2SeqLMOutput:()=>wP,SequenceClassifierOutput:()=>xt,SiglipModel:()=>Bo,SiglipPreTrainedModel:()=>Xn,SiglipTextModel:()=>vn,SiglipVisionModel:()=>dt,SmolLM3ForCausalLM:()=>TM,SmolLM3Model:()=>xM,SmolLM3PreTrainedModel:()=>wc,SmolVLMForConditionalGeneration:()=>yn,SnacDecoderModel:()=>X0,SnacEncoderModel:()=>Q0,SnacModel:()=>q0,SnacPreTrainedModel:()=>pi,SpeechT5ForSpeechToText:()=>Ry,SpeechT5ForTextToSpeech:()=>jy,SpeechT5HifiGan:()=>Ny,SpeechT5Model:()=>$T,SpeechT5PreTrainedModel:()=>si,SqueezeBertForMaskedLM:()=>ee,SqueezeBertForQuestionAnswering:()=>Me,SqueezeBertForSequenceClassification:()=>se,SqueezeBertModel:()=>U,SqueezeBertPreTrainedModel:()=>$,StableLmForCausalLM:()=>u0,StableLmModel:()=>c0,StableLmPreTrainedModel:()=>Cu,Starcoder2ForCausalLM:()=>e0,Starcoder2Model:()=>Zy,Starcoder2PreTrainedModel:()=>Tu,StyleTextToSpeech2Model:()=>By,StyleTextToSpeech2PreTrainedModel:()=>zy,SupertonicForConditionalGeneration:()=>wu,SupertonicPreTrainedModel:()=>Vy,Swin2SRForImageSuperResolution:()=>_b,Swin2SRModel:()=>hb,Swin2SRPreTrainedModel:()=>iu,SwinForImageClassification:()=>pb,SwinForSemanticSegmentation:()=>mb,SwinModel:()=>db,SwinPreTrainedModel:()=>Ya,T5ForConditionalGeneration:()=>rr,T5Model:()=>Et,T5PreTrainedModel:()=>$t,TableTransformerForObjectDetection:()=>sb,TableTransformerModel:()=>rb,TableTransformerObjectDetectionOutput:()=>nb,TableTransformerPreTrainedModel:()=>su,TokenClassifierOutput:()=>Er,TrOCRForCausalLM:()=>Wy,TrOCRPreTrainedModel:()=>Uy,UltravoxModel:()=>Fu,UltravoxPreTrainedModel:()=>L0,UniSpeechForCTC:()=>by,UniSpeechForSequenceClassification:()=>yy,UniSpeechModel:()=>wy,UniSpeechPreTrainedModel:()=>ti,UniSpeechSatForAudioFrameClassification:()=>Py,UniSpeechSatForCTC:()=>xy,UniSpeechSatForSequenceClassification:()=>Ty,UniSpeechSatModel:()=>vy,UniSpeechSatPreTrainedModel:()=>qo,VaultGemmaForCausalLM:()=>qM,VaultGemmaModel:()=>HM,VaultGemmaPreTrainedModel:()=>Ic,ViTForImageClassification:()=>fw,ViTMAEModel:()=>Tw,ViTMAEPreTrainedModel:()=>xw,ViTMSNForImageClassification:()=>Ew,ViTMSNModel:()=>Pw,ViTMSNPreTrainedModel:()=>Wc,ViTModel:()=>_w,ViTPreTrainedModel:()=>Nc,VisionEncoderDecoderModel:()=>Wn,VitMatteForImageMatting:()=>Aw,VitMattePreTrainedModel:()=>Iw,VitPoseForPoseEstimation:()=>bw,VitPosePreTrainedModel:()=>ww,VitsModel:()=>Eu,VitsModelOutput:()=>Pv,VitsPreTrainedModel:()=>a0,VoxtralForConditionalGeneration:()=>z0,Wav2Vec2BertForCTC:()=>Cy,Wav2Vec2BertForSequenceClassification:()=>Sy,Wav2Vec2BertModel:()=>Ey,Wav2Vec2BertPreTrainedModel:()=>ri,Wav2Vec2ForAudioFrameClassification:()=>py,Wav2Vec2ForCTC:()=>uy,Wav2Vec2ForSequenceClassification:()=>dy,Wav2Vec2Model:()=>cy,Wav2Vec2PreTrainedModel:()=>rn,WavLMForAudioFrameClassification:()=>Ly,WavLMForCTC:()=>Fy,WavLMForSequenceClassification:()=>Oy,WavLMForXVector:()=>Dy,WavLMModel:()=>Ay,WavLMPreTrainedModel:()=>so,WeSpeakerResNetModel:()=>My,WeSpeakerResNetPreTrainedModel:()=>gy,WhisperForConditionalGeneration:()=>Vn,WhisperModel:()=>za,WhisperPreTrainedModel:()=>Vs,XLMForQuestionAnswering:()=>Oa,XLMForSequenceClassification:()=>Aa,XLMForTokenClassification:()=>Fa,XLMModel:()=>$a,XLMPreTrainedModel:()=>Zs,XLMRobertaForMaskedLM:()=>Co,XLMRobertaForQuestionAnswering:()=>La,XLMRobertaForSequenceClassification:()=>So,XLMRobertaForTokenClassification:()=>ko,XLMRobertaModel:()=>Da,XLMRobertaPreTrainedModel:()=>en,XLMWithLMHeadModel:()=>Ia,XVectorOutput:()=>xv,YolosForObjectDetection:()=>Xb,YolosModel:()=>Qb,YolosObjectDetectionOutput:()=>Jb,YolosPreTrainedModel:()=>_u});var s=t("./src/configs.js"),n=t("./src/backends/onnx.js"),o=t("./src/utils/dtypes.js"),i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),c=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),d=t("./src/generation/configuration_utils.js"),u=t("./src/utils/tensor.js"),f=t("./src/utils/image.js"),_=t("./src/utils/maths.js"),y=t("./src/generation/stopping_criteria.js"),I=t("./src/generation/logits_sampler.js"),w=t("./src/env.js"),v=t("./src/models/whisper/generation_whisper.js"),k=t("./src/models/whisper/common_whisper.js");const T={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11,ImageAudioTextToText:12,Supertonic:13},b=new Map,P=new Map,x=new Map;async function S(g,M,N){let ae=N.config?.["transformers.js_config"]??{},me=N.device??ae.device;me&&typeof me!="string"&&(me.hasOwnProperty(M)?me=me[M]:(console.warn(`device not specified for "${M}". Using the default device.`),me=null));const _e=me??(w.apis.IS_NODE_ENV?"cpu":"wasm"),Se=(0,n.deviceToExecutionProviders)(_e),Le=ae.device_config??{};Le.hasOwnProperty(_e)&&(ae={...ae,...Le[_e]});let Ge=N.dtype??ae.dtype;if(typeof Ge!="string"&&(Ge&&Ge.hasOwnProperty(M)?Ge=Ge[M]:(Ge=o.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??o.DATA_TYPES.fp32,console.warn(`dtype not specified for "${M}". Using the default dtype (${Ge}) for this device (${_e}).`))),Ge===o.DATA_TYPES.auto){let At=ae.dtype;typeof At!="string"&&(At=At?.[M]),At&&At!==o.DATA_TYPES.auto&&o.DATA_TYPES.hasOwnProperty(At)?Ge=At:Ge=o.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??o.DATA_TYPES.fp32}const st=Ge;if(o.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(st)){if(st===o.DATA_TYPES.fp16&&_e==="webgpu"&&!await(0,o.isWebGpuFp16Supported)())throw new Error(`The device (${_e}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${st}. Should be one of: ${Object.keys(o.DATA_TYPES).join(", ")}`);const wt=ae.kv_cache_dtype,bt=wt?typeof wt=="string"?wt:wt[st]??"float32":void 0;if(bt&&!["float32","float16"].includes(bt))throw new Error(`Invalid kv_cache_dtype: ${bt}. Should be one of: float32, float16`);const Ct={dtype:st,kv_cache_dtype:bt,device:_e},mt=o.DEFAULT_DTYPE_SUFFIX_MAPPING[st],Lt=`${M}${mt}.onnx`,_t=`${N.subfolder??""}/${Lt}`,pt={...N.session_options};pt.executionProviders??=Se;const Ft=ae.free_dimension_overrides;Ft?pt.freeDimensionOverrides??=Ft:_e.startsWith("webnn")&&!pt.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 Wt=w.apis.IS_NODE_ENV&&w.env.useFSCache,er=(0,l.getModelFile)(g,_t,!0,N,Wt),nr=N.use_external_data_format??ae.use_external_data_format;let mr=[];if(nr){let At;typeof nr=="object"?nr.hasOwnProperty(Lt)?At=nr[Lt]:nr.hasOwnProperty(M)?At=nr[M]:At=!1:At=nr;const ur=+At;if(ur>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${ur}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let Ar=0;Ar{const ao=await(0,l.getModelFile)(g,Wr,!0,N,Wt);ys(ao instanceof Uint8Array?{path:kn,data:ao}:kn)}))}}else pt.externalData!==void 0&&(mr=pt.externalData.map(async At=>{if(typeof At.data=="string"){const ur=await(0,l.getModelFile)(g,At.data,!0,N);return{...At,data:ur}}return At}));if(mr.length>0){const At=await Promise.all(mr);w.apis.IS_NODE_ENV||(pt.externalData=At)}if(_e==="webgpu"){const At=(0,s.getCacheShapes)(N.config,{prefix:"present"});if(Object.keys(At).length>0&&!(0,n.isONNXProxy)()){const ur={};for(const Ar in At)ur[Ar]="gpu-buffer";pt.preferredOutputLocation=ur}}return{buffer_or_path:await er,session_options:pt,session_config:Ct}}async function O(g,M,N){return Object.fromEntries(await Promise.all(Object.keys(M).map(async ae=>{const{buffer_or_path:me,session_options:_e,session_config:Se}=await S(g,M[ae],N),Le=await(0,n.createInferenceSession)(me,_e,Se);return[ae,Le]})))}async function F(g,M,N){return Object.fromEntries(await Promise.all(Object.keys(M).map(async ae=>{const me=await(0,l.getModelJSON)(g,M[ae],!1,N);return[ae,me]})))}function H(g,M){const N=Object.create(null),ae=[];for(const Se of g.inputNames){const Le=M[Se];if(!(Le instanceof u.Tensor)){ae.push(Se);continue}N[Se]=(0,n.isONNXProxy)()?Le.clone():Le}if(ae.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ae.join(", ")}.`);const me=Object.keys(M).length,_e=g.inputNames.length;if(me>_e){let Se=Object.keys(M).filter(Le=>!g.inputNames.includes(Le));console.warn(`WARNING: Too many inputs were provided (${me} > ${_e}). The following inputs will be ignored: "${Se.join(", ")}".`)}return N}async function W(g,M){const N=H(g,M);try{const ae=Object.fromEntries(Object.entries(N).map(([_e,Se])=>[_e,Se.ort_tensor])),me=await(0,n.runInferenceSession)(g,ae);return B(me)}catch(ae){const me=Object.fromEntries(Object.entries(N).map(([_e,Se])=>{const Le={type:Se.type,dims:Se.dims,location:Se.location};return Le.location!=="gpu-buffer"&&(Le.data=Se.data),[_e,Le]}));throw console.error(`An error occurred during model execution: "${ae}".`),console.error("Inputs given to model:",me),ae}}function B(g){for(let M in g)(0,n.isONNXTensor)(g[M])?g[M]=new u.Tensor(g[M]):typeof g[M]=="object"&&B(g[M]);return g}function Y(g){if(g instanceof u.Tensor)return g;if(g.length===0)throw Error("items must be non-empty");if(Array.isArray(g[0])){if(g.some(M=>M.length!==g[0].length))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");return new u.Tensor("int64",BigInt64Array.from(g.flat().map(M=>BigInt(M))),[g.length,g[0].length])}else return new u.Tensor("int64",BigInt64Array.from(g.map(M=>BigInt(M))),[1,g.length])}function X(g){return new u.Tensor("bool",[g],[1])}async function J(g,M){let{encoder_outputs:N,input_ids:ae,decoder_input_ids:me,..._e}=M;if(!N){const Le=(0,a.pick)(M,g.sessions.model.inputNames);N=(await re(g,Le)).last_hidden_state}return _e.input_ids=me,_e.encoder_hidden_states=N,g.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(_e.encoder_attention_mask=M.attention_mask),await le(g,_e,!0)}async function re(g,M){const N=g.sessions.model,ae=(0,a.pick)(M,N.inputNames);if(N.inputNames.includes("inputs_embeds")&&!ae.inputs_embeds){if(!M.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ae.inputs_embeds=await g.encode_text({input_ids:M.input_ids})}if(N.inputNames.includes("token_type_ids")&&!ae.token_type_ids){if(!ae.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");ae.token_type_ids=(0,u.zeros_like)(ae.input_ids)}if(N.inputNames.includes("pixel_mask")&&!ae.pixel_mask){if(!ae.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const me=ae.pixel_values.dims;ae.pixel_mask=(0,u.ones)([me[0],me[2],me[3]])}return await W(N,ae)}async function ne(g,M){const N=await g.encode(M);return await g.decode(N)}async function le(g,M,N=!1){const ae=g.sessions[N?"decoder_model_merged":"model"],{past_key_values:me,..._e}=M;if(ae.inputNames.includes("use_cache_branch")&&(_e.use_cache_branch=X(!!me)),ae.inputNames.includes("position_ids")&&_e.attention_mask&&!_e.position_ids){const Le=["paligemma","gemma3_text","gemma3"].includes(g.config.model_type)?1:0;_e.position_ids=Ae(_e,me,Le)}g.addPastKeyValues(_e,me);const Se=(0,a.pick)(_e,ae.inputNames);return await W(ae,Se)}function pe({modality_token_id:g,inputs_embeds:M,modality_features:N,input_ids:ae,attention_mask:me}){const _e=ae.tolist().map(st=>st.reduce((wt,bt,Ct)=>(bt==g&&wt.push(Ct),wt),[])),Se=_e.reduce((st,wt)=>st+wt.length,0),Le=N.dims[0];if(Se!==Le)throw new Error(`Number of tokens and features do not match: tokens: ${Se}, features ${Le}`);let Ge=0;for(let st=0;st<_e.length;++st){const wt=_e[st],bt=M[st];for(let Ct=0;Ct_e.dims[1]||me<_e.dims[1]&&(N.input_ids=_e.slice(null,[me,null]))}return N}function Ve(g,M,N,ae){return N.past_key_values&&(M=M.map(me=>[me.at(-1)])),{...N,decoder_input_ids:Y(M)}}function Te(g,...M){return g.config.is_encoder_decoder?Ve(g,...M):ke(g,...M)}function Q(g,M,N,ae){const me=!!N.past_key_values;return ae.guidance_scale!==null&&ae.guidance_scale>1&&(me?N.input_ids=(0,u.cat)([N.input_ids,N.input_ids],0):(N.input_ids=(0,u.cat)([N.input_ids,(0,u.full_like)(N.input_ids,BigInt(ae.pad_token_id))],0),N.attention_mask=(0,u.cat)([N.attention_mask,(0,u.full_like)(N.attention_mask,0n)],0))),(me||!N.pixel_values)&&(N.pixel_values=(0,u.full)([0,0,3,384,384],1)),me&&(N.images_seq_mask=new u.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),N.images_emb_mask=new u.Tensor("bool",new Array(0).fill(!1),[1,1,0])),N}class z extends i.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(M,N,ae){super(),this.config=M,this.sessions=N,this.configs=ae;const me=x.get(this.constructor),_e=b.get(me);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,_e){case T.DecoderOnly:this.can_generate=!0,this._forward=le,this._prepare_inputs_for_generation=ke;break;case T.Seq2Seq:case T.Vision2Seq:case T.Musicgen:this.can_generate=!0,this._forward=J,this._prepare_inputs_for_generation=Ve;break;case T.EncoderDecoder:this._forward=J;break;case T.ImageTextToText:this.can_generate=!0,this._forward=te,this._prepare_inputs_for_generation=Te;break;case T.AudioTextToText:this.can_generate=!0,this._forward=D,this._prepare_inputs_for_generation=Te;break;case T.Phi3V:case T.ImageAudioTextToText:this.can_generate=!0,this._prepare_inputs_for_generation=Te;break;case T.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Q;break;case T.AutoEncoder:this._forward=ne;break;default:this._forward=re;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const M=[];for(const N of Object.values(this.sessions))N?.handler?.dispose&&M.push(N.handler.dispose());return await Promise.all(M)}static async from_pretrained(M,{progress_callback:N=null,config:ae=null,cache_dir:me=null,local_files_only:_e=!1,revision:Se="main",model_file_name:Le=null,subfolder:Ge="onnx",device:st=null,dtype:wt=null,use_external_data_format:bt=null,session_options:Ct={}}={}){let mt={progress_callback:N,config:ae,cache_dir:me,local_files_only:_e,revision:Se,model_file_name:Le,subfolder:Ge,device:st,dtype:wt,use_external_data_format:bt,session_options:Ct};const Lt=x.get(this),_t=b.get(Lt);ae=mt.config=await s.AutoConfig.from_pretrained(M,mt);let pt;if(_t===T.DecoderOnly)pt=await Promise.all([O(M,{model:mt.model_file_name??"model"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.Seq2Seq||_t===T.Vision2Seq)pt=await Promise.all([O(M,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.MaskGeneration)pt=await Promise.all([O(M,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},mt)]);else if(_t===T.EncoderDecoder)pt=await Promise.all([O(M,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},mt)]);else if(_t===T.ImageTextToText){const Ft={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};ae.is_encoder_decoder&&(Ft.model="encoder_model"),pt=await Promise.all([O(M,Ft,mt),F(M,{generation_config:"generation_config.json"},mt)])}else if(_t===T.AudioTextToText){const Ft={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};pt=await Promise.all([O(M,Ft,mt),F(M,{generation_config:"generation_config.json"},mt)])}else if(_t===T.ImageAudioTextToText){const Ft={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};pt=await Promise.all([O(M,Ft,mt),F(M,{generation_config:"generation_config.json"},mt)])}else if(_t===T.Musicgen)pt=await Promise.all([O(M,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.MultiModality)pt=await Promise.all([O(M,{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"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.Phi3V)pt=await Promise.all([O(M,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},mt),F(M,{generation_config:"generation_config.json"},mt)]);else if(_t===T.AutoEncoder)pt=await Promise.all([O(M,{encoder_model:"encoder_model",decoder_model:"decoder_model"},mt)]);else if(_t===T.Supertonic)pt=await Promise.all([O(M,{text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"},mt)]);else{if(_t!==T.EncoderOnly){const Ft=Lt??ae?.model_type;Ft!=="custom"&&console.warn(`Model type for '${Ft}' not found, assuming encoder-only architecture. Please report this at ${c.GITHUB_ISSUE_URL}.`)}pt=await Promise.all([O(M,{model:mt.model_file_name??"model"},mt)])}return new this(ae,...pt)}async _call(M){return await this.forward(M)}async forward(M){return await this._forward(this,M)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(M,N,ae=null){const me=new p.LogitsProcessorList;if(M.repetition_penalty!==null&&M.repetition_penalty!==1&&me.push(new p.RepetitionPenaltyLogitsProcessor(M.repetition_penalty)),M.no_repeat_ngram_size!==null&&M.no_repeat_ngram_size>0&&me.push(new p.NoRepeatNGramLogitsProcessor(M.no_repeat_ngram_size)),M.bad_words_ids!==null&&me.push(new p.NoBadWordsLogitsProcessor(M.bad_words_ids,M.eos_token_id)),M.min_length!==null&&M.eos_token_id!==null&&M.min_length>0&&me.push(new p.MinLengthLogitsProcessor(M.min_length,M.eos_token_id)),M.min_new_tokens!==null&&M.eos_token_id!==null&&M.min_new_tokens>0&&me.push(new p.MinNewTokensLengthLogitsProcessor(N,M.min_new_tokens,M.eos_token_id)),M.forced_bos_token_id!==null&&me.push(new p.ForcedBOSTokenLogitsProcessor(M.forced_bos_token_id)),M.forced_eos_token_id!==null&&me.push(new p.ForcedEOSTokenLogitsProcessor(M.max_length,M.forced_eos_token_id)),M.begin_suppress_tokens!==null){const _e=N>1||M.forced_bos_token_id===null?N:N+1;me.push(new p.SuppressTokensAtBeginLogitsProcessor(M.begin_suppress_tokens,_e))}return M.guidance_scale!==null&&M.guidance_scale>1&&me.push(new p.ClassifierFreeGuidanceLogitsProcessor(M.guidance_scale)),M.temperature===0&&M.do_sample&&(console.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),M.do_sample=!1),M.do_sample&&M.temperature!==null&&M.temperature!==1&&me.push(new p.TemperatureLogitsWarper(M.temperature)),ae!==null&&me.extend(ae),me}_prepare_generation_config(M,N,ae=d.GenerationConfig){const me={...this.config};for(const Se of["decoder","generator","text_config"])Se in me&&Object.assign(me,me[Se]);const _e=new ae(me);return Object.assign(_e,this.generation_config??{}),M&&Object.assign(_e,M),N&&Object.assign(_e,(0,a.pick)(N,Object.getOwnPropertyNames(_e))),_e}_get_stopping_criteria(M,N=null){const ae=new y.StoppingCriteriaList;return M.max_length!==null&&ae.push(new y.MaxLengthCriteria(M.max_length,this.config.max_position_embeddings??null)),M.eos_token_id!==null&&ae.push(new y.EosTokenCriteria(M.eos_token_id)),N&&ae.extend(N),ae}_validate_model_class(){if(!this.can_generate){const M=[Lu,zu,Du,Ou],N=x.get(this.constructor),ae=new Set,me=this.config.model_type;for(const Se of M){const Le=Se.get(me);Le&&ae.add(Le[0])}let _e=`The current model class (${N}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ae.size>0&&(_e+=` Please use the following class instead: ${[...ae].join(", ")}`),Error(_e)}}prepare_inputs_for_generation(...M){return this._prepare_inputs_for_generation(this,...M)}_update_model_kwargs_for_generation({generated_input_ids:M,outputs:N,model_inputs:ae,is_encoder_decoder:me}){return ae.past_key_values=this.getPastKeyValues(N,ae.past_key_values),ae.input_ids=new u.Tensor("int64",M.flat(),[M.length,1]),me||(ae.attention_mask=(0,u.cat)([ae.attention_mask,(0,u.ones)([ae.attention_mask.dims[0],1])],1)),ae.position_ids=null,ae}_prepare_model_inputs({inputs:M,bos_token_id:N,model_kwargs:ae}){const me=(0,a.pick)(ae,this.forward_params),_e=this.main_input_name;if(_e in me){if(M)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else me[_e]=M;return{inputs_tensor:me[_e],model_inputs:me,model_input_name:_e}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:M,model_inputs:N,model_input_name:ae,generation_config:me}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!N.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Se,pixel_values:Le,attention_mask:Ge,...st}=N,wt=await this._prepare_inputs_embeds(N);N={...st,...(0,a.pick)(wt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:_e}=await re(this,N);if(me.guidance_scale!==null&&me.guidance_scale>1)_e=(0,u.cat)([_e,(0,u.full_like)(_e,0)],0),"attention_mask"in N&&(N.attention_mask=(0,u.cat)([N.attention_mask,(0,u.zeros_like)(N.attention_mask)],0));else if(N.decoder_input_ids){const Se=Y(N.decoder_input_ids).dims[0];if(Se!==_e.dims[0]){if(_e.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${_e.dims[0]}) than the decoder inputs (${Se}).`);_e=(0,u.cat)(Array.from({length:Se},()=>_e),0)}}return N.encoder_outputs=_e,N}_prepare_decoder_input_ids_for_generation({batch_size:M,model_input_name:N,model_kwargs:ae,decoder_start_token_id:me,bos_token_id:_e,generation_config:Se}){let{decoder_input_ids:Le,...Ge}=ae;if(!(Le instanceof u.Tensor)){if(Le)Array.isArray(Le[0])||(Le=Array.from({length:M},()=>Le));else if(me??=_e,this.config.model_type==="musicgen")Le=Array.from({length:M*this.config.decoder.num_codebooks},()=>[me]);else if(Array.isArray(me)){if(me.length!==M)throw new Error(`\`decoder_start_token_id\` expcted to have length ${M} but got ${me.length}`);Le=me}else Le=Array.from({length:M},()=>[me]);Le=Y(Le)}return ae.decoder_attention_mask=(0,u.ones_like)(Le),{input_ids:Le,model_inputs:Ge}}async generate({inputs:M=null,generation_config:N=null,logits_processor:ae=null,stopping_criteria:me=null,streamer:_e=null,...Se}){this._validate_model_class(),N=this._prepare_generation_config(N,Se);let{inputs_tensor:Le,model_inputs:Ge,model_input_name:st}=this._prepare_model_inputs({inputs:M,model_kwargs:Se});const wt=this.config.is_encoder_decoder;wt&&("encoder_outputs"in Ge||(Ge=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Le,model_inputs:Ge,model_input_name:st,generation_config:N})));let bt;wt?{input_ids:bt,model_inputs:Ge}=this._prepare_decoder_input_ids_for_generation({batch_size:Ge[st].dims.at(0),model_input_name:st,model_kwargs:Ge,decoder_start_token_id:N.decoder_start_token_id,bos_token_id:N.bos_token_id,generation_config:N}):bt=Ge[st];let Ct=bt.dims.at(-1);N.max_new_tokens!==null&&(N.max_length=Ct+N.max_new_tokens);const mt=this._get_logits_processor(N,Ct,ae),Lt=this._get_stopping_criteria(N,me),_t=Ge[st].dims.at(0),pt=I.LogitsSampler.getSampler(N),Ft=new Array(_t).fill(0),Wt=bt.tolist();_e&&_e.put(Wt);let er,nr={};for(;;){if(Ge=this.prepare_inputs_for_generation(Wt,Ge,N),er=await this.forward(Ge),N.output_attentions&&N.return_dict_in_generate){const Wr=this.getAttentions(er);for(const ys in Wr)ys in nr||(nr[ys]=[]),nr[ys].push(Wr[ys])}const At=er.logits.slice(null,-1,null),ur=mt(Wt,At),Ar=[];for(let Wr=0;WrWr))break;Ge=this._update_model_kwargs_for_generation({generated_input_ids:Ar,outputs:er,model_inputs:Ge,is_encoder_decoder:wt})}_e&&_e.end();const mr=this.getPastKeyValues(er,Ge.past_key_values,!0),fr=new u.Tensor("int64",Wt.flat(),[Wt.length,Wt[0].length]);if(N.return_dict_in_generate)return{sequences:fr,past_key_values:mr,...nr};for(const At of Object.values(er))At.location==="gpu-buffer"&&At.dispose();return fr}getPastKeyValues(M,N,ae=!1){const me=Object.create(null);for(const _e in M)if(_e.startsWith("present")){const Se=_e.replace("present_conv","past_conv").replace("present","past_key_values"),Le=_e.includes("encoder");if(Le&&N?me[Se]=N[Se]:me[Se]=M[_e],N&&(!Le||ae)){const Ge=N[Se];Ge.location==="gpu-buffer"&&Ge.dispose()}}return me}getAttentions(M){const N={};for(const ae of["cross_attentions","encoder_attentions","decoder_attentions"])for(const me in M)me.startsWith(ae)&&(ae in N||(N[ae]=[]),N[ae].push(M[me]));return N}addPastKeyValues(M,N){if(N)Object.assign(M,N);else{const ae=this.sessions.decoder_model_merged??this.sessions.model,me=(M[this.main_input_name]??M.attention_mask)?.dims?.[0]??1,_e=ae?.config?.kv_cache_dtype??"float32",Se=_e==="float16"?u.DataTypeMap.float16:u.DataTypeMap.float32,Le=(0,s.getCacheShapes)(this.config,{batch_size:me});for(const Ge in Le){const st=Le[Ge].reduce((wt,bt)=>wt*bt,1);M[Ge]=new u.Tensor(_e,new Se(st),Le[Ge])}}}async encode_image({pixel_values:M}){return(await W(this.sessions.vision_encoder,{pixel_values:M})).image_features}async encode_text({input_ids:M}){return(await W(this.sessions.embed_tokens,{input_ids:M})).inputs_embeds}async encode_audio({audio_values:M}){return(await W(this.sessions.audio_encoder,{audio_values:M})).audio_features}}class de{}class be extends de{constructor({last_hidden_state:M,hidden_states:N=null,attentions:ae=null}){super(),this.last_hidden_state=M,this.hidden_states=N,this.attentions=ae}}class ve extends z{}class xe extends ve{}class Ce extends ve{async _call(M){return new Ir(await super._call(M))}}class ge extends ve{async _call(M){return new xt(await super._call(M))}}class De extends ve{async _call(M){return new Er(await super._call(M))}}class fe extends ve{async _call(M){return new Br(await super._call(M))}}class Pe extends z{}class We extends Pe{}class Fe extends Pe{async _call(M){return new Ir(await super._call(M))}}class tt extends Pe{async _call(M){return new xt(await super._call(M))}}class Re extends Pe{async _call(M){return new Er(await super._call(M))}}class rt extends Pe{async _call(M){return new Br(await super._call(M))}}class Ze extends z{}class je extends Ze{}class Oe extends Ze{async _call(M){return new Ir(await super._call(M))}}class at extends Ze{async _call(M){return new xt(await super._call(M))}}class ht extends Ze{async _call(M){return new Er(await super._call(M))}}class Nt extends z{}class kt extends Nt{}class gr extends Nt{}class Or extends z{}class Bt extends Or{}class jr extends z{}class Qs extends jr{}class Xs extends jr{async _call(M){return new Ir(await super._call(M))}}class Js extends jr{async _call(M){return new xt(await super._call(M))}}class ar extends jr{async _call(M){return new Er(await super._call(M))}}class kr extends jr{async _call(M){return new Br(await super._call(M))}}class Jr extends z{}class Bs extends Jr{}class ft extends Jr{async _call(M){return new Ir(await super._call(M))}}class qt extends Jr{async _call(M){return new xt(await super._call(M))}}class Ts extends Jr{async _call(M){return new Er(await super._call(M))}}class Ps extends Jr{async _call(M){return new Br(await super._call(M))}}class Gr extends z{}class yt extends Gr{}class Es extends Gr{async _call(M){return new Ir(await super._call(M))}}class C extends Gr{async _call(M){return new xt(await super._call(M))}}class q extends Gr{async _call(M){return new Er(await super._call(M))}}class R extends Gr{async _call(M){return new Br(await super._call(M))}}class G extends z{}class Z extends G{}class ce extends G{async _call(M){return new Ir(await super._call(M))}}class ye extends G{async _call(M){return new xt(await super._call(M))}}class et extends G{async _call(M){return new Er(await super._call(M))}}class ut extends G{async _call(M){return new Br(await super._call(M))}}class He extends z{}class Mt extends He{}class qe extends He{async _call(M){return new Ir(await super._call(M))}}class Pt extends He{async _call(M){return new xt(await super._call(M))}}class It extends He{async _call(M){return new Er(await super._call(M))}}class Mr extends He{async _call(M){return new Br(await super._call(M))}}class pr extends z{}class ir extends pr{}class Tr extends pr{async _call(M){return new Ir(await super._call(M))}}class Cs extends pr{async _call(M){return new xt(await super._call(M))}}class Dr extends pr{async _call(M){return new Er(await super._call(M))}}class Ss extends pr{async _call(M){return new Br(await super._call(M))}}class Lr extends z{}class zr extends Lr{}class ns extends Lr{async _call(M){return new xt(await super._call(M))}}class wr extends Lr{async _call(M){return new Er(await super._call(M))}}class lr extends Lr{async _call(M){return new Br(await super._call(M))}}class Kr extends Lr{async _call(M){return new Ir(await super._call(M))}}class os extends z{}class Rs extends os{}class ks extends os{async _call(M){return new Ir(await super._call(M))}}class $s extends os{async _call(M){return new xt(await super._call(M))}}class Is extends os{async _call(M){return new Er(await super._call(M))}}class as extends z{}class Nr extends as{}class ze extends as{async _call(M){return new Ir(await super._call(M))}}class Ue extends as{async _call(M){return new xt(await super._call(M))}}class nt extends as{async _call(M){return new Br(await super._call(M))}}class Kt extends z{}class js extends Kt{}class As extends Kt{async _call(M){return new Ir(await super._call(M))}}class Ns extends Kt{async _call(M){return new xt(await super._call(M))}}class Nn extends Kt{async _call(M){return new Er(await super._call(M))}}class ue extends Kt{async _call(M){return new Br(await super._call(M))}}class $ extends z{}class U extends ${}class ee extends ${async _call(M){return new Ir(await super._call(M))}}class se extends ${async _call(M){return new xt(await super._call(M))}}class Me extends ${async _call(M){return new Br(await super._call(M))}}class $e extends z{}class Xe extends $e{}class Je extends $e{async _call(M){return new xt(await super._call(M))}}class Ye extends $e{async _call(M){return new Br(await super._call(M))}}class Ke extends $e{async _call(M){return new Ir(await super._call(M))}}class $t extends z{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class Et extends $t{}class rr extends $t{}class br extends z{}class Jt extends br{}class sr extends br{}class Ht extends z{}class Hr extends Ht{}class is extends Ht{}class Pr extends z{}class ws extends Pr{}class Yt extends Pr{}class hr extends Pr{async _call(M){return new xt(await super._call(M))}}class $r extends z{}class Yr extends $r{}class bs extends $r{}class yr extends $r{async _call(M){return new xt(await super._call(M))}}class ls extends $r{}class vr extends z{}class Zt extends vr{}class _r extends vr{}class cr extends z{}class Ur extends cr{}class Ys extends cr{}class Fs extends z{}class Eo extends Fs{}class Ea extends Fs{async _call(M){return new Ir(await super._call(M))}}class Ca extends Fs{async _call(M){return new xt(await super._call(M))}}class Sa extends Fs{async _call(M){return new Er(await super._call(M))}}class ka extends Fs{async _call(M){return new Br(await super._call(M))}}class Zs extends z{}class $a extends Zs{}class Ia extends Zs{async _call(M){return new Ir(await super._call(M))}}class Aa extends Zs{async _call(M){return new xt(await super._call(M))}}class Fa extends Zs{async _call(M){return new Er(await super._call(M))}}class Oa extends Zs{async _call(M){return new Br(await super._call(M))}}class en extends z{}class Da extends en{}class Co extends en{async _call(M){return new Ir(await super._call(M))}}class So extends en{async _call(M){return new xt(await super._call(M))}}class ko extends en{async _call(M){return new Er(await super._call(M))}}class La extends en{async _call(M){return new Br(await super._call(M))}}class $o extends z{}class Io extends $o{}class Ao extends $o{}class Vs extends z{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]}class za extends Vs{}class Vn extends Vs{_prepare_generation_config(M,N){return super._prepare_generation_config(M,N,v.WhisperGenerationConfig)}_retrieve_init_tokens(M){const N=[M.decoder_start_token_id];let ae=M.language;const me=M.task;if(M.is_multilingual){ae||(console.warn("No language specified - defaulting to English (en)."),ae="en");const Se=`<|${(0,k.whisper_language_to_code)(ae)}|>`;N.push(M.lang_to_id[Se]),N.push(M.task_to_id[me??"transcribe"])}else if(ae||me)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!M.return_timestamps&&M.no_timestamps_token_id&&N.at(-1)!==M.no_timestamps_token_id?N.push(M.no_timestamps_token_id):M.return_timestamps&&N.at(-1)===M.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),N.pop()),N.filter(_e=>_e!=null)}async generate({inputs:M=null,generation_config:N=null,logits_processor:ae=null,stopping_criteria:me=null,..._e}){N=this._prepare_generation_config(N,_e);const Se=_e.decoder_input_ids??this._retrieve_init_tokens(N);if(N.return_timestamps&&(ae??=new p.LogitsProcessorList,ae.push(new p.WhisperTimeStampLogitsProcessor(N,Se))),N.begin_suppress_tokens&&(ae??=new p.LogitsProcessorList,ae.push(new p.SuppressTokensAtBeginLogitsProcessor(N.begin_suppress_tokens,Se.length))),N.return_token_timestamps){if(!N.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.");N.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),N.output_attentions=!0,N.return_dict_in_generate=!0}const Le=await super.generate({inputs:M,generation_config:N,logits_processor:ae,decoder_input_ids:Se,..._e});return N.return_token_timestamps&&(Le.token_timestamps=this._extract_token_timestamps(Le,N.alignment_heads,N.num_frames)),Le}_extract_token_timestamps(M,N,ae=null,me=.02){if(!M.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`.");ae==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 Se=M.cross_attentions,Le=Array.from({length:this.config.decoder_layers},(_t,pt)=>(0,u.cat)(Se.map(Ft=>Ft[pt]),2)),Ge=(0,u.stack)(N.map(([_t,pt])=>{if(_t>=Le.length)throw new Error(`Layer index ${_t} is out of bounds for cross attentions (length ${Le.length}).`);return ae?Le[_t].slice(null,pt,null,[0,ae]):Le[_t].slice(null,pt)})).transpose(1,0,2,3),[st,wt]=(0,u.std_mean)(Ge,-2,0,!0),bt=Ge.clone();for(let _t=0;_tFt[At+1]-Ft[At]),nr=(0,a.mergeArrays)([1],er).map(fr=>!!fr),mr=[];for(let fr=0;frArray.from({length:M.dims[0]},er=>Array.from({length:M.dims[1]},nr=>1))),Lt=N?N.tolist():[],_t=ae?ae.tolist():[];let pt=0,Ft=0;for(let Wt=0;WtCt[Wt][Cr]==1),mr=er.reduce((tr,Cr,nn)=>(Cr==Ge&&tr.push(nn),tr),[]).map(tr=>er[tr+1]),fr=mr.filter(tr=>tr==Se).length,At=mr.filter(tr=>tr==Le).length;let ur=[],Ar=0,kn=fr,Wr=At;for(let tr=0;trvs>Ar&&In==Se),nn=er.findIndex((In,vs)=>vs>Ar&&In==Le),$n=kn>0&&Cr!==-1?Cr:er.length+1,io=Wr>0&&nn!==-1?nn:er.length+1;let hi,Bu,Ru,ju;$n0?(0,_.max)(ur.at(-1))[0]+1:0;ur.push(Array.from({length:3*Vu},(In,vs)=>Ev+vs%Vu));const Uu=Vu+Ev,fi=vP*Nu*_i,xP=Array.from({length:fi},(In,vs)=>Uu+Math.floor(vs/(Nu*_i))),TP=Array.from({length:fi},(In,vs)=>Uu+Math.floor(vs/_i)%Nu),PP=Array.from({length:fi},(In,vs)=>Uu+vs%_i);ur.push([xP,TP,PP].flat()),Ar=hi+fi}if(Ar0?(0,_.max)(ur.at(-1))[0]+1:0,Cr=er.length-Ar;ur.push(Array.from({length:3*Cr},(nn,$n)=>tr+$n%Cr))}const ys=ur.reduce((tr,Cr)=>tr+Cr.length,0),oo=new Array(ys);let ao=0;for(let tr=0;tr<3;++tr)for(let Cr=0;Crbt[pt%bt.length]),Lt=Array.from({length:Ct[0]},(_t,pt)=>(0,_.max)(bt.subarray(Ct[1]*pt,Ct[1]*(pt+1)))[0]+1n+BigInt(Ct[1]));return[new u.Tensor("int64",mt,[3,...Ct]),new u.Tensor("int64",Lt,[Lt.length,1])]}else{const[bt,Ct]=M.dims,mt=BigInt64Array.from({length:3*bt*Ct},(Lt,_t)=>BigInt(Math.floor(_t%Ct/bt)));return[new u.Tensor("int64",mt,[3,...M.dims]),(0,u.zeros)([bt,1])]}}async encode_image({pixel_values:M,image_grid_thw:N}){return(await W(this.sessions.vision_encoder,{pixel_values:M,grid_thw:N})).image_features}_merge_input_ids_with_image_features(M){return oe({image_token_id:this.config.image_token_id,...M})}prepare_inputs_for_generation(M,N,ae){if(N.attention_mask&&!N.position_ids)if(!N.past_key_values)[N.position_ids,N.rope_deltas]=this.get_rope_index(N.input_ids,N.image_grid_thw,N.video_grid_thw,N.attention_mask);else{N.pixel_values=null;const me=BigInt(Object.values(N.past_key_values)[0].dims.at(-2)),_e=N.rope_deltas.map(Se=>me+Se);N.position_ids=(0,u.stack)([_e,_e,_e],0)}return N}}class Lc extends z{}class ow extends Lc{}class aw extends Lc{}class zc extends z{}class iw extends zc{}class lw extends zc{}class Bc extends z{}class cw extends Bc{}class uw extends Bc{}class Rc extends z{}class dw extends Rc{}class pw extends Rc{}class jc extends z{}class mw extends jc{}class hw extends jc{}class Nc extends z{}class _w extends Nc{}class fw extends Nc{async _call(M){return new xt(await super._call(M))}}class Vc extends z{}class gw extends Vc{}class Mw extends Vc{async _call(M){return new xt(await super._call(M))}}class ww extends z{}class bw extends ww{}class Uc extends z{}class yw extends Uc{}class vw extends Uc{async _call(M){return new xt(await super._call(M))}}class xw extends z{}class Tw extends xw{}class Wc extends z{}class Pw extends Wc{}class Ew extends Wc{async _call(M){return new xt(await super._call(M))}}class Cw extends z{}class Sw extends Cw{}class Gc extends z{}class kw extends Gc{}class $w extends Gc{async _call(M){return new xt(await super._call(M))}}class Iw extends z{}class Aw extends Iw{async _call(M){return new Tv(await super._call(M))}}class Kc extends z{}class Fw extends Kc{}class Ow extends Kc{async _call(M){return new xt(await super._call(M))}}class Hc extends z{}class Dw extends Hc{}class Lw extends Hc{async _call(M){return new xt(await super._call(M))}}class qc extends z{}class zw extends qc{}class Bw extends qc{}class Qc extends z{}class Rw extends Qc{}class jw extends Qc{}class Xc extends z{}class Nw extends Xc{}class Vw extends Xc{async _call(M){return new xt(await super._call(M))}}class Ja extends z{}class Uw extends Ja{}class Ww extends Ja{async _call(M){return new Yc(await super._call(M))}}class Jc extends Ja{async _call(M){return new Gw(await super._call(M))}}class Yc extends de{constructor({logits:M,pred_boxes:N}){super(),this.logits=M,this.pred_boxes=N}}class Gw extends de{constructor({logits:M,pred_boxes:N,pred_masks:ae}){super(),this.logits=M,this.pred_boxes=N,this.pred_masks=ae}}class Zc extends z{}class Kw extends Zc{}class Hw extends Zc{async _call(M){return new Ho(await super._call(M))}}class Ho extends de{constructor({logits:M,pred_boxes:N}){super(),this.logits=M,this.pred_boxes=N}}class eu extends z{}class qw extends eu{}class Qw extends eu{async _call(M){return new Xw(await super._call(M))}}class Xw extends Ho{}class tu extends z{}class Jw extends tu{}class Yw extends tu{async _call(M){return new Zw(await super._call(M))}}class Zw extends Ho{}class ru extends z{}class eb extends ru{}class tb extends ru{async _call(M){return new Ho(await super._call(M))}}class su extends z{}class rb extends su{}class sb extends su{async _call(M){return new nb(await super._call(M))}}class nb extends Yc{}class nu extends z{}class ob extends nu{}class ab extends nu{async _call(M){return new xt(await super._call(M))}}class ou extends z{}class ib extends ou{}class lb extends ou{async _call(M){return new xt(await super._call(M))}}class au extends z{}class cb extends au{}class ub extends au{async _call(M){return new xt(await super._call(M))}}class Ya extends z{}class db extends Ya{}class pb extends Ya{async _call(M){return new xt(await super._call(M))}}class mb extends Ya{}class iu extends z{}class hb extends iu{}class _b extends iu{}class lu extends z{}class fb extends lu{}class gb extends lu{}class Mb extends z{}class wb extends Mb{}class Za extends z{}class bb extends Za{}class yb extends Za{}class vb extends Za{}class xb extends z{}class Tb extends xb{}class Pb extends z{}class Eb extends Pb{}class Cb extends z{}class Sb extends Cb{}class cu extends z{}class kb extends cu{}class $b extends cu{}class uu extends z{}class Ib extends uu{}class Ab extends uu{}class Fb extends z{}class Ob extends Fb{}class du extends z{}class Db extends du{}class Lb extends du{async _call(M){return new xt(await super._call(M))}}class pu extends z{}class zb extends pu{}class Bb extends pu{async _call(M){return new xt(await super._call(M))}}class mu extends z{}class Rb extends mu{}class jb extends mu{async _call(M){return new xt(await super._call(M))}}class hu extends z{}class Nb extends hu{}class Vb extends hu{async _call(M){return new xt(await super._call(M))}}class Ub extends z{}class Wb extends Ub{}class Gb extends z{}class Kb extends Gb{}class Hb extends z{}class qb extends Hb{}class _u extends z{}class Qb extends _u{}class Xb extends _u{async _call(M){return new Jb(await super._call(M))}}class Jb extends de{constructor({logits:M,pred_boxes:N}){super(),this.logits=M,this.pred_boxes=N}}class Yb extends z{}class Zb extends Yb{async get_image_embeddings({pixel_values:M}){return await re(this,{pixel_values:M})}async forward(M){!M.image_embeddings||!M.image_positional_embeddings?M={...M,...await this.get_image_embeddings(M)}:M={...M},M.input_labels??=(0,u.ones)(M.input_points.dims.slice(0,-1));const N={image_embeddings:M.image_embeddings,image_positional_embeddings:M.image_positional_embeddings};return M.input_points&&(N.input_points=M.input_points),M.input_labels&&(N.input_labels=M.input_labels),M.input_boxes&&(N.input_boxes=M.input_boxes),await W(this.sessions.prompt_encoder_mask_decoder,N)}async _call(M){return new ey(await super._call(M))}}class ey extends de{constructor({iou_scores:M,pred_masks:N}){super(),this.iou_scores=M,this.pred_masks=N}}class ty extends de{constructor({iou_scores:M,pred_masks:N,object_score_logits:ae}){super(),this.iou_scores=M,this.pred_masks=N,this.object_score_logits=ae}}class ry extends z{}class ei extends ry{async get_image_embeddings({pixel_values:M}){return await re(this,{pixel_values:M})}async forward(M){const{num_feature_levels:N}=this.config.vision_config;if(Array.from({length:N},(Se,Le)=>`image_embeddings.${Le}`).some(Se=>!M[Se])?M={...M,...await this.get_image_embeddings(M)}:M={...M},M.input_points){if(M.input_boxes&&M.input_boxes.dims[1]!==1)throw new Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");const Se=M.input_points.dims;M.input_labels??=(0,u.ones)(Se.slice(0,-1)),M.input_boxes??=(0,u.full)([Se[0],0,4],0)}else if(M.input_boxes){const Se=M.input_boxes.dims;M.input_labels=(0,u.full)([Se[0],Se[1],0],-1n),M.input_points=(0,u.full)([Se[0],1,0,2],0)}else throw new Error("At least one of `input_points` or `input_boxes` must be provided.");const me=this.sessions.prompt_encoder_mask_decoder,_e=(0,a.pick)(M,me.inputNames);return await W(me,_e)}async _call(M){return new ty(await super._call(M))}}class sy extends ei{}class ny extends ei{}class fu extends z{}class oy extends fu{}class ay extends fu{}class gu extends z{}class iy extends gu{}class ly extends gu{}class rn extends z{}class cy extends rn{}class uy extends rn{async _call(M){return new sn(await super._call(M))}}class dy extends rn{async _call(M){return new xt(await super._call(M))}}class py extends rn{async _call(M){return new Er(await super._call(M))}}class my extends z{}class hy extends my{async _call(M){return new sn(await super._call(M))}}class Mu extends z{}class _y extends Mu{}class fy extends Mu{async _call(M){return new Er(await super._call(M))}}class gy extends z{}class My extends gy{}class ti extends z{}class wy extends ti{}class by extends ti{async _call(M){return new sn(await super._call(M))}}class yy extends ti{async _call(M){return new xt(await super._call(M))}}class qo extends z{}class vy extends qo{}class xy extends qo{async _call(M){return new sn(await super._call(M))}}class Ty extends qo{async _call(M){return new xt(await super._call(M))}}class Py extends qo{async _call(M){return new Er(await super._call(M))}}class ri extends z{}class Ey extends ri{}class Cy extends ri{async _call(M){return new sn(await super._call(M))}}class Sy extends ri{async _call(M){return new xt(await super._call(M))}}class kT extends z{}class ky extends rn{}class $y extends rn{async _call(M){return new sn(await super._call(M))}}class Iy extends rn{async _call(M){return new xt(await super._call(M))}}class so extends z{}class Ay extends so{}class Fy extends so{async _call(M){return new sn(await super._call(M))}}class Oy extends so{async _call(M){return new xt(await super._call(M))}}class Dy extends so{async _call(M){return new xv(await super._call(M))}}class Ly extends so{async _call(M){return new Er(await super._call(M))}}class zy extends z{}class By extends zy{}class si extends z{}class $T extends si{}class Ry extends si{}class jy extends si{async generate_speech(M,N,{threshold:ae=.5,minlenratio:me=0,maxlenratio:_e=20,vocoder:Se=null}={}){const Le={input_ids:M},{encoder_outputs:Ge,encoder_attention_mask:st}=await re(this,Le),wt=Ge.dims[1]/this.config.reduction_factor,bt=Math.floor(wt*_e),Ct=Math.floor(wt*me),mt=this.config.num_mel_bins;let Lt=[],_t=null,pt=null,Ft=0;for(;;){++Ft;const nr=X(!!pt);let mr;pt?mr=pt.output_sequence_out:mr=new u.Tensor("float32",new Float32Array(mt),[1,1,mt]);let fr={use_cache_branch:nr,output_sequence:mr,encoder_attention_mask:st,speaker_embeddings:N,encoder_hidden_states:Ge};this.addPastKeyValues(fr,_t),pt=await W(this.sessions.decoder_model_merged,fr),_t=this.getPastKeyValues(pt,_t);const{prob:At,spectrum:ur}=pt;if(Lt.push(ur),Ft>=Ct&&(Array.from(At.data).filter(Ar=>Ar>=ae).length>0||Ft>=bt))break}const Wt=(0,u.cat)(Lt),{waveform:er}=await W(Se.sessions.model,{spectrogram:Wt});return{spectrogram:Wt,waveform:er}}}class Ny extends z{main_input_name="spectrogram"}class Vy extends z{}class wu extends Vy{async generate_speech({input_ids:M,attention_mask:N,style:ae,num_inference_steps:me=5,speed:_e=1.05}){const{sampling_rate:Se,chunk_compress_factor:Le,base_chunk_size:Ge,latent_dim:st}=this.config,{last_hidden_state:wt,durations:bt}=await W(this.sessions.text_encoder,{input_ids:M,attention_mask:N,style:ae});bt.div_(_e);const Ct=bt.max().item()*Se,mt=Ge*Le,Lt=Math.floor((Ct+mt-1)/mt),_t=M.dims[0],pt=(0,u.ones)([_t,Lt]),Ft=(0,u.full)([_t],me);let Wt=(0,u.randn)([_t,st*Le,Lt]);for(let nr=0;nr0&&Ct<=_e&&(M.data[Se++]=M.data[st])}const Le=Math.floor(N/me),Ge=Se/(Le*me);return new u.Tensor(M.type,M.data.slice(0,Se),[Le,me,Ge])}prepare_inputs_for_generation(M,N,ae){let me=structuredClone(M);for(let Se=0;Se=Le&&(me[Se][Le]=BigInt(this.config.decoder.pad_token_id));return ae.guidance_scale!==null&&ae.guidance_scale>1&&(me=me.concat(me)),super.prepare_inputs_for_generation(me,N,ae)}async generate(M){const N=await super.generate(M),ae=this._apply_and_filter_by_delay_pattern_mask(N).unsqueeze_(0),{audio_values:me}=await W(this.sessions.encodec_decode,{audio_codes:ae});return me}}class ai extends z{}class m0 extends ai{}class h0 extends ai{async _call(M){return new xt(await super._call(M))}}class _0 extends ai{}class ii extends z{}class f0 extends ii{}class g0 extends ii{async _call(M){return new xt(await super._call(M))}}class M0 extends ii{}class li extends z{}class w0 extends li{}class b0 extends li{async _call(M){return new xt(await super._call(M))}}class y0 extends li{}class ci extends z{}class v0 extends ci{}class x0 extends ci{async _call(M){return new xt(await super._call(M))}}class T0 extends ci{}class P0 extends z{}class E0 extends P0{}class C0 extends z{}class S0 extends C0{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...M){super(...M),this._generation_mode="text"}async forward(M){const N=this._generation_mode??"text";let ae;if(N==="text"||!M.past_key_values){const Ge=this.sessions.prepare_inputs_embeds,st=(0,a.pick)(M,Ge.inputNames);ae=await W(Ge,st)}else{const Ge=this.sessions.gen_img_embeds,st=(0,a.pick)({image_ids:M.input_ids},Ge.inputNames);ae=await W(Ge,st)}const me={...M,...ae},_e=await le(this,me),Se=this.sessions[N==="text"?"lm_head":"gen_head"];if(!Se)throw new Error(`Unable to find "${Se}" generation head`);const Le=await W(Se,(0,a.pick)(_e,Se.inputNames));return{...ae,..._e,...Le}}async generate(M){return this._generation_mode="text",super.generate(M)}async generate_images(M){this._generation_mode="image";const N=(M.inputs??M[this.main_input_name]).dims[1],me=(await super.generate(M)).slice(null,[N,null]),_e=this.sessions.image_decode,{decoded_image:Se}=await W(_e,{generated_tokens:me}),Le=Se.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Ge=[];for(const st of Le){const wt=f.RawImage.fromTensor(st);Ge.push(wt)}return Ge}}class k0 extends de{constructor({char_logits:M,bpe_logits:N,wp_logits:ae}){super(),this.char_logits=M,this.bpe_logits=N,this.wp_logits=ae}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class $0 extends z{}class I0 extends $0{async _call(M){return new k0(await super._call(M))}}class Iu extends z{}class A0 extends Iu{}class F0 extends Iu{}class Au extends z{}class O0 extends Au{}class D0 extends Au{}class L0 extends z{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]}class Fu extends L0{_merge_input_ids_with_audio_features(M){const N=M.audio_features.dims.at(-1),ae=M.audio_features.view(-1,N);return K({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...M,audio_features:ae})}}class z0 extends Fu{}class ui extends z{main_input_name="input_values";forward_params=["input_values"]}class B0 extends de{constructor({audio_codes:M}){super(),this.audio_codes=M}}class R0 extends de{constructor({audio_values:M}){super(),this.audio_values=M}}class j0 extends ui{async encode(M){return new B0(await W(this.sessions.encoder_model,M))}async decode(M){return new R0(await W(this.sessions.decoder_model,M))}}class N0 extends ui{static async from_pretrained(M,N={}){return super.from_pretrained(M,{...N,model_file_name:N.model_file_name??"encoder_model"})}}class V0 extends ui{static async from_pretrained(M,N={}){return super.from_pretrained(M,{...N,model_file_name:N.model_file_name??"decoder_model"})}}class di extends z{main_input_name="input_values";forward_params=["input_values"]}class U0 extends de{constructor({audio_codes:M}){super(),this.audio_codes=M}}class W0 extends de{constructor({audio_values:M}){super(),this.audio_values=M}}class G0 extends di{async encode(M){return new U0(await W(this.sessions.encoder_model,M))}async decode(M){return new W0(await W(this.sessions.decoder_model,M))}}class K0 extends di{static async from_pretrained(M,N={}){return super.from_pretrained(M,{...N,model_file_name:N.model_file_name??"encoder_model"})}}class H0 extends di{static async from_pretrained(M,N={}){return super.from_pretrained(M,{...N,model_file_name:N.model_file_name??"decoder_model"})}}class pi extends z{main_input_name="input_values";forward_params=["input_values"]}class q0 extends pi{async encode(M){return await W(this.sessions.encoder_model,M)}async decode(M){return await W(this.sessions.decoder_model,M)}}class Q0 extends pi{static async from_pretrained(M,N={}){return super.from_pretrained(M,{...N,model_file_name:N.model_file_name??"encoder_model"})}}class X0 extends pi{static async from_pretrained(M,N={}){return super.from_pretrained(M,{...N,model_file_name:N.model_file_name??"decoder_model"})}}class Ut{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(M,{progress_callback:N=null,config:ae=null,cache_dir:me=null,local_files_only:_e=!1,revision:Se="main",model_file_name:Le=null,subfolder:Ge="onnx",device:st=null,dtype:wt=null,use_external_data_format:bt=null,session_options:Ct={}}={}){const mt={progress_callback:N,config:ae,cache_dir:me,local_files_only:_e,revision:Se,model_file_name:Le,subfolder:Ge,device:st,dtype:wt,use_external_data_format:bt,session_options:Ct};if(mt.config=await s.AutoConfig.from_pretrained(M,mt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const Lt=mt.config.model_type;for(const _t of this.MODEL_CLASS_MAPPINGS){let pt=_t.get(Lt);if(!pt){for(const Ft of _t.values())if(Ft[0]===Lt){pt=Ft;break}if(!pt)continue}return await pt[1].from_pretrained(M,mt)}if(this.BASE_IF_FAIL)return vv.has(Lt)||console.warn(`Unknown model class "${Lt}", attempting to construct from base class.`),await z.from_pretrained(M,mt);throw Error(`Unsupported model type: ${Lt}`)}}const OT=new Map([["bert",["BertModel",xe]],["neobert",["NeoBertModel",We]],["modernbert",["ModernBertModel",je]],["nomic_bert",["NomicBertModel",Bt]],["roformer",["RoFormerModel",Qs]],["electra",["ElectraModel",yt]],["esm",["EsmModel",Rs]],["convbert",["ConvBertModel",Bs]],["camembert",["CamembertModel",Z]],["deberta",["DebertaModel",Mt]],["deberta-v2",["DebertaV2Model",ir]],["mpnet",["MPNetModel",js]],["albert",["AlbertModel",Xe]],["distilbert",["DistilBertModel",zr]],["roberta",["RobertaModel",Eo]],["xlm",["XLMModel",$a]],["xlm-roberta",["XLMRobertaModel",Da]],["clap",["ClapModel",s0]],["clip",["CLIPModel",Lo]],["clipseg",["CLIPSegModel",jo]],["chinese_clip",["ChineseCLIPModel",Ro]],["siglip",["SiglipModel",Bo]],["jina_clip",["JinaCLIPModel",Tn]],["mobilebert",["MobileBertModel",Nr]],["squeezebert",["SqueezeBertModel",U]],["wav2vec2",["Wav2Vec2Model",cy]],["wav2vec2-bert",["Wav2Vec2BertModel",Ey]],["unispeech",["UniSpeechModel",wy]],["unispeech-sat",["UniSpeechSatModel",vy]],["hubert",["HubertModel",ky]],["wavlm",["WavLMModel",Ay]],["audio-spectrogram-transformer",["ASTModel",Io]],["vits",["VitsModel",Eu]],["pyannote",["PyAnnoteModel",_y]],["wespeaker-resnet",["WeSpeakerResNetModel",My]],["detr",["DetrModel",Uw]],["rt_detr",["RTDetrModel",Kw]],["rt_detr_v2",["RTDetrV2Model",qw]],["rf_detr",["RFDetrModel",Jw]],["d_fine",["DFineModel",eb]],["table-transformer",["TableTransformerModel",rb]],["vit",["ViTModel",_w]],["ijepa",["IJepaModel",gw]],["pvt",["PvtModel",yw]],["vit_msn",["ViTMSNModel",Pw]],["vit_mae",["ViTMAEModel",Tw]],["groupvit",["GroupViTModel",Sw]],["fastvit",["FastViTModel",kw]],["mobilevit",["MobileViTModel",Fw]],["mobilevitv2",["MobileViTV2Model",Dw]],["owlvit",["OwlViTModel",zw]],["owlv2",["Owlv2Model",Rw]],["beit",["BeitModel",Nw]],["deit",["DeiTModel",ob]],["hiera",["HieraModel",ib]],["convnext",["ConvNextModel",Db]],["convnextv2",["ConvNextV2Model",zb]],["dinov2",["Dinov2Model",Rb]],["dinov2_with_registers",["Dinov2WithRegistersModel",Nb]],["dinov3_vit",["DINOv3ViTModel",Wb]],["dinov3_convnext",["DINOv3ConvNextModel",Kb]],["resnet",["ResNetModel",cb]],["swin",["SwinModel",db]],["swin2sr",["Swin2SRModel",hb]],["donut-swin",["DonutSwinModel",Ob]],["yolos",["YolosModel",Qb]],["dpt",["DPTModel",fb]],["glpn",["GLPNModel",Ib]],["hifigan",["SpeechT5HifiGan",Ny]],["efficientnet",["EfficientNetModel",d0]],["decision_transformer",["DecisionTransformerModel",E0]],["patchtst",["PatchTSTForPrediction",A0]],["patchtsmixer",["PatchTSMixerForPrediction",O0]],["mobilenet_v1",["MobileNetV1Model",m0]],["mobilenet_v2",["MobileNetV2Model",f0]],["mobilenet_v3",["MobileNetV3Model",w0]],["mobilenet_v4",["MobileNetV4Model",v0]],["maskformer",["MaskFormerModel",kb]],["mgp-str",["MgpstrForSceneTextRecognition",I0]],["style_text_to_speech_2",["StyleTextToSpeech2Model",By]]]),DT=new Map([["t5",["T5Model",Et]],["longt5",["LongT5Model",Jt]],["mt5",["MT5Model",Hr]],["bart",["BartModel",ws]],["mbart",["MBartModel",Yr]],["marian",["MarianModel",oy]],["whisper",["WhisperModel",za]],["m2m_100",["M2M100Model",iy]],["blenderbot",["BlenderbotModel",Zt]],["blenderbot-small",["BlenderbotSmallModel",Ur]]]),LT=new Map([["mimi",["MimiModel",j0]],["dac",["DacModel",G0]],["snac",["SnacModel",q0]]]),zT=new Map([["bloom",["BloomModel",cw]],["jais",["JAISModel",Uo]],["gpt2",["GPT2Model",Yn]],["gptj",["GPTJModel",h]],["gpt_bigcode",["GPTBigCodeModel",L]],["gpt_neo",["GPTNeoModel",eo]],["gpt_neox",["GPTNeoXModel",Go]],["codegen",["CodeGenModel",Ee]],["llama",["LlamaModel",it]],["nanochat",["NanoChatModel",Us]],["arcee",["ArceeModel",wM]],["lfm2",["Lfm2Model",yM]],["smollm3",["SmolLM3Model",xM]],["exaone",["ExaoneModel",kM]],["olmo",["OlmoModel",FM]],["olmo2",["Olmo2Model",DM]],["mobilellm",["MobileLLMModel",IM]],["granite",["GraniteModel",zM]],["granitemoehybrid",["GraniteMoeHybridModel",RM]],["cohere",["CohereModel",NM]],["gemma",["GemmaModel",UM]],["gemma2",["Gemma2Model",GM]],["vaultgemma",["VaultGemmaModel",HM]],["gemma3_text",["Gemma3Model",QM]],["helium",["HeliumModel",PM]],["glm",["GlmModel",CM]],["openelm",["OpenELMModel",JM]],["qwen2",["Qwen2Model",ZM]],["qwen3",["Qwen3Model",tw]],["phi",["PhiModel",ow]],["phi3",["Phi3Model",iw]],["mpt",["MptModel",dw]],["opt",["OPTModel",mw]],["mistral",["MistralModel",Gy]],["ministral",["MinistralModel",Hy]],["ministral3",["Ministral3Model",Qy]],["ernie4_5",["Ernie4_5Model",Jy]],["starcoder2",["Starcoder2Model",Zy]],["falcon",["FalconModel",t0]],["stablelm",["StableLmModel",c0]],["modernbert-decoder",["ModernBertDecoderModel",kt]]]),Ou=new Map([["speecht5",["SpeechT5ForSpeechToText",Ry]],["whisper",["WhisperForConditionalGeneration",Vn]],["lite-whisper",["LiteWhisperForConditionalGeneration",Ba]],["moonshine",["MoonshineForConditionalGeneration",Un]]]),J0=new Map([["speecht5",["SpeechT5ForTextToSpeech",jy]]]),Y0=new Map([["vits",["VitsModel",Eu]],["musicgen",["MusicgenForConditionalGeneration",$u]],["supertonic",["SupertonicForConditionalGeneration",wu]]]),Z0=new Map([["bert",["BertForSequenceClassification",ge]],["neobert",["NeoBertForSequenceClassification",tt]],["modernbert",["ModernBertForSequenceClassification",at]],["roformer",["RoFormerForSequenceClassification",Js]],["electra",["ElectraForSequenceClassification",C]],["esm",["EsmForSequenceClassification",$s]],["convbert",["ConvBertForSequenceClassification",qt]],["camembert",["CamembertForSequenceClassification",ye]],["deberta",["DebertaForSequenceClassification",Pt]],["deberta-v2",["DebertaV2ForSequenceClassification",Cs]],["mpnet",["MPNetForSequenceClassification",Ns]],["albert",["AlbertForSequenceClassification",Je]],["distilbert",["DistilBertForSequenceClassification",ns]],["roberta",["RobertaForSequenceClassification",Ca]],["xlm",["XLMForSequenceClassification",Aa]],["xlm-roberta",["XLMRobertaForSequenceClassification",So]],["bart",["BartForSequenceClassification",hr]],["mbart",["MBartForSequenceClassification",yr]],["mobilebert",["MobileBertForSequenceClassification",Ue]],["squeezebert",["SqueezeBertForSequenceClassification",se]]]),ev=new Map([["bert",["BertForTokenClassification",De]],["neobert",["NeoBertForTokenClassification",Re]],["modernbert",["ModernBertForTokenClassification",ht]],["roformer",["RoFormerForTokenClassification",ar]],["electra",["ElectraForTokenClassification",q]],["esm",["EsmForTokenClassification",Is]],["convbert",["ConvBertForTokenClassification",Ts]],["camembert",["CamembertForTokenClassification",et]],["deberta",["DebertaForTokenClassification",It]],["deberta-v2",["DebertaV2ForTokenClassification",Dr]],["mpnet",["MPNetForTokenClassification",Nn]],["distilbert",["DistilBertForTokenClassification",wr]],["roberta",["RobertaForTokenClassification",Sa]],["xlm",["XLMForTokenClassification",Fa]],["xlm-roberta",["XLMRobertaForTokenClassification",ko]]]),Du=new Map([["t5",["T5ForConditionalGeneration",rr]],["longt5",["LongT5ForConditionalGeneration",sr]],["mt5",["MT5ForConditionalGeneration",is]],["bart",["BartForConditionalGeneration",Yt]],["mbart",["MBartForConditionalGeneration",bs]],["marian",["MarianMTModel",ay]],["m2m_100",["M2M100ForConditionalGeneration",ly]],["blenderbot",["BlenderbotForConditionalGeneration",_r]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Ys]]]),Lu=new Map([["bloom",["BloomForCausalLM",uw]],["gpt2",["GPT2LMHeadModel",Vo]],["jais",["JAISLMHeadModel",Cn]],["gptj",["GPTJForCausalLM",E]],["gpt_bigcode",["GPTBigCodeForCausalLM",V]],["gpt_neo",["GPTNeoForCausalLM",Wo]],["gpt_neox",["GPTNeoXForCausalLM",Ko]],["codegen",["CodeGenForCausalLM",Be]],["llama",["LlamaForCausalLM",vt]],["nanochat",["NanoChatForCausalLM",Xa]],["llama4_text",["Llama4ForCausalLM",Vt]],["arcee",["ArceeForCausalLM",bM]],["lfm2",["Lfm2ForCausalLM",vM]],["smollm3",["SmolLM3ForCausalLM",TM]],["exaone",["ExaoneForCausalLM",$M]],["olmo",["OlmoForCausalLM",OM]],["olmo2",["Olmo2ForCausalLM",LM]],["mobilellm",["MobileLLMForCausalLM",AM]],["granite",["GraniteForCausalLM",BM]],["granitemoehybrid",["GraniteMoeHybridForCausalLM",jM]],["cohere",["CohereForCausalLM",VM]],["gemma",["GemmaForCausalLM",WM]],["gemma2",["Gemma2ForCausalLM",KM]],["vaultgemma",["VaultGemmaForCausalLM",qM]],["gemma3_text",["Gemma3ForCausalLM",XM]],["helium",["HeliumForCausalLM",EM]],["glm",["GlmForCausalLM",SM]],["openelm",["OpenELMForCausalLM",YM]],["qwen2",["Qwen2ForCausalLM",ew]],["qwen3",["Qwen3ForCausalLM",rw]],["phi",["PhiForCausalLM",aw]],["phi3",["Phi3ForCausalLM",lw]],["mpt",["MptForCausalLM",pw]],["opt",["OPTForCausalLM",hw]],["mbart",["MBartForCausalLM",ls]],["mistral",["MistralForCausalLM",Ky]],["ministral",["MinistralForCausalLM",qy]],["ministral3",["Ministral3ForCausalLM",Xy]],["ernie4_5",["Ernie4_5ForCausalLM",Yy]],["starcoder2",["Starcoder2ForCausalLM",e0]],["falcon",["FalconForCausalLM",r0]],["trocr",["TrOCRForCausalLM",Wy]],["stablelm",["StableLmForCausalLM",u0]],["modernbert-decoder",["ModernBertDecoderForCausalLM",gr]],["phi3_v",["Phi3VForCausalLM",Qn]]]),BT=new Map([["multi_modality",["MultiModalityCausalLM",S0]]]),tv=new Map([["bert",["BertForMaskedLM",Ce]],["neobert",["NeoBertForMaskedLM",Fe]],["modernbert",["ModernBertForMaskedLM",Oe]],["roformer",["RoFormerForMaskedLM",Xs]],["electra",["ElectraForMaskedLM",Es]],["esm",["EsmForMaskedLM",ks]],["convbert",["ConvBertForMaskedLM",ft]],["camembert",["CamembertForMaskedLM",ce]],["deberta",["DebertaForMaskedLM",qe]],["deberta-v2",["DebertaV2ForMaskedLM",Tr]],["mpnet",["MPNetForMaskedLM",As]],["albert",["AlbertForMaskedLM",Ke]],["distilbert",["DistilBertForMaskedLM",Kr]],["roberta",["RobertaForMaskedLM",Ea]],["xlm",["XLMWithLMHeadModel",Ia]],["xlm-roberta",["XLMRobertaForMaskedLM",Co]],["mobilebert",["MobileBertForMaskedLM",ze]],["squeezebert",["SqueezeBertForMaskedLM",ee]]]),rv=new Map([["bert",["BertForQuestionAnswering",fe]],["neobert",["NeoBertForQuestionAnswering",rt]],["roformer",["RoFormerForQuestionAnswering",kr]],["electra",["ElectraForQuestionAnswering",R]],["convbert",["ConvBertForQuestionAnswering",Ps]],["camembert",["CamembertForQuestionAnswering",ut]],["deberta",["DebertaForQuestionAnswering",Mr]],["deberta-v2",["DebertaV2ForQuestionAnswering",Ss]],["mpnet",["MPNetForQuestionAnswering",ue]],["albert",["AlbertForQuestionAnswering",Ye]],["distilbert",["DistilBertForQuestionAnswering",lr]],["roberta",["RobertaForQuestionAnswering",ka]],["xlm",["XLMForQuestionAnswering",Oa]],["xlm-roberta",["XLMRobertaForQuestionAnswering",La]],["mobilebert",["MobileBertForQuestionAnswering",nt]],["squeezebert",["SqueezeBertForQuestionAnswering",Me]]]),zu=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Wn]],["idefics3",["Idefics3ForConditionalGeneration",Hn]],["smolvlm",["SmolVLMForConditionalGeneration",yn]]]),sv=new Map([["llava",["LlavaForConditionalGeneration",Gn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Ra]],["moondream1",["Moondream1ForConditionalGeneration",ja]],["florence2",["Florence2ForConditionalGeneration",Va]],["qwen2-vl",["Qwen2VLForConditionalGeneration",nw]],["idefics3",["Idefics3ForConditionalGeneration",Hn]],["smolvlm",["SmolVLMForConditionalGeneration",yn]],["paligemma",["PaliGemmaForConditionalGeneration",Wa]],["llava_qwen2",["LlavaQwen2ForCausalLM",Do]],["gemma3n",["Gemma3nForConditionalGeneration",Kn]],["mistral3",["Mistral3ForConditionalGeneration",bn]]]),nv=new Map([["ultravox",["UltravoxModel",Fu]],["voxtral",["VoxtralForConditionalGeneration",z0]]]),RT=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Wn]]]),ov=new Map([["vit",["ViTForImageClassification",fw]],["ijepa",["IJepaForImageClassification",Mw]],["pvt",["PvtForImageClassification",vw]],["vit_msn",["ViTMSNForImageClassification",Ew]],["fastvit",["FastViTForImageClassification",$w]],["mobilevit",["MobileViTForImageClassification",Ow]],["mobilevitv2",["MobileViTV2ForImageClassification",Lw]],["beit",["BeitForImageClassification",Vw]],["deit",["DeiTForImageClassification",ab]],["hiera",["HieraForImageClassification",lb]],["convnext",["ConvNextForImageClassification",Lb]],["convnextv2",["ConvNextV2ForImageClassification",Bb]],["dinov2",["Dinov2ForImageClassification",jb]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",Vb]],["resnet",["ResNetForImageClassification",ub]],["swin",["SwinForImageClassification",pb]],["segformer",["SegformerForImageClassification",i0]],["efficientnet",["EfficientNetForImageClassification",p0]],["mobilenet_v1",["MobileNetV1ForImageClassification",h0]],["mobilenet_v2",["MobileNetV2ForImageClassification",g0]],["mobilenet_v3",["MobileNetV3ForImageClassification",b0]],["mobilenet_v4",["MobileNetV4ForImageClassification",x0]]]),av=new Map([["detr",["DetrForObjectDetection",Ww]],["rt_detr",["RTDetrForObjectDetection",Hw]],["rt_detr_v2",["RTDetrV2ForObjectDetection",Qw]],["rf_detr",["RFDetrForObjectDetection",Yw]],["d_fine",["DFineForObjectDetection",tb]],["table-transformer",["TableTransformerForObjectDetection",sb]],["yolos",["YolosForObjectDetection",Xb]]]),iv=new Map([["owlvit",["OwlViTForObjectDetection",Bw]],["owlv2",["Owlv2ForObjectDetection",jw]],["grounding-dino",["GroundingDinoForObjectDetection",qb]]]),no=new Map([["detr",["DetrForSegmentation",Jc]],["clipseg",["CLIPSegForImageSegmentation",No]]]),lv=new Map([["segformer",["SegformerForSemanticSegmentation",l0]],["sapiens",["SapiensForSemanticSegmentation",bb]],["swin",["SwinForSemanticSegmentation",mb]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",_0]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",M0]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",y0]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",T0]]]),cv=new Map([["detr",["DetrForSegmentation",Jc]],["maskformer",["MaskFormerForInstanceSegmentation",$b]]]),uv=new Map([["sam",["SamModel",Zb]],["sam2",["Sam2Model",ei]],["edgetam",["EdgeTamModel",sy]],["sam3_tracker",["Sam3TrackerModel",ny]]]),dv=new Map([["wav2vec2",["Wav2Vec2ForCTC",uy]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Cy]],["unispeech",["UniSpeechForCTC",by]],["unispeech-sat",["UniSpeechSatForCTC",xy]],["wavlm",["WavLMForCTC",Fy]],["hubert",["HubertForCTC",$y]],["parakeet_ctc",["ParakeetForCTC",hy]]]),pv=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",dy]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Sy]],["unispeech",["UniSpeechForSequenceClassification",yy]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Ty]],["wavlm",["WavLMForSequenceClassification",Oy]],["hubert",["HubertForSequenceClassification",Iy]],["audio-spectrogram-transformer",["ASTForAudioClassification",Ao]]]),mv=new Map([["wavlm",["WavLMForXVector",Dy]]]),hv=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Py]],["wavlm",["WavLMForAudioFrameClassification",Ly]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",py]],["pyannote",["PyAnnoteForAudioFrameClassification",fy]]]),_v=new Map([["vitmatte",["VitMatteForImageMatting",Aw]]]),jT=new Map([["patchtst",["PatchTSTForPrediction",F0]],["patchtsmixer",["PatchTSMixerForPrediction",D0]]]),fv=new Map([["swin2sr",["Swin2SRForImageSuperResolution",_b]]]),gv=new Map([["dpt",["DPTForDepthEstimation",gb]],["depth_anything",["DepthAnythingForDepthEstimation",wb]],["glpn",["GLPNForDepthEstimation",Ab]],["sapiens",["SapiensForDepthEstimation",yb]],["depth_pro",["DepthProForDepthEstimation",Tb]],["metric3d",["Metric3DForDepthEstimation",Eb]],["metric3dv2",["Metric3Dv2ForDepthEstimation",Sb]]]),Mv=new Map([["sapiens",["SapiensForNormalEstimation",vb]]]),wv=new Map([["vitpose",["VitPoseForPoseEstimation",bw]]]),bv=new Map([["clip",["CLIPVisionModelWithProjection",qa]],["siglip",["SiglipVisionModel",dt]],["jina_clip",["JinaCLIPVisionModel",Pn]]]),yv=[[OT,T.EncoderOnly],[DT,T.EncoderDecoder],[zT,T.DecoderOnly],[LT,T.AutoEncoder],[Z0,T.EncoderOnly],[ev,T.EncoderOnly],[Du,T.Seq2Seq],[Ou,T.Seq2Seq],[Lu,T.DecoderOnly],[BT,T.MultiModality],[tv,T.EncoderOnly],[rv,T.EncoderOnly],[zu,T.Vision2Seq],[sv,T.ImageTextToText],[nv,T.AudioTextToText],[ov,T.EncoderOnly],[no,T.EncoderOnly],[cv,T.EncoderOnly],[lv,T.EncoderOnly],[_v,T.EncoderOnly],[jT,T.EncoderOnly],[fv,T.EncoderOnly],[gv,T.EncoderOnly],[Mv,T.EncoderOnly],[wv,T.EncoderOnly],[av,T.EncoderOnly],[iv,T.EncoderOnly],[uv,T.MaskGeneration],[dv,T.EncoderOnly],[pv,T.EncoderOnly],[J0,T.Seq2Seq],[Y0,T.EncoderOnly],[mv,T.EncoderOnly],[hv,T.EncoderOnly],[bv,T.EncoderOnly]];for(const[g,M]of yv)for(const[N,ae]of g.values())b.set(N,M),x.set(ae,N),P.set(N,ae);const NT=[["MusicgenForConditionalGeneration",$u,T.Musicgen],["Phi3VForCausalLM",Qn,T.Phi3V],["CLIPTextModelWithProjection",zo,T.EncoderOnly],["SiglipTextModel",vn,T.EncoderOnly],["JinaCLIPTextModel",Zr,T.EncoderOnly],["ClapTextModelWithProjection",n0,T.EncoderOnly],["ClapAudioModelWithProjection",o0,T.EncoderOnly],["DacEncoderModel",K0,T.EncoderOnly],["DacDecoderModel",H0,T.EncoderOnly],["MimiEncoderModel",N0,T.EncoderOnly],["MimiDecoderModel",V0,T.EncoderOnly],["SnacEncoderModel",Q0,T.EncoderOnly],["SnacDecoderModel",X0,T.EncoderOnly],["Gemma3nForConditionalGeneration",Kn,T.ImageAudioTextToText],["SupertonicForConditionalGeneration",wu,T.Supertonic]];for(const[g,M,N]of NT)b.set(g,N),x.set(M,g),P.set(g,M);const vv=new Map([["modnet",no],["birefnet",no],["isnet",no],["ben",no]]);for(const[g,M]of vv.entries())M.set(g,["PreTrainedModel",z]),b.set(g,T.EncoderOnly),x.set(z,g),P.set(g,z);class VT extends Ut{static MODEL_CLASS_MAPPINGS=yv.map(M=>M[0]);static BASE_IF_FAIL=!0}class UT extends Ut{static MODEL_CLASS_MAPPINGS=[Z0]}class WT extends Ut{static MODEL_CLASS_MAPPINGS=[ev]}class GT extends Ut{static MODEL_CLASS_MAPPINGS=[Du]}class KT extends Ut{static MODEL_CLASS_MAPPINGS=[Ou]}class HT extends Ut{static MODEL_CLASS_MAPPINGS=[J0]}class qT extends Ut{static MODEL_CLASS_MAPPINGS=[Y0]}class QT extends Ut{static MODEL_CLASS_MAPPINGS=[Lu]}class XT extends Ut{static MODEL_CLASS_MAPPINGS=[tv]}class JT extends Ut{static MODEL_CLASS_MAPPINGS=[rv]}class YT extends Ut{static MODEL_CLASS_MAPPINGS=[zu]}class ZT extends Ut{static MODEL_CLASS_MAPPINGS=[ov]}class eP extends Ut{static MODEL_CLASS_MAPPINGS=[no]}class tP extends Ut{static MODEL_CLASS_MAPPINGS=[lv]}class rP extends Ut{static MODEL_CLASS_MAPPINGS=[cv]}class sP extends Ut{static MODEL_CLASS_MAPPINGS=[av]}class nP extends Ut{static MODEL_CLASS_MAPPINGS=[iv]}class oP extends Ut{static MODEL_CLASS_MAPPINGS=[uv]}class aP extends Ut{static MODEL_CLASS_MAPPINGS=[dv]}class iP extends Ut{static MODEL_CLASS_MAPPINGS=[pv]}class lP extends Ut{static MODEL_CLASS_MAPPINGS=[mv]}class cP extends Ut{static MODEL_CLASS_MAPPINGS=[hv]}class uP extends Ut{static MODEL_CLASS_MAPPINGS=[RT]}class dP extends Ut{static MODEL_CLASS_MAPPINGS=[_v]}class pP extends Ut{static MODEL_CLASS_MAPPINGS=[fv]}class mP extends Ut{static MODEL_CLASS_MAPPINGS=[gv]}class hP extends Ut{static MODEL_CLASS_MAPPINGS=[Mv]}class _P extends Ut{static MODEL_CLASS_MAPPINGS=[wv]}class fP extends Ut{static MODEL_CLASS_MAPPINGS=[bv]}class gP extends Ut{static MODEL_CLASS_MAPPINGS=[sv]}class MP extends Ut{static MODEL_CLASS_MAPPINGS=[nv]}class wP extends de{constructor({logits:M,past_key_values:N,encoder_outputs:ae,decoder_attentions:me=null,cross_attentions:_e=null}){super(),this.logits=M,this.past_key_values=N,this.encoder_outputs=ae,this.decoder_attentions=me,this.cross_attentions=_e}}class xt extends de{constructor({logits:M,...N}){super(),this.logits=M;const ae=Object.values(N);ae.length>0&&(this.attentions=ae)}}class xv extends de{constructor({logits:M,embeddings:N}){super(),this.logits=M,this.embeddings=N}}class Er extends de{constructor({logits:M}){super(),this.logits=M}}class Ir extends de{constructor({logits:M}){super(),this.logits=M}}class Br extends de{constructor({start_logits:M,end_logits:N}){super(),this.start_logits=M,this.end_logits=N}}class sn extends de{constructor({logits:M}){super(),this.logits=M}}class bP extends de{constructor({logits:M,past_key_values:N}){super(),this.logits=M,this.past_key_values=N}}class Tv extends de{constructor({alphas:M}){super(),this.alphas=M}}class Pv extends de{constructor({waveform:M,spectrogram:N}){super(),this.waveform=M,this.spectrogram=N}}}),"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":((e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,c=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=c,this.window=(0,n.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(a,l){return(0,n.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:l,transpose:!0})}async _call(a){(0,s.validate_audio_inputs)(a,"ASTFeatureExtractor");const l=await this._extract_fbank_features(a,this.config.max_length);if(this.config.do_normalize){const c=this.std*2,p=l.data;for(let d=0;d{t.r(r),t.d(r,{AutoFeatureExtractor:()=>i});var s=t("./src/utils/constants.js"),n=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var o=t("./src/models/feature_extractors.js");class i{static async from_pretrained(l,c={}){const p=await(0,n.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,c),d=p.feature_extractor_type,u=o[d];if(!u)throw new Error(`Unknown feature_extractor_type: '${d}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new u(p)}}}),"./src/models/auto/image_processing_auto.js":((e,r,t)=>{t.r(r),t.d(r,{AutoImageProcessor:()=>a});var s=t("./src/utils/constants.js"),n=t("./src/utils/hub.js"),o=t("./src/base/image_processors_utils.js"),i=t("./src/models/image_processors.js");class a{static async from_pretrained(c,p={}){const d=await(0,n.getModelJSON)(c,s.IMAGE_PROCESSOR_NAME,!0,p),u=d.image_processor_type??d.feature_extractor_type;let f=i[u?.replace(/Fast$/,"")];return f||(u!==void 0&&console.warn(`Image processor type '${u}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),f=o.ImageProcessor),new f(d)}}}),"./src/models/auto/processing_auto.js":((e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>c});var s=t("./src/utils/constants.js"),n=t("./src/utils/hub.js"),o=t("./src/base/processing_utils.js"),i=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class c{static async from_pretrained(d,u={}){const f=await(0,n.getModelJSON)(d,s.IMAGE_PROCESSOR_NAME,!0,u),{image_processor_type:_,feature_extractor_type:y,processor_class:I}=f;if(I&&i[I])return i[I].from_pretrained(d,u);if(!_&&!y)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const w={};if(_){const k=a[_.replace(/Fast$/,"")];if(!k)throw new Error(`Unknown image_processor_type: '${_}'.`);w.image_processor=new k(f)}if(y){const k=a[y];if(k)w.image_processor=new k(f);else{const T=l[y];if(!T)throw new Error(`Unknown feature_extractor_type: '${y}'.`);w.feature_extractor=new T(f)}}const v={};return new o.Processor(v,w,null)}}}),"./src/models/beit/image_processing_beit.js":((e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/bit/image_processing_bit.js":((e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/chinese_clip/image_processing_chinese_clip.js":((e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/clap/feature_extraction_clap.js":((e,r,t)=>{t.r(r),t.d(r,{ClapFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,n.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,n.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,n.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,c,p){let d;const u=a.length-l;if(u>0)if(c==="rand_trunc"){const f=Math.floor(Math.random()*(u+1));a=a.subarray(f,f+l),d=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${c}" not implemented`);else{if(u<0){let f=new Float64Array(l);if(f.set(a),p==="repeat")for(let _=a.length;_{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>o,CLIPImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/convnext/image_processing_convnext.js":((e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>o,ConvNextImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){const l=this.size?.shortest_edge;if(l===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(l<384){const c=Math.floor(l/this.crop_pct),[p,d]=this.get_resize_output_image_size(a,{shortest_edge:c});a=await a.resize(p,d,{resample:this.resample}),a=await a.center_crop(l,l)}else a=await a.resize(l,l,{resample:this.resample});return a}}class o extends n{}}),"./src/models/dac/feature_extraction_dac.js":((e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>n});var s=t("./src/models/encodec/feature_extraction_encodec.js");class n extends s.EncodecFeatureExtractor{}}),"./src/models/deit/image_processing_deit.js":((e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>o,DeiTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/detr/image_processing_detr.js":((e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{async _call(l){const c=await super._call(l),p=[c.pixel_values.dims[0],64,64],d=(0,n.full)(p,1n);return{...c,pixel_mask:d}}post_process_object_detection(...l){return(0,s.post_process_object_detection)(...l)}post_process_panoptic_segmentation(...l){return(0,s.post_process_panoptic_segmentation)(...l)}post_process_instance_segmentation(...l){return(0,s.post_process_instance_segmentation)(...l)}}class i extends o{}}),"./src/models/dinov3_vit/image_processing_dinov3_vit.js":((e,r,t)=>{t.r(r),t.d(r,{DINOv3ViTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/donut/image_processing_donut.js":((e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>o,DonutImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{pad_image(a,l,c,p={}){const[d,u,f]=l;let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(f).fill(_));let y=this.image_std;Array.isArray(y)||(y=new Array(f).fill(_));const I=_.map((w,v)=>-w/y[v]);return super.pad_image(a,l,c,{center:!0,constant_values:I,...p})}}class o extends n{}}),"./src/models/dpt/image_processing_dpt.js":((e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>o,DPTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/efficientnet/image_processing_efficientnet.js":((e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n 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:()=>o});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js");class o extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"EncodecFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=this.config.feature_size;if(a.length%l!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${l}).`);const c=[1,l,a.length/l];return{input_values:new n.Tensor("float32",a,c)}}}}),"./src/models/feature_extractors.js":((e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>o.ClapFeatureExtractor,DacFeatureExtractor:()=>i.DacFeatureExtractor,EncodecFeatureExtractor:()=>n.EncodecFeatureExtractor,Gemma3nAudioFeatureExtractor:()=>a.Gemma3nAudioFeatureExtractor,ImageFeatureExtractor:()=>w.ImageProcessor,MoonshineFeatureExtractor:()=>l.MoonshineFeatureExtractor,ParakeetFeatureExtractor:()=>c.ParakeetFeatureExtractor,PyAnnoteFeatureExtractor:()=>p.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>u.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>f.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>_.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>y.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>I.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),n=t("./src/models/encodec/feature_extraction_encodec.js"),o=t("./src/models/clap/feature_extraction_clap.js"),i=t("./src/models/dac/feature_extraction_dac.js"),a=t("./src/models/gemma3n/feature_extraction_gemma3n.js"),l=t("./src/models/moonshine/feature_extraction_moonshine.js"),c=t("./src/models/parakeet/feature_extraction_parakeet.js"),p=t("./src/models/pyannote/feature_extraction_pyannote.js"),d=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),u=t("./src/models/snac/feature_extraction_snac.js"),f=t("./src/models/speecht5/feature_extraction_speecht5.js"),_=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),y=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),I=t("./src/models/whisper/feature_extraction_whisper.js"),w=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"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;constructor(l,c,p){super(l,c,p);const{tasks_answer_post_processing_type:d,task_prompts_without_inputs:u,task_prompts_with_input:f}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(d??{})),this.task_prompts_without_inputs=new Map(Object.entries(u??{})),this.task_prompts_with_input=new Map(Object.entries(f??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const c=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))c.push(this.task_prompts_without_inputs.get(p));else{for(const[d,u]of this.task_prompts_with_input)if(p.includes(d)){c.push(u.replaceAll("{input}",p).replaceAll(d,""));break}c.length!==l.length&&c.push(p)}return c}post_process_generation(l,c,p){const d=this.tasks_answer_post_processing_type.get(c)??"pure_text";l=l.replaceAll("","").replaceAll("","");let u;switch(d){case"pure_text":u=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const f=d==="ocr"?"quad_boxes":"bboxes",_=l.matchAll(this.regexes[f]),y=[],I=[];for(const[w,v,...k]of _)y.push(v?v.trim():y.at(-1)??""),I.push(k.map((T,b)=>(Number(T)+.5)/this.size_per_bin*p[b%2]));u={labels:y,[f]:I};break;default:throw new Error(`Task "${c}" (of type "${d}") not yet implemented.`)}return{[c]:u}}async _call(l,c=null,p={}){if(!l&&!c)throw new Error("Either text or images must be provided");const d=await this.image_processor(l,p),u=c?this.tokenizer(this.construct_prompts(c),p):{};return{...d,...u}}}}),"./src/models/gemma3n/feature_extraction_gemma3n.js":((e,r,t)=>{t.r(r),t.d(r,{Gemma3nAudioFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const{fft_length:c,feature_size:p,min_frequency:d,max_frequency:u,sampling_rate:f,frame_length:_}=this.config,y=(0,o.mel_filter_bank)(Math.floor(1+c/2),p,d,u,f,null,"htk",!1);this.mel_filters=y,this.window=(0,o.window_function)(_,"hann")}async _extract_fbank_features(l,c){return(0,o.spectrogram)(l,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(l,{max_length:c=48e4,truncation:p=!0,padding:d=!0,pad_to_multiple_of:u=128}={}){if((0,s.validate_audio_inputs)(l,"Gemma3nAudioFeatureExtractor"),p&&l.length>c&&(l=l.slice(0,c)),d&&l.length%u!==0){const y=u-l.length%u,I=new Float64Array(l.length+y);I.set(l),this.config.padding_value!==0&&I.fill(this.config.padding_value,l.length),l=I}const f=await this._extract_fbank_features(l,this.config.max_length),_=(0,n.full)([1,f.dims[0]],!0);return{input_features:f.unsqueeze_(0),input_features_mask:_}}}}),"./src/models/gemma3n/processing_gemma3n.js":((e,r,t)=>{t.r(r),t.d(r,{Gemma3nProcessor:()=>a});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js");t("./src/utils/image.js"),t("./src/utils/audio.js");class a extends s.Processor{static image_processor_class=n.AutoImageProcessor;static feature_extractor_class=o.AutoFeatureExtractor;static tokenizer_class=i.AutoTokenizer;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(c,p,d){super(c,p,d),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:u,boa_token:f,audio_token:_,eoa_token:y,image_token_id:I,boi_token:w,image_token:v,eoi_token:k}=this.tokenizer.config;this.audio_token_id=u,this.boa_token=f,this.audio_token=_;const T=_.repeat(this.audio_seq_length);this.full_audio_sequence=` ${f}${T}${y} `,this.image_token_id=I,this.boi_token=w,this.image_token=v;const b=v.repeat(this.image_seq_length);this.full_image_sequence=` ${w}${b}${k} `}async _call(c,p=null,d=null,u={}){typeof c=="string"&&(c=[c]);let f;d&&(f=await this.feature_extractor(d,u),c=c.map(I=>I.replaceAll(this.audio_token,this.full_audio_sequence)));let _;return p&&(_=await this.image_processor(p,u),c=c.map(I=>I.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(c,u),..._,...f}}}}),"./src/models/glpn/image_processing_glpn.js":((e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/grounding_dino/image_processing_grounding_dino.js":((e,r,t)=>{t.r(r),t.d(r,{GroundingDinoImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{async _call(a){const l=await super._call(a),c=l.pixel_values.dims,p=(0,n.ones)([c[0],c[2],c[3]]);return{...l,pixel_mask:p}}}}),"./src/models/grounding_dino/processing_grounding_dino.js":((e,r,t)=>{t.r(r),t.d(r,{GroundingDinoProcessor:()=>l});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js"),i=t("./src/base/image_processors_utils.js");function a(c,p){const u=c.dims.at(-1)-1,f=c.tolist();f.fill(!1,0,1),f.fill(!1,u);const _=p.tolist();return f.map((y,I)=>y?I:null).filter(y=>y!==null).map(y=>_[y])}class l extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;async _call(p,d,u={}){const f=p?await this.image_processor(p,u):{};return{...d?this.tokenizer(d,u):{},...f}}post_process_grounded_object_detection(p,d,{box_threshold:u=.25,text_threshold:f=.25,target_sizes:_=null}={}){const{logits:y,pred_boxes:I}=p,w=y.dims[0];if(_!==null&&_.length!==w)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const v=y.dims.at(1),k=y.sigmoid(),T=k.max(-1).tolist(),b=I.tolist().map(x=>x.map(S=>(0,i.center_to_corners_format)(S))),P=[];for(let x=0;xB.map((Y,X)=>Y*S[(X+1)%2])));const O=T[x],F=[],H=[],W=[];for(let B=0;B{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{constructor(a){super(a),this.do_image_splitting=a.do_image_splitting??!0,this.max_image_size=a.max_image_size}get_resize_for_vision_encoder(a,l){let[c,p]=a.dims.slice(-2);const d=p/c;return p>=c?(p=Math.ceil(p/l)*l,c=Math.floor(p/d),c=Math.ceil(c/l)*l):(c=Math.ceil(c/l)*l,p=Math.floor(c*d),p=Math.ceil(p/l)*l),{height:c,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:c=!1}={}){let p;if(!Array.isArray(a))p=[[a]];else{if(a.length===0||!a[0])throw new Error("No images provided.");Array.isArray(a[0])?p=a:p=[a]}let d=[],u=[],f=[];const _=[],y=[];for(const x of p){let S=await Promise.all(x.map(H=>this.preprocess(H)));_.push(...S.map(H=>H.original_size)),y.push(...S.map(H=>H.reshaped_input_size)),S.forEach(H=>H.pixel_values.unsqueeze_(0));const{longest_edge:O}=this.max_image_size;let F;if(l??this.do_image_splitting){let H=new Array(S.length),W=new Array(S.length);F=await Promise.all(S.map(async(B,Y)=>{const X=this.get_resize_for_vision_encoder(B.pixel_values,O),J=await(0,n.interpolate_4d)(B.pixel_values,{size:[X.height,X.width]}),{frames:re,num_splits_h:ne,num_splits_w:le}=await this.split_image(J,this.max_image_size);return H[Y]=ne,W[Y]=le,(0,n.cat)(re,0)})),u.push(H),f.push(W)}else{const H=[O,O];F=await Promise.all(S.map(W=>(0,n.interpolate_4d)(W.pixel_values,{size:H}))),u.push(new Array(S.length).fill(0)),f.push(new Array(S.length).fill(0))}d.push((0,n.cat)(F,0))}const I=d.length,[w,v,k,T]=d[0].dims;let b,P;if(I===1)b=d[0].unsqueeze_(0),P=(0,n.full)([I,w,k,T],!0);else{const x=Math.max(...d.map(F=>F.dims.at(0)));P=(0,n.full)([I,x,k,T],!0);const S=P.data,O=x*k*T;for(let F=0;Fc||f>p){_=Math.ceil(u/c),y=Math.ceil(f/p);const I=Math.ceil(u/_),w=Math.ceil(f/y);for(let T=0;T<_;++T)for(let b=0;b{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");var i=t("./src/utils/core.js");function a(d,u,f,_,y,I){let w="";for(let v=0;v`+y.repeat(d);w+=` `}return w+=` ${_}${I}`+y.repeat(d)+`${_}`,w}function l(d,u,f,_){return`${u}${_}`+f.repeat(d)+`${u}`}function c(d,u,f,_,y,I){return d===0&&u===0?l(f,_,y,I):a(f,d,u,_,y,I)}class p extends s.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;static uses_processor_config=!0;fake_image_token="";image_token="";global_img_token="";async _call(u,f=null,_={}){_.return_row_col_info??=!0;let y;f&&(y=await this.image_processor(f,_)),Array.isArray(u)||(u=[u]);const I=y.rows??[new Array(u.length).fill(0)],w=y.cols??[new Array(u.length).fill(0)],v=this.config.image_seq_len,k=[],T=[];for(let P=0;Pc(B,O[Y],v,this.fake_image_token,this.image_token,this.global_img_token)),H=x.split(this.image_token);if(H.length===0)throw new Error("The image token should be present in the text.");let W=H[0];for(let B=0;B{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>n.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>o.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DINOv3ViTImageProcessor:()=>p.DINOv3ViTImageProcessor,DPTFeatureExtractor:()=>u.DPTFeatureExtractor,DPTImageProcessor:()=>u.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>c.DetrFeatureExtractor,DetrImageProcessor:()=>c.DetrImageProcessor,DonutFeatureExtractor:()=>d.DonutFeatureExtractor,DonutImageProcessor:()=>d.DonutImageProcessor,EfficientNetImageProcessor:()=>f.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>y.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>I.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>v.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>k.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>T.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>b.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>b.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>P.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>P.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>x.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>x.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>S.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>S.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>O.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>O.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>F.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>F.MobileViTImageProcessor,NougatImageProcessor:()=>H.NougatImageProcessor,OwlViTFeatureExtractor:()=>B.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>B.OwlViTImageProcessor,Owlv2ImageProcessor:()=>W.Owlv2ImageProcessor,Phi3VImageProcessor:()=>Y.Phi3VImageProcessor,PixtralImageProcessor:()=>X.PixtralImageProcessor,PvtImageProcessor:()=>J.PvtImageProcessor,Qwen2VLImageProcessor:()=>re.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>ne.RTDetrImageProcessor,Sam2ImageProcessor:()=>pe.Sam2ImageProcessor,Sam3ImageProcessor:()=>oe.Sam3ImageProcessor,SamImageProcessor:()=>le.SamImageProcessor,SegformerFeatureExtractor:()=>K.SegformerFeatureExtractor,SegformerImageProcessor:()=>K.SegformerImageProcessor,SiglipImageProcessor:()=>j.SiglipImageProcessor,SmolVLMImageProcessor:()=>D.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>te.Swin2SRImageProcessor,VLMImageProcessor:()=>w.VLMImageProcessor,ViTFeatureExtractor:()=>he.ViTFeatureExtractor,ViTImageProcessor:()=>he.ViTImageProcessor,VitMatteImageProcessor:()=>Ae.VitMatteImageProcessor,VitPoseImageProcessor:()=>ke.VitPoseImageProcessor,YolosFeatureExtractor:()=>Ve.YolosFeatureExtractor,YolosImageProcessor:()=>Ve.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),n=t("./src/models/bit/image_processing_bit.js"),o=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),i=t("./src/models/clip/image_processing_clip.js"),a=t("./src/models/convnext/image_processing_convnext.js"),l=t("./src/models/deit/image_processing_deit.js"),c=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/dinov3_vit/image_processing_dinov3_vit.js"),d=t("./src/models/donut/image_processing_donut.js"),u=t("./src/models/dpt/image_processing_dpt.js"),f=t("./src/models/efficientnet/image_processing_efficientnet.js"),_=t("./src/models/glpn/image_processing_glpn.js"),y=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),I=t("./src/models/idefics3/image_processing_idefics3.js"),w=t("./src/models/janus/image_processing_janus.js"),v=t("./src/models/jina_clip/image_processing_jina_clip.js"),k=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),T=t("./src/models/mask2former/image_processing_mask2former.js"),b=t("./src/models/maskformer/image_processing_maskformer.js"),P=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),x=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),S=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),O=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),F=t("./src/models/mobilevit/image_processing_mobilevit.js"),H=t("./src/models/nougat/image_processing_nougat.js"),W=t("./src/models/owlv2/image_processing_owlv2.js"),B=t("./src/models/owlvit/image_processing_owlvit.js"),Y=t("./src/models/phi3_v/image_processing_phi3_v.js"),X=t("./src/models/pixtral/image_processing_pixtral.js"),J=t("./src/models/pvt/image_processing_pvt.js"),re=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),ne=t("./src/models/rt_detr/image_processing_rt_detr.js"),le=t("./src/models/sam/image_processing_sam.js"),pe=t("./src/models/sam2/image_processing_sam2.js"),oe=t("./src/models/sam3/image_processing_sam3.js"),K=t("./src/models/segformer/image_processing_segformer.js"),j=t("./src/models/siglip/image_processing_siglip.js"),D=t("./src/models/smolvlm/image_processing_smolvlm.js"),te=t("./src/models/swin2sr/image_processing_swin2sr.js"),he=t("./src/models/vit/image_processing_vit.js"),Ae=t("./src/models/vitmatte/image_processing_vitmatte.js"),ke=t("./src/models/vitpose/image_processing_vitpose.js"),Ve=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:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{constructor(i){super({do_pad:!0,pad_size:{width:i.image_size,height:i.image_size},...i}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(i,a,l,c){return super.pad_image(i,a,l,{constant_values:this.constant_values,center:!0,...c})}}}),"./src/models/janus/processing_janus.js":((e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>c});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js"),i=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class c extends s.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;static uses_processor_config=!0;constructor(d,u,f){super(d,u,f),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(d,{images:u=null,chat_template:f="default"}={}){u?Array.isArray(u)||(u=[u]):u=await Promise.all(d.filter(F=>F.images).flatMap(F=>F.images).map(F=>l.RawImage.read(F)));const _=this.tokenizer,y=_.apply_chat_template(d,{tokenize:!1,add_generation_prompt:!0,chat_template:f}),I=F=>_.encode(F,{add_special_tokens:!1}),w=y.split(this.image_tag),v=w.length-1;if(u.length!==v)throw new Error(`Number of images provided (${u.length}) does not match number of "${this.image_tag}" image tags (${v})`);const[k,T,b]=_.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let P=I(w[0]),x=new Array(P.length).fill(!1);for(let F=1;F0){const F=await this.image_processor(u);return F.pixel_values.unsqueeze_(0),{...O,...F}}return O}}}),"./src/models/jina_clip/image_processing_jina_clip.js":((e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{constructor(i){const{resize_mode:a,fill_color:l,interpolation:c,size:p,...d}=i,u=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},f=c==="bicubic"?3:2;super({...d,size:u,resample:f,do_center_crop:!0,crop_size:p,do_normalize:!0})}}}),"./src/models/jina_clip/processing_jina_clip.js":((e,r,t)=>{t.r(r),t.d(r,{JinaCLIPProcessor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;async _call(l=null,c=null,p={}){if(!l&&!c)throw new Error("Either text or images must be provided");const d=l?this.tokenizer(l,p):{},u=c?await this.image_processor(c,p):{};return{...d,...u}}}}),"./src/models/llava/processing_llava.js":((e,r,t)=>{t.r(r),t.d(r,{LlavaProcessor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;static uses_processor_config=!0;async _call(l,c=null,p={}){const d=await this.image_processor(l,p);if(c){const[f,_]=d.pixel_values.dims.slice(-2),{image_token:y,patch_size:I,num_additional_image_tokens:w}=this.config,v=Math.floor(f/I)*Math.floor(_/I)+w;c=structuredClone(c),Array.isArray(c)||(c=[c]);for(let k=0;k{t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}}),"./src/models/mask2former/image_processing_mask2former.js":((e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>n});var s=t("./src/models/maskformer/image_processing_maskformer.js");class n extends s.MaskFormerImageProcessor{}}),"./src/models/maskformer/image_processing_maskformer.js":((e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>o,MaskFormerImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n 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 o extends n{}}),"./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"),n=t("./src/models/auto/image_processing_auto.js"),o=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{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(p,d){if(!a.hasOwnProperty(d))throw new Error(`Format ${d} is not supported.`);const[u,f]=a[d],_=this[u].bind(this),[y,I]=p.dims,w=[],v=[],k=p.tolist();for(let b=0;b0?S.reduce((F,H)=>F*H,1):0;v.push(x),w.push(O)}return[_(v),w]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(d=>d.replaceAll(" ",""))}batch_decode([p,d,u]){const[f,_]=this._decode_helper(p,"char"),[y,I]=this._decode_helper(d,"bpe"),[w,v]=this._decode_helper(u,"wp"),k=[],T=[];for(let b=0;b{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>o,MobileNetV1ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":((e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>o,MobileNetV2ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":((e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>o,MobileNetV3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":((e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>o,MobileNetV4ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/mobilevit/image_processing_mobilevit.js":((e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>o,MobileViTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/moonshine/feature_extraction_moonshine.js":((e,r,t)=>{t.r(r),t.d(r,{MoonshineFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js");class o 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 n.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"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=s.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/nougat/image_processing_nougat.js":((e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>n});var s=t("./src/models/donut/image_processing_donut.js");class n extends s.DonutImageProcessor{}}),"./src/models/owlv2/image_processing_owlv2.js":((e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>n});var s=t("./src/models/owlvit/image_processing_owlvit.js");class n extends s.OwlViTImageProcessor{}}),"./src/models/owlvit/image_processing_owlvit.js":((e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>o,OwlViTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class o extends n{}}),"./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"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.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"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");const i="";function a(c,p,d,u,f){return`${u.repeat(d*f)}${p}${c} `}class l extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;static uses_processor_config=!1;async _call(p,d=null,u={}){d||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),d=""),Array.isArray(p)||(p=[p]),Array.isArray(d)||(d=[d]);const f=this.tokenizer.bos_token,_=this.image_processor.config.image_seq_length;let y;d.some(v=>v.includes(i))?y=d.map(v=>{const k=v.replaceAll(i,i.repeat(_)),T=k.lastIndexOf(i),b=T===-1?0:T+i.length;return k.slice(0,b)+f+k.slice(b)+` `}):(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."),y=d.map(v=>a(v,f,_,i,p.length)));const I=this.tokenizer(y,u);return{...await this.image_processor(p,u),...I}}}}),"./src/models/parakeet/feature_extraction_parakeet.js":((e,r,t)=>{t.r(r),t.d(r,{ParakeetFeatureExtractor:()=>a});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/audio.js");const i=1e-5;class a extends s.FeatureExtractor{constructor(c){super(c),this.config.mel_filters??=(0,o.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");const p=(0,o.window_function)(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);const d=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(p,d)}async _extract_fbank_features(c){const p=this.config.preemphasis;c=new Float64Array(c);for(let u=c.length-1;u>=1;--u)c[u]-=p*c[u-1];return await(0,o.spectrogram)(c,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:2**-24})}async _call(c){(0,s.validate_audio_inputs)(c,"ParakeetFeatureExtractor");const p=await this._extract_fbank_features(c),d=Math.floor((c.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),u=p.data;u.fill(0,d*p.dims[1]);const[f,_]=p.dims,y=new Float64Array(_),I=new Float64Array(_);for(let k=0;k1?d-1:1;for(let k=0;k<_;++k){const T=y[k]/d,b=(I[k]-d*T*T)/w,x=1/(Math.sqrt(b)+i);for(let S=0;S{t.r(r),t.d(r,{Phi3VImageProcessor:()=>p});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");const o=336,i=[2,3],{ceil:a,floor:l,sqrt:c}=Math;class p extends s.ImageProcessor{constructor(u){super({...u,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=u.num_crops}calc_num_image_tokens_from_image_size(u,f){const{num_img_tokens:_}=this.config;return l((l(f/o)*l(u/o)+1)*_+1+(l(f/o)+1)*c(_))}get_resize_output_image_size(u,f){const _=this._num_crops,[y,I]=u.size;let w=y/I,v=1;for(;v*Math.ceil(v/w)<=_;)v+=1;v-=1;const k=Math.floor(v*336),T=Math.floor(k/w);return[k,T]}pad_image(u,f,_,y={}){const[I,w]=f,v=o*a(I/o),k=o*a(w/o),T=[1,1,1].map((b,P)=>(b-this.image_mean[P])/this.image_std[P]);return super.pad_image(u,f,{width:k,height:v},{center:!0,constant_values:T,...y})}async _call(u,{num_crops:f=null}={}){if(this._num_crops=f??=this.config.num_crops,f<4||c(f)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(u)||(u=[u]);const _=u.length,y=await Promise.all(u.map(x=>this.preprocess(x))),I=y.map(x=>x.original_size),w=y.map(x=>x.reshaped_input_size),v=[];for(const{pixel_values:x}of y){x.unsqueeze_(0);const[S,O]=x.dims.slice(-2),F=await(0,n.interpolate_4d)(x,{size:[o,o],mode:"bicubic"});if(f>0){const H=[],W=c(f),B=l(O/W),Y=l(S/W);for(let J=0;Jx.map(S=>o*a(S/o))),b=new n.Tensor("int64",T.flat(),[_,2]),P=T.map(([x,S])=>this.calc_num_image_tokens_from_image_size(S,x));return{pixel_values:k,original_sizes:I,reshaped_input_sizes:w,image_sizes:b,num_img_tokens:P}}}}),"./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"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");const i="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;async _call(p,d=null,{padding:u=!0,truncation:f=!0,num_crops:_=null}={}){Array.isArray(p)||(p=[p]);let y,I;if(d){I=await this.image_processor(d,{num_crops:_});const{num_img_tokens:w}=I,v=p.map((T,b)=>T.split(a).join(i.repeat(w[b])));y=this.tokenizer(v,{padding:u,truncation:f});const k=this.tokenizer.model.convert_tokens_to_ids([i])[0];y.input_ids.map_(T=>T==k?-T:T)}else y=this.tokenizer(p);return{...y,...I}}}}),"./src/models/pixtral/image_processing_pixtral.js":((e,r,t)=>{t.r(r),t.d(r,{PixtralImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{get_resize_output_image_size(i,a){const{longest_edge:l}=a;if(l===void 0)throw new Error("size must contain 'longest_edge'");const[c,p]=i.size,d=Math.max(c,p)/l;let u=c,f=p;d>1&&(u=Math.floor(c/d),f=Math.floor(p/d));const{patch_size:_,spatial_merge_size:y}=this.config;if(!y)throw new Error("config must contain 'spatial_merge_size'");const I=_*y,w=Math.floor((u-1)/I)+1,v=Math.floor((f-1)/I)+1;return[w*I,v*I]}}}),"./src/models/pixtral/processing_pixtral.js":((e,r,t)=>{t.r(r),t.d(r,{PixtralProcessor:()=>i});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class i extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;static uses_processor_config=!0;async _call(l,c=null,p={}){const d=await this.image_processor(l,p);if(c){const[f,_]=d.pixel_values.dims.slice(-2),{image_token:y,image_break_token:I,image_end_token:w,patch_size:v,spatial_merge_size:k}=this.config,T=v*k,b=Math.floor(f/T),P=Math.floor(_/T);c=structuredClone(c),Array.isArray(c)||(c=[c]);for(let x=0;x{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,Gemma3nProcessor:()=>n.Gemma3nProcessor,GroundingDinoProcessor:()=>o.GroundingDinoProcessor,Idefics3Processor:()=>i.Idefics3Processor,JinaCLIPProcessor:()=>l.JinaCLIPProcessor,LlavaProcessor:()=>c.LlavaProcessor,MgpstrProcessor:()=>p.MgpstrProcessor,MoonshineProcessor:()=>d.MoonshineProcessor,OwlViTProcessor:()=>u.OwlViTProcessor,PaliGemmaProcessor:()=>f.PaliGemmaProcessor,Phi3VProcessor:()=>_.Phi3VProcessor,PixtralProcessor:()=>y.PixtralProcessor,PyAnnoteProcessor:()=>I.PyAnnoteProcessor,Qwen2VLProcessor:()=>w.Qwen2VLProcessor,Sam2Processor:()=>k.Sam2Processor,Sam2VideoProcessor:()=>k.Sam2VideoProcessor,SamProcessor:()=>v.SamProcessor,SmolVLMProcessor:()=>T.SmolVLMProcessor,SpeechT5Processor:()=>b.SpeechT5Processor,UltravoxProcessor:()=>P.UltravoxProcessor,VLChatProcessor:()=>a.VLChatProcessor,VoxtralProcessor:()=>x.VoxtralProcessor,Wav2Vec2Processor:()=>S.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>O.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>F.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),n=t("./src/models/gemma3n/processing_gemma3n.js"),o=t("./src/models/grounding_dino/processing_grounding_dino.js"),i=t("./src/models/idefics3/processing_idefics3.js"),a=t("./src/models/janus/processing_janus.js"),l=t("./src/models/jina_clip/processing_jina_clip.js"),c=t("./src/models/llava/processing_llava.js"),p=t("./src/models/mgp_str/processing_mgp_str.js"),d=t("./src/models/moonshine/processing_moonshine.js"),u=t("./src/models/owlvit/processing_owlvit.js"),f=t("./src/models/paligemma/processing_paligemma.js"),_=t("./src/models/phi3_v/processing_phi3_v.js"),y=t("./src/models/pixtral/processing_pixtral.js"),I=t("./src/models/pyannote/processing_pyannote.js"),w=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),v=t("./src/models/sam/processing_sam.js"),k=t("./src/models/sam2/processing_sam2.js"),T=t("./src/models/smolvlm/processing_smolvlm.js"),b=t("./src/models/speecht5/processing_speecht5.js"),P=t("./src/models/ultravox/processing_ultravox.js"),x=t("./src/models/voxtral/processing_voxtral.js"),S=t("./src/models/wav2vec2/processing_wav2vec2.js"),O=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),F=t("./src/models/whisper/processing_whisper.js")}),"./src/models/pvt/image_processing_pvt.js":((e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n 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"),n=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");class i extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const c=[1,1,l.length];return{input_values:new n.Tensor("float32",l,c)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,c){const p=c/this.samples_to_frames(c)/this.config.sampling_rate,d=[];for(const u of l.tolist()){const f=[];let _=-1;for(let y=0;y({id:y,start:I*p,end:w*p,confidence:v/(w-I)})))}return d}}}),"./src/models/pyannote/processing_pyannote.js":((e,r,t)=>{t.r(r),t.d(r,{PyAnnoteProcessor:()=>o});var s=t("./src/base/processing_utils.js"),n=t("./src/models/pyannote/feature_extraction_pyannote.js");class o extends s.Processor{static feature_extractor_class=n.PyAnnoteFeatureExtractor;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}}}),"./src/models/qwen2_vl/image_processing_qwen2_vl.js":((e,r,t)=>{t.r(r),t.d(r,{Qwen2VLImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{async _call(a,...l){const{pixel_values:c,original_sizes:p,reshaped_input_sizes:d}=await super._call(a,...l);let u=c;const{temporal_patch_size:f,merge_size:_,patch_size:y}=this.config;u.dims[0]===1&&(u=(0,n.cat)(Array.from({length:f},()=>u),0));const I=u.dims[0]/f,w=u.dims[1],v=Math.floor(u.dims[2]/y),k=Math.floor(u.dims[3]/y),T=u.view(I,f,w,Math.floor(v/_),_,y,Math.floor(k/_),_,y).permute(0,3,6,4,7,2,1,5,8).view(I*v*k,w*f*y*y),b=new n.Tensor("int64",[I,v,k],[1,3]);return{pixel_values:T,image_grid_thw:b,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"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");t("./src/utils/image.js");class i extends s.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;async _call(l,c=null,...p){Array.isArray(l)||(l=[l]);let d,u;if(c&&(d=await this.image_processor(c),u=d.image_grid_thw),u){let _=this.image_processor.config.merge_size**2,y=0;const I=u.tolist();l=l.map(w=>{for(;w.includes("<|image_pad|>");){const v=Number(I[y++].reduce((k,T)=>k*T,1n));w=w.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(v/_)))}return w.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...d}}}}),"./src/models/rt_detr/image_processing_rt_detr.js":((e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n 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"),n=t("./src/utils/core.js"),o=t("./src/utils/tensor.js");class i extends s.ImageProcessor{reshape_input_points(l,c,p,d=!1){l=structuredClone(l);let u=(0,n.calculateDimensions)(l);if(u.length===3)d||(u=[1,...u]),l=[l];else if(u.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let f=0;fd!==c.dims[u]))throw Error(`The first ${p.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new o.Tensor("int64",l.flat(1/0).map(BigInt),p)}async _call(l,{input_points:c=null,input_labels:p=null,input_boxes:d=null}={}){const u=await super._call(l);if(c&&(u.input_points=this.reshape_input_points(c,u.original_sizes,u.reshaped_input_sizes)),p){if(!u.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");u.input_labels=this.add_input_labels(p,u.input_points)}return d&&(u.input_boxes=this.reshape_input_points(d,u.original_sizes,u.reshaped_input_sizes,!0)),u}async post_process_masks(l,c,p,{mask_threshold:d=0,binarize:u=!0,pad_size:f=null}={}){const _=[];f=f??this.pad_size??this.size;const y=[f.height,f.width];for(let I=0;Id&&(b[P]=1);k=new o.Tensor("bool",b,k.dims)}_.push(k)}return _}generate_crop_boxes(l,c,{crop_n_layers:p=0,overlap_ratio:d=512/1500,points_per_crop:u=32,crop_n_points_downscale_factor:f=1}={}){}}}),"./src/models/sam/processing_sam.js":((e,r,t)=>{t.r(r),t.d(r,{SamProcessor:()=>o});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js");class o extends s.Processor{static image_processor_class=n.AutoImageProcessor;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)}}}),"./src/models/sam2/image_processing_sam2.js":((e,r,t)=>{t.r(r),t.d(r,{Sam2ImageProcessor:()=>s.SamImageProcessor});var s=t("./src/models/sam/image_processing_sam.js")}),"./src/models/sam2/processing_sam2.js":((e,r,t)=>{t.r(r),t.d(r,{Sam2Processor:()=>n,Sam2VideoProcessor:()=>o});var s=t("./src/models/sam/processing_sam.js");class n extends s.SamProcessor{}class o extends n{}}),"./src/models/sam3/image_processing_sam3.js":((e,r,t)=>{t.r(r),t.d(r,{Sam3ImageProcessor:()=>s.Sam2ImageProcessor});var s=t("./src/models/sam2/image_processing_sam2.js")}),"./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"),n=t("./src/utils/tensor.js"),o=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const c=this.config.sampling_rate,p=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(c/2),c,null,"kaldi",!0);this.mel_filters=p,this.window=(0,o.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(l,c){return l=l.map(p=>p*32768),(0,o.spectrogram)(l,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:c,transpose:!0})}async _call(l,{padding:c=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:d=!0,return_attention_mask:u=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let f=await this._extract_fbank_features(l,this.config.max_length);if(d){const[b,P]=f.dims,x=f.data;for(let S=0;S0){const O=new Float32Array(P*(b+S));O.set(x),O.fill(this.config.padding_value,x.length);const F=b+S;f=new n.Tensor(f.type,O,[F,P]),u&&(_=new n.Tensor("int64",new BigInt64Array(F),[1,F]),_.data.fill(1n,0,b))}}const[y,I]=f.dims,w=this.config.stride;if(y%w!==0)throw new Error(`The number of frames (${y}) must be a multiple of the stride (${w}).`);const k=f.view(1,Math.floor(y/w),I*w),T={input_features:k};if(u){const b=k.dims[1],P=new BigInt64Array(b);if(_){const x=_.data;for(let S=1,O=0;S{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>o,SegformerImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class o extends n{}}),"./src/models/siglip/image_processing_siglip.js":((e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n 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:()=>n});var s=t("./src/models/dac/feature_extraction_dac.js");class n extends s.DacFeatureExtractor{}}),"./src/models/speecht5/feature_extraction_speecht5.js":((e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");class n 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"),n=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js");class i extends s.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=o.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/swin2sr/image_processing_swin2sr.js":((e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{pad_image(i,a,l,c={}){const[p,d,u]=a;return super.pad_image(i,a,{width:d+(l-d%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...c})}}}),"./src/models/ultravox/processing_ultravox.js":((e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=s.AutoFeatureExtractor;static uses_processor_config=!0;async _call(l,c=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let d={};if(c){const f=c.length,{input_features:_}=await this.feature_extractor(c,{...p,max_length:f}),y=Math.round(f/this.config.encoder_ds_factor+1e-4),I=1+Math.ceil(y/this.config.stack_factor);d.audio_token_len=[I],d.audio_values=_;const w=this.config.audio_placeholder;if(!l.includes(w))throw new Error(`The input text does not contain the image token ${w}.`);l=l.replaceAll(w,w.repeat(I))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...d}}}}),"./src/models/vit/image_processing_vit.js":((e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>o,ViTImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{}class o extends n{}}),"./src/models/vitmatte/image_processing_vitmatte.js":((e,r,t)=>{t.r(r),t.d(r,{VitMatteImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{async _call(a,l){Array.isArray(a)||(a=[a]),Array.isArray(l)||(l=[l]);const c=await Promise.all(a.map(u=>this.preprocess(u))),p=await Promise.all(l.map(u=>this.preprocess(u,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,n.stack)(c.map((u,f)=>(0,n.cat)([u.pixel_values,p[f].pixel_values],0)),0),original_sizes:c.map(u=>u.original_size),reshaped_input_sizes:c.map(u=>u.reshaped_input_size)}}}}),"./src/models/vitpose/image_processing_vitpose.js":((e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_pose_estimation(i,a,{threshold:l=null}={}){const c=i.tolist(),[p,d,u,f]=i.dims,_=[];for(let y=0;y{t.r(r),t.d(r,{VoxtralProcessor:()=>d});var s=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js"),i=t("./src/utils/tensor.js");const a="[AUDIO]",l="[BEGIN_AUDIO]",c=375;function p(u,f){const _=[];for(let y=0;yp(F,T)),P=b.map(F=>F.length),x=b.flat(),S=(await Promise.all(x.map(F=>this.feature_extractor(F,y)))).map(F=>F.input_features);I.audio_values=S.length>1?(0,i.cat)(S,0):S[0];let O=v[0];for(let F=0;F{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js");class o extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const c=a.reduce((d,u)=>d+u,0)/a.length,p=a.reduce((d,u)=>d+(u-c)**2,0)/a.length;return a.map(d=>(d-c)/Math.sqrt(p+1e-7))}async _call(a){(0,s.validate_audio_inputs)(a,"Wav2Vec2FeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));let l=a;this.config.do_normalize&&(l=this._zero_mean_unit_var_norm(l));const c=[1,l.length];return{input_values:new n.Tensor("float32",l,c),attention_mask:new n.Tensor("int64",new BigInt64Array(l.length).fill(1n),c)}}}}),"./src/models/wav2vec2/processing_wav2vec2.js":((e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>i});var s=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=s.AutoTokenizer;static feature_extractor_class=n.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./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"),n=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=s.AutoTokenizer;static feature_extractor_class=n.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/wespeaker/feature_extraction_wespeaker.js":((e,r,t)=>{t.r(r),t.d(r,{WeSpeakerFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,c=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=c,this.window=(0,n.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,n.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(a){(0,s.validate_audio_inputs)(a,"WeSpeakerFeatureExtractor");const l=(await this._extract_fbank_features(a)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const c=l.mean(1).data,p=l.data,[d,u,f]=l.dims;for(let _=0;_{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>n,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>o,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"]],n=new Map(s),o=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=o.get(a);if(l===void 0){const c=a.match(/^<\|([a-z]{2})\|>$/);if(c&&(a=c[1]),n.has(a))l=a;else{const d=a.length===2?n.keys():n.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 n=t("./src/utils/audio.js"),o=t("./src/utils/maths.js");class i extends s.FeatureExtractor{constructor(l){super(l),this.config.mel_filters??=(0,n.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,n.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const c=await(0,n.spectrogram)(l,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(l.length/this.config.hop_length),this.config.nb_max_frames)}),p=c.data,d=(0,o.max)(p)[0];for(let u=0;ud?(l.length>this.config.n_samples&&console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),p=l.slice(0,d)):(p=new Float32Array(d),p.set(l)),{input_features:(await this._extract_fbank_features(p)).unsqueeze_(0)}}}}),"./src/models/whisper/generation_whisper.js":((e,r,t)=>{t.r(r),t.d(r,{WhisperGenerationConfig:()=>n});var s=t("./src/generation/configuration_utils.js");class n extends s.GenerationConfig{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;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"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class i extends o.Processor{static tokenizer_class=n.AutoTokenizer;static feature_extractor_class=s.AutoFeatureExtractor;async _call(l){return await this.feature_extractor(l)}}}),"./src/models/yolos/image_processing_yolos.js":((e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>o,YolosImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js");class n extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class o extends n{}}),"./src/ops/registry.js":((e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>i});var s=t("./src/backends/onnx.js"),n=t("./src/utils/tensor.js");const o=async(a,l,c)=>{const p=await(0,s.createInferenceSession)(new Uint8Array(a),l);return(async d=>{const u=(0,s.isONNXProxy)(),f=Object.fromEntries(Object.entries(d).map(([y,I])=>[y,(u?I.clone():I).ort_tensor])),_=await(0,s.runInferenceSession)(p,f);return Array.isArray(c)?c.map(y=>new n.Tensor(_[y])):new n.Tensor(_[c])})};class i{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=o([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=o([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=o([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=o([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=o([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=o([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=o([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=o([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}}}),"./src/pipelines.js":((e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>W,AutomaticSpeechRecognitionPipeline:()=>Y,BackgroundRemovalPipeline:()=>ne,DepthEstimationPipeline:()=>te,DocumentQuestionAnsweringPipeline:()=>K,FeatureExtractionPipeline:()=>F,FillMaskPipeline:()=>k,ImageClassificationPipeline:()=>J,ImageFeatureExtractionPipeline:()=>H,ImageSegmentationPipeline:()=>re,ImageToImagePipeline:()=>D,ImageToTextPipeline:()=>X,ObjectDetectionPipeline:()=>pe,Pipeline:()=>y,QuestionAnsweringPipeline:()=>v,SummarizationPipeline:()=>b,Text2TextGenerationPipeline:()=>T,TextClassificationPipeline:()=>I,TextGenerationPipeline:()=>S,TextToAudioPipeline:()=>j,TokenClassificationPipeline:()=>w,TranslationPipeline:()=>P,ZeroShotAudioClassificationPipeline:()=>B,ZeroShotClassificationPipeline:()=>O,ZeroShotImageClassificationPipeline:()=>le,ZeroShotObjectDetectionPipeline:()=>oe,pipeline:()=>ke});var s=t("./src/tokenizers.js"),n=t("./src/models.js"),o=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),c=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),d=t("./src/utils/image.js");async function u(Te){return Array.isArray(Te)||(Te=[Te]),await Promise.all(Te.map(Q=>d.RawImage.read(Q)))}async function f(Te,Q){return Array.isArray(Te)||(Te=[Te]),await Promise.all(Te.map(z=>typeof z=="string"||z instanceof URL?(0,c.read_audio)(z,Q):z instanceof Float64Array?new Float32Array(z):z))}function _(Te,Q){Q&&(Te=Te.map(xe=>xe|0));const[z,de,be,ve]=Te;return{xmin:z,ymin:de,xmax:be,ymax:ve}}class y extends i.Callable{constructor({task:Q,model:z,tokenizer:de=null,processor:be=null}){super(),this.task=Q,this.model=z,this.tokenizer=de,this.processor=be}async dispose(){await this.model.dispose()}}class I extends y{constructor(Q){super(Q)}async _call(Q,{top_k:z=1}={}){const de=this.tokenizer(Q,{padding:!0,truncation:!0}),be=await this.model(de),ve=this.model.config.problem_type==="multi_label_classification"?ge=>ge.sigmoid():ge=>new p.Tensor("float32",(0,l.softmax)(ge.data),ge.dims),xe=this.model.config.id2label,Ce=[];for(const ge of be.logits){const De=ve(ge),fe=await(0,p.topk)(De,z),Pe=fe[0].tolist(),Fe=fe[1].tolist().map((tt,Re)=>({label:xe?xe[tt]:`LABEL_${tt}`,score:Pe[Re]}));z===1?Ce.push(...Fe):Ce.push(Fe)}return Array.isArray(Q)||z===1?Ce:Ce[0]}}class w extends y{constructor(Q){super(Q)}async _call(Q,{ignore_labels:z=["O"]}={}){const de=Array.isArray(Q),be=this.tokenizer(de?Q:[Q],{padding:!0,truncation:!0}),xe=(await this.model(be)).logits,Ce=this.model.config.id2label,ge=[];for(let De=0;DeOe==this.tokenizer.sep_token_id);ge[Pe].map((Oe,at)=>Oe==1&&(at===0||at>Fe&&De.findIndex(ht=>ht==We[at])===-1));const tt=ve[Pe].tolist(),Re=xe[Pe].tolist();for(let Oe=1;Oeat==We[Oe])!==-1)&&(tt[Oe]=-1/0,Re[Oe]=-1/0);const rt=(0,l.softmax)(tt).map((Oe,at)=>[Oe,at]),Ze=(0,l.softmax)(Re).map((Oe,at)=>[Oe,at]);rt[0][0]=0,Ze[0][0]=0;const je=(0,a.product)(rt,Ze).filter(Oe=>Oe[0][1]<=Oe[1][1]).map(Oe=>[Oe[0][1],Oe[1][1],Oe[0][0]*Oe[1][0]]).sort((Oe,at)=>at[2]-Oe[2]);for(let Oe=0;Oett==this.tokenizer.mask_token_id);if(De===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const fe=be[Ce][De],Pe=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(fe.data),fe.dims),z),We=Pe[0].tolist(),Fe=Pe[1].tolist();ve.push(Fe.map((tt,Re)=>{const rt=ge.slice();return rt[De]=tt,{score:We[Re],token:Number(tt),token_str:this.tokenizer.decode([tt]),sequence:this.tokenizer.decode(rt,{skip_special_tokens:!0})}}))}return Array.isArray(Q)?ve:ve[0]}}class T extends y{_key="generated_text";constructor(Q){super(Q)}async _call(Q,z={}){Array.isArray(Q)||(Q=[Q]),this.model.config.prefix&&(Q=Q.map(ge=>this.model.config.prefix+ge));const de=this.model.config.task_specific_params;de&&de[this.task]&&de[this.task].prefix&&(Q=Q.map(ge=>de[this.task].prefix+ge));const be=this.tokenizer,ve={padding:!0,truncation:!0};let xe;this instanceof P&&"_build_translation_inputs"in be?xe=be._build_translation_inputs(Q,ve,z):xe=be(Q,ve);const Ce=await this.model.generate({...xe,...z});return be.batch_decode(Ce,{skip_special_tokens:!0}).map(ge=>({[this._key]:ge}))}}class b extends T{_key="summary_text";constructor(Q){super(Q)}}class P extends T{_key="translation_text";constructor(Q){super(Q)}}function x(Te){return Array.isArray(Te)&&Te.every(Q=>"role"in Q&&"content"in Q)}class S extends y{constructor(Q){super(Q)}async _call(Q,z={}){let de=!1,be=!1,ve=z.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,xe;if(typeof Q=="string")xe=Q=[Q];else if(Array.isArray(Q)&&Q.every(Fe=>typeof Fe=="string"))de=!0,xe=Q;else{if(x(Q))Q=[Q];else if(Array.isArray(Q)&&Q.every(x))de=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");be=!0,xe=Q.map(Fe=>this.tokenizer.apply_chat_template(Fe,{tokenize:!1,add_generation_prompt:!0})),ve=!1}const Ce=be?!1:z.return_full_text??!0;this.tokenizer.padding_side="left";const ge=this.tokenizer(xe,{add_special_tokens:ve,padding:!0,truncation:!0}),De=await this.model.generate({...ge,...z}),fe=this.tokenizer.batch_decode(De,{skip_special_tokens:!0});let Pe;!Ce&&ge.input_ids.dims.at(-1)>0&&(Pe=this.tokenizer.batch_decode(ge.input_ids,{skip_special_tokens:!0}).map(Fe=>Fe.length));const We=Array.from({length:Q.length},Fe=>[]);for(let Fe=0;Fe[z.toLowerCase(),de])),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,z,{hypothesis_template:de="This example is {}.",multi_label:be=!1}={}){const ve=Array.isArray(Q);ve||(Q=[Q]),Array.isArray(z)||(z=[z]);const xe=z.map(De=>de.replace("{}",De)),Ce=be||z.length===1,ge=[];for(const De of Q){const fe=[];for(const Fe of xe){const tt=this.tokenizer(De,{text_pair:Fe,padding:!0,truncation:!0}),Re=await this.model(tt);Ce?fe.push([Re.logits.data[this.contradiction_id],Re.logits.data[this.entailment_id]]):fe.push(Re.logits.data[this.entailment_id])}const We=(Ce?fe.map(Fe=>(0,l.softmax)(Fe)[1]):(0,l.softmax)(fe)).map((Fe,tt)=>[Fe,tt]).sort((Fe,tt)=>tt[0]-Fe[0]);ge.push({sequence:De,labels:We.map(Fe=>z[Fe[1]]),scores:We.map(Fe=>Fe[0])})}return ve?ge:ge[0]}}class F extends y{constructor(Q){super(Q)}async _call(Q,{pooling:z="none",normalize:de=!1,quantize:be=!1,precision:ve="binary"}={}){const xe=this.tokenizer(Q,{padding:!0,truncation:!0}),Ce=await this.model(xe);let ge=Ce.last_hidden_state??Ce.logits??Ce.token_embeddings;switch(z){case"none":break;case"mean":ge=(0,p.mean_pooling)(ge,xe.attention_mask);break;case"first_token":case"cls":ge=ge.slice(null,0);break;case"last_token":case"eos":ge=ge.slice(null,-1);break;default:throw Error(`Pooling method '${z}' not supported.`)}return de&&(ge=ge.normalize(2,-1)),be&&(ge=(0,p.quantize_embeddings)(ge,ve)),ge}}class H extends y{constructor(Q){super(Q)}async _call(Q,{pool:z=null}={}){const de=await u(Q),{pixel_values:be}=await this.processor(de),ve=await this.model({pixel_values:be});let xe;if(z){if(!("pooler_output"in ve))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");xe=ve.pooler_output}else xe=ve.last_hidden_state??ve.logits??ve.image_embeds;return xe}}class W extends y{constructor(Q){super(Q)}async _call(Q,{top_k:z=5}={}){const de=this.processor.feature_extractor.config.sampling_rate,be=await f(Q,de),ve=this.model.config.id2label,xe=[];for(const Ce of be){const ge=await this.processor(Ce),fe=(await this.model(ge)).logits[0],Pe=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(fe.data),fe.dims),z),We=Pe[0].tolist(),tt=Pe[1].tolist().map((Re,rt)=>({label:ve?ve[Re]:`LABEL_${Re}`,score:We[rt]}));xe.push(tt)}return Array.isArray(Q)?xe:xe[0]}}class B extends y{constructor(Q){super(Q)}async _call(Q,z,{hypothesis_template:de="This is a sound of {}."}={}){const be=!Array.isArray(Q);be&&(Q=[Q]);const ve=z.map(fe=>de.replace("{}",fe)),xe=this.tokenizer(ve,{padding:!0,truncation:!0}),Ce=this.processor.feature_extractor.config.sampling_rate,ge=await f(Q,Ce),De=[];for(const fe of ge){const Pe=await this.processor(fe),We=await this.model({...xe,...Pe}),Fe=(0,l.softmax)(We.logits_per_audio.data);De.push([...Fe].map((tt,Re)=>({score:tt,label:z[Re]})))}return be?De[0]:De}}class Y extends y{constructor(Q){super(Q)}async _call(Q,z={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(Q,z);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(Q,z);case"moonshine":return this._call_moonshine(Q,z);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(Q,z){z.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),z.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const de=!Array.isArray(Q);de&&(Q=[Q]);const be=this.processor.feature_extractor.config.sampling_rate,ve=await f(Q,be),xe=[];for(const Ce of ve){const ge=await this.processor(Ce),fe=(await this.model(ge)).logits[0],Pe=[];for(const Fe of fe)Pe.push((0,l.max)(Fe.data)[1]);const We=this.tokenizer.decode(Pe,{skip_special_tokens:!0}).trim();xe.push({text:We})}return de?xe[0]:xe}async _call_whisper(Q,z){const de=z.return_timestamps??!1,be=z.chunk_length_s??0,ve=z.force_full_sequences??!1;let xe=z.stride_length_s??null;const Ce={...z};de==="word"&&(Ce.return_token_timestamps=!0,Ce.return_timestamps=!1);const ge=!Array.isArray(Q);ge&&(Q=[Q]);const De=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,fe=this.processor.feature_extractor.config.hop_length,Pe=this.processor.feature_extractor.config.sampling_rate,We=await f(Q,Pe),Fe=[];for(const tt of We){let Re=[];if(be>0){if(xe===null)xe=be/6;else if(be<=xe)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const je=Pe*be,Oe=Pe*xe,at=je-2*Oe;let ht=0;for(;;){const Nt=ht+je,kt=tt.subarray(ht,Nt),gr=await this.processor(kt),Or=ht===0,Bt=Nt>=tt.length;if(Re.push({stride:[kt.length,Or?0:Oe,Bt?0:Oe],input_features:gr.input_features,is_last:Bt}),Bt)break;ht+=at}}else Re=[{stride:[tt.length,0,0],input_features:(await this.processor(tt)).input_features,is_last:!0}];for(const je of Re){Ce.num_frames=Math.floor(je.stride[0]/fe);const Oe=await this.model.generate({inputs:je.input_features,...Ce});de==="word"?(je.tokens=Oe.sequences.tolist()[0],je.token_timestamps=Oe.token_timestamps.tolist()[0].map(at=>(0,l.round)(at,2))):je.tokens=Oe[0].tolist(),je.stride=je.stride.map(at=>at/Pe)}const[rt,Ze]=this.tokenizer._decode_asr(Re,{time_precision:De,return_timestamps:de,force_full_sequences:ve});Fe.push({text:rt,...Ze})}return ge?Fe[0]:Fe}async _call_moonshine(Q,z){const de=!Array.isArray(Q);de&&(Q=[Q]);const be=this.processor.feature_extractor.config.sampling_rate,ve=await f(Q,be),xe=[];for(const Ce of ve){const ge=await this.processor(Ce),De=Math.floor(Ce.length/be)*6,fe=await this.model.generate({max_new_tokens:De,...z,...ge}),Pe=this.processor.batch_decode(fe,{skip_special_tokens:!0})[0];xe.push({text:Pe})}return de?xe[0]:xe}}class X extends y{constructor(Q){super(Q)}async _call(Q,z={}){const de=Array.isArray(Q),be=await u(Q),{pixel_values:ve}=await this.processor(be),xe=[];for(const Ce of ve){Ce.dims=[1,...Ce.dims];const ge=await this.model.generate({inputs:Ce,...z}),De=this.tokenizer.batch_decode(ge,{skip_special_tokens:!0}).map(fe=>({generated_text:fe.trim()}));xe.push(De)}return de?xe:xe[0]}}class J extends y{constructor(Q){super(Q)}async _call(Q,{top_k:z=5}={}){const de=await u(Q),{pixel_values:be}=await this.processor(de),ve=await this.model({pixel_values:be}),xe=this.model.config.id2label,Ce=[];for(const ge of ve.logits){const De=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(ge.data),ge.dims),z),fe=De[0].tolist(),We=De[1].tolist().map((Fe,tt)=>({label:xe?xe[Fe]:`LABEL_${Fe}`,score:fe[tt]}));Ce.push(We)}return Array.isArray(Q)?Ce:Ce[0]}}class re extends y{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:z=.5,mask_threshold:de=.5,overlap_mask_area_threshold:be=.8,label_ids_to_fuse:ve=null,target_sizes:xe=null,subtask:Ce=null}={}){if(Array.isArray(Q)&&Q.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const De=await u(Q),fe=De.map(je=>[je.height,je.width]),Pe=await this.processor(De),{inputNames:We,outputNames:Fe}=this.model.sessions.model;if(!We.includes("pixel_values")){if(We.length!==1)throw Error(`Expected a single input name, but got ${We.length} inputs: ${We}.`);const je=We[0];if(je in Pe)throw Error(`Input name ${je} already exists in the inputs.`);Pe[je]=Pe.pixel_values}const tt=await this.model(Pe);let Re=null;if(Ce!==null)Re=this.subtasks_mapping[Ce];else if(this.processor.image_processor){for(const[je,Oe]of Object.entries(this.subtasks_mapping))if(Oe in this.processor.image_processor){Re=this.processor.image_processor[Oe].bind(this.processor.image_processor),Ce=je;break}}const rt=this.model.config.id2label,Ze=[];if(Ce)if(Ce==="panoptic"||Ce==="instance"){const je=Re(tt,z,de,be,ve,xe??fe)[0],Oe=je.segmentation;for(const at of je.segments_info){const ht=new Uint8ClampedArray(Oe.data.length);for(let kt=0;ktgr<-1e-5||gr>1+1e-5)&&Nt.sigmoid_();const kt=await d.RawImage.fromTensor(Nt.mul_(255).to("uint8")).resize(ht[1],ht[0]);Ze.push({label:null,score:null,mask:kt})}}return Ze}}class ne extends re{constructor(Q){super(Q)}async _call(Q,z={}){if(Array.isArray(Q)&&Q.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const be=await u(Q),ve=await super._call(Q,z);return be.map((Ce,ge)=>{const De=Ce.clone();return De.putAlpha(ve[ge].mask),De})}}class le extends y{constructor(Q){super(Q)}async _call(Q,z,{hypothesis_template:de="This is a photo of {}"}={}){const be=Array.isArray(Q),ve=await u(Q),xe=z.map(We=>de.replace("{}",We)),Ce=this.tokenizer(xe,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:ge}=await this.processor(ve),De=await this.model({...Ce,pixel_values:ge}),fe=this.model.config.model_type==="siglip"?We=>We.sigmoid().data:We=>(0,l.softmax)(We.data),Pe=[];for(const We of De.logits_per_image){const tt=[...fe(We)].map((Re,rt)=>({score:Re,label:z[rt]}));tt.sort((Re,rt)=>rt.score-Re.score),Pe.push(tt)}return be?Pe:Pe[0]}}class pe extends y{constructor(Q){super(Q)}async _call(Q,{threshold:z=.9,percentage:de=!1}={}){const be=Array.isArray(Q);if(be&&Q.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const ve=await u(Q),xe=de?null:ve.map(Fe=>[Fe.height,Fe.width]),{pixel_values:Ce,pixel_mask:ge}=await this.processor(ve),De=await this.model({pixel_values:Ce,pixel_mask:ge}),fe=this.processor.image_processor.post_process_object_detection(De,z,xe),Pe=this.model.config.id2label,We=fe.map(Fe=>Fe.boxes.map((tt,Re)=>({score:Fe.scores[Re],label:Pe[Fe.classes[Re]],box:_(tt,!de)})));return be?We:We[0]}}class oe extends y{constructor(Q){super(Q)}async _call(Q,z,{threshold:de=.1,top_k:be=null,percentage:ve=!1}={}){const xe=Array.isArray(Q),Ce=await u(Q),ge=this.tokenizer(z,{padding:!0,truncation:!0}),De=await this.processor(Ce),fe=[];for(let Pe=0;Pe({score:Ze.scores[Oe],label:Ze.labels[Oe],box:_(je,!ve)}))}else{const Ze=this.processor.image_processor.post_process_object_detection(Re,de,Fe,!0)[0];rt=Ze.boxes.map((je,Oe)=>({score:Ze.scores[Oe],label:z[Ze.classes[Oe]],box:_(je,!ve)}))}rt.sort((Ze,je)=>je.score-Ze.score),be!==null&&(rt=rt.slice(0,be)),fe.push(rt)}return xe?fe:fe[0]}}class K extends y{constructor(Q){super(Q)}async _call(Q,z,de={}){const be=(await u(Q))[0],{pixel_values:ve}=await this.processor(be),xe=`${z}`,Ce=this.tokenizer(xe,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,ge=await this.model.generate({inputs:ve,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ce,...de}),fe=this.tokenizer.batch_decode(ge)[0].match(/(.*?)<\/s_answer>/);let Pe=null;return fe&&fe.length>=2&&(Pe=fe[1].trim()),[{answer:Pe}]}}class j extends y{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(Q){super(Q),this.vocoder=Q.vocoder??null}async _prepare_speaker_embeddings(Q){if((typeof Q=="string"||Q instanceof URL)&&(Q=new Float32Array(await(await fetch(Q)).arrayBuffer())),Q instanceof Float32Array)Q=new p.Tensor("float32",Q,[Q.length]);else if(!(Q instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");return Q}async _call(Q,{speaker_embeddings:z=null,num_inference_steps:de,speed:be}={}){return this.processor?this._call_text_to_spectrogram(Q,{speaker_embeddings:z}):this.model.config.model_type==="supertonic"?this._call_supertonic(Q,{speaker_embeddings:z,num_inference_steps:de,speed:be}):this._call_text_to_waveform(Q)}async _call_supertonic(Q,{speaker_embeddings:z,num_inference_steps:de,speed:be}){if(!z)throw new Error("Speaker embeddings must be provided for Supertonic models.");z=await this._prepare_speaker_embeddings(z);const{sampling_rate:ve,style_dim:xe}=this.model.config;z=z.view(1,-1,xe);const Ce=this.tokenizer(Q,{padding:!0,truncation:!0}),{waveform:ge}=await this.model.generate_speech({...Ce,style:z,num_inference_steps:de,speed:be});return new c.RawAudio(ge.data,ve)}async _call_text_to_waveform(Q){const z=this.tokenizer(Q,{padding:!0,truncation:!0}),{waveform:de}=await this.model(z),be=this.model.config.sampling_rate;return new c.RawAudio(de.data,be)}async _call_text_to_spectrogram(Q,{speaker_embeddings:z}){this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await n.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"}));const{input_ids:de}=this.tokenizer(Q,{padding:!0,truncation:!0});z=await this._prepare_speaker_embeddings(z),z=z.view(1,-1);const{waveform:be}=await this.model.generate_speech(de,z,{vocoder:this.vocoder}),ve=this.processor.feature_extractor.config.sampling_rate;return new c.RawAudio(be.data,ve)}}class D extends y{constructor(Q){super(Q)}async _call(Q){const z=await u(Q),de=await this.processor(z),be=await this.model(de),ve=[];for(const xe of be.reconstruction){const Ce=xe.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");ve.push(d.RawImage.fromTensor(Ce))}return ve.length>1?ve:ve[0]}}class te extends y{constructor(Q){super(Q)}async _call(Q){const z=await u(Q),de=await this.processor(z),{predicted_depth:be}=await this.model(de),ve=[];for(let xe=0;xe1?ve:ve[0]}}const he=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:I,model:n.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:w,model:n.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:v,model:n.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:k,model:n.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:b,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:P,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:T,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:S,model:n.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:O,model:n.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:W,model:n.AutoModelForAudioClassification,processor:o.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:B,model:n.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:Y,model:[n.AutoModelForSpeechSeq2Seq,n.AutoModelForCTC],processor:o.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:j,model:[n.AutoModelForTextToWaveform,n.AutoModelForTextToSpectrogram],processor:[o.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:X,model:n.AutoModelForVision2Seq,processor:o.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:J,model:n.AutoModelForImageClassification,processor:o.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:re,model:[n.AutoModelForImageSegmentation,n.AutoModelForSemanticSegmentation,n.AutoModelForUniversalSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:ne,model:[n.AutoModelForImageSegmentation,n.AutoModelForSemanticSegmentation,n.AutoModelForUniversalSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:le,model:n.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:pe,model:n.AutoModelForObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:oe,model:n.AutoModelForZeroShotObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:K,model:n.AutoModelForDocumentQuestionAnswering,processor:o.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:D,model:n.AutoModelForImageToImage,processor:o.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:te,model:n.AutoModelForDepthEstimation,processor:o.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:F,model:n.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:o.AutoProcessor,pipeline:H,model:[n.AutoModelForImageFeatureExtraction,n.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Ae=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ke(Te,Q=null,{progress_callback:z=null,config:de=null,cache_dir:be=null,local_files_only:ve=!1,revision:xe="main",device:Ce=null,dtype:ge=null,subfolder:De="onnx",use_external_data_format:fe=null,model_file_name:Pe=null,session_options:We={}}={}){Te=Ae[Te]??Te;const Fe=he[Te.split("_",1)[0]];if(!Fe)throw Error(`Unsupported pipeline: ${Te}. Must be one of [${Object.keys(he)}]`);Q||(Q=Fe.default.model,console.log(`No model specified. Using default model: "${Q}".`));const tt={progress_callback:z,config:de,cache_dir:be,local_files_only:ve,revision:xe,device:Ce,dtype:ge,subfolder:De,use_external_data_format:fe,model_file_name:Pe,session_options:We},Re=new Map([["tokenizer",Fe.tokenizer],["model",Fe.model],["processor",Fe.processor]]),rt=await Ve(Re,Q,tt);rt.task=Te,(0,a.dispatchCallback)(z,{status:"ready",task:Te,model:Q});const Ze=Fe.pipeline;return new Ze(rt)}async function Ve(Te,Q,z){const de=Object.create(null),be=[];for(const[ve,xe]of Te.entries()){if(!xe)continue;let Ce;Array.isArray(xe)?Ce=new Promise(async(ge,De)=>{let fe;for(const Pe of xe){if(Pe===null){ge(null);return}try{ge(await Pe.from_pretrained(Q,z));return}catch(We){if(We.message?.includes("Unsupported model type"))fe=We;else if(We.message?.includes("Could not locate file"))fe=We;else{De(We);return}}}De(fe)}):Ce=xe.from_pretrained(Q,z),de[ve]=Ce,be.push(Ce)}await Promise.all(be);for(const[ve,xe]of Object.entries(de))de[ve]=await xe;return de}}),"./src/tokenizers.js":((e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Ts,AutoTokenizer:()=>Nn,BartTokenizer:()=>He,BertTokenizer:()=>qt,BlenderbotSmallTokenizer:()=>Ue,BlenderbotTokenizer:()=>ze,BloomTokenizer:()=>It,CLIPTokenizer:()=>$s,CamembertTokenizer:()=>Z,CodeGenTokenizer:()=>ks,CodeLlamaTokenizer:()=>ir,CohereTokenizer:()=>As,ConvBertTokenizer:()=>q,DebertaTokenizer:()=>yt,DebertaV2Tokenizer:()=>Es,DistilBertTokenizer:()=>G,ElectraTokenizer:()=>ye,EsmTokenizer:()=>Lr,FalconTokenizer:()=>Dr,GPT2Tokenizer:()=>ut,GPTNeoXTokenizer:()=>Ss,GemmaTokenizer:()=>ns,Grok1Tokenizer:()=>wr,HerbertTokenizer:()=>C,LlamaTokenizer:()=>pr,M2M100Tokenizer:()=>os,MBart50Tokenizer:()=>qe,MBartTokenizer:()=>Mt,MPNetTokenizer:()=>Cs,MarianTokenizer:()=>as,MgpstrTokenizer:()=>Ns,MobileBertTokenizer:()=>Ps,NllbTokenizer:()=>Kr,NougatTokenizer:()=>Kt,PreTrainedTokenizer:()=>ft,Qwen2Tokenizer:()=>zr,RoFormerTokenizer:()=>R,RobertaTokenizer:()=>Pt,SiglipTokenizer:()=>Is,SpeechT5Tokenizer:()=>nt,SqueezeBertTokenizer:()=>Gr,T5Tokenizer:()=>et,TokenizerModel:()=>H,VitsTokenizer:()=>js,Wav2Vec2CTCTokenizer:()=>Nr,WhisperTokenizer:()=>Rs,XLMRobertaTokenizer:()=>Tr,XLMTokenizer:()=>ce,is_chinese_char:()=>k});var s=t("./src/utils/generic.js"),n=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),c=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function d(ue,$){const U=await Promise.all([(0,o.getModelJSON)(ue,"tokenizer.json",!0,$),(0,o.getModelJSON)(ue,"tokenizer_config.json",!0,$)]);return $.legacy!==null&&(U[1].legacy=$.legacy),U}function u(ue,$){const U=[];let ee=0;for(const se of ue.matchAll($)){const Me=se[0];ee0&&U.push(Me),ee=se.index+Me.length}return ee=19968&&ue<=40959||ue>=13312&&ue<=19903||ue>=131072&&ue<=173791||ue>=173824&&ue<=177983||ue>=177984&&ue<=178207||ue>=178208&&ue<=183983||ue>=63744&&ue<=64255||ue>=194560&&ue<=195103}function T(ue,$,U){const ee=[];let se=0;for(;sethis.tokens_to_ids.get(U)??this.unk_token_id)}convert_ids_to_tokens($){return $.map(U=>this.vocab[U]??this.unk_token)}}class W extends H{constructor($){super($),this.tokens_to_ids=_($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.max_input_chars_per_word=$.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[U,ee]of this.tokens_to_ids)this.vocab[ee]=U}encode($){const U=[];for(const ee of $){const se=[...ee];if(se.length>this.max_input_chars_per_word){U.push(this.unk_token);continue}let Me=!1,$e=0;const Xe=[];for(;$e0&&(Ke=this.config.continuing_subword_prefix+Ke),this.tokens_to_ids.has(Ke)){Ye=Ke;break}--Je}if(Ye===null){Me=!0;break}Xe.push(Ye),$e=Je}Me?U.push(this.unk_token):U.push(...Xe)}return U}}class B extends H{constructor($,U){super($);const ee=$.vocab.length;this.vocab=new Array(ee),this.scores=new Array(ee);for(let se=0;se[se,Me])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=U.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($){const U=$.chars,ee=1;let se=0;for(;se{const ue=[...Array.from({length:94},(se,Me)=>Me+33),...Array.from({length:12},(se,Me)=>Me+161),...Array.from({length:82},(se,Me)=>Me+174)],$=ue.slice();let U=0;for(let se=0;se<256;++se)ue.includes(se)||(ue.push(se),$.push(256+U),U+=1);const ee=$.map(se=>String.fromCharCode(se));return Object.fromEntries(ue.map((se,Me)=>[se,ee[Me]]))})(),X=(0,n.reverseDictionary)(Y);class J extends H{constructor($){super($),this.tokens_to_ids=_($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ee,se]of this.tokens_to_ids)this.vocab[se]=ee;const U=Array.isArray($.merges[0]);this.merges=U?$.merges:$.merges.map(ee=>ee.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ee,se)=>[JSON.stringify(ee),se])),this.end_of_word_suffix=$.end_of_word_suffix,this.continuing_subword_suffix=$.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($){if($.length===0)return[];const U=this.cache.get($);if(U!==void 0)return U;const ee=Array.from($);this.end_of_word_suffix&&(ee[ee.length-1]+=this.end_of_word_suffix);let se=[];if(ee.length>1){const Me=new l.PriorityQueue((Je,Ye)=>Je.score`<0x${Xe.toString(16).toUpperCase().padStart(2,"0")}>`);$e.every(Xe=>this.tokens_to_ids.has(Xe))?U.push(...$e):U.push(this.unk_token)}else U.push(this.unk_token)}return U}}class re extends H{constructor($,U){super($),this.tokens_to_ids=_(U.target_lang?$.vocab[U.target_lang]:$.vocab),this.bos_token=U.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=U.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=U.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=U.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[ee,se]of this.tokens_to_ids)this.vocab[se]=ee}encode($){return $}}class ne extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"BertNormalizer":return new Te($);case"Precompiled":return new Bt($);case"Sequence":return new Ve($);case"Replace":return new le($);case"NFC":return new oe($);case"NFD":return new K($);case"NFKC":return new j($);case"NFKD":return new D($);case"Strip":return new te($);case"StripAccents":return new he($);case"Lowercase":return new Ae($);case"Prepend":return new ke($);default:throw new Error(`Unknown Normalizer type: ${$.type}`)}}normalize($){throw Error("normalize should be implemented in subclass.")}_call($){return this.normalize($)}}class le extends ne{normalize($){const U=f(this.config.pattern);return U===null?$:$.replaceAll(U,this.config.content)}}class pe extends ne{form=void 0;normalize($){return $=$.normalize(this.form),$}}class oe extends pe{form="NFC"}class K extends pe{form="NFD"}class j extends pe{form="NFKC"}class D extends pe{form="NFKD"}class te extends ne{normalize($){return this.config.strip_left&&this.config.strip_right?$=$.trim():(this.config.strip_left&&($=$.trimStart()),this.config.strip_right&&($=$.trimEnd())),$}}class he extends ne{normalize($){return $=w($),$}}class Ae extends ne{normalize($){return $=$.toLowerCase(),$}}class ke extends ne{normalize($){return $=this.config.prepend+$,$}}class Ve extends ne{constructor($){super($),this.normalizers=$.normalizers.map(U=>ne.fromConfig(U))}normalize($){return this.normalizers.reduce((U,ee)=>ee.normalize(U),$)}}class Te extends ne{_tokenize_chinese_chars($){const U=[];for(let ee=0;ee<$.length;++ee){const se=$[ee],Me=se.charCodeAt(0);k(Me)?(U.push(" "),U.push(se),U.push(" ")):U.push(se)}return U.join("")}stripAccents($){return $.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}_is_control($){switch($){case" ":case` `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test($)}}_clean_text($){const U=[];for(const ee of $){const se=ee.charCodeAt(0);se===0||se===65533||this._is_control(ee)||(/^\s$/.test(ee)?U.push(" "):U.push(ee))}return U.join("")}normalize($){return this.config.clean_text&&($=this._clean_text($)),this.config.handle_chinese_chars&&($=this._tokenize_chinese_chars($)),this.config.lowercase?($=$.toLowerCase(),this.config.strip_accents!==!1&&($=this.stripAccents($))):this.config.strip_accents&&($=this.stripAccents($)),$}}class Q extends s.Callable{static fromConfig($){if($===null)return null;switch($.type){case"BertPreTokenizer":return new z($);case"Sequence":return new jr($);case"Whitespace":return new Qs($);case"WhitespaceSplit":return new Xs($);case"Metaspace":return new gr($);case"ByteLevel":return new de($);case"Split":return new be($);case"Punctuation":return new ve($);case"Digits":return new xe($);case"Replace":return new Js($);case"FixedLength":return new ar($);default:throw new Error(`Unknown PreTokenizer type: ${$.type}`)}}pre_tokenize_text($,U){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize($,U){return(Array.isArray($)?$.map(ee=>this.pre_tokenize_text(ee,U)):this.pre_tokenize_text($,U)).flat()}_call($,U){return this.pre_tokenize($,U)}}class z extends Q{constructor($){super(),this.pattern=new RegExp(`[^\\s${P}]+|[${P}]`,"gu")}pre_tokenize_text($,U){return $.trim().match(this.pattern)||[]}}class de extends Q{constructor($){super(),this.config=$,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=Y,this.text_encoder=new TextEncoder}pre_tokenize_text($,U){return this.add_prefix_space&&!$.startsWith(" ")&&($=" "+$),(this.use_regex?$.match(this.pattern)||[]:[$]).map(se=>Array.from(this.text_encoder.encode(se),Me=>this.byte_encoder[Me]).join(""))}}class be extends Q{constructor($){super(),this.config=$,this.pattern=f(this.config.pattern,this.config.invert)}pre_tokenize_text($,U){return this.pattern===null?[]:this.config.invert?$.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?$.split(this.pattern).filter(ee=>ee):u($,this.pattern)}}class ve extends Q{constructor($){super(),this.config=$,this.pattern=new RegExp(`[^${P}]+|[${P}]+`,"gu")}pre_tokenize_text($,U){return $.match(this.pattern)||[]}}class xe extends Q{constructor($){super(),this.config=$;const U=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(U,"gu")}pre_tokenize_text($,U){return $.match(this.pattern)||[]}}class Ce extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"TemplateProcessing":return new fe($);case"ByteLevel":return new Pe($);case"RobertaProcessing":return new De($);case"BertProcessing":return new ge($);case"Sequence":return new We($);default:throw new Error(`Unknown PostProcessor type: ${$.type}`)}}post_process($,...U){throw Error("post_process should be implemented in subclass.")}_call($,...U){return this.post_process($,...U)}}class ge extends Ce{constructor($){super($),this.cls=$.cls[0],this.sep=$.sep[0]}post_process($,U=null,{add_special_tokens:ee=!0}={}){ee&&($=(0,n.mergeArrays)([this.cls],$,[this.sep]));let se=new Array($.length).fill(0);if(U!==null){const Me=ee&&this instanceof De?[this.sep]:[],$e=ee?[this.sep]:[];$=(0,n.mergeArrays)($,Me,U,$e),se=(0,n.mergeArrays)(se,new Array(U.length+Me.length+$e.length).fill(1))}return{tokens:$,token_type_ids:se}}}class De extends ge{}class fe extends Ce{constructor($){super($),this.single=$.single,this.pair=$.pair}post_process($,U=null,{add_special_tokens:ee=!0}={}){const se=U===null?this.single:this.pair;let Me=[],$e=[];for(const Xe of se)"SpecialToken"in Xe?ee&&(Me.push(Xe.SpecialToken.id),$e.push(Xe.SpecialToken.type_id)):"Sequence"in Xe&&(Xe.Sequence.id==="A"?(Me=(0,n.mergeArrays)(Me,$),$e=(0,n.mergeArrays)($e,new Array($.length).fill(Xe.Sequence.type_id))):Xe.Sequence.id==="B"&&(Me=(0,n.mergeArrays)(Me,U),$e=(0,n.mergeArrays)($e,new Array(U.length).fill(Xe.Sequence.type_id))));return{tokens:Me,token_type_ids:$e}}}class Pe extends Ce{post_process($,U=null){return U&&($=(0,n.mergeArrays)($,U)),{tokens:$}}}class We extends Ce{constructor($){super($),this.processors=$.processors.map(U=>Ce.fromConfig(U))}post_process($,U=null,ee={}){let se;for(const Me of this.processors)if(Me instanceof Pe)$=Me.post_process($).tokens,U&&(U=Me.post_process(U).tokens);else{const $e=Me.post_process($,U,ee);$=$e.tokens,se=$e.token_type_ids}return{tokens:$,token_type_ids:se}}}class Fe extends s.Callable{constructor($){super(),this.config=$,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=$.trim_offsets}static fromConfig($){if($===null)return null;switch($.type){case"WordPiece":return new je($);case"Metaspace":return new Or($);case"ByteLevel":return new Oe($);case"Replace":return new tt($);case"ByteFallback":return new Re($);case"Fuse":return new rt($);case"Strip":return new Ze($);case"Sequence":return new ht($);case"CTC":return new at($);case"BPEDecoder":return new Nt($);default:throw new Error(`Unknown Decoder type: ${$.type}`)}}_call($){return this.decode($)}decode($){return this.decode_chain($).join("")}decode_chain($){throw Error("`decode_chain` should be implemented in subclass.")}}class tt extends Fe{decode_chain($){const U=f(this.config.pattern);return U===null?$:$.map(ee=>ee.replaceAll(U,this.config.content))}}class Re extends Fe{constructor($){super($),this.text_decoder=new TextDecoder}decode_chain($){const U=[];let ee=[];for(const se of $){let Me=null;if(se.length===6&&se.startsWith("<0x")&&se.endsWith(">")){const $e=parseInt(se.slice(3,5),16);isNaN($e)||(Me=$e)}if(Me!==null)ee.push(Me);else{if(ee.length>0){const $e=this.text_decoder.decode(Uint8Array.from(ee));U.push($e),ee=[]}U.push(se)}}if(ee.length>0){const se=this.text_decoder.decode(Uint8Array.from(ee));U.push(se),ee=[]}return U}}class rt extends Fe{decode_chain($){return[$.join("")]}}class Ze extends Fe{constructor($){super($),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain($){return $.map(U=>{let ee=0;for(let Me=0;Me(ee!==0&&(U.startsWith(this.config.prefix)?U=U.replace(this.config.prefix,""):U=" "+U),this.cleanup&&(U=I(U)),U))}}class Oe extends Fe{constructor($){super($),this.byte_decoder=X,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string($){const U=$.join(""),ee=new Uint8Array([...U].map(Me=>this.byte_decoder[Me]));return this.text_decoder.decode(ee)}decode_chain($){const U=[];let ee=[];for(const se of $)this.added_tokens.find(Me=>Me.content===se)!==void 0?(ee.length>0&&(U.push(this.convert_tokens_to_string(ee)),ee=[]),U.push(se)):ee.push(se);return ee.length>0&&U.push(this.convert_tokens_to_string(ee)),U}}class at extends Fe{constructor($){super($),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($){if($.length===0)return"";const U=[$[0]];for(let Me=1;Me<$.length;++Me)$[Me]!==U.at(-1)&&U.push($[Me]);let se=U.filter(Me=>Me!==this.pad_token).join("");return this.cleanup&&(se=I(se).replaceAll(this.word_delimiter_token," ").trim()),se}decode_chain($){return[this.convert_tokens_to_string($)]}}class ht extends Fe{constructor($){super($),this.decoders=$.decoders.map(U=>Fe.fromConfig(U))}decode_chain($){return this.decoders.reduce((U,ee)=>ee.decode_chain(U),$)}}class Nt extends Fe{constructor($){super($),this.suffix=this.config.suffix}decode_chain($){return $.map((U,ee)=>U.replaceAll(this.suffix,ee===$.length-1?"":" "))}}class kt extends Fe{decode_chain($){let U="";for(let ee=1;ee<$.length;ee+=2)U+=$[ee];return[U]}}class gr extends Q{constructor($){super(),this.replacement=$.replacement,this.strRep=$.str_rep||this.replacement,this.prepend_scheme=$.prepend_scheme??"always"}pre_tokenize_text($,{section_index:U=void 0}={}){let ee=$.replaceAll(" ",this.strRep);return!ee.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&U===0)&&(ee=this.strRep+ee),[ee]}}class Or extends Fe{constructor($){super($),this.replacement=$.replacement}decode_chain($){const U=[];for(let ee=0;ee<$.length;++ee){let se=$[ee].replaceAll(this.replacement," ");ee==0&&se.startsWith(" ")&&(se=se.substring(1)),U.push(se)}return U}}class Bt extends ne{constructor($){super($),this.charsmap=$.precompiled_charsmap}normalize($){return $=$.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),$=$.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),$.includes("~")?$=$.split("~").map(ee=>ee.normalize("NFKC")).join("~"):$=$.normalize("NFKC"),$}}class jr extends Q{constructor($){super(),this.tokenizers=$.pretokenizers.map(U=>Q.fromConfig(U))}pre_tokenize_text($,U){return this.tokenizers.reduce((ee,se)=>se.pre_tokenize(ee,U),[$])}}class Qs extends Q{constructor($){super()}pre_tokenize_text($,U){return $.match(/\w+|[^\w\s]+/g)||[]}}class Xs extends Q{constructor($){super()}pre_tokenize_text($,U){return b($)}}class Js extends Q{constructor($){super(),this.config=$,this.pattern=f(this.config.pattern),this.content=this.config.content}pre_tokenize_text($,U){return this.pattern===null?[$]:[$.replaceAll(this.pattern,this.config.content)]}}class ar extends Q{constructor($){super(),this._length=$.length}pre_tokenize_text($,U){const ee=[];for(let se=0;se<$.length;se+=this._length)ee.push($.slice(se,se+this._length));return ee}}const kr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Jr(ue,$,U,ee){for(const se of Object.keys(ue)){const Me=$-ue[se].length,$e=U(se),Xe=new Array(Me).fill($e);ue[se]=ee==="right"?(0,n.mergeArrays)(ue[se],Xe):(0,n.mergeArrays)(Xe,ue[se])}}function Bs(ue,$){for(const U of Object.keys(ue))ue[U].length=$}class ft extends s.Callable{return_token_type_ids=!1;padding_side="right";constructor($,U){super(),this.config=U,this.normalizer=ne.fromConfig($.normalizer),this.pre_tokenizer=Q.fromConfig($.pre_tokenizer),this.model=H.fromConfig($.model,U),this.post_processor=Ce.fromConfig($.post_processor),this.decoder=Fe.fromConfig($.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ee of $.added_tokens){const se=new F(ee);this.added_tokens.push(se),this.model.tokens_to_ids.set(se.content,se.id),this.model.vocab[se.id]=se.content,se.special&&(this.special_tokens.push(se.content),this.all_special_ids.push(se.id))}if(this.additional_special_tokens=U.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(ee=>ee.content)),this.added_tokens_map=new Map(this.added_tokens.map(ee=>[ee.content,ee])),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=U.model_max_length,this.remove_space=U.remove_space,this.clean_up_tokenization_spaces=U.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=U.do_lowercase_and_remove_accent??!1,U.padding_side&&(this.padding_side=U.padding_side),this.add_bos_token=U.add_bos_token,this.add_eos_token=U.add_eos_token,this.legacy=!1,this.chat_template=U.chat_template??null,Array.isArray(this.chat_template)){const ee=Object.create(null);for(const{name:se,template:Me}of this.chat_template){if(typeof se!="string"||typeof Me!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ee[se]=Me}this.chat_template=ee}this._compiled_template_cache=new Map}getToken(...$){for(const U of $){const ee=this.config[U];if(ee)if(typeof ee=="object"){if(ee.__type==="AddedToken")return ee.content;throw Error(`Unknown token: ${ee}`)}else return ee}return null}static async from_pretrained($,{progress_callback:U=null,config:ee=null,cache_dir:se=null,local_files_only:Me=!1,revision:$e="main",legacy:Xe=null}={}){const Je=await d($,{progress_callback:U,config:ee,cache_dir:se,local_files_only:Me,revision:$e,legacy:Xe});return new this(...Je)}_call($,{text_pair:U=null,add_special_tokens:ee=!0,padding:se=!1,truncation:Me=null,max_length:$e=null,return_tensor:Xe=!0,return_token_type_ids:Je=null}={}){const Ye=Array.isArray($);let Ke;if(Ye){if($.length===0)throw Error("text array must be non-empty");if(U!==null){if(Array.isArray(U)){if($.length!==U.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Ke=$.map((Et,rr)=>this._encode_plus(Et,{text_pair:U[rr],add_special_tokens:ee,return_token_type_ids:Je}))}else Ke=$.map(Et=>this._encode_plus(Et,{add_special_tokens:ee,return_token_type_ids:Je}))}else{if($==null)throw Error("text may not be null or undefined");if(Array.isArray(U))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Ke=[this._encode_plus($,{text_pair:U,add_special_tokens:ee,return_token_type_ids:Je})]}if($e===null?$e=this.model_max_length:Me===null&&(se===!0?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),$e=this.model_max_length):se===!1&&(console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),Me=!0)),se===!0&&($e=Math.min((0,i.max)(Ke.map(Et=>Et.input_ids.length))[0],$e??1/0)),$e=Math.min($e,this.model_max_length??1/0),se||Me)for(let Et=0;Et$e?Me&&Bs(Ke[Et],$e):se&&Jr(Ke[Et],$e,rr=>rr==="input_ids"?this.pad_token_id:0,this.padding_side));const $t={};if(Xe){if(!(se&&Me)&&Ke.some(rr=>{for(const br of Object.keys(rr))if(rr[br].length!==Ke[0][br]?.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=[Ke.length,Ke[0].input_ids.length];for(const rr of Object.keys(Ke[0]))$t[rr]=new a.Tensor("int64",BigInt64Array.from(Ke.flatMap(br=>br[rr]).map(BigInt)),Et)}else{for(const Et of Object.keys(Ke[0]))$t[Et]=Ke.map(rr=>rr[Et]);if(!Ye)for(const Et of Object.keys($t))$t[Et]=$t[Et][0]}return $t}_encode_text($){if($===null)return null;const U=this.added_tokens_splitter.split($);for(let se=0;se0&&(U[se-1]=U[se-1].trimEnd()),Me.rstrip&&se{if(se.length===0)return[];if(this.added_tokens_map.has(se))return[se];if(this.remove_space===!0&&(se=se.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(se=v(se)),this.normalizer!==null&&(se=this.normalizer(se)),se.length===0)return[];const $e=this.pre_tokenizer!==null?this.pre_tokenizer(se,{section_index:Me}):[se];return this.model($e)})}_encode_plus($,{text_pair:U=null,add_special_tokens:ee=!0,return_token_type_ids:se=null}={}){const{tokens:Me,token_type_ids:$e}=this._tokenize_helper($,{pair:U,add_special_tokens:ee}),Xe=this.model.convert_tokens_to_ids(Me),Je={input_ids:Xe,attention_mask:new Array(Xe.length).fill(1)};return(se??this.return_token_type_ids)&&$e&&(Je.token_type_ids=$e),Je}_tokenize_helper($,{pair:U=null,add_special_tokens:ee=!1}={}){const se=this._encode_text($),Me=this._encode_text(U);return this.post_processor?this.post_processor(se,Me,{add_special_tokens:ee}):{tokens:(0,n.mergeArrays)(se??[],Me??[])}}tokenize($,{pair:U=null,add_special_tokens:ee=!1}={}){return this._tokenize_helper($,{pair:U,add_special_tokens:ee}).tokens}encode($,{text_pair:U=null,add_special_tokens:ee=!0,return_token_type_ids:se=null}={}){return this._encode_plus($,{text_pair:U,add_special_tokens:ee,return_token_type_ids:se}).input_ids}batch_decode($,U={}){return $ instanceof a.Tensor&&($=$.tolist()),$.map(ee=>this.decode(ee,U))}decode($,U={}){if($ instanceof a.Tensor&&($=y($)),!Array.isArray($)||$.length===0||!(0,n.isIntegralNumber)($[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single($,U)}decode_single($,{skip_special_tokens:U=!1,clean_up_tokenization_spaces:ee=null}){let se=this.model.convert_ids_to_tokens($);U&&(se=se.filter($e=>!this.special_tokens.includes($e)));let Me=this.decoder?this.decoder(se):se.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Me=Me.replaceAll(this.decoder.end_of_word_suffix," "),U&&(Me=Me.trim())),(ee??this.clean_up_tokenization_spaces)&&(Me=I(Me)),Me}get_chat_template({chat_template:$=null,tools:U=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ee=this.chat_template;if($!==null&&Object.hasOwn(ee,$))$=ee[$];else if($===null)if(U!==null&&"tool_use"in ee)$=ee.tool_use;else if("default"in ee)$=ee.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(ee).sort()}.`)}else if($===null)if(this.chat_template)$=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 $}apply_chat_template($,{tools:U=null,documents:ee=null,chat_template:se=null,add_generation_prompt:Me=!1,tokenize:$e=!0,padding:Xe=!1,truncation:Je=!1,max_length:Ye=null,return_tensor:Ke=!0,return_dict:$t=!1,tokenizer_kwargs:Et={},...rr}={}){if(se=this.get_chat_template({chat_template:se,tools:U}),typeof se!="string")throw Error(`chat_template must be a string, but got ${typeof se}`);let br=this._compiled_template_cache.get(se);br===void 0&&(br=new c.Template(se),this._compiled_template_cache.set(se,br));const Jt=Object.create(null);for(const Ht of kr){const Hr=this.getToken(Ht);Hr&&(Jt[Ht]=Hr)}const sr=br.render({messages:$,add_generation_prompt:Me,tools:U,documents:ee,...Jt,...rr});if($e){const Ht=this._call(sr,{add_special_tokens:!1,padding:Xe,truncation:Je,max_length:Ye,return_tensor:Ke,...Et});return $t?Ht:Ht.input_ids}return sr}}class qt extends ft{return_token_type_ids=!0}class Ts extends ft{return_token_type_ids=!0}class Ps extends ft{return_token_type_ids=!0}class Gr extends ft{return_token_type_ids=!0}class yt extends ft{return_token_type_ids=!0}class Es extends ft{return_token_type_ids=!0}class C extends ft{return_token_type_ids=!0}class q extends ft{return_token_type_ids=!0}class R extends ft{return_token_type_ids=!0}class G extends ft{}class Z extends ft{}class ce extends ft{return_token_type_ids=!0;constructor($,U){super($,U),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class ye extends ft{return_token_type_ids=!0}class et extends ft{}class ut extends ft{}class He extends ft{}class Mt extends ft{constructor($,U){super($,U),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ee=>this.languageRegex.test(ee)),this.lang_to_token=ee=>ee}_build_translation_inputs($,U,ee){return lr(this,$,U,ee)}}class qe extends Mt{}class Pt extends ft{}class It extends ft{}const Mr="▁";class pr extends ft{padding_side="left";constructor($,U){super($,U),this.legacy=U.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new gr({replacement:Mr,prepend_scheme:"first"}))}_encode_text($){if($===null)return null;if(this.legacy||$.length===0)return super._encode_text($);let U=super._encode_text(Mr+$.replaceAll(Mr," "));return U.length>1&&U[0]===Mr&&this.special_tokens.includes(U[1])&&(U=U.slice(1)),U}}class ir extends ft{}class Tr extends ft{}class Cs extends ft{}class Dr extends ft{}class Ss extends ft{}class Lr extends ft{}class zr extends ft{}class ns extends ft{}class wr extends ft{}function lr(ue,$,U,ee){if(!("language_codes"in ue)||!Array.isArray(ue.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in ue)||!(ue.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in ue)||typeof ue.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const se=ee.src_lang,Me=ee.tgt_lang;if(!ue.language_codes.includes(Me))throw new Error(`Target language code "${Me}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);if(se!==void 0){if(!ue.language_codes.includes(se))throw new Error(`Source language code "${se}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);for(const $e of ue.post_processor.config.single)if("SpecialToken"in $e&&ue.languageRegex.test($e.SpecialToken.id)){$e.SpecialToken.id=ue.lang_to_token(se);break}}return ee.forced_bos_token_id=ue.model.convert_tokens_to_ids([ue.lang_to_token(Me)])[0],ue._call($,U)}class Kr extends ft{constructor($,U){super($,U),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ee=>this.languageRegex.test(ee)),this.lang_to_token=ee=>ee}_build_translation_inputs($,U,ee){return lr(this,$,U,ee)}}class os extends ft{constructor($,U){super($,U),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ee=>this.languageRegex.test(ee)).map(ee=>ee.slice(2,-2)),this.lang_to_token=ee=>`__${ee}__`}_build_translation_inputs($,U,ee){return lr(this,$,U,ee)}}class Rs extends ft{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr($,{return_timestamps:U=!1,return_language:ee=!1,time_precision:se=null,force_full_sequences:Me=!0}={}){if(se===null)throw Error("Must specify time_precision");let $e=null;const Xe=U==="word";function Je(){return{language:$e,timestamp:[null,null],text:""}}const Ye=[];let Ke=Je(),$t=0;const Et=this.timestamp_begin,br=Et+1500;let Jt=[],sr=[],Ht=!1,Hr=null;const is=new Set(this.all_special_ids);for(const Yt of $){const hr=Yt.tokens,$r=Xe?Yt.token_timestamps:null;let Yr=null,bs=Et;if("stride"in Yt){const[vr,Zt,_r]=Yt.stride;if($t-=Zt,Hr=vr-_r,Zt&&(bs=Zt/se+Et),_r)for(let cr=hr.length-1;cr>=0;--cr){const Ur=Number(hr[cr]);if(Ur>=Et){if(Yr!==null&&(Ur-Et)*se=Et&&Zt<=br){const _r=(Zt-Et)*se+$t,cr=(0,i.round)(_r,2);if(Yr!==null&&Zt>=Yr)Ht=!0;else if(Ht||Jt.length>0&&Zt0?(Jt.push(yr),Xe&&sr.push(ls)):Jt.every(vr=>vr.length===0)&&(Ke=Je(),Jt=[],yr=[],sr=[],ls=[])}if(Jt.length>0){if(Me&&U)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Yt,hr]=this.findLongestCommonSequence(Jt,sr),$r=this.decode(Yt);Ke.text=$r,Xe&&(Ke.words=this.collateWordTimestamps(Yt,hr,$e)),Ye.push(Ke)}let Pr=Object.create(null);const ws=Ye.map(Yt=>Yt.text).join("");if(U||ee){for(let Yt=0;Yt0;let Xe=$e?[]:null,Je=$e?U[0]:null;for(let Ye=1;Ye<$.length;++Ye){const Ke=$[Ye];let $t=0,Et=[se,se,0,0];const rr=Ke.length;for(let Pr=1;PrZt===bs[_r]&&Je[ws+_r]<=U[Ye][$r+_r]).length:yr=hr.filter((Zt,_r)=>Zt===bs[_r]).length;const ls=Pr/1e4,vr=yr/Pr+ls;yr>1&&vr>$t&&($t=vr,Et=[ws,Yt,$r,Yr])}const[br,Jt,sr,Ht]=Et,Hr=Math.floor((Jt+br)/2),is=Math.floor((Ht+sr)/2);Me.push(...ee.slice(0,Hr)),ee=Ke.slice(is),se=ee.length,$e&&(Xe.push(...Je.slice(0,Hr)),Je=U[Ye].slice(is))}return Me.push(...ee),$e?(Xe.push(...Je),[Me,Xe]):[Me,[]]}collateWordTimestamps($,U,ee){const[se,Me,$e]=this.combineTokensIntoWords($,ee),Xe=[];for(let Je=0;Je=se){const Xe=(($e-se)*ee).toFixed(2);Me.push(`<|${Xe}|>`),Me.push([])}else Me[Me.length-1].push($e);return Me=Me.map($e=>typeof $e=="string"?$e:super.decode($e,U)),Me.join("")}splitTokensOnUnicode($){const U=this.decode($,{decode_with_timestamps:!0}),ee="�",se=[],Me=[],$e=[];let Xe=[],Je=[],Ye=0;for(let Ke=0;Ke<$.length;++Ke){const $t=$[Ke];Xe.push($t),Je.push(Ke);const Et=this.decode(Xe,{decode_with_timestamps:!0});(!Et.includes(ee)||U[Ye+Et.indexOf(ee)]===ee)&&(se.push(Et),Me.push(Xe),$e.push(Je),Xe=[],Je=[],Ye+=Et.length)}return[se,Me,$e]}splitTokensOnSpaces($){const[U,ee,se]=this.splitTokensOnUnicode($),Me=[],$e=[],Xe=[],Je=new RegExp(`^[${P}]$`,"gu");for(let Ye=0;Ye=this.model.tokens_to_ids.get("<|endoftext|>"),br=Ke.startsWith(" "),Jt=Ke.trim(),sr=Je.test(Jt);if(rr||br||sr||Me.length===0)Me.push(Ke),$e.push($t),Xe.push(Et);else{const Ht=Me.length-1;Me[Ht]+=Ke,$e[Ht].push(...$t),Xe[Ht].push(...Et)}}return[Me,$e,Xe]}mergePunctuations($,U,ee,se,Me){const $e=structuredClone($),Xe=structuredClone(U),Je=structuredClone(ee);let Ye=$e.length-2,Ke=$e.length-1;for(;Ye>=0;)$e[Ye].startsWith(" ")&&se.includes($e[Ye].trim())?($e[Ke]=$e[Ye]+$e[Ke],Xe[Ke]=(0,n.mergeArrays)(Xe[Ye],Xe[Ke]),Je[Ke]=(0,n.mergeArrays)(Je[Ye],Je[Ke]),$e[Ye]="",Xe[Ye]=[],Je[Ye]=[]):Ke=Ye,--Ye;for(Ye=0,Ke=1;Ke<$e.length;)!$e[Ye].endsWith(" ")&&Me.includes($e[Ke])?($e[Ye]+=$e[Ke],Xe[Ye]=(0,n.mergeArrays)(Xe[Ye],Xe[Ke]),Je[Ye]=(0,n.mergeArrays)(Je[Ye],Je[Ke]),$e[Ke]="",Xe[Ke]=[],Je[Ke]=[]):Ye=Ke,++Ke;return[$e.filter($t=>$t),Xe.filter($t=>$t.length>0),Je.filter($t=>$t.length>0)]}}class ks extends ft{}class $s extends ft{}class Is extends ft{}class as extends ft{constructor($,U){super($,U),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ee=>this.languageRegex.test(ee)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text($){if($===null)return null;const[U,...ee]=$.trim().split(this.languageRegex);if(ee.length===0)return super._encode_text(U);if(ee.length===2){const[se,Me]=ee;return this.supported_language_codes.includes(se)||console.warn(`Unsupported language code "${se}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,n.mergeArrays)([se],super._encode_text(Me))}}}class Nr extends ft{}class ze extends ft{}class Ue extends ft{}class nt extends ft{}class Kt extends ft{}class js extends ft{constructor($,U){super($,U),this.decoder=new kt({})}}class As extends ft{}class Ns extends ft{}class Nn{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:et,DistilBertTokenizer:G,CamembertTokenizer:Z,DebertaTokenizer:yt,DebertaV2Tokenizer:Es,BertTokenizer:qt,HerbertTokenizer:C,ConvBertTokenizer:q,RoFormerTokenizer:R,XLMTokenizer:ce,ElectraTokenizer:ye,MobileBertTokenizer:Ps,SqueezeBertTokenizer:Gr,AlbertTokenizer:Ts,GPT2Tokenizer:ut,BartTokenizer:He,MBartTokenizer:Mt,MBart50Tokenizer:qe,RobertaTokenizer:Pt,WhisperTokenizer:Rs,CodeGenTokenizer:ks,CLIPTokenizer:$s,SiglipTokenizer:Is,MarianTokenizer:as,BloomTokenizer:It,NllbTokenizer:Kr,M2M100Tokenizer:os,LlamaTokenizer:pr,CodeLlamaTokenizer:ir,XLMRobertaTokenizer:Tr,MPNetTokenizer:Cs,FalconTokenizer:Dr,GPTNeoXTokenizer:Ss,EsmTokenizer:Lr,Wav2Vec2CTCTokenizer:Nr,BlenderbotTokenizer:ze,BlenderbotSmallTokenizer:Ue,SpeechT5Tokenizer:nt,NougatTokenizer:Kt,VitsTokenizer:js,Qwen2Tokenizer:zr,GemmaTokenizer:ns,Grok1Tokenizer:wr,CohereTokenizer:As,MgpstrTokenizer:Ns,PreTrainedTokenizer:ft};static async from_pretrained($,{progress_callback:U=null,config:ee=null,cache_dir:se=null,local_files_only:Me=!1,revision:$e="main",legacy:Xe=null}={}){const[Je,Ye]=await d($,{progress_callback:U,config:ee,cache_dir:se,local_files_only:Me,revision:$e,legacy:Xe}),Ke=Ye.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let $t=this.TOKENIZER_CLASS_MAPPING[Ke];return $t||(console.warn(`Unknown tokenizer class "${Ke}", attempting to construct from base class.`),$t=ft),new $t(Je,Ye)}}}),"./src/utils/audio.js":((e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>W,hamming:()=>u,hanning:()=>d,mel_filter_bank:()=>k,read_audio:()=>c,spectrogram:()=>S,window_function:()=>O});var s=t("./src/utils/hub.js"),n=t("./src/utils/maths.js"),o=t("./src/utils/core.js"),i=t("./src/env.js"),a=t("./src/utils/tensor.js"),l=t("?7992");async function c(B,Y){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 X=await(await(0,s.getFile)(B)).arrayBuffer(),J=new AudioContext({sampleRate:Y});typeof Y>"u"&&console.warn(`No sampling rate provided, using default of ${J.sampleRate}Hz.`);const re=await J.decodeAudioData(X);let ne;if(re.numberOfChannels===2){const le=Math.sqrt(2),pe=re.getChannelData(0),oe=re.getChannelData(1);ne=new Float32Array(pe.length);for(let K=0;K2595*Math.log10(1+B/700),kaldi:B=>1127*Math.log(1+B/700),slaney:(B,Y=1e3,X=15,J=27/Math.log(6.4))=>B>=Y?X+Math.log(B/Y)*J:3*B/200};function _(B,Y="htk"){const X=f[Y];if(!X)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof B=="number"?X(B):B.map(J=>X(J))}const y={htk:B=>700*(10**(B/2595)-1),kaldi:B=>700*(Math.exp(B/1127)-1),slaney:(B,Y=1e3,X=15,J=Math.log(6.4)/27)=>B>=X?Y*Math.exp(J*(B-X)):200*B/3};function I(B,Y="htk"){const X=y[Y];if(!X)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof B=="number"?X(B):B.map(J=>X(J))}function w(B,Y){const X=Float64Array.from({length:Y.length-1},(le,pe)=>Y[pe+1]-Y[pe]),J=Array.from({length:B.length},()=>new Array(Y.length));for(let le=0;lenew Array(B.length));for(let le=0;leB+J*ne)}function k(B,Y,X,J,re,ne=null,le="htk",pe=!1){if(ne!==null&&ne!=="slaney")throw new Error('norm must be one of null or "slaney"');if(B<2)throw new Error(`Require num_frequency_bins: ${B} >= 2`);if(X>J)throw new Error(`Require min_frequency: ${X} <= max_frequency: ${J}`);const oe=_(X,le),K=_(J,le),j=v(oe,K,Y+2);let D=I(j,le),te;if(pe){const Ae=re/((B-1)*2);te=_(Float64Array.from({length:B},(ke,Ve)=>Ve*Ae),le),D=j}else te=v(0,Math.floor(re/2),B);const he=w(te,D);if(ne!==null&&ne==="slaney")for(let Ae=0;Aere)throw Error(`frame_length (${X}) may not be larger than fft_length (${re})`);if(xe!==X)throw new Error(`Length of the window (${xe}) must equal frame_length (${X})`);if(J<=0)throw new Error("hop_length must be greater than zero");if(ne===null&&D!==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(!j)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(le)switch(pe){case"reflect":{const je=Math.floor((re-1)/2)+1;B=T(B,je,je);break}case"constant":{const je=Math.floor(re/2),Oe=new B.constructor(B.length+2*je);Oe.set(B,je),B=Oe;break}default:throw new Error(`pad_mode="${pe}" not implemented yet.`)}let Ce=Math.floor(1+Math.floor((B.length-X)/J));Q!==null&&CeCe?de&&(fe=z):fe=De=z);const Pe=new n.FFT(re),We=new Float64Array(re),Fe=new Float64Array(Pe.outputBufferSize),tt=new Float32Array(ge*fe);for(let je=0;je=1;--ht)We[ht]-=K*We[ht-1];We[0]*=1-K}for(let ht=0;htMath.pow(pe,.85));break;default:throw new Error(`Unknown window type ${Y}.`)}if(X&&(le=le.subarray(0,B)),J===null)return le;if(B>J)throw new Error(`Length of the window (${B}) may not be larger than frame_length (${J})`);return le}function F(B,Y){let X=44;const J=new ArrayBuffer(X+B.length*4),re=new DataView(J);H(re,0,"RIFF"),re.setUint32(4,36+B.length*4,!0),H(re,8,"WAVE"),H(re,12,"fmt "),re.setUint32(16,16,!0),re.setUint16(20,3,!0),re.setUint16(22,1,!0),re.setUint32(24,Y,!0),re.setUint32(28,Y*4,!0),re.setUint16(32,4,!0),re.setUint16(34,32,!0),H(re,36,"data"),re.setUint32(40,B.length*4,!0);for(let ne=0;ne{let ne=await re.arrayBuffer();l.writeFileSync(J,Buffer.from(ne))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await X(Y,this.toBlob())}}}),"./src/utils/constants.js":((e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>n,FEATURE_EXTRACTOR_NAME:()=>o,GENERATION_CONFIG_NAME:()=>c,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",n="config.json",o="preprocessor_config.json",i=o,a="processor_config.json",l="chat_template.jinja",c="generation_config.json"}),"./src/utils/core.js":((e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>c,calculateReflectOffset:()=>f,count:()=>w,dispatchCallback:()=>s,escapeRegExp:()=>o,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>I,mergeArrays:()=>d,pick:()=>y,pop:()=>p,product:()=>u,reverseDictionary:()=>n,saveBlob:()=>_});function s(v,k){v&&v(k)}function n(v){return Object.fromEntries(Object.entries(v).map(([k,T])=>[T,k]))}function o(v){return v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(v){return v?.prototype?.__proto__?.constructor?.name==="TypedArray"}function a(v){return Number.isInteger(v)||typeof v=="bigint"}function l(v){return v==null||v===-1}function c(v){const k=[];let T=v;for(;Array.isArray(T);)k.push(T.length),T=T[0];return k}function p(v,k,T=void 0){const b=v[k];if(b!==void 0)return delete v[k],b;if(T===void 0)throw Error(`Key ${k} does not exist in object.`);return T}function d(...v){return Array.prototype.concat.apply([],v)}function u(...v){return v.reduce((k,T)=>k.flatMap(b=>T.map(P=>[b,P])))}function f(v,k){return Math.abs((v+k)%(2*k)-k)}function _(v,k){const T=URL.createObjectURL(k),b=document.createElement("a");b.href=T,b.download=v,b.click(),b.remove(),URL.revokeObjectURL(T)}function y(v,k){return Object.assign({},...k.map(T=>{if(v[T]!==void 0)return{[T]:v[T]}}))}function I(v){let k=0;for(const T of v)++k;return k}function w(v,k){let T=0;for(const b of v)b===k&&++T;return T}}),"./src/utils/data-structures.js":((e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>n,DictionarySplitter:()=>l,LRUCache:()=>c,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(d=(f,_)=>f>_,u=1/0){this._heap=[],this._comparator=d,this._maxSize=u}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...d){return this.extend(d)}extend(d){for(const u of d)if(this.size0&&this._swap(0,u),this._heap.pop(),this._siftDown(),d}replace(d){const u=this.peek();return this._heap[0]=d,this._siftDown(),u}_parent(d){return(d+1>>>1)-1}_left(d){return(d<<1)+1}_right(d){return d+1<<1}_greater(d,u){return this._comparator(this._heap[d],this._heap[u])}_swap(d,u){const f=this._heap[d];this._heap[d]=this._heap[u],this._heap[u]=f}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(d){for(;d>0&&this._greater(d,this._parent(d));)this._swap(d,this._parent(d)),d=this._parent(d)}_siftDown(){let d=0;for(;this._left(d)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const _=new a(this.bosTokenId,0,0,0,0),y=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(_.clone()),this.nodes.push(y.clone()),this.beginNodes[this.len].push(y),this.endNodes[0].push(_)}insert(d,u,f,_){const y=this.nodes.length,I=new a(_,y,d,u,f);this.beginNodes[d].push(I),this.endNodes[d+u].push(I),this.nodes.push(I)}viterbi(){const d=this.len;let u=0;for(;u<=d;){if(this.beginNodes[u].length==0)return[];for(let w of this.beginNodes[u]){w.prev=null;let v=0,k=null;for(let T of this.endNodes[u]){const b=T.backtraceScore+w.score;(k===null||b>v)&&(k=T.clone(),v=b)}if(k!==null)w.prev=k,w.backtraceScore=v;else return[]}++u}const f=[],y=this.beginNodes[d][0].prev;if(y===null)return[];let I=y.clone();for(;I.prev!==null;)f.push(I.clone()),I=I.clone().prev.clone();return f.reverse(),f}piece(d){return this.chars.slice(d.pos,d.pos+d.length).join("")}tokens(){return this.viterbi().map(u=>this.piece(u))}tokenIds(){return this.viterbi().map(u=>u.tokenId)}}class a{constructor(d,u,f,_,y){this.tokenId=d,this.nodeId=u,this.pos=f,this.length=_,this.score=y,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){const u=Object.create(null);for(const f of d){let _=u;for(let y=0;y_&&u.push(d.slice(_,y)),u.push(w),y+=w.length,_=y):++y}return _this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}}),"./src/utils/devices.js":((e,r,t)=>{t.r(r),t.d(r,{DEVICE_TYPES:()=>s});const s=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})}),"./src/utils/dtypes.js":((e,r,t)=>{t.r(r),t.d(r,{DATA_TYPES:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>o});var s=t("./src/env.js"),n=t("./src/utils/devices.js");const o=(function(){let c;return async function(){if(c===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)c=!1;else try{c=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{c=!1}return c}})(),i=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[n.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 n=function(...o){return n._call(...o)};return Object.setPrototypeOf(n,new.target.prototype)}_call(...n){throw Error("Must implement _call method in subclass")}}}),"./src/utils/hub.js":((e,r,t)=>{t.r(r),t.d(r,{MAX_EXTERNAL_DATA_CHUNKS:()=>a,getFile:()=>f,getModelFile:()=>v,getModelJSON:()=>T,getModelText:()=>k});var s=t("?7992"),n=t("?5af5"),o=t("./src/env.js"),i=t("./src/utils/core.js");const a=100,l={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class c{constructor(S){if(this.filePath=S,this.headers=new Headers,this.exists=s.existsSync(S),this.exists){this.status=200,this.statusText="OK";let O=s.statSync(S);this.headers.set("content-length",O.size.toString()),this.updateContentType();const F=s.createReadStream(S);this.body=new ReadableStream({start(H){F.on("data",W=>H.enqueue(W)),F.on("end",()=>H.close()),F.on("error",W=>H.error(W))},cancel(){F.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const S=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[S]??"application/octet-stream")}clone(){let S=new c(this.filePath);return S.exists=this.exists,S.status=this.status,S.statusText=this.statusText,S.headers=new Headers(this.headers),S}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const S=await s.promises.readFile(this.filePath);return new Blob([S],{type:this.headers.get("content-type")})}async text(){return await s.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function p(x,S=null,O=null){let F;try{F=new URL(x)}catch{return!1}return!(S&&!S.includes(F.protocol)||O&&!O.includes(F.hostname))}const d=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function u(x){return!(!d.test(x)||x.includes("..")||x.includes("--")||x.endsWith(".git")||x.endsWith(".ipynb"))}async function f(x){if(o.env.useFS&&!p(x,["http:","https:","blob:"]))return new c(x instanceof URL?x.protocol==="file:"?x.pathname:x.toString():x);if(typeof process<"u"&&process?.release?.name==="node"){const S=!!pc?.TESTING_REMOTELY,O=o.env.version,F=new Headers;if(F.set("User-Agent",`transformers.js/${O}; is_ci/${S};`),p(x,["http:","https:"],["huggingface.co","hf.co"])){const W=pc?.HF_TOKEN??pc?.HF_ACCESS_TOKEN;W&&F.set("Authorization",`Bearer ${W}`)}return fetch(x,{headers:F})}else return fetch(x)}const _={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function y(x,S,O){if(!O)return null;const F=_[x]??`Error (${x}) occurred while trying to load file`;throw Error(`${F}: "${S}".`)}class I{constructor(S){this.path=S}async match(S){let O=n.join(this.path,S),F=new c(O);if(F.exists)return F}async put(S,O,F=void 0){let H=n.join(this.path,S);try{const W=O.headers.get("Content-Length"),B=parseInt(W??"0");let Y=0;await s.promises.mkdir(n.dirname(H),{recursive:!0});const X=s.createWriteStream(H),J=O.body.getReader();for(;;){const{done:re,value:ne}=await J.read();if(re)break;await new Promise((pe,oe)=>{X.write(ne,K=>{if(K){oe(K);return}pe()})}),Y+=ne.length;const le=B?Y/B*100:0;F?.({progress:le,loaded:Y,total:B})}X.close()}catch(W){try{await s.promises.unlink(H)}catch{}throw W}}}async function w(x,...S){for(let O of S)try{let F=await x.match(O);if(F)return F}catch{continue}}async function v(x,S,O=!0,F={},H=!1){if(!o.env.allowLocalModels){if(F.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(!o.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)(F.progress_callback,{status:"initiate",name:x,file:S});let W;if(!W&&o.env.useCustomCache){if(!o.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!o.env.customCache.match||!o.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");W=o.env.customCache}if(!W&&o.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{W=await caches.open("transformers-cache")}catch(te){console.warn("An error occurred while opening the browser cache:",te)}}if(!W&&o.env.useFSCache){if(!o.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");W=new I(F.cache_dir??o.env.cacheDir)}const B=F.revision??"main",Y=P(x,S),X=u(x),J=X?P(o.env.localModelPath,Y):Y,re=P(o.env.remoteHost,o.env.remotePathTemplate.replaceAll("{model}",x).replaceAll("{revision}",encodeURIComponent(B)),S);let ne;const le=W instanceof I?B==="main"?Y:P(x,B,S):re;let pe=!1,oe;W&&(oe=await w(W,J,le));const K=oe!==void 0;if(oe===void 0){if(o.env.allowLocalModels)if(p(Y,["http:","https:"])){if(F.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${Y}.`);if(!o.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${Y}.`)}else try{oe=await f(J),ne=J}catch(he){console.warn(`Unable to load from local path "${J}": "${he}"`)}if(oe===void 0||oe.status===404){if(F.local_files_only||!o.env.allowRemoteModels){if(O)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${J}".`);return null}if(!X)throw Error(`Local file missing at "${J}" and download aborted due to invalid model ID "${x}".`);if(oe=await f(re),oe.status!==200)return y(oe.status,re,O);ne=le}pe=W&&typeof Response<"u"&&oe instanceof Response&&oe.status===200}(0,i.dispatchCallback)(F.progress_callback,{status:"download",name:x,file:S});let j;if(!(o.apis.IS_NODE_ENV&&H)){let te;F.progress_callback?K&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(te=new Uint8Array(await oe.arrayBuffer()),(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:x,file:S,progress:100,loaded:te.length,total:te.length})):te=await b(oe,he=>{(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:x,file:S,...he})}):te=new Uint8Array(await oe.arrayBuffer()),j=te}if(pe&&ne&&await W.match(ne)===void 0)if(j)await W.put(ne,new Response(j,{headers:oe.headers})).catch(te=>{console.warn(`Unable to add response to browser cache: ${te}.`)});else{const te=F.progress_callback?he=>(0,i.dispatchCallback)(F.progress_callback,{status:"progress",name:x,file:S,...he}):void 0;await W.put(ne,oe,te)}if((0,i.dispatchCallback)(F.progress_callback,{status:"done",name:x,file:S}),j){if(!o.apis.IS_NODE_ENV&&H)throw new Error("Cannot return path in a browser environment.");return j}if(oe instanceof c)return oe.filePath;const D=await W?.match(ne);if(D instanceof c)return D.filePath;if(D instanceof Response)return new Uint8Array(await D.arrayBuffer());if(typeof D=="string")return D;throw new Error("Unable to get model file path or buffer.")}async function k(x,S,O=!0,F={}){const H=await v(x,S,O,F,!1);return H===null?null:new TextDecoder("utf-8").decode(H)}async function T(x,S,O=!0,F={}){const H=await k(x,S,O,F);return H===null?{}:JSON.parse(H)}async function b(x,S){const O=x.headers.get("Content-Length");O===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let F=parseInt(O??"0"),H=new Uint8Array(F),W=0;const B=x.body.getReader();async function Y(){const{done:X,value:J}=await B.read();if(X)return;const re=W+J.length;if(re>F){F=re;const le=new Uint8Array(F);le.set(H),H=le}H.set(J,W),W=re;const ne=W/F*100;return S({progress:ne,loaded:W,total:F}),Y()}return await Y(),H}function P(...x){return x=x.map((S,O)=>(O&&(S=S.replace(new RegExp("^/"),"")),O!==x.length-1&&(S=S.replace(new RegExp("/$"),"")),S)),x.join("/")}}),"./src/utils/image.js":((e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>_,load_image:()=>y});var s=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),o=t("./src/env.js"),i=t("./src/utils/tensor.js"),a=t("?2b25");let l,c,p;const d=o.apis.IS_BROWSER_ENV||o.apis.IS_WEBWORKER_ENV;if(d)l=(I,w)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(I,w)},p=self.createImageBitmap,c=self.ImageData;else if(a)p=async I=>{const v=(await I.metadata()).channels,{data:k,info:T}=await I.rotate().raw().toBuffer({resolveWithObject:!0}),b=new _(new Uint8ClampedArray(k),T.width,T.height,T.channels);return v!==void 0&&v!==T.channels&&b.convert(v),b};else throw new Error("Unable to load image processing library.");const u={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},f=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _{constructor(w,v,k,T){this.data=w,this.width=v,this.height=k,this.channels=T}get size(){return[this.width,this.height]}static async read(w){if(w instanceof _)return w;if(typeof w=="string"||w instanceof URL)return await this.fromURL(w);if(w instanceof Blob)return await this.fromBlob(w);if(typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&w instanceof OffscreenCanvas)return this.fromCanvas(w);throw new Error(`Unsupported input type: ${typeof w}`)}static fromCanvas(w){if(!d)throw new Error("fromCanvas() is only supported in browser environments.");const k=w.getContext("2d").getImageData(0,0,w.width,w.height).data;return new _(k,w.width,w.height,4)}static async fromURL(w){const v=await(0,n.getFile)(w);if(v.status!==200)throw new Error(`Unable to read image from "${w}" (${v.status} ${v.statusText})`);const k=await v.blob();return this.fromBlob(k)}static async fromBlob(w){if(d){const v=await p(w),k=l(v.width,v.height).getContext("2d");return k.drawImage(v,0,0),new this(k.getImageData(0,0,v.width,v.height).data,v.width,v.height,4)}else{const v=a(await w.arrayBuffer());return await p(v)}}static fromTensor(w,v="CHW"){if(w.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${w.dims.length} dimensions.`);if(v==="CHW")w=w.transpose(1,2,0);else if(v!=="HWC")throw new Error(`Unsupported channel format: ${v}`);if(!(w.data instanceof Uint8ClampedArray||w.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${w.type}`);switch(w.dims[2]){case 1:case 2:case 3:case 4:return new _(w.data,w.dims[1],w.dims[0],w.dims[2]);default:throw new Error(`Unsupported number of channels: ${w.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const w=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let v=0,k=0;v=0?S=k:F=-k,T>=0?O=T:H=-T,x.drawImage(P,S,O,w,v,F,H,w,v),new _(x.getImageData(0,0,w,v).data,w,v,4).convert(b)}else{let b=this.toSharp();if(k>=0&&T>=0)b=b.extract({left:Math.floor(k),top:Math.floor(T),width:w,height:v});else if(k<=0&&T<=0){const P=Math.floor(-T),x=Math.floor(-k);b=b.extend({top:P,left:x,right:w-this.width-x,bottom:v-this.height-P})}else{let P=[0,0],x=0;T<0?(P[0]=Math.floor(-T),P[1]=v-this.height-P[0]):x=Math.floor(T);let S=[0,0],O=0;k<0?(S[0]=Math.floor(-k),S[1]=w-this.width-S[0]):O=Math.floor(k),b=b.extend({top:P[0],bottom:P[1],left:S[0],right:S[1]}).extract({left:O,top:x,width:w,height:v})}return await p(b)}}async toBlob(w="image/png",v=1){if(!d)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:w,quality:v})}toTensor(w="CHW"){let v=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(w!=="HWC")if(w==="CHW")v=v.permute(2,0,1);else throw new Error(`Unsupported channel format: ${w}`);return v}toCanvas(){if(!d)throw new Error("toCanvas() is only supported in browser environments.");const w=this.clone().rgba(),v=l(w.width,w.height),k=new c(w.data,w.width,w.height);return v.getContext("2d").putImageData(k,0,0),v}split(){const{data:w,width:v,height:k,channels:T}=this,b=w.constructor,P=w.length/T,x=Array.from({length:T},()=>new b(P));for(let S=0;Snew _(S,v,k,1))}_update(w,v,k,T=null){return this.data=w,this.width=v,this.height=k,T!==null&&(this.channels=T),this}clone(){return new _(this.data.slice(),this.width,this.height,this.channels)}convert(w){if(this.channels===w)return this;switch(w){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(w){if(d){if(o.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const v=w.split(".").pop().toLowerCase(),k=f.get(v)??"image/png",T=await this.toBlob(k);(0,s.saveBlob)(w,T)}else{if(o.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 y=_.read.bind(_)}),"./src/utils/maths.js":((e,r,t)=>{t.r(r),t.d(r,{FFT:()=>y,bankers_round:()=>v,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>k,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>c,max:()=>d,medianFilter:()=>I,min:()=>p,permute_data:()=>n,round:()=>w,softmax:()=>o});function s(T,[b,P,x],[S,O],F="bilinear",H=!1){const W=O/x,B=S/P,Y=new T.constructor(S*O*b),X=P*x,J=S*O;for(let re=0;re=0;--H)S[H]=W,x[H]=b[P[H]],W*=x[H];const O=P.map((H,W)=>S[P.indexOf(W)]),F=new T.constructor(T.length);for(let H=0;H=0;--B)W+=Y%b[B]*O[B],Y=Math.floor(Y/b[B]);F[W]=T[H]}return[F,x]}function o(T){const b=d(T)[0],P=T.map(O=>Math.exp(O-b)),x=P.reduce((O,F)=>O+F,0);return P.map(O=>O/x)}function i(T){const b=d(T)[0];let P=0;for(let O=0;OO-b-x)}function a(T,b){let P=0;for(let x=0;xb+P*P,0))}function p(T){if(T.length===0)throw Error("Array must not be empty");let b=T[0],P=0;for(let x=1;xb&&(b=T[x],P=x);return[b,P]}function u(T){return T>0&&(T&T-1)===0}class f{constructor(b){if(this.size=b|0,this.size<=1||!u(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=b<<1,this.table=new Float64Array(this.size*2);for(let x=0;xx;x<<=1)++P;this._width=P%2===0?P-1:P,this._bitrev=new Int32Array(1<>>S&3)<>>1);for(let S=0;S>>1]=b[S];return x}toComplexArray(b,P){const x=P||this.createComplexArray();for(let S=0;S>>1],x[S+1]=0;return x}transform(b,P){if(b===P)throw new Error("Input and output buffers must be different");this._transform4(b,P,1)}realTransform(b,P){if(b===P)throw new Error("Input and output buffers must be different");this._realTransform4(b,P,1)}inverseTransform(b,P){if(b===P)throw new Error("Input and output buffers must be different");this._transform4(b,P,-1);for(let x=0;x>=2;F>=2;F>>=2){H=S/F<<1;const J=H>>>2;for(W=0;W>>1,F>>>1)}else for(W=0,B=0;W>>1,F>>>1,x)}const X=this.table;for(F>>=2;F>=2;F>>=2){H=S/F<<1;const re=H>>>1,ne=re>>>1,le=ne>>>1;for(W=0;W>>1;for(let re=2;re>1;++Y){const X=(Y+1-b)**2/2,J=Math.sqrt(W**2+B**2)**X,re=X*Math.atan2(B,W),ne=2*Y;O[ne]=J*Math.cos(re),O[ne+1]=J*Math.sin(re),F[ne]=O[ne],F[ne+1]=-O[ne+1]}this._slicedChirpBuffer=O.subarray(P,x),this._f=new f(S>>1),this._f.transform(this._chirpBuffer,F)}_transform(b,P,x){const S=this._buffer1,O=this._buffer2,F=this._outBuffer1,H=this._outBuffer2,W=this._chirpBuffer,B=this._slicedChirpBuffer,Y=this._a;if(x)for(let X=0;X>1,ne=P[re];S[X]=ne*B[X],S[J]=ne*B[J]}else for(let X=0;X=T.length&&(W=2*(T.length-1)-W),x[F++]=T[W]}x.sort(),P[O]=x[S]}return P}function w(T,b){const P=Math.pow(10,b);return Math.round(T*P)/P}function v(T){const b=Math.round(T);return Math.abs(T)%1===.5?b%2===0?b:b-1:b}function k(T){const b=T.length,P=T[0].length,x=[b+1,P+1],S=Array.from({length:x[0]},()=>Array(x[1]).fill(1/0));S[0][0]=0;const O=Array.from({length:x[0]},()=>Array(x[1]).fill(-1));for(let Y=1;Y0||H>0;)switch(W.push(F-1),B.push(H-1),O[F][H]){case 0:--F,--H;break;case 1:--F;break;case 2:--H;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${F}, ${H}]. Please file a bug report.`)}return W.reverse(),B.reverse(),[W,B]}}),"./src/utils/tensor.js":((e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>P,full:()=>B,full_like:()=>Y,interpolate:()=>p,interpolate_4d:()=>d,layer_norm:()=>v,matmul:()=>u,mean:()=>F,mean_pooling:()=>w,ones:()=>X,ones_like:()=>J,permute:()=>c,quantize_embeddings:()=>oe,rand:()=>le,randn:()=>pe,rfft:()=>f,slice:()=>I,stack:()=>x,std_mean:()=>O,topk:()=>_,zeros:()=>re,zeros_like:()=>ne});var s=t("./src/utils/maths.js"),n=t("./src/backends/onnx.js"),o=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{get dims(){return this.ort_tensor.dims}set dims(j){this.ort_tensor.dims=j}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}ort_tensor;constructor(...j){return(0,n.isONNXTensor)(j[0])?this.ort_tensor=j[0]:this.ort_tensor=new n.Tensor(j[0],j[1],j[2]),new Proxy(this,{get:(D,te)=>{if(typeof te=="string"){let he=Number(te);if(Number.isInteger(he))return D._getitem(he)}return D[te]},set:(D,te,he)=>D[te]=he})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[j,...D]=this.dims;if(D.length>0){const te=D.reduce((he,Ae)=>he*Ae);for(let he=0;he0){const he=te.reduce((Ae,ke)=>Ae*ke);return this._subarray(j,he,te)}else return new a(this.type,[this.data[j]],te)}indexOf(j){const D=this.data;for(let te=0;teve)throw new Error(`Invalid slice: ${de}`);const xe=[Math.max(be,0),Math.min(ve,this.dims[z])];te.push(xe),D.push(xe[1]-xe[0])}else throw new Error(`Invalid slice: ${de}`)}const he=te.map(([z,de])=>de-z),Ae=he.reduce((z,de)=>z*de),ke=this.data,Ve=new ke.constructor(Ae),Te=this.stride();let Q=!0;for(let z=1;z=0;--be){const xe=he[be];de+=(ve%xe+te[be][0])*Te[be],ve=Math.floor(ve/xe)}Ve[z]=ke[de]}return new a(this.type,Ve,D)}permute(...j){return c(this,j)}transpose(...j){return this.permute(...j)}sum(j=null,D=!1){return this.norm(1,j,D)}norm(j="fro",D=null,te=!1){if(j==="fro")j=2;else if(typeof j=="string")throw Error(`Unsupported norm: ${j}`);const he=this.data,Ae=(Q,z)=>Q+z**j;if(D===null){const Q=he.reduce(Ae,0)**(1/j);return new a(this.type,[Q],[])}const[ke,Ve,Te]=S(Ae,this,D,te);if(j!==1)for(let Q=0;Q=0;--Te){const de=this.dims[Te];if(Te!==D){const be=Q%de;Ve+=be*z,z*=this.dims[Te]}Q=Math.floor(Q/de)}he[ke]/=Ae[Ve]}return this}normalize(j=2,D=1){return this.clone().normalize_(j,D)}stride(){return H(this.dims)}squeeze(j=null){return new a(this.type,this.data,k(this.dims,j))}squeeze_(j=null){return this.dims=k(this.dims,j),this}unsqueeze(j=null){return new a(this.type,this.data,T(this.dims,j))}unsqueeze_(j=null){return this.dims=T(this.dims,j),this}flatten_(j=0,D=-1){D=(D+this.dims.length)%this.dims.length;let te=this.dims.slice(0,j),he=this.dims.slice(j,D+1),Ae=this.dims.slice(D+1);return this.dims=[...te,he.reduce((ke,Ve)=>ke*Ve,1),...Ae],this}flatten(j=0,D=-1){return this.clone().flatten_(j,D)}view(...j){let D=-1;for(let he=0;heVe!==D?Ae*ke:Ae,1);j[D]=te.length/he}return new a(this.type,te,j)}neg_(){const j=this.data;for(let D=0;Dj?1:0;return new a("bool",D,this.dims)}lt(j){const D=new Uint8Array(this.data.length),te=this.data;for(let he=0;heMath.min(ke,Ve),this,j,D,1/0);return new a(te,he,Ae)}max(j=null,D=!1){if(j===null){const ke=(0,s.max)(this.data)[0];return new a(this.type,[ke],[])}const[te,he,Ae]=S((ke,Ve)=>Math.max(ke,Ve),this,j,D,-1/0);return new a(te,he,Ae)}argmin(j=null,D=!1){if(j!==null)throw new Error("`dim !== null` not yet implemented.");const te=(0,s.min)(this.data)[1];return new a("int64",[BigInt(te)],[])}argmax(j=null,D=!1){if(j!==null)throw new Error("`dim !== null` not yet implemented.");const te=(0,s.max)(this.data)[1];return new a("int64",[BigInt(te)],[])}to(j){if(this.type===j)return this;if(!i.hasOwnProperty(j))throw new Error(`Unsupported type: ${j}`);let D;const te=["int64","uint64"].includes(this.type),he=["int64","uint64"].includes(j);return te&&!he?D=Number:!te&&he&&(["float16","float32","float64"].includes(this.type)?D=Ae=>BigInt(Math.floor(Ae)):D=BigInt),new a(j,i[j].from(this.data,D),this.dims)}}function l(K,j){const D=K.length,te=j.reduce((Ae,ke)=>Ae*ke);if(D!==te)throw Error(`cannot reshape array of size ${D} into shape (${j})`);let he=K;for(let Ae=j.length-1;Ae>=0;Ae--)he=he.reduce((ke,Ve)=>{let Te=ke[ke.length-1];return Te.lengthnew a("int64",K,[K.length]);async function I(K,j,D,te,he){return await(await o.TensorOpRegistry.slice)({x:K,s:y(j),e:y(D),a:y(te),t:y(he??new Array(te.length).fill(1))})}function w(K,j){const D=K.data,te=j.data,he=[K.dims[0],K.dims[2]],Ae=new D.constructor(he[0]*he[1]),[ke,Ve,Te]=K.dims;let Q=0;for(let z=0;zD!==1):typeof j=="number"?K[j]===1&&K.splice(j,1):Array.isArray(j)&&(K=K.filter((D,te)=>D!==1||!j.includes(te))),K}function T(K,j){return j=b(j,K.length+1),K=K.slice(),K.splice(j,0,1),K}function b(K,j,D=null,te=!0){if(K<-j||K>=j){if(te)throw new Error(`IndexError: index ${K} is out of bounds for dimension${D===null?"":" "+D} with size ${j}`);return K<-j?0:j}return K<0&&(K=(K%j+j)%j),K}function P(K,j=0){j=b(j,K[0].dims.length);const D=K[0].dims.slice();D[j]=K.reduce((ke,Ve)=>ke+Ve.dims[j],0);const te=D.reduce((ke,Ve)=>ke*Ve,1),he=new K[0].data.constructor(te),Ae=K[0].type;if(j===0){let ke=0;for(const Ve of K){const Te=Ve.data;he.set(Te,ke),ke+=Te.length}}else{let ke=0;for(let Ve=0;Ve=0;--be){const Ce=Q[be];let ge=ve%Ce;be===j&&(ge+=ke),de+=ge*xe,xe*=D[be],ve=Math.floor(ve/Ce)}he[de]=Te[z]}ke+=Q[j]}}return new a(Ae,he,D)}function x(K,j=0){return P(K.map(D=>D.unsqueeze(j)),j)}function S(K,j,D=null,te=!1,he=null){const Ae=j.data,ke=j.dims;D=b(D,ke.length);const Ve=ke.slice();Ve[D]=1;const Te=new Ae.constructor(Ae.length/ke[D]);he!==null&&Te.fill(he);for(let Q=0;Q=0;--de){const xe=ke[de];if(de!==D){const Ce=be%xe;z+=Ce*ve,ve*=Ve[de]}be=Math.floor(be/xe)}Te[z]=K(Te[z],Ae[Q],Q,z)}return te||Ve.splice(D,1),[j.type,Te,Ve]}function O(K,j=null,D=1,te=!1){const he=K.data,Ae=K.dims;if(j===null){const ve=he.reduce((De,fe)=>De+fe,0)/he.length,xe=Math.sqrt(he.reduce((De,fe)=>De+(fe-ve)**2,0)/(he.length-D)),Ce=new a(K.type,[ve],[]);return[new a(K.type,[xe],[]),Ce]}j=b(j,Ae.length);const ke=F(K,j,te),Ve=ke.data,[Te,Q,z]=S((be,ve,xe,Ce)=>be+(ve-Ve[Ce])**2,K,j,te);for(let be=0;beQ+z,0);return new a(K.type,[Te/he.length],[])}j=b(j,te.length);const[Ae,ke,Ve]=S((Te,Q)=>Te+Q,K,j,D);if(te[j]!==1)for(let Te=0;Te=0;--D)j[D]=te,te*=K[D];return j}function W(K,j,D,te){const he=K.reduce((Ae,ke)=>Ae*ke,1);return new a(D,new te(he).fill(j),K)}function B(K,j){let D,te;if(typeof j=="number")D="float32",te=Float32Array;else if(typeof j=="bigint")D="int64",te=BigInt64Array;else if(typeof j=="boolean")D="bool",te=Uint8Array;else throw new Error(`Unsupported data type: ${typeof j}`);return W(K,j,D,te)}function Y(K,j){return B(K.dims,j)}function X(K){return W(K,1n,"int64",BigInt64Array)}function J(K){return X(K.dims)}function re(K){return W(K,0n,"int64",BigInt64Array)}function ne(K){return re(K.dims)}function le(K){const j=K.reduce((D,te)=>D*te,1);return new a("float32",Float32Array.from({length:j},()=>Math.random()),K)}function pe(K){const j=K.reduce((te,he)=>te*he,1);function D(){const te=1-Math.random(),he=1-Math.random();return Math.sqrt(-2*Math.log(te))*Math.cos(2*Math.PI*he)}return new a("float32",Float32Array.from({length:j},()=>D()),K)}function oe(K,j){if(K.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(K.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(j))throw new Error("The precision must be either 'binary' or 'ubinary'");const D=j==="binary",te=D?"int8":"uint8",he=D?Int8Array:Uint8Array,Ae=K.data,ke=new he(Ae.length/8);for(let Ve=0;Ve0?1:0,Q=Math.floor(Ve/8),z=Ve%8;ke[Q]|=Te<<7-z,D&&z===0&&(ke[Q]-=128)}return new a(te,ke,[K.dims[0],K.dims[1]/8])}}),"./src/utils/video.js":((e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>i,RawVideoFrame:()=>o,load_video:()=>a});var s=t("./src/utils/image.js"),n=t("./src/env.js");class o{constructor(c,p){this.image=c,this.timestamp=p}}class i{constructor(c,p){c.length>0&&c[0]instanceof s.RawImage&&(c=c.map((d,u)=>new o(d,(u+1)/(c.length+1)*p))),this.frames=c,this.duration=p}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function a(l,{num_frames:c=null,fps:p=null}={}){if(!n.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(c==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const d=[],u=document.createElement("video");if(u.crossOrigin="anonymous",u.muted=!0,typeof l=="string")u.src=l;else if(l instanceof Blob)u.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)u.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(k=>u.onloadedmetadata=k),u.seekable.start(0)===u.seekable.end(0)){const T=await(await fetch(u.src)).blob();u.src=URL.createObjectURL(T),await new Promise(b=>u.onloadedmetadata=b)}const f=u.duration;let _,y;c!=null?(_=c,y=c===1?0:f/(c-1)):(y=1/p,_=Math.floor(f/y));let I=[];for(let k=0;k<_;++k)I.push(c===1?f/2:k*y);const w=document.createElement("canvas");w.width=u.videoWidth,w.height=u.videoHeight;const v=w.getContext("2d",{willReadFrequently:!0});for(const k of I){u.currentTime=k,await new Promise(x=>{u.onseeked=x}),v.drawImage(u,0,0,w.width,w.height);const T=v.getImageData(0,0,w.width,w.height),b=new s.RawImage(T.data,w.width,w.height,4),P=new o(b,k);d.push(P)}return u.remove(),new i(d,f)}})},lM={};function jt(e){var r=lM[e];if(r!==void 0)return r.exports;var t=lM[e]={exports:{}};return mT[e](t,t.exports,jt),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;jt.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 n=Object.create(null);jt.r(n);var o={};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=>o[a]=()=>t[a]);return o.default=()=>t,jt.d(n,o),n}})(),jt.d=(e,r)=>{for(var t in r)jt.o(r,t)&&!jt.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},jt.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),jt.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var m={};(()=>{jt.r(m),jt.d(m,{ASTFeatureExtractor:()=>d.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,ArceeForCausalLM:()=>t.ArceeForCausalLM,ArceeModel:()=>t.ArceeModel,ArceePreTrainedModel:()=>t.ArceePreTrainedModel,AudioClassificationPipeline:()=>r.AudioClassificationPipeline,AutoConfig:()=>n.AutoConfig,AutoFeatureExtractor:()=>u.AutoFeatureExtractor,AutoImageProcessor:()=>y.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:()=>v.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:()=>k.BaseStreamer,BeitFeatureExtractor:()=>_.BeitFeatureExtractor,BeitForImageClassification:()=>t.BeitForImageClassification,BeitModel:()=>t.BeitModel,BeitPreTrainedModel:()=>t.BeitPreTrainedModel,BertForMaskedLM:()=>t.BertForMaskedLM,BertForQuestionAnswering:()=>t.BertForQuestionAnswering,BertForSequenceClassification:()=>t.BertForSequenceClassification,BertForTokenClassification:()=>t.BertForTokenClassification,BertModel:()=>t.BertModel,BertPreTrainedModel:()=>t.BertPreTrainedModel,BertTokenizer:()=>s.BertTokenizer,BitImageProcessor:()=>_.BitImageProcessor,BlenderbotForConditionalGeneration:()=>t.BlenderbotForConditionalGeneration,BlenderbotModel:()=>t.BlenderbotModel,BlenderbotPreTrainedModel:()=>t.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>t.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>t.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>t.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>s.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>s.BlenderbotTokenizer,BloomForCausalLM:()=>t.BloomForCausalLM,BloomModel:()=>t.BloomModel,BloomPreTrainedModel:()=>t.BloomPreTrainedModel,BloomTokenizer:()=>s.BloomTokenizer,CLIPFeatureExtractor:()=>_.CLIPFeatureExtractor,CLIPImageProcessor:()=>_.CLIPImageProcessor,CLIPModel:()=>t.CLIPModel,CLIPPreTrainedModel:()=>t.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>t.CLIPSegForImageSegmentation,CLIPSegModel:()=>t.CLIPSegModel,CLIPSegPreTrainedModel:()=>t.CLIPSegPreTrainedModel,CLIPTextModel:()=>t.CLIPTextModel,CLIPTextModelWithProjection:()=>t.CLIPTextModelWithProjection,CLIPTokenizer:()=>s.CLIPTokenizer,CLIPVisionModel:()=>t.CLIPVisionModel,CLIPVisionModelWithProjection:()=>t.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>t.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>t.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>t.CamembertForSequenceClassification,CamembertForTokenClassification:()=>t.CamembertForTokenClassification,CamembertModel:()=>t.CamembertModel,CamembertPreTrainedModel:()=>t.CamembertPreTrainedModel,CamembertTokenizer:()=>s.CamembertTokenizer,CausalLMOutput:()=>t.CausalLMOutput,CausalLMOutputWithPast:()=>t.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>_.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>d.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>b.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>s.CodeGenTokenizer,CodeLlamaTokenizer:()=>s.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>s.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>s.ConvBertTokenizer,ConvNextFeatureExtractor:()=>_.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>_.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DFineForObjectDetection:()=>t.DFineForObjectDetection,DFineModel:()=>t.DFineModel,DFinePreTrainedModel:()=>t.DFinePreTrainedModel,DINOv3ConvNextModel:()=>t.DINOv3ConvNextModel,DINOv3ConvNextPreTrainedModel:()=>t.DINOv3ConvNextPreTrainedModel,DINOv3ViTImageProcessor:()=>_.DINOv3ViTImageProcessor,DINOv3ViTModel:()=>t.DINOv3ViTModel,DINOv3ViTPreTrainedModel:()=>t.DINOv3ViTPreTrainedModel,DPTFeatureExtractor:()=>_.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>_.DPTImageProcessor,DPTModel:()=>t.DPTModel,DPTPreTrainedModel:()=>t.DPTPreTrainedModel,DacDecoderModel:()=>t.DacDecoderModel,DacDecoderOutput:()=>t.DacDecoderOutput,DacEncoderModel:()=>t.DacEncoderModel,DacEncoderOutput:()=>t.DacEncoderOutput,DacFeatureExtractor:()=>d.DacFeatureExtractor,DacModel:()=>t.DacModel,DacPreTrainedModel:()=>t.DacPreTrainedModel,DataTypeMap:()=>l.DataTypeMap,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>s.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>s.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>_.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>_.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>r.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>_.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>_.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>s.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>r.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>_.DonutFeatureExtractor,DonutImageProcessor:()=>_.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EdgeTamModel:()=>t.EdgeTamModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>_.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>s.ElectraTokenizer,EncodecFeatureExtractor:()=>d.EncodecFeatureExtractor,EosTokenCriteria:()=>T.EosTokenCriteria,Ernie4_5ForCausalLM:()=>t.Ernie4_5ForCausalLM,Ernie4_5Model:()=>t.Ernie4_5Model,Ernie4_5PreTrainedModel:()=>t.Ernie4_5PreTrainedModel,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>s.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>c.FFT,FalconForCausalLM:()=>t.FalconForCausalLM,FalconModel:()=>t.FalconModel,FalconPreTrainedModel:()=>t.FalconPreTrainedModel,FalconTokenizer:()=>s.FalconTokenizer,FastViTForImageClassification:()=>t.FastViTForImageClassification,FastViTModel:()=>t.FastViTModel,FastViTPreTrainedModel:()=>t.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>r.FeatureExtractionPipeline,FeatureExtractor:()=>p.FeatureExtractor,FillMaskPipeline:()=>r.FillMaskPipeline,Florence2ForConditionalGeneration:()=>t.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>t.Florence2PreTrainedModel,Florence2Processor:()=>w.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>b.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>b.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>t.GLPNForDepthEstimation,GLPNModel:()=>t.GLPNModel,GLPNPreTrainedModel:()=>t.GLPNPreTrainedModel,GPT2LMHeadModel:()=>t.GPT2LMHeadModel,GPT2Model:()=>t.GPT2Model,GPT2PreTrainedModel:()=>t.GPT2PreTrainedModel,GPT2Tokenizer:()=>s.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>t.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>t.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>t.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>t.GPTJForCausalLM,GPTJModel:()=>t.GPTJModel,GPTJPreTrainedModel:()=>t.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>t.GPTNeoForCausalLM,GPTNeoModel:()=>t.GPTNeoModel,GPTNeoPreTrainedModel:()=>t.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>t.GPTNeoXForCausalLM,GPTNeoXModel:()=>t.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>t.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>s.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>t.Gemma2ForCausalLM,Gemma2Model:()=>t.Gemma2Model,Gemma2PreTrainedModel:()=>t.Gemma2PreTrainedModel,Gemma3ForCausalLM:()=>t.Gemma3ForCausalLM,Gemma3Model:()=>t.Gemma3Model,Gemma3PreTrainedModel:()=>t.Gemma3PreTrainedModel,Gemma3nAudioFeatureExtractor:()=>d.Gemma3nAudioFeatureExtractor,Gemma3nForConditionalGeneration:()=>t.Gemma3nForConditionalGeneration,Gemma3nPreTrainedModel:()=>t.Gemma3nPreTrainedModel,Gemma3nProcessor:()=>w.Gemma3nProcessor,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>s.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GraniteMoeHybridForCausalLM:()=>t.GraniteMoeHybridForCausalLM,GraniteMoeHybridModel:()=>t.GraniteMoeHybridModel,GraniteMoeHybridPreTrainedModel:()=>t.GraniteMoeHybridPreTrainedModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>w.GroundingDinoProcessor,GroupViTModel:()=>t.GroupViTModel,GroupViTPreTrainedModel:()=>t.GroupViTPreTrainedModel,HeliumForCausalLM:()=>t.HeliumForCausalLM,HeliumModel:()=>t.HeliumModel,HeliumPreTrainedModel:()=>t.HeliumPreTrainedModel,HerbertTokenizer:()=>s.HerbertTokenizer,HieraForImageClassification:()=>t.HieraForImageClassification,HieraModel:()=>t.HieraModel,HieraPreTrainedModel:()=>t.HieraPreTrainedModel,HubertForCTC:()=>t.HubertForCTC,HubertForSequenceClassification:()=>t.HubertForSequenceClassification,HubertModel:()=>t.HubertModel,HubertPreTrainedModel:()=>t.HubertPreTrainedModel,IJepaForImageClassification:()=>t.IJepaForImageClassification,IJepaModel:()=>t.IJepaModel,IJepaPreTrainedModel:()=>t.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>t.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>_.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>w.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>d.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>f.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>T.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>_.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>w.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,Lfm2ForCausalLM:()=>t.Lfm2ForCausalLM,Lfm2Model:()=>t.Lfm2Model,Lfm2PreTrainedModel:()=>t.Lfm2PreTrainedModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,Llama4ForCausalLM:()=>t.Llama4ForCausalLM,Llama4PreTrainedModel:()=>t.Llama4PreTrainedModel,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>_.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LlavaProcessor:()=>w.LlavaProcessor,LlavaQwen2ForCausalLM:()=>t.LlavaQwen2ForCausalLM,LogitsProcessor:()=>b.LogitsProcessor,LogitsProcessorList:()=>b.LogitsProcessorList,LogitsWarper:()=>b.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,Mask2FormerImageProcessor:()=>_.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>_.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>_.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>T.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:()=>b.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>b.MinNewTokensLengthLogitsProcessor,Ministral3ForCausalLM:()=>t.Ministral3ForCausalLM,Ministral3Model:()=>t.Ministral3Model,Ministral3PreTrainedModel:()=>t.Ministral3PreTrainedModel,MinistralForCausalLM:()=>t.MinistralForCausalLM,MinistralModel:()=>t.MinistralModel,MinistralPreTrainedModel:()=>t.MinistralPreTrainedModel,Mistral3ForConditionalGeneration:()=>t.Mistral3ForConditionalGeneration,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>_.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>_.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>_.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>_.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>_.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>_.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>_.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>_.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>_.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>_.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertDecoderForCausalLM:()=>t.ModernBertDecoderForCausalLM,ModernBertDecoderModel:()=>t.ModernBertDecoderModel,ModernBertDecoderPreTrainedModel:()=>t.ModernBertDecoderPreTrainedModel,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>d.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>w.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NanoChatForCausalLM:()=>t.NanoChatForCausalLM,NanoChatModel:()=>t.NanoChatModel,NanoChatPreTrainedModel:()=>t.NanoChatPreTrainedModel,NeoBertForMaskedLM:()=>t.NeoBertForMaskedLM,NeoBertForQuestionAnswering:()=>t.NeoBertForQuestionAnswering,NeoBertForSequenceClassification:()=>t.NeoBertForSequenceClassification,NeoBertForTokenClassification:()=>t.NeoBertForTokenClassification,NeoBertModel:()=>t.NeoBertModel,NeoBertPreTrainedModel:()=>t.NeoBertPreTrainedModel,NllbTokenizer:()=>s.NllbTokenizer,NoBadWordsLogitsProcessor:()=>b.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>b.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>_.NougatImageProcessor,NougatTokenizer:()=>s.NougatTokenizer,OPTForCausalLM:()=>t.OPTForCausalLM,OPTModel:()=>t.OPTModel,OPTPreTrainedModel:()=>t.OPTPreTrainedModel,ObjectDetectionPipeline:()=>r.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>t.Olmo2ForCausalLM,Olmo2Model:()=>t.Olmo2Model,Olmo2PreTrainedModel:()=>t.Olmo2PreTrainedModel,OlmoForCausalLM:()=>t.OlmoForCausalLM,OlmoModel:()=>t.OlmoModel,OlmoPreTrainedModel:()=>t.OlmoPreTrainedModel,OpenELMForCausalLM:()=>t.OpenELMForCausalLM,OpenELMModel:()=>t.OpenELMModel,OpenELMPreTrainedModel:()=>t.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>_.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>_.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>w.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>_.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>w.PaliGemmaProcessor,ParakeetFeatureExtractor:()=>d.ParakeetFeatureExtractor,ParakeetForCTC:()=>t.ParakeetForCTC,ParakeetPreTrainedModel:()=>t.ParakeetPreTrainedModel,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>_.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>w.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PixtralImageProcessor:()=>_.PixtralImageProcessor,PixtralProcessor:()=>w.PixtralProcessor,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>n.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>I.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>_.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>d.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>w.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>t.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>r.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>t.Qwen2ForCausalLM,Qwen2Model:()=>t.Qwen2Model,Qwen2PreTrainedModel:()=>t.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>s.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>t.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>_.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>w.Qwen2VLProcessor,Qwen3ForCausalLM:()=>t.Qwen3ForCausalLM,Qwen3Model:()=>t.Qwen3Model,Qwen3PreTrainedModel:()=>t.Qwen3PreTrainedModel,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>_.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>o.RawAudio,RawImage:()=>i.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>b.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,Sam2ImageProcessor:()=>_.Sam2ImageProcessor,Sam2ImageSegmentationOutput:()=>t.Sam2ImageSegmentationOutput,Sam2Model:()=>t.Sam2Model,Sam2PreTrainedModel:()=>t.Sam2PreTrainedModel,Sam2Processor:()=>w.Sam2Processor,Sam2VideoProcessor:()=>w.Sam2VideoProcessor,Sam3ImageProcessor:()=>_.Sam3ImageProcessor,Sam3TrackerModel:()=>t.Sam3TrackerModel,SamImageProcessor:()=>_.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>w.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>_.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>_.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>_.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>s.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SmolLM3ForCausalLM:()=>t.SmolLM3ForCausalLM,SmolLM3Model:()=>t.SmolLM3Model,SmolLM3PreTrainedModel:()=>t.SmolLM3PreTrainedModel,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>_.SmolVLMImageProcessor,SmolVLMProcessor:()=>w.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>d.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>d.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>w.SpeechT5Processor,SpeechT5Tokenizer:()=>s.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>s.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>T.StoppingCriteria,StoppingCriteriaList:()=>T.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SupertonicForConditionalGeneration:()=>t.SupertonicForConditionalGeneration,SupertonicPreTrainedModel:()=>t.SupertonicPreTrainedModel,SuppressTokensAtBeginLogitsProcessor:()=>b.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>_.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinForSemanticSegmentation:()=>t.SwinForSemanticSegmentation,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>s.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>b.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>k.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>b.TopKLogitsWarper,TopPLogitsWarper:()=>b.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>w.UltravoxProcessor,UniSpeechForCTC:()=>t.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>t.UniSpeechForSequenceClassification,UniSpeechModel:()=>t.UniSpeechModel,UniSpeechPreTrainedModel:()=>t.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>t.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>t.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>t.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>t.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>t.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>w.VLChatProcessor,VLMImageProcessor:()=>_.VLMImageProcessor,VaultGemmaForCausalLM:()=>t.VaultGemmaForCausalLM,VaultGemmaModel:()=>t.VaultGemmaModel,VaultGemmaPreTrainedModel:()=>t.VaultGemmaPreTrainedModel,ViTFeatureExtractor:()=>_.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>_.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>_.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>_.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,VoxtralForConditionalGeneration:()=>t.VoxtralForConditionalGeneration,VoxtralProcessor:()=>w.VoxtralProcessor,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>s.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>d.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>w.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>w.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>d.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>d.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>w.WhisperProcessor,WhisperTextStreamer:()=>k.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>b.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>s.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>s.XLMRobertaTokenizer,XLMTokenizer:()=>s.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>_.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>_.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>r.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>r.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>r.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>r.ZeroShotObjectDetectionPipeline,bankers_round:()=>c.bankers_round,cat:()=>l.cat,cos_sim:()=>c.cos_sim,dot:()=>c.dot,dynamic_time_warping:()=>c.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getCacheShapes:()=>n.getCacheShapes,hamming:()=>o.hamming,hanning:()=>o.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>c.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>i.load_image,load_video:()=>a.load_video,log_softmax:()=>c.log_softmax,magnitude:()=>c.magnitude,matmul:()=>l.matmul,max:()=>c.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>c.medianFilter,mel_filter_bank:()=>o.mel_filter_bank,min:()=>c.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>c.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,randn:()=>l.randn,read_audio:()=>o.read_audio,rfft:()=>l.rfft,round:()=>c.round,slice:()=>l.slice,softmax:()=>c.softmax,spectrogram:()=>o.spectrogram,stack:()=>l.stack,std_mean:()=>l.std_mean,topk:()=>l.topk,window_function:()=>o.window_function,zeros:()=>l.zeros,zeros_like:()=>l.zeros_like});var e=jt("./src/env.js"),r=jt("./src/pipelines.js"),t=jt("./src/models.js"),s=jt("./src/tokenizers.js"),n=jt("./src/configs.js"),o=jt("./src/utils/audio.js"),i=jt("./src/utils/image.js"),a=jt("./src/utils/video.js"),l=jt("./src/utils/tensor.js"),c=jt("./src/utils/maths.js"),p=jt("./src/base/feature_extraction_utils.js"),d=jt("./src/models/feature_extractors.js"),u=jt("./src/models/auto/feature_extraction_auto.js"),f=jt("./src/base/image_processors_utils.js"),_=jt("./src/models/image_processors.js"),y=jt("./src/models/auto/image_processing_auto.js"),I=jt("./src/base/processing_utils.js"),w=jt("./src/models/processors.js"),v=jt("./src/models/auto/processing_auto.js"),k=jt("./src/generation/streamers.js"),T=jt("./src/generation/stopping_criteria.js"),b=jt("./src/generation/logits_process.js")})(),m.ASTFeatureExtractor,m.ASTForAudioClassification,m.ASTModel,m.ASTPreTrainedModel,m.AlbertForMaskedLM,m.AlbertForQuestionAnswering,m.AlbertForSequenceClassification,m.AlbertModel,m.AlbertPreTrainedModel,m.AlbertTokenizer,m.ArceeForCausalLM,m.ArceeModel,m.ArceePreTrainedModel,m.AudioClassificationPipeline,m.AutoConfig,m.AutoFeatureExtractor,m.AutoImageProcessor,m.AutoModel,m.AutoModelForAudioClassification,m.AutoModelForAudioFrameClassification,m.AutoModelForAudioTextToText,m.AutoModelForCTC;var hT=m.AutoModelForCausalLM;m.AutoModelForDepthEstimation,m.AutoModelForDocumentQuestionAnswering,m.AutoModelForImageClassification,m.AutoModelForImageFeatureExtraction,m.AutoModelForImageMatting,m.AutoModelForImageSegmentation,m.AutoModelForImageTextToText,m.AutoModelForImageToImage,m.AutoModelForMaskGeneration,m.AutoModelForMaskedLM,m.AutoModelForNormalEstimation,m.AutoModelForObjectDetection,m.AutoModelForPoseEstimation,m.AutoModelForQuestionAnswering,m.AutoModelForSemanticSegmentation,m.AutoModelForSeq2SeqLM,m.AutoModelForSequenceClassification,m.AutoModelForSpeechSeq2Seq,m.AutoModelForTextToSpectrogram,m.AutoModelForTextToWaveform,m.AutoModelForTokenClassification,m.AutoModelForUniversalSegmentation,m.AutoModelForVision2Seq,m.AutoModelForXVector,m.AutoModelForZeroShotObjectDetection,m.AutoProcessor;var _T=m.AutoTokenizer;m.AutomaticSpeechRecognitionPipeline,m.BackgroundRemovalPipeline,m.BartForConditionalGeneration,m.BartForSequenceClassification,m.BartModel,m.BartPretrainedModel,m.BartTokenizer,m.BaseModelOutput,m.BaseStreamer,m.BeitFeatureExtractor,m.BeitForImageClassification,m.BeitModel,m.BeitPreTrainedModel,m.BertForMaskedLM,m.BertForQuestionAnswering,m.BertForSequenceClassification,m.BertForTokenClassification,m.BertModel,m.BertPreTrainedModel,m.BertTokenizer,m.BitImageProcessor,m.BlenderbotForConditionalGeneration,m.BlenderbotModel,m.BlenderbotPreTrainedModel,m.BlenderbotSmallForConditionalGeneration,m.BlenderbotSmallModel,m.BlenderbotSmallPreTrainedModel,m.BlenderbotSmallTokenizer,m.BlenderbotTokenizer,m.BloomForCausalLM,m.BloomModel,m.BloomPreTrainedModel,m.BloomTokenizer,m.CLIPFeatureExtractor,m.CLIPImageProcessor,m.CLIPModel,m.CLIPPreTrainedModel,m.CLIPSegForImageSegmentation,m.CLIPSegModel,m.CLIPSegPreTrainedModel,m.CLIPTextModel,m.CLIPTextModelWithProjection,m.CLIPTokenizer,m.CLIPVisionModel,m.CLIPVisionModelWithProjection,m.CamembertForMaskedLM,m.CamembertForQuestionAnswering,m.CamembertForSequenceClassification,m.CamembertForTokenClassification,m.CamembertModel,m.CamembertPreTrainedModel,m.CamembertTokenizer,m.CausalLMOutput,m.CausalLMOutputWithPast,m.ChineseCLIPFeatureExtractor,m.ChineseCLIPModel,m.ChineseCLIPPreTrainedModel,m.ClapAudioModelWithProjection,m.ClapFeatureExtractor,m.ClapModel,m.ClapPreTrainedModel,m.ClapTextModelWithProjection,m.ClassifierFreeGuidanceLogitsProcessor,m.CodeGenForCausalLM,m.CodeGenModel,m.CodeGenPreTrainedModel,m.CodeGenTokenizer,m.CodeLlamaTokenizer,m.CohereForCausalLM,m.CohereModel,m.CoherePreTrainedModel,m.CohereTokenizer,m.ConvBertForMaskedLM,m.ConvBertForQuestionAnswering,m.ConvBertForSequenceClassification,m.ConvBertForTokenClassification,m.ConvBertModel,m.ConvBertPreTrainedModel,m.ConvBertTokenizer,m.ConvNextFeatureExtractor,m.ConvNextForImageClassification,m.ConvNextImageProcessor,m.ConvNextModel,m.ConvNextPreTrainedModel,m.ConvNextV2ForImageClassification,m.ConvNextV2Model,m.ConvNextV2PreTrainedModel,m.DFineForObjectDetection,m.DFineModel,m.DFinePreTrainedModel,m.DINOv3ConvNextModel,m.DINOv3ConvNextPreTrainedModel,m.DINOv3ViTImageProcessor,m.DINOv3ViTModel,m.DINOv3ViTPreTrainedModel,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.EdgeTamModel,m.EfficientNetForImageClassification,m.EfficientNetImageProcessor,m.EfficientNetModel,m.EfficientNetPreTrainedModel,m.ElectraForMaskedLM,m.ElectraForQuestionAnswering,m.ElectraForSequenceClassification,m.ElectraForTokenClassification,m.ElectraModel,m.ElectraPreTrainedModel,m.ElectraTokenizer,m.EncodecFeatureExtractor,m.EosTokenCriteria,m.Ernie4_5ForCausalLM,m.Ernie4_5Model,m.Ernie4_5PreTrainedModel,m.EsmForMaskedLM,m.EsmForSequenceClassification,m.EsmForTokenClassification,m.EsmModel,m.EsmPreTrainedModel,m.EsmTokenizer,m.ExaoneForCausalLM,m.ExaoneModel,m.ExaonePreTrainedModel,m.FFT,m.FalconForCausalLM,m.FalconModel,m.FalconPreTrainedModel,m.FalconTokenizer,m.FastViTForImageClassification,m.FastViTModel,m.FastViTPreTrainedModel,m.FeatureExtractionPipeline,m.FeatureExtractor,m.FillMaskPipeline,m.Florence2ForConditionalGeneration,m.Florence2PreTrainedModel,m.Florence2Processor,m.ForcedBOSTokenLogitsProcessor,m.ForcedEOSTokenLogitsProcessor,m.GLPNFeatureExtractor,m.GLPNForDepthEstimation,m.GLPNModel,m.GLPNPreTrainedModel,m.GPT2LMHeadModel,m.GPT2Model,m.GPT2PreTrainedModel,m.GPT2Tokenizer,m.GPTBigCodeForCausalLM,m.GPTBigCodeModel,m.GPTBigCodePreTrainedModel,m.GPTJForCausalLM,m.GPTJModel,m.GPTJPreTrainedModel,m.GPTNeoForCausalLM,m.GPTNeoModel,m.GPTNeoPreTrainedModel,m.GPTNeoXForCausalLM,m.GPTNeoXModel,m.GPTNeoXPreTrainedModel,m.GPTNeoXTokenizer,m.Gemma2ForCausalLM,m.Gemma2Model,m.Gemma2PreTrainedModel,m.Gemma3ForCausalLM,m.Gemma3Model,m.Gemma3PreTrainedModel,m.Gemma3nAudioFeatureExtractor,m.Gemma3nForConditionalGeneration,m.Gemma3nPreTrainedModel,m.Gemma3nProcessor,m.GemmaForCausalLM,m.GemmaModel,m.GemmaPreTrainedModel,m.GemmaTokenizer,m.GlmForCausalLM,m.GlmModel,m.GlmPreTrainedModel,m.GraniteForCausalLM,m.GraniteModel,m.GraniteMoeHybridForCausalLM,m.GraniteMoeHybridModel,m.GraniteMoeHybridPreTrainedModel,m.GranitePreTrainedModel,m.Grok1Tokenizer,m.GroundingDinoForObjectDetection,m.GroundingDinoImageProcessor,m.GroundingDinoPreTrainedModel,m.GroundingDinoProcessor,m.GroupViTModel,m.GroupViTPreTrainedModel,m.HeliumForCausalLM,m.HeliumModel,m.HeliumPreTrainedModel,m.HerbertTokenizer,m.HieraForImageClassification,m.HieraModel,m.HieraPreTrainedModel,m.HubertForCTC,m.HubertForSequenceClassification,m.HubertModel,m.HubertPreTrainedModel,m.IJepaForImageClassification,m.IJepaModel,m.IJepaPreTrainedModel,m.Idefics3ForConditionalGeneration,m.Idefics3ImageProcessor,m.Idefics3PreTrainedModel,m.Idefics3Processor,m.ImageClassificationPipeline,m.ImageFeatureExtractionPipeline,m.ImageFeatureExtractor,m.ImageMattingOutput,m.ImageProcessor,m.ImageSegmentationPipeline,m.ImageToImagePipeline,m.ImageToTextPipeline,m.InterruptableStoppingCriteria,m.JAISLMHeadModel,m.JAISModel,m.JAISPreTrainedModel,m.JinaCLIPImageProcessor,m.JinaCLIPModel,m.JinaCLIPPreTrainedModel,m.JinaCLIPProcessor,m.JinaCLIPTextModel,m.JinaCLIPVisionModel,m.Lfm2ForCausalLM,m.Lfm2Model,m.Lfm2PreTrainedModel,m.LiteWhisperForConditionalGeneration,m.Llama4ForCausalLM,m.Llama4PreTrainedModel,m.LlamaForCausalLM,m.LlamaModel,m.LlamaPreTrainedModel,m.LlamaTokenizer,m.LlavaForConditionalGeneration,m.LlavaOnevisionForConditionalGeneration,m.LlavaOnevisionImageProcessor,m.LlavaPreTrainedModel,m.LlavaProcessor,m.LlavaQwen2ForCausalLM,m.LogitsProcessor,m.LogitsProcessorList,m.LogitsWarper,m.LongT5ForConditionalGeneration,m.LongT5Model,m.LongT5PreTrainedModel,m.M2M100ForConditionalGeneration,m.M2M100Model,m.M2M100PreTrainedModel,m.M2M100Tokenizer,m.MBart50Tokenizer,m.MBartForCausalLM,m.MBartForConditionalGeneration,m.MBartForSequenceClassification,m.MBartModel,m.MBartPreTrainedModel,m.MBartTokenizer,m.MPNetForMaskedLM,m.MPNetForQuestionAnswering,m.MPNetForSequenceClassification,m.MPNetForTokenClassification,m.MPNetModel,m.MPNetPreTrainedModel,m.MPNetTokenizer,m.MT5ForConditionalGeneration,m.MT5Model,m.MT5PreTrainedModel,m.MarianMTModel,m.MarianModel,m.MarianPreTrainedModel,m.MarianTokenizer,m.Mask2FormerImageProcessor,m.MaskFormerFeatureExtractor,m.MaskFormerForInstanceSegmentation,m.MaskFormerImageProcessor,m.MaskFormerModel,m.MaskFormerPreTrainedModel,m.MaskedLMOutput,m.MaxLengthCriteria,m.Metric3DForDepthEstimation,m.Metric3DPreTrainedModel,m.Metric3Dv2ForDepthEstimation,m.Metric3Dv2PreTrainedModel,m.MgpstrForSceneTextRecognition,m.MgpstrModelOutput,m.MgpstrPreTrainedModel,m.MgpstrProcessor,m.MgpstrTokenizer,m.MimiDecoderModel,m.MimiDecoderOutput,m.MimiEncoderModel,m.MimiEncoderOutput,m.MimiModel,m.MimiPreTrainedModel,m.MinLengthLogitsProcessor,m.MinNewTokensLengthLogitsProcessor,m.Ministral3ForCausalLM,m.Ministral3Model,m.Ministral3PreTrainedModel,m.MinistralForCausalLM,m.MinistralModel,m.MinistralPreTrainedModel,m.Mistral3ForConditionalGeneration,m.MistralForCausalLM,m.MistralModel,m.MistralPreTrainedModel,m.MobileBertForMaskedLM,m.MobileBertForQuestionAnswering,m.MobileBertForSequenceClassification,m.MobileBertModel,m.MobileBertPreTrainedModel,m.MobileBertTokenizer,m.MobileLLMForCausalLM,m.MobileLLMModel,m.MobileLLMPreTrainedModel,m.MobileNetV1FeatureExtractor,m.MobileNetV1ForImageClassification,m.MobileNetV1ForSemanticSegmentation,m.MobileNetV1ImageProcessor,m.MobileNetV1Model,m.MobileNetV1PreTrainedModel,m.MobileNetV2FeatureExtractor,m.MobileNetV2ForImageClassification,m.MobileNetV2ForSemanticSegmentation,m.MobileNetV2ImageProcessor,m.MobileNetV2Model,m.MobileNetV2PreTrainedModel,m.MobileNetV3FeatureExtractor,m.MobileNetV3ForImageClassification,m.MobileNetV3ForSemanticSegmentation,m.MobileNetV3ImageProcessor,m.MobileNetV3Model,m.MobileNetV3PreTrainedModel,m.MobileNetV4FeatureExtractor,m.MobileNetV4ForImageClassification,m.MobileNetV4ForSemanticSegmentation,m.MobileNetV4ImageProcessor,m.MobileNetV4Model,m.MobileNetV4PreTrainedModel,m.MobileViTFeatureExtractor,m.MobileViTForImageClassification,m.MobileViTImageProcessor,m.MobileViTModel,m.MobileViTPreTrainedModel,m.MobileViTV2ForImageClassification,m.MobileViTV2Model,m.MobileViTV2PreTrainedModel,m.ModelOutput,m.ModernBertDecoderForCausalLM,m.ModernBertDecoderModel,m.ModernBertDecoderPreTrainedModel,m.ModernBertForMaskedLM,m.ModernBertForSequenceClassification,m.ModernBertForTokenClassification,m.ModernBertModel,m.ModernBertPreTrainedModel,m.Moondream1ForConditionalGeneration,m.MoonshineFeatureExtractor,m.MoonshineForConditionalGeneration,m.MoonshineModel,m.MoonshinePreTrainedModel,m.MoonshineProcessor,m.MptForCausalLM,m.MptModel,m.MptPreTrainedModel,m.MultiModalityCausalLM,m.MultiModalityPreTrainedModel,m.MusicgenForCausalLM,m.MusicgenForConditionalGeneration,m.MusicgenModel,m.MusicgenPreTrainedModel,m.NanoChatForCausalLM,m.NanoChatModel,m.NanoChatPreTrainedModel,m.NeoBertForMaskedLM,m.NeoBertForQuestionAnswering,m.NeoBertForSequenceClassification,m.NeoBertForTokenClassification,m.NeoBertModel,m.NeoBertPreTrainedModel,m.NllbTokenizer,m.NoBadWordsLogitsProcessor,m.NoRepeatNGramLogitsProcessor,m.NomicBertModel,m.NomicBertPreTrainedModel,m.NougatImageProcessor,m.NougatTokenizer,m.OPTForCausalLM,m.OPTModel,m.OPTPreTrainedModel,m.ObjectDetectionPipeline,m.Olmo2ForCausalLM,m.Olmo2Model,m.Olmo2PreTrainedModel,m.OlmoForCausalLM,m.OlmoModel,m.OlmoPreTrainedModel,m.OpenELMForCausalLM,m.OpenELMModel,m.OpenELMPreTrainedModel,m.OwlViTFeatureExtractor,m.OwlViTForObjectDetection,m.OwlViTImageProcessor,m.OwlViTModel,m.OwlViTPreTrainedModel,m.OwlViTProcessor,m.Owlv2ForObjectDetection,m.Owlv2ImageProcessor,m.Owlv2Model,m.Owlv2PreTrainedModel,m.PaliGemmaForConditionalGeneration,m.PaliGemmaPreTrainedModel,m.PaliGemmaProcessor,m.ParakeetFeatureExtractor,m.ParakeetForCTC,m.ParakeetPreTrainedModel,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.PixtralImageProcessor,m.PixtralProcessor,m.PreTrainedModel,m.PreTrainedTokenizer,m.PretrainedConfig,m.PretrainedMixin,m.Processor,m.PvtForImageClassification,m.PvtImageProcessor,m.PvtModel,m.PvtPreTrainedModel,m.PyAnnoteFeatureExtractor,m.PyAnnoteForAudioFrameClassification,m.PyAnnoteModel,m.PyAnnotePreTrainedModel,m.PyAnnoteProcessor,m.QuestionAnsweringModelOutput,m.QuestionAnsweringPipeline,m.Qwen2ForCausalLM,m.Qwen2Model,m.Qwen2PreTrainedModel,m.Qwen2Tokenizer,m.Qwen2VLForConditionalGeneration,m.Qwen2VLImageProcessor,m.Qwen2VLPreTrainedModel,m.Qwen2VLProcessor,m.Qwen3ForCausalLM,m.Qwen3Model,m.Qwen3PreTrainedModel,m.RFDetrForObjectDetection,m.RFDetrModel,m.RFDetrObjectDetectionOutput,m.RFDetrPreTrainedModel,m.RTDetrForObjectDetection,m.RTDetrImageProcessor,m.RTDetrModel,m.RTDetrObjectDetectionOutput,m.RTDetrPreTrainedModel,m.RTDetrV2ForObjectDetection,m.RTDetrV2Model,m.RTDetrV2ObjectDetectionOutput,m.RTDetrV2PreTrainedModel,m.RawAudio,m.RawImage,m.RawVideo,m.RawVideoFrame,m.RepetitionPenaltyLogitsProcessor,m.ResNetForImageClassification,m.ResNetModel,m.ResNetPreTrainedModel,m.RoFormerForMaskedLM,m.RoFormerForQuestionAnswering,m.RoFormerForSequenceClassification,m.RoFormerForTokenClassification,m.RoFormerModel,m.RoFormerPreTrainedModel,m.RoFormerTokenizer,m.RobertaForMaskedLM,m.RobertaForQuestionAnswering,m.RobertaForSequenceClassification,m.RobertaForTokenClassification,m.RobertaModel,m.RobertaPreTrainedModel,m.RobertaTokenizer,m.Sam2ImageProcessor,m.Sam2ImageSegmentationOutput,m.Sam2Model,m.Sam2PreTrainedModel,m.Sam2Processor,m.Sam2VideoProcessor,m.Sam3ImageProcessor,m.Sam3TrackerModel,m.SamImageProcessor,m.SamImageSegmentationOutput,m.SamModel,m.SamPreTrainedModel,m.SamProcessor,m.SapiensForDepthEstimation,m.SapiensForNormalEstimation,m.SapiensForSemanticSegmentation,m.SapiensPreTrainedModel,m.SeamlessM4TFeatureExtractor,m.SegformerFeatureExtractor,m.SegformerForImageClassification,m.SegformerForSemanticSegmentation,m.SegformerImageProcessor,m.SegformerModel,m.SegformerPreTrainedModel,m.Seq2SeqLMOutput,m.SequenceClassifierOutput,m.SiglipImageProcessor,m.SiglipModel,m.SiglipPreTrainedModel,m.SiglipTextModel,m.SiglipTokenizer,m.SiglipVisionModel,m.SmolLM3ForCausalLM,m.SmolLM3Model,m.SmolLM3PreTrainedModel,m.SmolVLMForConditionalGeneration,m.SmolVLMImageProcessor,m.SmolVLMProcessor,m.SnacDecoderModel,m.SnacEncoderModel,m.SnacFeatureExtractor,m.SnacModel,m.SnacPreTrainedModel,m.SpeechT5FeatureExtractor,m.SpeechT5ForSpeechToText,m.SpeechT5ForTextToSpeech,m.SpeechT5HifiGan,m.SpeechT5Model,m.SpeechT5PreTrainedModel,m.SpeechT5Processor,m.SpeechT5Tokenizer,m.SqueezeBertForMaskedLM,m.SqueezeBertForQuestionAnswering,m.SqueezeBertForSequenceClassification,m.SqueezeBertModel,m.SqueezeBertPreTrainedModel,m.SqueezeBertTokenizer,m.StableLmForCausalLM,m.StableLmModel,m.StableLmPreTrainedModel,m.Starcoder2ForCausalLM,m.Starcoder2Model,m.Starcoder2PreTrainedModel,m.StoppingCriteria,m.StoppingCriteriaList,m.StyleTextToSpeech2Model,m.StyleTextToSpeech2PreTrainedModel,m.SummarizationPipeline,m.SupertonicForConditionalGeneration,m.SupertonicPreTrainedModel,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.VaultGemmaForCausalLM,m.VaultGemmaModel,m.VaultGemmaPreTrainedModel,m.ViTFeatureExtractor,m.ViTForImageClassification,m.ViTImageProcessor,m.ViTMAEModel,m.ViTMAEPreTrainedModel,m.ViTMSNForImageClassification,m.ViTMSNModel,m.ViTMSNPreTrainedModel,m.ViTModel,m.ViTPreTrainedModel,m.VisionEncoderDecoderModel,m.VitMatteForImageMatting,m.VitMatteImageProcessor,m.VitMattePreTrainedModel,m.VitPoseForPoseEstimation,m.VitPoseImageProcessor,m.VitPosePreTrainedModel,m.VitsModel,m.VitsModelOutput,m.VitsPreTrainedModel,m.VitsTokenizer,m.VoxtralForConditionalGeneration,m.VoxtralProcessor,m.Wav2Vec2BertForCTC,m.Wav2Vec2BertForSequenceClassification,m.Wav2Vec2BertModel,m.Wav2Vec2BertPreTrainedModel,m.Wav2Vec2CTCTokenizer,m.Wav2Vec2FeatureExtractor,m.Wav2Vec2ForAudioFrameClassification,m.Wav2Vec2ForCTC,m.Wav2Vec2ForSequenceClassification,m.Wav2Vec2Model,m.Wav2Vec2PreTrainedModel,m.Wav2Vec2Processor,m.Wav2Vec2ProcessorWithLM,m.WavLMForAudioFrameClassification,m.WavLMForCTC,m.WavLMForSequenceClassification,m.WavLMForXVector,m.WavLMModel,m.WavLMPreTrainedModel,m.WeSpeakerFeatureExtractor,m.WeSpeakerResNetModel,m.WeSpeakerResNetPreTrainedModel,m.WhisperFeatureExtractor,m.WhisperForConditionalGeneration,m.WhisperModel,m.WhisperPreTrainedModel,m.WhisperProcessor,m.WhisperTextStreamer,m.WhisperTimeStampLogitsProcessor,m.WhisperTokenizer,m.XLMForQuestionAnswering,m.XLMForSequenceClassification,m.XLMForTokenClassification,m.XLMModel,m.XLMPreTrainedModel,m.XLMRobertaForMaskedLM,m.XLMRobertaForQuestionAnswering,m.XLMRobertaForSequenceClassification,m.XLMRobertaForTokenClassification,m.XLMRobertaModel,m.XLMRobertaPreTrainedModel,m.XLMRobertaTokenizer,m.XLMTokenizer,m.XLMWithLMHeadModel,m.XVectorOutput,m.YolosFeatureExtractor,m.YolosForObjectDetection,m.YolosImageProcessor,m.YolosModel,m.YolosObjectDetectionOutput,m.YolosPreTrainedModel,m.ZeroShotAudioClassificationPipeline,m.ZeroShotClassificationPipeline,m.ZeroShotImageClassificationPipeline,m.ZeroShotObjectDetectionPipeline,m.bankers_round,m.cat,m.cos_sim,m.dot,m.dynamic_time_warping,m.env,m.full,m.full_like,m.getCacheShapes,m.hamming,m.hanning,m.interpolate,m.interpolate_4d,m.interpolate_data,m.is_chinese_char,m.layer_norm,m.load_image,m.load_video,m.log_softmax,m.magnitude,m.matmul,m.max,m.mean,m.mean_pooling,m.medianFilter,m.mel_filter_bank,m.min,m.ones,m.ones_like,m.permute,m.permute_data,m.pipeline,m.quantize_embeddings,m.rand,m.randn,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;const cM=Symbol("Comlink.proxy"),fT=Symbol("Comlink.endpoint"),gT=Symbol("Comlink.releaseProxy"),mc=Symbol("Comlink.finalizer"),ya=Symbol("Comlink.thrown"),uM=e=>typeof e=="object"&&e!==null||typeof e=="function",MT={canHandle:e=>uM(e)&&e[cM],serialize(e){const{port1:r,port2:t}=new MessageChannel;return hc(e,r),[t,[t]]},deserialize(e){return e.start(),vT(e)}},wT={canHandle:e=>uM(e)&&ya in e,serialize({value:e}){let r;return e instanceof Error?r={isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:r={isError:!1,value:e},[r,[]]},deserialize(e){throw e.isError?Object.assign(new Error(e.value.message),e.value):e.value}},dM=new Map([["proxy",MT],["throw",wT]]);function bT(e,r){for(const t of e)if(r===t||t==="*"||t instanceof RegExp&&t.test(r))return!0;return!1}function hc(e,r=globalThis,t=["*"]){r.addEventListener("message",function s(n){if(!n||!n.data)return;if(!bT(t,n.origin)){console.warn(`Invalid origin '${n.origin}' for comlink proxy`);return}const{id:o,type:i,path:a}=Object.assign({path:[]},n.data),l=(n.data.argumentList||[]).map(wn);let c;try{const p=a.slice(0,-1).reduce((u,f)=>u[f],e),d=a.reduce((u,f)=>u[f],e);switch(i){case"GET":c=d;break;case"SET":p[a.slice(-1)[0]]=wn(n.data.value),c=!0;break;case"APPLY":c=d.apply(p,l);break;case"CONSTRUCT":{const u=new d(...l);c=CT(u)}break;case"ENDPOINT":{const{port1:u,port2:f}=new MessageChannel;hc(e,f),c=ET(u,[u])}break;case"RELEASE":c=void 0;break;default:return}}catch(p){c={value:p,[ya]:0}}Promise.resolve(c).catch(p=>({value:p,[ya]:0})).then(p=>{const[d,u]=Pa(p);r.postMessage(Object.assign(Object.assign({},d),{id:o}),u),i==="RELEASE"&&(r.removeEventListener("message",s),pM(r),mc in e&&typeof e[mc]=="function"&&e[mc]())}).catch(p=>{const[d,u]=Pa({value:new TypeError("Unserializable return value"),[ya]:0});r.postMessage(Object.assign(Object.assign({},d),{id:o}),u)})}),r.start&&r.start()}function yT(e){return e.constructor.name==="MessagePort"}function pM(e){yT(e)&&e.close()}function vT(e,r){const t=new Map;return e.addEventListener("message",function(n){const{data:o}=n;if(!o||!o.id)return;const i=t.get(o.id);if(i)try{i(o)}finally{t.delete(o.id)}}),_c(e,t,[],r)}function va(e){if(e)throw new Error("Proxy has been released and is not useable")}function mM(e){return jn(e,new Map,{type:"RELEASE"}).then(()=>{pM(e)})}const xa=new WeakMap,Ta="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{const r=(xa.get(e)||0)-1;xa.set(e,r),r===0&&mM(e)});function xT(e,r){const t=(xa.get(r)||0)+1;xa.set(r,t),Ta&&Ta.register(e,r,e)}function TT(e){Ta&&Ta.unregister(e)}function _c(e,r,t=[],s=function(){}){let n=!1;const o=new Proxy(s,{get(i,a){if(va(n),a===gT)return()=>{TT(o),mM(e),r.clear(),n=!0};if(a==="then"){if(t.length===0)return{then:()=>o};const l=jn(e,r,{type:"GET",path:t.map(c=>c.toString())}).then(wn);return l.then.bind(l)}return _c(e,r,[...t,a])},set(i,a,l){va(n);const[c,p]=Pa(l);return jn(e,r,{type:"SET",path:[...t,a].map(d=>d.toString()),value:c},p).then(wn)},apply(i,a,l){va(n);const c=t[t.length-1];if(c===fT)return jn(e,r,{type:"ENDPOINT"}).then(wn);if(c==="bind")return _c(e,r,t.slice(0,-1));const[p,d]=hM(l);return jn(e,r,{type:"APPLY",path:t.map(u=>u.toString()),argumentList:p},d).then(wn)},construct(i,a){va(n);const[l,c]=hM(a);return jn(e,r,{type:"CONSTRUCT",path:t.map(p=>p.toString()),argumentList:l},c).then(wn)}});return xT(o,e),o}function PT(e){return Array.prototype.concat.apply([],e)}function hM(e){const r=e.map(Pa);return[r.map(t=>t[0]),PT(r.map(t=>t[1]))]}const _M=new WeakMap;function ET(e,r){return _M.set(e,r),e}function CT(e){return Object.assign(e,{[cM]:!0})}function Pa(e){for(const[r,t]of dM)if(t.canHandle(e)){const[s,n]=t.serialize(e);return[{type:"HANDLER",name:r,value:s},n]}return[{type:"RAW",value:e},_M.get(e)||[]]}function wn(e){switch(e.type){case"HANDLER":return dM.get(e.name).deserialize(e.value);case"RAW":return e.value}}function jn(e,r,t,s){return new Promise(n=>{const o=ST();r.set(o,n),e.start&&e.start(),e.postMessage(Object.assign({id:o},t),s)})}function ST(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}const fM="onnx-community/functiongemma-270m-it-ONNX";let gM=null;function MM(e){return gM??=(async()=>{console.log("[Worker] Loading model...");const[r,t]=await Promise.all([_T.from_pretrained(fM,{progress_callback:e}),hT.from_pretrained(fM,{dtype:"q4",device:"webgpu",progress_callback:e})]);return console.log("[Worker] Model loaded!"),{model:t,tokenizer:r}})(),gM}hc({async initModel(e){console.log("[Worker] initModel called"),await MM(e),console.log("[Worker] initModel completed")},async generate(e,r){console.log("[Worker] ========== GENERATE =========="),console.log("[Worker] Messages:",JSON.stringify(e,null,2));const{model:t,tokenizer:s}=await MM(),n=s.apply_chat_template(e,{tools:r,tokenize:!0,add_generation_prompt:!0,return_dict:!0});console.log("[Worker] Input token count:",n.input_ids.dims[1]);const o=await t.generate({...n,max_new_tokens:512}),i=n.input_ids.dims[1],a=s.decode(o.slice(0,[i,null]),{skip_special_tokens:!1});return console.log("[Worker] Raw output:",a),a}})})();