const Yi=new Map,fn=[],ov=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=Yi.get(e);if(s===void 0)Yi.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=fn.indexOf(e);n!==-1&&fn.splice(n,1);for(let o=0;o{const r=Yi.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?fn:t;let n;const o=[],a=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&&a.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 i=r.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]},lv="1.21.0";let Bh="warning";const ns={wasm:{},webgl:{},webgpu:{},versions:{common:lv},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}`);Bh=e}},get logLevel(){return Bh}};Object.defineProperty(ns,"logLevel",{enumerable:!0});const uv=ns,cv=(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 a=r?.format!==void 0?r.format:"RGB",i=r?.norm;let l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));const p=o*n;let u=0,d=p,f=p*2,_=-1;a==="RGBA"?(u=0,d=p,f=p*2,_=p*3):a==="RGB"?(u=0,d=p,f=p*2):a==="RBG"&&(u=0,f=p,d=p*2);for(let P=0;P{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let n,o,a;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[1],a=e.dims[3]):(n=e.dims[3],o=e.dims[2],a=e.dims[1]);const i=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 u=o*n;if(r!==void 0&&(r.format!==void 0&&a===4&&r.format!=="RGBA"||a===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const d=4;let f=0,_=1,P=2,I=3,M=0,g=u,S=u*2,E=-1;i==="RGBA"?(M=0,g=u,S=u*2,E=u*3):i==="RGB"?(M=0,g=u,S=u*2):i==="RBG"&&(M=0,S=u,g=u*2),s=t.createImageData(n,o);for(let x=0;x{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,a;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"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];const i=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 u=4,d=0,f=1,_=2,P=3,I=0,M=c,g=c*2,S=-1;i==="RGB"&&(u=3,d=0,f=1,_=2,P=-1),l==="RGBA"?S=c*3:l==="RBG"?(I=0,g=c,M=c*2):l==="BGR"&&(g=0,M=c,I=c*2);for(let x=0;x{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 a,i=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 u=c(p);if(u!=null){let d=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(d=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(i=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=d,i.width=f}else i.tensorFormat="RGBA",i.height=d,i.width=f;u.drawImage(e,0,0),a=u.getImageData(0,0,f,d).data}else throw new Error("Can not access image data")}else if(s){let p,u;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,u=r.resizedWidth):(p=e.height,u=e.width),r!==void 0&&(i=r),i.format="RGBA",i.height=p,i.width=u,r!==void 0){const d=l();d.width=u,d.height=p;const f=c(d);if(f!=null)f.putImageData(e,0,0),a=f.getImageData(0,0,u,p).data;else throw new Error("Can not access image data")}else a=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 u=c(p);if(u!=null){const d=e.height,f=e.width;return u.drawImage(e,0,0,f,d),a=u.getImageData(0,0,f,d).data,i.height=d,i.width=f,xl(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,u)=>{const d=l(),f=c(d);if(!e||!f)return u();const _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{d.width=_.width,d.height=_.height,f.drawImage(_,0,0,d.width,d.height);const P=f.getImageData(0,0,d.width,d.height);i.height=d.height,i.width=d.width,p(xl(P.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return xl(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},mv=(e,r)=>{const{width:t,height:s,download:n,dispose:o}=r,a=[1,s,t,4];return new jr({location:"texture",type:"float32",texture:e,dims:a,download:n,dispose:o})},hv=(e,r)=>{const{dataType:t,dims:s,download:n,dispose:o}=r;return new jr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:n,dispose:o})},_v=(e,r)=>{const{dataType:t,dims:s,download:n,dispose:o}=r;return new jr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:n,dispose:o})},fv=(e,r,t)=>new jr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),Zn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Zi=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Rh=!1;const gv=()=>{if(!Rh){Rh=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(Zn.set("int64",BigInt64Array),Zi.set(BigInt64Array,"int64")),r&&(Zn.set("uint64",BigUint64Array),Zi.set(BigUint64Array,"uint64")),s?(Zn.set("float16",t),Zi.set(t,"float16")):Zn.set("float16",Uint16Array)}},wv=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new jr(e.type,e.data,r);case"cpu-pinned":return new jr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new jr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new jr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new jr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let jr=class{constructor(r,t,s){gv();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 i=Zn.get(n);if(!i)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(r.data instanceof i))throw new TypeError(`buffer should be of type ${i.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 i,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.");i=t}else{const c=Zn.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"?i=c.from(t,BigInt):i=c.from(t)}else if(t instanceof c)i=t;else if(t instanceof Uint8ClampedArray)if(r==="uint8")i=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)i=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",i=r;else if(c==="boolean")n="bool",i=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${c}.`)}else if(r instanceof Uint8ClampedArray)n="uint8",i=Uint8Array.from(r);else{const c=Zi.get(r.constructor);if(c===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);n=c,i=r}if(l===void 0)l=[i.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");o=l,this.cpuData=i,this.dataLocation="cpu"}const a=wv(o);if(this.cpuData&&a!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(a/2)===this.cpuData.length))throw new Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=o,this.size=a}static async fromImage(r,t){return pv(r,t)}static fromTexture(r,t){return mv(r,t)}static fromGpuBuffer(r,t){return hv(r,t)}static fromMLTensor(r,t){return _v(r,t)}static fromPinnedBuffer(r,t,s){return fv(r,t,s)}toDataURL(r){return cv(this,r)}toImageData(r){return dv(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 Mv(this,r)}};const Jn=jr,yw=(e,r)=>{(typeof ns.trace>"u"?!ns.wasm.trace:!ns.trace)||console.timeStamp(`${e}::ORT::${r}`)},vw=(e,r)=>{const t=new Error().stack?.split(/\r\n|\r|\n/g)||[];let s=!1;for(let n=0;n{(typeof ns.trace>"u"?!ns.wasm.trace:!ns.trace)||vw("BEGIN",e)},Eu=e=>{(typeof ns.trace>"u"?!ns.wasm.trace:!ns.trace)||vw("END",e)};let bv=class xw{constructor(r){this.handler=r}async run(r,t,s){Tu();const n={};let o={};if(typeof r!="object"||r===null||r instanceof Jn||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof Jn)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!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 u of this.outputNames)if(p.indexOf(u)!==-1){const d=t[u];(d===null||d instanceof Jn)&&(c=!0,a=!1,n[u]=d)}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(a)for(const c of this.outputNames)n[c]=null;const i=await this.handler.run(r,n,o),l={};for(const c in i)if(Object.hasOwnProperty.call(i,c)){const p=i[c];p instanceof Jn?l[c]=p:l[c]=new Jn(p.type,p.data,p.dims)}return Eu(),l}async release(){return this.handler.dispose()}static async create(r,t,s,n){Tu();let o,a={};if(typeof r=="string"){if(o=r,typeof t=="object"&&t!==null)a=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)a=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 u=0,d=r.byteLength;if(typeof t=="object"&&t!==null)a=t;else if(typeof t=="number"){if(u=t,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(d=r.byteLength-u,typeof s=="number"){if(d=s,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||u+d>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-u}].`);if(typeof n=="object"&&n!==null)a=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,u,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[i,l]=await av(a),c=await i.createInferenceSessionHandler(o,l);return Eu(),new xw(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const yv=bv;var vv=Object.freeze({__proto__:null,InferenceSession:yv,TRACE:yw,TRACE_FUNC_BEGIN:Tu,TRACE_FUNC_END:Eu,Tensor:Jn,env:uv,registerBackend:ov});/*! * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */var Vu=Object.defineProperty,xv=Object.getOwnPropertyDescriptor,Tv=Object.getOwnPropertyNames,Ev=Object.prototype.hasOwnProperty,Pv=(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')}),ze=(e,r)=>()=>(e&&(r=e(e=0)),r),no=(e,r)=>{for(var t in r)Vu(e,t,{get:r[t],enumerable:!0})},Cv=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of Tv(r))!Ev.call(e,n)&&n!==t&&Vu(e,n,{get:()=>r[n],enumerable:!(s=xv(r,n))||s.enumerable});return e},Ko=e=>Cv(Vu({},"__esModule",{value:!0}),e),Io,js,Mn,Nh,Tw,Ew=ze(()=>{Io=new Map,js=[],Mn=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=Io.get(e);if(s===void 0)Io.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=js.indexOf(e);n!==-1&&js.splice(n,1);for(let o=0;o{let r=Io.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}}},Tw=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?js:t,n,o=[],a=new Set;for(let l of s){let c=await Nh(l);typeof c=="string"?o.push({name:l,err:c}):(n||(n=c),n===c&&a.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 i=r.filter(l=>a.has(typeof l=="string"?l:l.name));return[n,new Proxy(e,{get:(l,c)=>c==="executionProviders"?i:Reflect.get(l,c)})]}}),Sv=ze(()=>{Ew()}),Pw,$v=ze(()=>{Pw="1.22.0-dev.20250409-89f8206ba4"}),Tl,Nr,Cw=ze(()=>{$v(),Tl="warning",Nr={wasm:{},webgl:{},webgpu:{},versions:{common:Pw},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}`);Tl=e}},get logLevel(){return Tl}},Object.defineProperty(Nr,"logLevel",{enumerable:!0})}),Lt,kv=ze(()=>{Cw(),Lt=Nr}),Sw,$w,Iv=ze(()=>{Sw=(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 a=r?.format!==void 0?r.format:"RGB",i=r?.norm,l,c;i===void 0||i.mean===void 0?l=[255,255,255,255]:typeof i.mean=="number"?l=[i.mean,i.mean,i.mean,i.mean]:(l=[i.mean[0],i.mean[1],i.mean[2],0],i.mean[3]!==void 0&&(l[3]=i.mean[3])),i===void 0||i.bias===void 0?c=[0,0,0,0]:typeof i.bias=="number"?c=[i.bias,i.bias,i.bias,i.bias]:(c=[i.bias[0],i.bias[1],i.bias[2],0],i.bias[3]!==void 0&&(c[3]=i.bias[3]));let p=o*n,u=0,d=p,f=p*2,_=-1;a==="RGBA"?(u=0,d=p,f=p*2,_=p*3):a==="RGB"?(u=0,d=p,f=p*2):a==="RBG"&&(u=0,f=p,d=p*2);for(let P=0;P{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let n,o,a;r?.tensorLayout!==void 0&&r.tensorLayout==="NHWC"?(n=e.dims[2],o=e.dims[1],a=e.dims[3]):(n=e.dims[3],o=e.dims[2],a=e.dims[1]);let i=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 u=o*n;if(r!==void 0&&(r.format!==void 0&&a===4&&r.format!=="RGBA"||a===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,f=0,_=1,P=2,I=3,M=0,g=u,S=u*2,E=-1;i==="RGBA"?(M=0,g=u,S=u*2,E=u*3):i==="RGB"?(M=0,g=u,S=u*2):i==="RBG"&&(M=0,S=u,g=u*2),s=t.createImageData(n,o);for(let x=0;x{Uu(),Bi=(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,a;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"?a=[n.bias,n.bias,n.bias,n.bias]:a=[n.bias[0],n.bias[1],n.bias[2],n.bias[3]??0];let i=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),u=4,d=0,f=1,_=2,P=3,I=0,M=c,g=c*2,S=-1;i==="RGB"&&(u=3,d=0,f=1,_=2,P=-1),l==="RGBA"?S=c*3:l==="RBG"?(I=0,g=c,M=c*2):l==="BGR"&&(g=0,M=c,I=c*2);for(let E=0;E{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",a,i=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 u=c(p);if(u!=null){let d=e.height,f=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(d=r.resizedHeight,f=r.resizedWidth),r!==void 0){if(i=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");i.tensorFormat="RGBA",i.height=d,i.width=f}else i.tensorFormat="RGBA",i.height=d,i.width=f;u.drawImage(e,0,0),a=u.getImageData(0,0,f,d).data}else throw new Error("Can not access image data")}else if(s){let p,u;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,u=r.resizedWidth):(p=e.height,u=e.width),r!==void 0&&(i=r),i.format="RGBA",i.height=p,i.width=u,r!==void 0){let d=l();d.width=u,d.height=p;let f=c(d);if(f!=null)f.putImageData(e,0,0),a=f.getImageData(0,0,u,p).data;else throw new Error("Can not access image data")}else a=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 u=c(p);if(u!=null){let d=e.height,f=e.width;return u.drawImage(e,0,0,f,d),a=u.getImageData(0,0,f,d).data,i.height=d,i.width=f,Bi(a,i)}else throw new Error("Can not access image data")}else{if(o)return new Promise((p,u)=>{let d=l(),f=c(d);if(!e||!f)return u();let _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{d.width=_.width,d.height=_.height,f.drawImage(_,0,0,d.width,d.height);let P=f.getImageData(0,0,d.width,d.height);i.height=d.height,i.width=d.width,p(Bi(P.data,i))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return Bi(a,i);throw new Error("Input data provided is not supported - aborted tensor creation")},Iw=(e,r)=>{let{width:t,height:s,download:n,dispose:o}=r,a=[1,s,t,4];return new Ar({location:"texture",type:"float32",texture:e,dims:a,download:n,dispose:o})},Aw=(e,r)=>{let{dataType:t,dims:s,download:n,dispose:o}=r;return new Ar({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:n,dispose:o})},Fw=(e,r)=>{let{dataType:t,dims:s,download:n,dispose:o}=r;return new Ar({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:n,dispose:o})},Ow=(e,r,t)=>new Ar({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),gn,jo,El,Dw,Fv=ze(()=>{gn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),jo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),El=!1,Dw=()=>{if(!El){El=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(gn.set("int64",BigInt64Array),jo.set(BigInt64Array,"int64")),r&&(gn.set("uint64",BigUint64Array),jo.set(BigUint64Array,"uint64")),s?(gn.set("float16",t),jo.set(t,"float16")):gn.set("float16",Uint16Array)}}}),Lw,zw,Ov=ze(()=>{Uu(),Lw=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Ar(e.type,e.data,r);case"cpu-pinned":return new Ar({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Ar({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Ar({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Ar({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Ar,Uu=ze(()=>{Iv(),Av(),Fv(),Ov(),Ar=class{constructor(e,r,t){Dw();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 a=gn.get(s);if(!a)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof a))throw new TypeError(`buffer should be of type ${a.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 a,i;if(typeof e=="string")if(s=e,i=t,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");a=r}else{let l=gn.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"?a=l.from(r,BigInt):a=l.from(r)}else if(r instanceof l)a=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")a=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)a=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(i=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",a=e;else if(l==="boolean")s="bool",a=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",a=Uint8Array.from(e);else{let l=jo.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,a=e}if(i===void 0)i=[a.length];else if(!Array.isArray(i))throw new TypeError("A tensor's dims must be a number array");n=i,this.cpuData=a,this.dataLocation="cpu"}let o=Lw(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 kw(e,r)}static fromTexture(e,r){return Iw(e,r)}static fromGpuBuffer(e,r){return Aw(e,r)}static fromMLTensor(e,r){return Fw(e,r)}static fromPinnedBuffer(e,r,t){return Ow(e,r,t)}toDataURL(e){return Sw(this,e)}toImageData(e){return $w(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 zw(this,e)}}}),ss,Bw=ze(()=>{Uu(),ss=Ar}),Ho,Pl,os,Vr,Rw=ze(()=>{Cw(),Ho=(e,r)=>{(typeof Nr.trace>"u"?!Nr.wasm.trace:!Nr.trace)||console.timeStamp(`${e}::ORT::${r}`)},Pl=(e,r)=>{let t=new Error().stack?.split(/\r\n|\r|\n/g)||[],s=!1;for(let n=0;n{(typeof Nr.trace>"u"?!Nr.wasm.trace:!Nr.trace)||Pl("BEGIN",e)},Vr=e=>{(typeof Nr.trace>"u"?!Nr.wasm.trace:!Nr.trace)||Pl("END",e)}}),Nw,Dv=ze(()=>{Ew(),Bw(),Rw(),Nw=class jw{constructor(r){this.handler=r}async run(r,t,s){os();let n={},o={};if(typeof r!="object"||r===null||r instanceof ss||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof ss)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.");a=!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 u of this.outputNames)if(p.indexOf(u)!==-1){let d=t[u];(d===null||d instanceof ss)&&(c=!0,a=!1,n[u]=d)}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(a)for(let c of this.outputNames)n[c]=null;let i=await this.handler.run(r,n,o),l={};for(let c in i)if(Object.hasOwnProperty.call(i,c)){let p=i[c];p instanceof ss?l[c]=p:l[c]=new ss(p.type,p.data,p.dims)}return Vr(),l}async release(){return this.handler.dispose()}static async create(r,t,s,n){os();let o,a={};if(typeof r=="string"){if(o=r,typeof t=="object"&&t!==null)a=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)a=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,u=0,d=r.byteLength;if(typeof t=="object"&&t!==null)a=t;else if(typeof t=="number"){if(u=t,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(d=r.byteLength-u,typeof s=="number"){if(d=s,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||u+d>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-u}].`);if(typeof n=="object"&&n!==null)a=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,u,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[i,l]=await Tw(a),c=await i.createInferenceSessionHandler(o,l);return Vr(),new jw(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}}}),Wu,Lv=ze(()=>{Dv(),Wu=Nw}),zv=ze(()=>{}),Bv=ze(()=>{}),Rv=ze(()=>{}),Nv=ze(()=>{}),Vw={};no(Vw,{InferenceSession:()=>Wu,TRACE:()=>Ho,TRACE_FUNC_BEGIN:()=>os,TRACE_FUNC_END:()=>Vr,Tensor:()=>ss,env:()=>Lt,registerBackend:()=>Mn});var is=ze(()=>{Sv(),kv(),Lv(),Bw(),zv(),Bv(),Rw(),Rv(),Nv()}),Gu=ze(()=>{}),Uw={};no(Uw,{default:()=>Ww});var Cl,Sl,Ww,jv=ze(()=>{Xy(),xn(),Ku(),Cl="ort-wasm-proxy-worker",Sl=globalThis.self?.name===Cl,Sl&&(self.onmessage=e=>{let{type:r,in:t}=e.data;try{switch(r){case"init-wasm":Hu(t.wasm).then(()=>{dc(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;pc(n,s).then(()=>{postMessage({type:r})},o=>{postMessage({type:r,err:o})});break}case"copy-from":{let{buffer:s}=t,n=ua(s);postMessage({type:r,out:n});break}case"create":{let{model:s,options:n}=t;mc(s,n).then(o=>{postMessage({type:r,out:o})},o=>{postMessage({type:r,err:o})});break}case"release":hc(t),postMessage({type:r});break;case"run":{let{sessionId:s,inputIndices:n,inputs:o,outputIndices:a,options:i}=t;_c(s,n,o,a,new Array(a.length).fill(null),i).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},gc([...o,...l]))},l=>{postMessage({type:r,err:l})});break}case"end-profiling":fc(t),postMessage({type:r});break;default:}}catch(s){postMessage({type:r,err:s})}}),Ww=Sl?null:e=>new Worker(e??Ir,{type:"module",name:Cl})}),Gw={};no(Gw,{default:()=>Kw});var $l,kl,Kw,jh,Vv=ze(()=>{kl=($l=import.meta.url,async function(e={}){var r,t,s=e,n=new Promise((m,T)=>{r=m,t=T}),o=typeof window=="object",a=typeof WorkerGlobalScope<"u",i=a&&self.name?.startsWith("em-pthread");s.mountExternalData=(m,T)=>{m.startsWith("./")&&(m=m.substring(2)),(s.Eb||(s.Eb=new Map)).set(m,T)},s.unmountExternalData=()=>{delete s.Eb};var l=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let c=m=>async(...T)=>{try{if(s.Fb)throw Error("Session already started");let k=s.Fb={dc:T[0],errors:[]},D=await m(...T);if(s.Fb!==k)throw Error("Session mismatch");s.Jb?.flush();let V=k.errors;if(0Te),0{if(m==="webgpu"){[s.Jb,s.Ub,s.Yb,s.Kb,s.Xb,s.jb,s.Zb,s.ac,s.Vb,s.Wb,s.$b]=T;let k=s.Jb;s.jsepRegisterBuffer=(D,V,ie,Te)=>k.registerBuffer(D,V,ie,Te),s.jsepGetBuffer=D=>k.getBuffer(D),s.jsepCreateDownloader=(D,V,ie)=>k.createDownloader(D,V,ie),s.jsepOnCreateSession=D=>{k.onCreateSession(D)},s.jsepOnReleaseSession=D=>{k.onReleaseSession(D)},s.jsepOnRunStart=D=>k.onRunStart(D),s.bc=(D,V)=>{k.upload(D,V)}}else if(m==="webnn"){let k=T[0];[s.nc,s.Nb,s.webnnEnsureTensor,s.Ob,s.webnnDownloadTensor]=T.slice(1),s.webnnReleaseTensorId=s.Nb,s.webnnUploadTensor=s.Ob,s.webnnOnRunStart=D=>k.onRunStart(D),s.webnnOnRunEnd=k.onRunEnd.bind(k),s.webnnRegisterMLContext=(D,V)=>{k.registerMLContext(D,V)},s.webnnOnReleaseSession=D=>{k.onReleaseSession(D)},s.webnnCreateMLTensorDownloader=(D,V)=>k.createMLTensorDownloader(D,V),s.webnnRegisterMLTensor=(D,V,ie,Te)=>k.registerMLTensor(D,V,ie,Te),s.webnnCreateMLContext=D=>k.createMLContext(D),s.webnnRegisterMLConstant=(D,V,ie,Te,Oe,We)=>k.registerMLConstant(D,V,ie,Te,Oe,s.Eb,We),s.webnnRegisterGraphInput=k.registerGraphInput.bind(k),s.webnnIsGraphInput=k.isGraphInput.bind(k),s.webnnCreateTemporaryTensor=k.createTemporaryTensor.bind(k),s.webnnIsInt64Supported=k.isInt64Supported.bind(k)}};let p=()=>{let m=(T,k,D)=>(...V)=>{let ie=Ht,Te=k?.();V=T(...V);let Oe=k?.();return Te!==Oe&&(T=Oe,D(Te),k=D=null),Ht!=ie?new Promise((We,Xe)=>{dr={resolve:We,reject:Xe}}):V};(()=>{for(let T of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])s[T]=m(s[T],()=>s[T],k=>s[T]=k)})(),c!==void 0&&(s._OrtRun=c(s._OrtRun),s._OrtRunWithBinding=c(s._OrtRunWithBinding)),p=void 0};s.asyncInit=()=>{p?.()};var u,d,f=Object.assign({},s),_=(m,T)=>{throw T},P="";(o||a)&&(a?P=self.location.href:typeof document<"u"&&document.currentScript&&(P=document.currentScript.src),$l&&(P=$l),P=P.startsWith("blob:")?"":P.slice(0,P.replace(/[?#].*/,"").lastIndexOf("/")+1),a&&(d=m=>{var T=new XMLHttpRequest;return T.open("GET",m,!1),T.responseType="arraybuffer",T.send(null),new Uint8Array(T.response)}),u=async m=>{if(ce(m))return new Promise((k,D)=>{var V=new XMLHttpRequest;V.open("GET",m,!0),V.responseType="arraybuffer",V.onload=()=>{V.status==200||V.status==0&&V.response?k(V.response):D(V.status)},V.onerror=D,V.send(null)});var T=await fetch(m,{credentials:"same-origin"});if(T.ok)return T.arrayBuffer();throw Error(T.status+" : "+T.url)});var I=console.log.bind(console),M=console.error.bind(console),g=I,S=M;Object.assign(s,f),f=null;var E,x,w,v,$,O,B,H,q,L,J,X,Q,te=s.wasmBinary,re=!1,ce=m=>m.startsWith("file://");function le(){return E.buffer!=v.buffer&&fe(),v}function N(){return E.buffer!=v.buffer&&fe(),$}function F(){return E.buffer!=v.buffer&&fe(),O}function G(){return E.buffer!=v.buffer&&fe(),B}function R(){return E.buffer!=v.buffer&&fe(),H}function ne(){return E.buffer!=v.buffer&&fe(),q}function be(){return E.buffer!=v.buffer&&fe(),L}function de(){return E.buffer!=v.buffer&&fe(),Q}if(i){let m=function(T){try{var k=T.data,D=k.Bb;if(D==="load"){let V=[];self.onmessage=ie=>V.push(ie),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let ie of V)m(ie);self.onmessage=m};for(let ie of k.Rb)s[ie]&&!s[ie].proxy||(s[ie]=(...Te)=>{postMessage({Bb:"callHandler",Qb:ie,args:Te})},ie=="print"&&(g=s[ie]),ie=="printErr"&&(S=s[ie]));E=k.kc,fe(),ve(k.lc)}else if(D==="run"){as(k.Ab),zn(k.Ab,0,0,1,0,0),er(),se(k.Ab),je||(Ln(),je=!0);try{fs(k.fc,k.Hb)}catch(V){if(V!="unwind")throw V}}else k.target!=="setimmediate"&&(D==="checkMailbox"?je&&_e():D&&(S(`worker: received unknown command ${D}`),S(k)))}catch(V){throw vo(),V}};var ve,je=!1;S=function(...T){T=T.join(" "),console.error(T)},self.alert=function(...T){postMessage({Bb:"alert",text:T.join(" "),ic:an()})},self.onunhandledrejection=T=>{throw T.reason||T},self.onmessage=m}function fe(){var m=E.buffer;s.HEAP8=v=new Int8Array(m),s.HEAP16=O=new Int16Array(m),s.HEAPU8=$=new Uint8Array(m),s.HEAPU16=B=new Uint16Array(m),s.HEAP32=H=new Int32Array(m),s.HEAPU32=q=new Uint32Array(m),s.HEAPF32=L=new Float32Array(m),s.HEAPF64=Q=new Float64Array(m),s.HEAP64=J=new BigInt64Array(m),s.HEAPU64=X=new BigUint64Array(m)}function K(){i?startWorker(s):et.Ca()}i||(E=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),fe());var U,pe=0,ye=null;function xe(){if(--pe==0&&ye){var m=ye;ye=null,m()}}function Ce(m){throw S(m="Aborted("+m+")"),re=!0,m=new WebAssembly.RuntimeError(m+". Build with -sASSERTIONS for more info."),t(m),m}function $e(){return{a:{L:Ne,Aa:Re,b:$s,$:gs,A:us,pa:Wr,X:cs,Z:ur,qa:De,na:He,ga:Ye,ma:cr,J:ks,Y:Or,V:Is,oa:As,W:ws,va:Kr,E:ds,Q:Ks,O:Hr,D:Xs,u:Qs,r:Js,P:Ys,z:ue,R:C,ja:W,T:Se,aa:Ge,M:Ke,F:Ve,ia:se,sa:Mt,t:rr,Ba:Nt,w:qt,o:or,l:Xt,c:Dr,n:Ds,j:Qo,v:Ls,p:Jo,f:Yo,s:Zo,m:ei,e:ti,k:io,i:ri,g:si,d:ao,da:ni,ea:da,fa:oi,ba:$n,ca:uo,N:co,xa:ai,ua:ui,h:In,C:mo,G:ci,ta:li,x:ho,ra:xs,U:di,q:ii,y:pa,K:pi,S:ma,za:mi,ya:hi,ka:fo,la:go,_:Me,B:wo,I:On,ha:Mo,H:Dn,a:E,wa:Ee}}}var Ae={829644:(m,T,k,D,V)=>{if(s===void 0||!s.Eb)return 1;if((m=Tt(Number(m>>>0))).startsWith("./")&&(m=m.substring(2)),!(m=s.Eb.get(m)))return 2;if(T=Number(T>>>0),k=Number(k>>>0),D=Number(D>>>0),T+k>m.byteLength)return 3;try{let ie=m.subarray(T,T+k);switch(V){case 0:N().set(ie,D>>>0);break;case 1:s.mc?s.mc(D,ie):s.bc(D,ie);break;default:return 4}return 0}catch{return 4}},830468:(m,T,k)=>{s.Ob(m,N().subarray(T>>>0,T+k>>>0))},830532:()=>s.nc(),830574:m=>{s.Nb(m)},830611:()=>{s.Vb()},830642:()=>{s.Wb()},830671:()=>{s.$b()},830696:m=>s.Ub(m),830729:m=>s.Yb(m),830761:(m,T,k)=>{s.Kb(Number(m),Number(T),Number(k),!0)},830824:(m,T,k)=>{s.Kb(Number(m),Number(T),Number(k))},830881:()=>typeof wasmOffsetConverter<"u",830938:m=>{s.jb("Abs",m,void 0)},830989:m=>{s.jb("Neg",m,void 0)},831040:m=>{s.jb("Floor",m,void 0)},831093:m=>{s.jb("Ceil",m,void 0)},831145:m=>{s.jb("Reciprocal",m,void 0)},831203:m=>{s.jb("Sqrt",m,void 0)},831255:m=>{s.jb("Exp",m,void 0)},831306:m=>{s.jb("Erf",m,void 0)},831357:m=>{s.jb("Sigmoid",m,void 0)},831412:(m,T,k)=>{s.jb("HardSigmoid",m,{alpha:T,beta:k})},831491:m=>{s.jb("Log",m,void 0)},831542:m=>{s.jb("Sin",m,void 0)},831593:m=>{s.jb("Cos",m,void 0)},831644:m=>{s.jb("Tan",m,void 0)},831695:m=>{s.jb("Asin",m,void 0)},831747:m=>{s.jb("Acos",m,void 0)},831799:m=>{s.jb("Atan",m,void 0)},831851:m=>{s.jb("Sinh",m,void 0)},831903:m=>{s.jb("Cosh",m,void 0)},831955:m=>{s.jb("Asinh",m,void 0)},832008:m=>{s.jb("Acosh",m,void 0)},832061:m=>{s.jb("Atanh",m,void 0)},832114:m=>{s.jb("Tanh",m,void 0)},832166:m=>{s.jb("Not",m,void 0)},832217:(m,T,k)=>{s.jb("Clip",m,{min:T,max:k})},832286:m=>{s.jb("Clip",m,void 0)},832338:(m,T)=>{s.jb("Elu",m,{alpha:T})},832396:m=>{s.jb("Gelu",m,void 0)},832448:m=>{s.jb("Relu",m,void 0)},832500:(m,T)=>{s.jb("LeakyRelu",m,{alpha:T})},832564:(m,T)=>{s.jb("ThresholdedRelu",m,{alpha:T})},832634:(m,T)=>{s.jb("Cast",m,{to:T})},832692:m=>{s.jb("Add",m,void 0)},832743:m=>{s.jb("Sub",m,void 0)},832794:m=>{s.jb("Mul",m,void 0)},832845:m=>{s.jb("Div",m,void 0)},832896:m=>{s.jb("Pow",m,void 0)},832947:m=>{s.jb("Equal",m,void 0)},833e3:m=>{s.jb("Greater",m,void 0)},833055:m=>{s.jb("GreaterOrEqual",m,void 0)},833117:m=>{s.jb("Less",m,void 0)},833169:m=>{s.jb("LessOrEqual",m,void 0)},833228:(m,T,k,D,V)=>{s.jb("ReduceMean",m,{keepDims:!!T,noopWithEmptyAxes:!!k,axes:D?Array.from(R().subarray(Number(D)>>>0,Number(V)>>>0)):[]})},833403:(m,T,k,D,V)=>{s.jb("ReduceMax",m,{keepDims:!!T,noopWithEmptyAxes:!!k,axes:D?Array.from(R().subarray(Number(D)>>>0,Number(V)>>>0)):[]})},833577:(m,T,k,D,V)=>{s.jb("ReduceMin",m,{keepDims:!!T,noopWithEmptyAxes:!!k,axes:D?Array.from(R().subarray(Number(D)>>>0,Number(V)>>>0)):[]})},833751:(m,T,k,D,V)=>{s.jb("ReduceProd",m,{keepDims:!!T,noopWithEmptyAxes:!!k,axes:D?Array.from(R().subarray(Number(D)>>>0,Number(V)>>>0)):[]})},833926:(m,T,k,D,V)=>{s.jb("ReduceSum",m,{keepDims:!!T,noopWithEmptyAxes:!!k,axes:D?Array.from(R().subarray(Number(D)>>>0,Number(V)>>>0)):[]})},834100:(m,T,k,D,V)=>{s.jb("ReduceL1",m,{keepDims:!!T,noopWithEmptyAxes:!!k,axes:D?Array.from(R().subarray(Number(D)>>>0,Number(V)>>>0)):[]})},834273:(m,T,k,D,V)=>{s.jb("ReduceL2",m,{keepDims:!!T,noopWithEmptyAxes:!!k,axes:D?Array.from(R().subarray(Number(D)>>>0,Number(V)>>>0)):[]})},834446:(m,T,k,D,V)=>{s.jb("ReduceLogSum",m,{keepDims:!!T,noopWithEmptyAxes:!!k,axes:D?Array.from(R().subarray(Number(D)>>>0,Number(V)>>>0)):[]})},834623:(m,T,k,D,V)=>{s.jb("ReduceSumSquare",m,{keepDims:!!T,noopWithEmptyAxes:!!k,axes:D?Array.from(R().subarray(Number(D)>>>0,Number(V)>>>0)):[]})},834803:(m,T,k,D,V)=>{s.jb("ReduceLogSumExp",m,{keepDims:!!T,noopWithEmptyAxes:!!k,axes:D?Array.from(R().subarray(Number(D)>>>0,Number(V)>>>0)):[]})},834983:m=>{s.jb("Where",m,void 0)},835036:(m,T,k)=>{s.jb("Transpose",m,{perm:T?Array.from(R().subarray(Number(T)>>>0,Number(k)>>>0)):[]})},835160:(m,T,k,D)=>{s.jb("DepthToSpace",m,{blocksize:T,mode:Tt(k),format:D?"NHWC":"NCHW"})},835293:(m,T,k,D)=>{s.jb("DepthToSpace",m,{blocksize:T,mode:Tt(k),format:D?"NHWC":"NCHW"})},835426:(m,T,k,D,V,ie,Te,Oe,We,Xe,ct,bt,Ct,Jt,Es)=>{s.jb("ConvTranspose",m,{format:We?"NHWC":"NCHW",autoPad:T,dilations:[k],group:D,kernelShape:[V],pads:[ie,Te],strides:[Oe],wIsConst:()=>!!le()[Xe>>>0],outputPadding:ct?Array.from(R().subarray(Number(ct)>>>0,Number(bt)>>>0)):[],outputShape:Ct?Array.from(R().subarray(Number(Ct)>>>0,Number(Jt)>>>0)):[],activation:Tt(Es)})},835859:(m,T,k,D,V,ie,Te,Oe,We,Xe,ct,bt,Ct,Jt)=>{s.jb("ConvTranspose",m,{format:Oe?"NHWC":"NCHW",autoPad:T,dilations:Array.from(R().subarray(Number(k)>>>0,2+(Number(k)>>>0)>>>0)),group:D,kernelShape:Array.from(R().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(R().subarray(Number(ie)>>>0,4+(Number(ie)>>>0)>>>0)),strides:Array.from(R().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!le()[We>>>0],outputPadding:Xe?Array.from(R().subarray(Number(Xe)>>>0,Number(ct)>>>0)):[],outputShape:bt?Array.from(R().subarray(Number(bt)>>>0,Number(Ct)>>>0)):[],activation:Tt(Jt)})},836520:(m,T,k,D,V,ie,Te,Oe,We,Xe,ct,bt,Ct,Jt,Es)=>{s.jb("ConvTranspose",m,{format:We?"NHWC":"NCHW",autoPad:T,dilations:[k],group:D,kernelShape:[V],pads:[ie,Te],strides:[Oe],wIsConst:()=>!!le()[Xe>>>0],outputPadding:ct?Array.from(R().subarray(Number(ct)>>>0,Number(bt)>>>0)):[],outputShape:Ct?Array.from(R().subarray(Number(Ct)>>>0,Number(Jt)>>>0)):[],activation:Tt(Es)})},836953:(m,T,k,D,V,ie,Te,Oe,We,Xe,ct,bt,Ct,Jt)=>{s.jb("ConvTranspose",m,{format:Oe?"NHWC":"NCHW",autoPad:T,dilations:Array.from(R().subarray(Number(k)>>>0,2+(Number(k)>>>0)>>>0)),group:D,kernelShape:Array.from(R().subarray(Number(V)>>>0,2+(Number(V)>>>0)>>>0)),pads:Array.from(R().subarray(Number(ie)>>>0,4+(Number(ie)>>>0)>>>0)),strides:Array.from(R().subarray(Number(Te)>>>0,2+(Number(Te)>>>0)>>>0)),wIsConst:()=>!!le()[We>>>0],outputPadding:Xe?Array.from(R().subarray(Number(Xe)>>>0,Number(ct)>>>0)):[],outputShape:bt?Array.from(R().subarray(Number(bt)>>>0,Number(Ct)>>>0)):[],activation:Tt(Jt)})},837614:(m,T)=>{s.jb("GlobalAveragePool",m,{format:T?"NHWC":"NCHW"})},837705:(m,T,k,D,V,ie,Te,Oe,We,Xe,ct,bt,Ct,Jt)=>{s.jb("AveragePool",m,{format:Jt?"NHWC":"NCHW",auto_pad:T,ceil_mode:k,count_include_pad:D,storage_order:V,dilations:ie?Array.from(R().subarray(Number(ie)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(R().subarray(Number(Oe)>>>0,Number(We)>>>0)):[],pads:Xe?Array.from(R().subarray(Number(Xe)>>>0,Number(ct)>>>0)):[],strides:bt?Array.from(R().subarray(Number(bt)>>>0,Number(Ct)>>>0)):[]})},838184:(m,T)=>{s.jb("GlobalAveragePool",m,{format:T?"NHWC":"NCHW"})},838275:(m,T,k,D,V,ie,Te,Oe,We,Xe,ct,bt,Ct,Jt)=>{s.jb("AveragePool",m,{format:Jt?"NHWC":"NCHW",auto_pad:T,ceil_mode:k,count_include_pad:D,storage_order:V,dilations:ie?Array.from(R().subarray(Number(ie)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(R().subarray(Number(Oe)>>>0,Number(We)>>>0)):[],pads:Xe?Array.from(R().subarray(Number(Xe)>>>0,Number(ct)>>>0)):[],strides:bt?Array.from(R().subarray(Number(bt)>>>0,Number(Ct)>>>0)):[]})},838754:(m,T)=>{s.jb("GlobalMaxPool",m,{format:T?"NHWC":"NCHW"})},838841:(m,T,k,D,V,ie,Te,Oe,We,Xe,ct,bt,Ct,Jt)=>{s.jb("MaxPool",m,{format:Jt?"NHWC":"NCHW",auto_pad:T,ceil_mode:k,count_include_pad:D,storage_order:V,dilations:ie?Array.from(R().subarray(Number(ie)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(R().subarray(Number(Oe)>>>0,Number(We)>>>0)):[],pads:Xe?Array.from(R().subarray(Number(Xe)>>>0,Number(ct)>>>0)):[],strides:bt?Array.from(R().subarray(Number(bt)>>>0,Number(Ct)>>>0)):[]})},839316:(m,T)=>{s.jb("GlobalMaxPool",m,{format:T?"NHWC":"NCHW"})},839403:(m,T,k,D,V,ie,Te,Oe,We,Xe,ct,bt,Ct,Jt)=>{s.jb("MaxPool",m,{format:Jt?"NHWC":"NCHW",auto_pad:T,ceil_mode:k,count_include_pad:D,storage_order:V,dilations:ie?Array.from(R().subarray(Number(ie)>>>0,Number(Te)>>>0)):[],kernel_shape:Oe?Array.from(R().subarray(Number(Oe)>>>0,Number(We)>>>0)):[],pads:Xe?Array.from(R().subarray(Number(Xe)>>>0,Number(ct)>>>0)):[],strides:bt?Array.from(R().subarray(Number(bt)>>>0,Number(Ct)>>>0)):[]})},839878:(m,T,k,D,V)=>{s.jb("Gemm",m,{alpha:T,beta:k,transA:D,transB:V})},839982:m=>{s.jb("MatMul",m,void 0)},840036:(m,T,k,D)=>{s.jb("ArgMax",m,{keepDims:!!T,selectLastIndex:!!k,axis:D})},840144:(m,T,k,D)=>{s.jb("ArgMin",m,{keepDims:!!T,selectLastIndex:!!k,axis:D})},840252:(m,T)=>{s.jb("Softmax",m,{axis:T})},840315:(m,T)=>{s.jb("Concat",m,{axis:T})},840375:(m,T,k,D,V)=>{s.jb("Split",m,{axis:T,numOutputs:k,splitSizes:D?Array.from(R().subarray(Number(D)>>>0,Number(V)>>>0)):[]})},840531:m=>{s.jb("Expand",m,void 0)},840585:(m,T)=>{s.jb("Gather",m,{axis:Number(T)})},840656:(m,T)=>{s.jb("GatherElements",m,{axis:Number(T)})},840735:(m,T)=>{s.jb("GatherND",m,{batch_dims:Number(T)})},840814:(m,T,k,D,V,ie,Te,Oe,We,Xe,ct)=>{s.jb("Resize",m,{antialias:T,axes:k?Array.from(R().subarray(Number(k)>>>0,Number(D)>>>0)):[],coordinateTransformMode:Tt(V),cubicCoeffA:ie,excludeOutside:Te,extrapolationValue:Oe,keepAspectRatioPolicy:Tt(We),mode:Tt(Xe),nearestMode:Tt(ct)})},841176:(m,T,k,D,V,ie,Te)=>{s.jb("Slice",m,{starts:T?Array.from(R().subarray(Number(T)>>>0,Number(k)>>>0)):[],ends:D?Array.from(R().subarray(Number(D)>>>0,Number(V)>>>0)):[],axes:ie?Array.from(R().subarray(Number(ie)>>>0,Number(Te)>>>0)):[]})},841440:m=>{s.jb("Tile",m,void 0)},841492:(m,T,k)=>{s.jb("InstanceNormalization",m,{epsilon:T,format:k?"NHWC":"NCHW"})},841606:(m,T,k)=>{s.jb("InstanceNormalization",m,{epsilon:T,format:k?"NHWC":"NCHW"})},841720:m=>{s.jb("Range",m,void 0)},841773:(m,T)=>{s.jb("Einsum",m,{equation:Tt(T)})},841854:(m,T,k,D,V)=>{s.jb("Pad",m,{mode:T,value:k,pads:D?Array.from(R().subarray(Number(D)>>>0,Number(V)>>>0)):[]})},841997:(m,T,k,D,V,ie)=>{s.jb("BatchNormalization",m,{epsilon:T,momentum:k,spatial:!!V,trainingMode:!!D,format:ie?"NHWC":"NCHW"})},842166:(m,T,k,D,V,ie)=>{s.jb("BatchNormalization",m,{epsilon:T,momentum:k,spatial:!!V,trainingMode:!!D,format:ie?"NHWC":"NCHW"})},842335:(m,T,k)=>{s.jb("CumSum",m,{exclusive:Number(T),reverse:Number(k)})},842432:(m,T,k)=>{s.jb("DequantizeLinear",m,{axis:T,blockSize:k})},842522:(m,T,k,D,V)=>{s.jb("GridSample",m,{align_corners:T,mode:Tt(k),padding_mode:Tt(D),format:V?"NHWC":"NCHW"})},842692:(m,T,k,D,V)=>{s.jb("GridSample",m,{align_corners:T,mode:Tt(k),padding_mode:Tt(D),format:V?"NHWC":"NCHW"})},842862:(m,T)=>{s.jb("ScatterND",m,{reduction:Tt(T)})},842947:(m,T,k,D,V,ie,Te,Oe,We)=>{s.jb("Attention",m,{numHeads:T,isUnidirectional:k,maskFilterValue:D,scale:V,doRotary:ie,qkvHiddenSizes:Te?Array.from(R().subarray(Number(Oe)>>>0,Number(Oe)+Te>>>0)):[],pastPresentShareBuffer:!!We})},843219:m=>{s.jb("BiasAdd",m,void 0)},843274:m=>{s.jb("BiasSplitGelu",m,void 0)},843335:m=>{s.jb("FastGelu",m,void 0)},843391:(m,T,k,D,V,ie,Te,Oe,We,Xe,ct,bt,Ct,Jt,Es,gi)=>{s.jb("Conv",m,{format:bt?"NHWC":"NCHW",auto_pad:T,dilations:k?Array.from(R().subarray(Number(k)>>>0,Number(D)>>>0)):[],group:V,kernel_shape:ie?Array.from(R().subarray(Number(ie)>>>0,Number(Te)>>>0)):[],pads:Oe?Array.from(R().subarray(Number(Oe)>>>0,Number(We)>>>0)):[],strides:Xe?Array.from(R().subarray(Number(Xe)>>>0,Number(ct)>>>0)):[],w_is_const:()=>!!le()[Number(Ct)>>>0],activation:Tt(Jt),activation_params:Es?Array.from(be().subarray(Number(Es)>>>0,Number(gi)>>>0)):[]})},843975:m=>{s.jb("Gelu",m,void 0)},844027:(m,T,k,D,V,ie,Te,Oe,We)=>{s.jb("GroupQueryAttention",m,{numHeads:T,kvNumHeads:k,scale:D,softcap:V,doRotary:ie,rotaryInterleaved:Te,smoothSoftmax:Oe,localWindowSize:We})},844244:(m,T,k,D)=>{s.jb("LayerNormalization",m,{axis:T,epsilon:k,simplified:!!D})},844355:(m,T,k,D)=>{s.jb("LayerNormalization",m,{axis:T,epsilon:k,simplified:!!D})},844466:(m,T,k,D,V,ie)=>{s.jb("MatMulNBits",m,{k:T,n:k,accuracyLevel:D,bits:V,blockSize:ie})},844593:(m,T,k,D,V,ie)=>{s.jb("MultiHeadAttention",m,{numHeads:T,isUnidirectional:k,maskFilterValue:D,scale:V,doRotary:ie})},844752:(m,T)=>{s.jb("QuickGelu",m,{alpha:T})},844816:(m,T,k,D,V)=>{s.jb("RotaryEmbedding",m,{interleaved:!!T,numHeads:k,rotaryEmbeddingDim:D,scale:V})},844955:(m,T,k)=>{s.jb("SkipLayerNormalization",m,{epsilon:T,simplified:!!k})},845057:(m,T,k)=>{s.jb("SkipLayerNormalization",m,{epsilon:T,simplified:!!k})},845159:(m,T,k,D)=>{s.jb("GatherBlockQuantized",m,{gatherAxis:T,quantizeAxis:k,blockSize:D})},845280:m=>{s.Zb(m)},845314:(m,T)=>s.ac(Number(m),Number(T),s.Fb.dc,s.Fb.errors)};function Re(m,T,k){return Br(async()=>{await s.Xb(Number(m),Number(T),Number(k))})}function Ne(){return typeof wasmOffsetConverter<"u"}class A{name="ExitStatus";constructor(T){this.message=`Program terminated with exit(${T})`,this.status=T}}var Y=m=>{m.terminate(),m.onmessage=()=>{}},z=[],ee=m=>{ke.length==0&&(lr(),It(ke[0]));var T=ke.pop();if(!T)return 6;st.push(T),_t[m.Ab]=T,T.Ab=m.Ab;var k={Bb:"run",fc:m.ec,Hb:m.Hb,Ab:m.Ab};return T.postMessage(k,m.Mb),0},oe=0,he=(m,T,...k)=>{for(var D=2*k.length,V=Vn(),ie=jn(8*D),Te=ie>>>3,Oe=0;Oe>>0]=We)}return m=Bn(m,0,D,ie,T),Bs(V),m};function Ee(m){if(i)return he(0,1,m);if(w=m,!(0{if(w=m,i)throw Fe(m),"unwind";Ee(m)},ke=[],st=[],ut=[],_t={},gt=m=>{var T=m.Ab;delete _t[T],ke.push(m),st.splice(st.indexOf(m),1),m.Ab=0,xo(T)};function er(){ut.forEach(m=>m())}var It=m=>new Promise(T=>{m.onmessage=V=>{var ie=(V=V.data).Bb;if(V.Gb&&V.Gb!=an()){var Te=_t[V.Gb];Te?Te.postMessage(V,V.Mb):S(`Internal error! Worker sent a message "${ie}" to target pthread ${V.Gb}, but that thread no longer exists!`)}else ie==="checkMailbox"?_e():ie==="spawnThread"?ee(V):ie==="cleanupThread"?gt(_t[V.hc]):ie==="loaded"?(m.loaded=!0,T(m)):ie==="alert"?alert(`Thread ${V.ic}: ${V.text}`):V.target==="setimmediate"?m.postMessage(V):ie==="callHandler"?s[V.Qb](...V.args):ie&&S(`worker sent an unknown command ${ie}`)},m.onerror=V=>{throw S(`worker sent an error! ${V.filename}:${V.lineno}: ${V.message}`),V};var k,D=[];for(k of[])s.propertyIsEnumerable(k)&&D.push(k);m.postMessage({Bb:"load",Rb:D,kc:E,lc:x})});function lr(){var m=new Worker((()=>{let T=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new T("ort.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});ke.push(m)}var as=m=>{fe();var T=ne()[m+52>>>2>>>0];m=ne()[m+56>>>2>>>0],Eo(T,T-m),Bs(T)},fs=(m,T)=>{oe=0,m=Un(m,T),0>>=0);throw T>>>=0,k>>>=0,ne()[D.Ib+16>>>2>>>0]=0,ne()[D.Ib+4>>>2>>>0]=T,ne()[D.Ib+8>>>2>>>0]=k,m}function ls(m,T,k,D){return i?he(2,1,m,T,k,D):gs(m,T,k,D)}function gs(m,T,k,D){if(m>>>=0,k>>>=0,D>>>=0,l===void 0)return 6;var V=[];return i&&V.length===0?ls(m,T>>>=0,k,D):(m={ec:k,Ab:m,Hb:D,Mb:V},i?(m.Bb="spawnThread",postMessage(m,V),0):ee(m))}var nt=typeof TextDecoder<"u"?new TextDecoder:void 0,Ur=(m,T=0,k=NaN)=>{var D=(T>>>=0)+k;for(k=T;m[k]&&!(k>=D);)++k;if(16(V=(240&V)==224?(15&V)<<12|ie<<6|Te:(7&V)<<18|ie<<12|Te<<6|63&m[T++])?D+=String.fromCharCode(V):(V-=65536,D+=String.fromCharCode(55296|V>>10,56320|1023&V))}}else D+=String.fromCharCode(V)}return D},Tt=(m,T)=>(m>>>=0)?Ur(N(),m,T):"";function us(m,T,k){return i?he(3,1,m,T,k):0}function Wr(m,T){if(i)return he(4,1,m,T)}var Gr=m=>{for(var T=0,k=0;k=D?T++:2047>=D?T+=2:55296<=D&&57343>=D?(T+=4,++k):T+=3}return T},yr=(m,T,k)=>{var D=N();if(T>>>=0,0=Te&&(Te=65536+((1023&Te)<<10)|1023&m.charCodeAt(++ie)),127>=Te){if(T>=k)break;D[T++>>>0]=Te}else{if(2047>=Te){if(T+1>=k)break;D[T++>>>0]=192|Te>>6}else{if(65535>=Te){if(T+2>=k)break;D[T++>>>0]=224|Te>>12}else{if(T+3>=k)break;D[T++>>>0]=240|Te>>18,D[T++>>>0]=128|Te>>12&63}D[T++>>>0]=128|Te>>6&63}D[T++>>>0]=128|63&Te}}D[T>>>0]=0,m=T-V}else m=0;return m};function cs(m,T){if(i)return he(5,1,m,T)}function ur(m,T,k){if(i)return he(6,1,m,T,k)}function De(m,T,k){return i?he(7,1,m,T,k):0}function He(m,T){if(i)return he(8,1,m,T)}function Ye(m,T,k){if(i)return he(9,1,m,T,k)}function cr(m,T,k,D){if(i)return he(10,1,m,T,k,D)}function ks(m,T,k,D){if(i)return he(11,1,m,T,k,D)}function Or(m,T,k,D){if(i)return he(12,1,m,T,k,D)}function Is(m){if(i)return he(13,1,m)}function As(m,T){if(i)return he(14,1,m,T)}function ws(m,T,k){if(i)return he(15,1,m,T,k)}var Fs,Sr,Kr=()=>Ce(""),_r=m=>{for(var T="";N()[m>>>0];)T+=Fs[N()[m++>>>0]];return T},Ms={},bs={};function vr(m,T,k={}){return function(D,V,ie={}){var Te=V.name;if(!D)throw new Sr(`type "${Te}" must have a positive integer typeid pointer`);if(bs.hasOwnProperty(D)){if(ie.Sb)return;throw new Sr(`Cannot register type '${Te}' twice`)}bs[D]=V,Ms.hasOwnProperty(D)&&(V=Ms[D],delete Ms[D],V.forEach(Oe=>Oe()))}(m,T,k)}var Os=(m,T,k)=>{switch(T){case 1:return k?D=>le()[D>>>0]:D=>N()[D>>>0];case 2:return k?D=>F()[D>>>1>>>0]:D=>G()[D>>>1>>>0];case 4:return k?D=>R()[D>>>2>>>0]:D=>ne()[D>>>2>>>0];case 8:return k?D=>J[D>>>3]:D=>X[D>>>3];default:throw new TypeError(`invalid integer width (${T}): ${m}`)}};function ds(m,T,k){k>>>=0,vr(m>>>=0,{name:T=_r(T>>>0),fromWireType:D=>D,toWireType:function(D,V){if(typeof V!="bigint"&&typeof V!="number")throw V=V===null?"null":(D=typeof V)=="object"||D==="array"||D==="function"?V.toString():""+V,new TypeError(`Cannot convert "${V}" to ${this.name}`);return typeof V=="number"&&(V=BigInt(V)),V},Cb:$r,readValueFromPointer:Os(T,k,T.indexOf("u")==-1),Db:null})}var $r=8;function Ks(m,T,k,D){vr(m>>>=0,{name:T=_r(T>>>0),fromWireType:function(V){return!!V},toWireType:function(V,ie){return ie?k:D},Cb:$r,readValueFromPointer:function(V){return this.fromWireType(N()[V>>>0])},Db:null})}var ys=[],xr=[];function Dr(m){9<(m>>>=0)&&--xr[m+1]==0&&(xr[m]=void 0,ys.push(m))}var tr=m=>{if(!m)throw new Sr("Cannot use deleted val. handle = "+m);return xr[m]},fr=m=>{switch(m){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let T=ys.pop()||xr.length;return xr[T]=m,xr[T+1]=1,T}};function vs(m){return this.fromWireType(ne()[m>>>2>>>0])}var Hs={name:"emscripten::val",fromWireType:m=>{var T=tr(m);return Dr(m),T},toWireType:(m,T)=>fr(T),Cb:$r,readValueFromPointer:vs,Db:null};function Hr(m){return vr(m>>>0,Hs)}var qs=(m,T)=>{switch(T){case 4:return function(k){return this.fromWireType(be()[k>>>2>>>0])};case 8:return function(k){return this.fromWireType(de()[k>>>3>>>0])};default:throw new TypeError(`invalid float width (${T}): ${m}`)}};function Xs(m,T,k){k>>>=0,vr(m>>>=0,{name:T=_r(T>>>0),fromWireType:D=>D,toWireType:(D,V)=>V,Cb:$r,readValueFromPointer:qs(T,k),Db:null})}function Qs(m,T,k,D,V){if(m>>>=0,k>>>=0,T=_r(T>>>0),V===-1&&(V=4294967295),V=Oe=>Oe,D===0){var ie=32-8*k;V=Oe=>Oe<>>ie}var Te=T.includes("unsigned")?function(Oe,We){return We>>>0}:function(Oe,We){return We};vr(m,{name:T,fromWireType:V,toWireType:Te,Cb:$r,readValueFromPointer:Os(T,k,D!==0),Db:null})}function Js(m,T,k){function D(ie){var Te=ne()[ie>>>2>>>0];return ie=ne()[ie+4>>>2>>>0],new V(le().buffer,ie,Te)}var V=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][T];vr(m>>>=0,{name:k=_r(k>>>0),fromWireType:D,Cb:$r,readValueFromPointer:D},{Sb:!0})}function Ys(m,T){vr(m>>>=0,{name:T=_r(T>>>0),fromWireType:function(k){for(var D,V=ne()[k>>>2>>>0],ie=k+4,Te=ie,Oe=0;Oe<=V;++Oe){var We=ie+Oe;Oe!=V&&N()[We>>>0]!=0||(Te=Tt(Te,We-Te),D===void 0?D=Te:(D+="\0",D+=Te),Te=We+1)}return kr(k),D},toWireType:function(k,D){D instanceof ArrayBuffer&&(D=new Uint8Array(D));var V=typeof D=="string";if(!(V||D instanceof Uint8Array||D instanceof Uint8ClampedArray||D instanceof Int8Array))throw new Sr("Cannot pass non-string to std::string");var ie=V?Gr(D):D.length,Te=zs(4+ie+1),Oe=Te+4;if(ne()[Te>>>2>>>0]=ie,V)yr(D,Oe,ie+1);else if(V)for(V=0;V>>0]=We}else for(V=0;V>>0]=D[V];return k!==null&&k.push(kr,Te),Te},Cb:$r,readValueFromPointer:vs,Db(k){kr(k)}})}var qr=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Zs=(m,T)=>{for(var k=m>>1,D=k+T/2;!(k>=D)&&G()[k>>>0];)++k;if(32<(k<<=1)-m&&qr)return qr.decode(N().slice(m,k));for(k="",D=0;!(D>=T/2);++D){var V=F()[m+2*D>>>1>>>0];if(V==0)break;k+=String.fromCharCode(V)}return k},en=(m,T,k)=>{if(k??=2147483647,2>k)return 0;var D=T;k=(k-=2)<2*m.length?k/2:m.length;for(var V=0;V>>1>>>0]=ie,T+=2}return F()[T>>>1>>>0]=0,T-D},tn=m=>2*m.length,rn=(m,T)=>{for(var k=0,D="";!(k>=T/4);){var V=R()[m+4*k>>>2>>>0];if(V==0)break;++k,65536<=V?(V-=65536,D+=String.fromCharCode(55296|V>>10,56320|1023&V)):D+=String.fromCharCode(V)}return D},ps=(m,T,k)=>{if(T>>>=0,k??=2147483647,4>k)return 0;var D=T;k=D+k-4;for(var V=0;V=ie&&(ie=65536+((1023&ie)<<10)|1023&m.charCodeAt(++V)),R()[T>>>2>>>0]=ie,(T+=4)+4>k)break}return R()[T>>>2>>>0]=0,T-D},En=m=>{for(var T=0,k=0;k=D&&++k,T+=4}return T};function ue(m,T,k){if(m>>>=0,T>>>=0,k=_r(k>>>=0),T===2)var D=Zs,V=en,ie=tn,Te=Oe=>G()[Oe>>>1>>>0];else T===4&&(D=rn,V=ps,ie=En,Te=Oe=>ne()[Oe>>>2>>>0]);vr(m,{name:k,fromWireType:Oe=>{for(var We,Xe=ne()[Oe>>>2>>>0],ct=Oe+4,bt=0;bt<=Xe;++bt){var Ct=Oe+4+bt*T;bt!=Xe&&Te(Ct)!=0||(ct=D(ct,Ct-ct),We===void 0?We=ct:(We+="\0",We+=ct),ct=Ct+T)}return kr(Oe),We},toWireType:(Oe,We)=>{if(typeof We!="string")throw new Sr(`Cannot pass non-string to C++ string type ${k}`);var Xe=ie(We),ct=zs(4+Xe+T);return ne()[ct>>>2>>>0]=Xe/T,V(We,ct+4,Xe+T),Oe!==null&&Oe.push(kr,ct),ct},Cb:$r,readValueFromPointer:vs,Db(Oe){kr(Oe)}})}function C(m,T){vr(m>>>=0,{Tb:!0,name:T=_r(T>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function W(m){zn(m>>>0,!a,1,!o,131072,!1),er()}var Z=m=>{if(!re)try{if(m(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(R(),m>>>2,m).value.then(_e),m+=128,Atomics.store(R(),m>>>2,1))}var _e=()=>{var m=an();m&&(se(m),Z(To))};function Se(m,T){(m>>>=0)==T>>>0?setTimeout(_e):i?postMessage({Gb:m,Bb:"checkMailbox"}):(m=_t[m])&&m.postMessage({Bb:"checkMailbox"})}var Ue=[];function Ge(m,T,k,D,V){for(T>>>=0,D/=2,Ue.length=D,k=V>>>0>>>3,V=0;V>>0];return(T?Ae[T]:fi[m])(...Ue)}var Ke=()=>{oe=0};function Ve(m){m>>>=0,i?postMessage({Bb:"cleanupThread",hc:m}):gt(_t[m])}function Mt(m){}var lt=(m,T)=>{var k=bs[m];if(k===void 0)throw m=yo(m),k=_r(m),kr(m),new Sr(`${T} has unknown type ${k}`);return k},zt=(m,T,k)=>{var D=[];return m=m.toWireType(D,k),D.length&&(ne()[T>>>2>>>0]=fr(D)),m};function rr(m,T,k){return T>>>=0,k>>>=0,m=tr(m>>>0),T=lt(T,"emval::as"),zt(T,k,m)}function Nt(m,T){return T>>>=0,m=tr(m>>>0),(T=lt(T,"emval::as")).toWireType(null,m)}var jt=m=>{try{m()}catch(T){Ce(T)}},Ot=0,Ht=null,ms=0,sr=[],Lr={},Dt={},nr=0,dr=null,zr=[];function Br(m){return function(T){if(!re){if(Ot===0){var k=!1,D=!1;T((V=0)=>{if(!re&&(ms=V,k=!0,D)){Ot=2,jt(()=>Wn(Ht)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),V=!1;try{var ie=function(){var We=R()[Ht+8>>>2>>>0];return We=et[Dt[We]],--oe,We()}()}catch(We){ie=We,V=!0}var Te=!1;if(!Ht){var Oe=dr;Oe&&(dr=null,(V?Oe.reject:Oe.resolve)(ie),Te=!0)}if(V&&!Te)throw ie}}),D=!0,k||(Ot=1,Ht=function(){var V=zs(65548),ie=V+12;ne()[V>>>2>>>0]=ie,ne()[V+4>>>2>>>0]=ie+65536,ie=sr[0];var Te=Lr[ie];return Te===void 0&&(Te=nr++,Lr[ie]=Te,Dt[Te]=ie),ie=Te,R()[V+8>>>2>>>0]=ie,V}(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),jt(()=>Po(Ht)))}else Ot===2?(Ot=0,jt(So),kr(Ht),Ht=null,zr.forEach(Z)):Ce(`invalid state: ${Ot}`);return ms}}(T=>{m().then(T)})}function qt(m){return m>>>=0,Br(async()=>{var T=await tr(m);return fr(T)})}var Tr=[];function or(m,T,k,D){return k>>>=0,D>>>=0,(m=Tr[m>>>0])(null,T=tr(T>>>0),k,D)}var Gt={},Rt=m=>{var T=Gt[m];return T===void 0?_r(m):T};function Xt(m,T,k,D,V){return k>>>=0,D>>>=0,V>>>=0,(m=Tr[m>>>0])(T=tr(T>>>0),T[k=Rt(k)],D,V)}var ir=()=>typeof globalThis=="object"?globalThis:Function("return this")();function Ds(m){return(m>>>=0)==0?fr(ir()):(m=Rt(m),fr(ir()[m]))}var Pn=m=>{var T=Tr.length;return Tr.push(m),T},Xo=(m,T)=>{for(var k=Array(m),D=0;D>>2>>>0],"parameter "+D);return k},oo=(m,T)=>Object.defineProperty(T,"name",{value:m});function Qo(m,T,k){var D=(T=Xo(m,T>>>0)).shift();m--;var V=`return function (obj, func, destructorsRef, args) { `,ie=0,Te=[];k===0&&Te.push("obj");for(var Oe=["retType"],We=[D],Xe=0;Xect.name).join(", ")}) => ${D.name}>`,Pn(oo(k,m))}function Ls(m){return m=Rt(m>>>0),fr(s[m])}function Jo(m,T){return T>>>=0,m=tr(m>>>0),T=tr(T),fr(m[T])}function Yo(m){9<(m>>>=0)&&(xr[m+1]+=1)}function Zo(){return fr([])}function ei(m){m=tr(m>>>0);for(var T=Array(m.length),k=0;k>>0))}function io(){return fr({})}function ri(m){for(var T=tr(m>>>=0);T.length;){var k=T.pop();T.pop()(k)}Dr(m)}function si(m,T,k){T>>>=0,k>>>=0,m=tr(m>>>0),T=tr(T),k=tr(k),m[T]=k}function ao(m,T){return T>>>=0,m=(m=lt(m>>>0,"_emval_take_value")).readValueFromPointer(T),fr(m)}function ni(m,T){m=-9007199254740992>m||9007199254740992>>=0,m=new Date(1e3*m),R()[T>>>2>>>0]=m.getUTCSeconds(),R()[T+4>>>2>>>0]=m.getUTCMinutes(),R()[T+8>>>2>>>0]=m.getUTCHours(),R()[T+12>>>2>>>0]=m.getUTCDate(),R()[T+16>>>2>>>0]=m.getUTCMonth(),R()[T+20>>>2>>>0]=m.getUTCFullYear()-1900,R()[T+24>>>2>>>0]=m.getUTCDay(),m=(m.getTime()-Date.UTC(m.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,R()[T+28>>>2>>>0]=m}var Cn=m=>m%4==0&&(m%100!=0||m%400==0),lo=[0,31,60,91,121,152,182,213,244,274,305,335],Sn=[0,31,59,90,120,151,181,212,243,273,304,334];function da(m,T){m=-9007199254740992>m||9007199254740992>>=0,m=new Date(1e3*m),R()[T>>>2>>>0]=m.getSeconds(),R()[T+4>>>2>>>0]=m.getMinutes(),R()[T+8>>>2>>>0]=m.getHours(),R()[T+12>>>2>>>0]=m.getDate(),R()[T+16>>>2>>>0]=m.getMonth(),R()[T+20>>>2>>>0]=m.getFullYear()-1900,R()[T+24>>>2>>>0]=m.getDay();var k=(Cn(m.getFullYear())?lo:Sn)[m.getMonth()]+m.getDate()-1|0;R()[T+28>>>2>>>0]=k,R()[T+36>>>2>>>0]=-60*m.getTimezoneOffset(),k=new Date(m.getFullYear(),6,1).getTimezoneOffset();var D=new Date(m.getFullYear(),0,1).getTimezoneOffset();m=0|(k!=D&&m.getTimezoneOffset()==Math.min(D,k)),R()[T+32>>>2>>>0]=m}function oi(m){m>>>=0;var T=new Date(R()[m+20>>>2>>>0]+1900,R()[m+16>>>2>>>0],R()[m+12>>>2>>>0],R()[m+8>>>2>>>0],R()[m+4>>>2>>>0],R()[m>>>2>>>0],0),k=R()[m+32>>>2>>>0],D=T.getTimezoneOffset(),V=new Date(T.getFullYear(),6,1).getTimezoneOffset(),ie=new Date(T.getFullYear(),0,1).getTimezoneOffset(),Te=Math.min(ie,V);return 0>k?R()[m+32>>>2>>>0]=+(V!=ie&&Te==D):0>>2>>>0]=T.getDay(),k=(Cn(T.getFullYear())?lo:Sn)[T.getMonth()]+T.getDate()-1|0,R()[m+28>>>2>>>0]=k,R()[m>>>2>>>0]=T.getSeconds(),R()[m+4>>>2>>>0]=T.getMinutes(),R()[m+8>>>2>>>0]=T.getHours(),R()[m+12>>>2>>>0]=T.getDate(),R()[m+16>>>2>>>0]=T.getMonth(),R()[m+20>>>2>>>0]=T.getYear(),m=T.getTime(),BigInt(isNaN(m)?-1:m/1e3)}function $n(m,T,k,D,V,ie,Te){return i?he(16,1,m,T,k,D,V,ie,Te):-52}function uo(m,T,k,D,V,ie){if(i)return he(17,1,m,T,k,D,V,ie)}var hs={},ii=()=>performance.timeOrigin+performance.now();function co(m,T){if(i)return he(18,1,m,T);if(hs[m]&&(clearTimeout(hs[m].id),delete hs[m]),!T)return 0;var k=setTimeout(()=>{delete hs[m],Z(()=>Nn(m,performance.timeOrigin+performance.now()))},T);return hs[m]={id:k,qc:T},0}function ai(m,T,k,D){m>>>=0,T>>>=0,k>>>=0,D>>>=0;var V=new Date().getFullYear(),ie=new Date(V,0,1).getTimezoneOffset();V=new Date(V,6,1).getTimezoneOffset();var Te=Math.max(ie,V);ne()[m>>>2>>>0]=60*Te,R()[T>>>2>>>0]=+(ie!=V),m=(T=Oe=>{var We=Math.abs(Oe);return`UTC${0<=Oe?"-":"+"}${String(Math.floor(We/60)).padStart(2,"0")}${String(We%60).padStart(2,"0")}`})(ie),T=T(V),VDate.now();function ui(m,T,k){return 0<=m&&3>=m?(m===0?m=Date.now():m=performance.timeOrigin+performance.now(),J[k>>>0>>>3]=BigInt(Math.round(1e6*m)),0):28}var kn=[],po=(m,T)=>{kn.length=0;for(var k;k=N()[m++>>>0];){var D=k!=105;T+=(D&=k!=112)&&T%8?4:0,kn.push(k==112?ne()[T>>>2>>>0]:k==106?J[T>>>3]:k==105?R()[T>>>2>>>0]:de()[T>>>3>>>0]),T+=D?8:4}return kn};function In(m,T,k){return m>>>=0,T=po(T>>>0,k>>>0),Ae[m](...T)}function mo(m,T,k){return m>>>=0,T=po(T>>>0,k>>>0),Ae[m](...T)}var ci=()=>{};function ho(m,T){return S(Tt(m>>>0,T>>>0))}var xs=()=>{throw oe+=1,"unwind"};function di(){return 4294901760}var pa=()=>navigator.hardwareConcurrency;function pi(){return Ce("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function ma(m){m>>>=0;var T=N().length;if(m<=T||4294901760=k;k*=2){var D=T*(1+.2/k);D=Math.min(D,m+100663296);e:{D=(Math.min(4294901760,65536*Math.ceil(Math.max(m,D)/65536))-E.buffer.byteLength+65535)/65536|0;try{E.grow(D),fe();var V=1;break e}catch{}V=void 0}if(V)return!0}return!1}var sn=()=>(Ce("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Ts={},_o=m=>{m.forEach(T=>{sn()})};function mi(){var m=Error().stack.toString().split(` `);return m[0]=="Error"&&m.shift(),_o(m),Ts.Lb=sn(),Ts.cc=m,Ts.Lb}function hi(m,T,k){if(m>>>=0,T>>>=0,Ts.Lb==m)var D=Ts.cc;else(D=Error().stack.toString().split(` `))[0]=="Error"&&D.shift(),_o(D);for(var V=3;D[V]&&sn()!=m;)++V;for(m=0;m>>2>>>0]=sn();return m}var An,Fn={},nn=()=>{if(!An){var m,T={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(m in Fn)Fn[m]===void 0?delete T[m]:T[m]=Fn[m];var k=[];for(m in T)k.push(`${m}=${T[m]}`);An=k}return An};function fo(m,T){if(i)return he(19,1,m,T);m>>>=0,T>>>=0;var k=0;return nn().forEach((D,V)=>{var ie=T+k;for(V=ne()[m+4*V>>>2>>>0]=ie,ie=0;ie>>0]=D.charCodeAt(ie);le()[V>>>0]=0,k+=D.length+1}),0}function go(m,T){if(i)return he(20,1,m,T);m>>>=0,T>>>=0;var k=nn();ne()[m>>>2>>>0]=k.length;var D=0;return k.forEach(V=>D+=V.length+1),ne()[T>>>2>>>0]=D,0}function wo(m){return i?he(21,1,m):52}function On(m,T,k,D){return i?he(22,1,m,T,k,D):52}function Mo(m,T,k,D){return i?he(23,1,m,T,k,D):70}var _i=[null,[],[]];function Dn(m,T,k,D){if(i)return he(24,1,m,T,k,D);T>>>=0,k>>>=0,D>>>=0;for(var V=0,ie=0;ie>>2>>>0],Oe=ne()[T+4>>>2>>>0];T+=8;for(var We=0;We>>0],ct=_i[m];Xe===0||Xe===10?((m===1?g:S)(Ur(ct)),ct.length=0):ct.push(Xe)}V+=Oe}return ne()[D>>>2>>>0]=V,0}i||function(){for(var m=s.numThreads-1;m--;)lr();z.unshift(()=>{pe++,function(T){i?T():Promise.all(ke.map(It)).then(T)}(()=>xe())})}();for(var bo=Array(256),on=0;256>on;++on)bo[on]=String.fromCharCode(on);Fs=bo,Sr=s.BindingError=class extends Error{constructor(m){super(m),this.name="BindingError"}},s.InternalError=class extends Error{constructor(m){super(m),this.name="InternalError"}},xr.push(0,1,void 0,1,null,1,!0,1,!1,1),s.count_emval_handles=()=>xr.length/2-5-ys.length;var et,fi=[Ee,Fe,ls,us,Wr,cs,ur,De,He,Ye,cr,ks,Or,Is,As,ws,$n,uo,co,fo,go,wo,On,Mo,Dn];(async function(){function m(D,V){return et=D.exports,et=function(){var ie=et,Te={};for(let[Oe,We]of Object.entries(ie))Te[Oe]=typeof We=="function"?(...Xe)=>{sr.push(Oe);try{return We(...Xe)}finally{re||(sr.pop(),Ht&&Ot===1&&sr.length===0&&(Ot=0,oe+=1,jt(Co),typeof Fibers<"u"&&Fibers.rc()))}}:We;return Te}(),et=function(){var ie=et,Te=We=>Xe=>We(Xe)>>>0,Oe=We=>()=>We()>>>0;return(ie=Object.assign({},ie)).Da=Te(ie.Da),ie.fb=Oe(ie.fb),ie.hb=Te(ie.hb),ie.tb=Te(ie.tb),ie.ub=Oe(ie.ub),ie.__cxa_get_exception_ptr=Te(ie.__cxa_get_exception_ptr),ie}(),ut.push(et.ib),x=V,xe(),et}pe++;var T=$e();if(s.instantiateWasm)return new Promise(D=>{s.instantiateWasm(T,(V,ie)=>{m(V,ie),D(V.exports)})});if(i)return new Promise(D=>{ve=V=>{var ie=new WebAssembly.Instance(V,$e());D(m(ie,V))}});U??=s.locateFile?s.locateFile?s.locateFile("ort-wasm-simd-threaded.jsep.wasm",P):P+"ort-wasm-simd-threaded.jsep.wasm":new URL(""+new URL("ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href,import.meta.url).href;try{var k=await async function(D){var V=U;if(!te&&typeof WebAssembly.instantiateStreaming=="function"&&!ce(V))try{var ie=fetch(V,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(ie,D)}catch(Te){S(`wasm streaming compile failed: ${Te}`),S("falling back to ArrayBuffer instantiation")}return async function(Te,Oe){try{var We=await async function(Xe){if(!te)try{var ct=await u(Xe);return new Uint8Array(ct)}catch{}if(Xe==U&&te)Xe=new Uint8Array(te);else{if(!d)throw"both async and sync fetching of the wasm failed";Xe=d(Xe)}return Xe}(Te);return await WebAssembly.instantiate(We,Oe)}catch(Xe){S(`failed to asynchronously prepare wasm: ${Xe}`),Ce(Xe)}}(V,D)}(T);return m(k.instance,k.module)}catch(D){return t(D),Promise.reject(D)}})();var yo=m=>(yo=et.Da)(m),Ln=()=>(Ln=et.Ea)();s._OrtInit=(m,T)=>(s._OrtInit=et.Fa)(m,T),s._OrtGetLastError=(m,T)=>(s._OrtGetLastError=et.Ga)(m,T),s._OrtCreateSessionOptions=(m,T,k,D,V,ie,Te,Oe,We,Xe)=>(s._OrtCreateSessionOptions=et.Ha)(m,T,k,D,V,ie,Te,Oe,We,Xe),s._OrtAppendExecutionProvider=(m,T,k,D,V)=>(s._OrtAppendExecutionProvider=et.Ia)(m,T,k,D,V),s._OrtAddFreeDimensionOverride=(m,T,k)=>(s._OrtAddFreeDimensionOverride=et.Ja)(m,T,k),s._OrtAddSessionConfigEntry=(m,T,k)=>(s._OrtAddSessionConfigEntry=et.Ka)(m,T,k),s._OrtReleaseSessionOptions=m=>(s._OrtReleaseSessionOptions=et.La)(m),s._OrtCreateSession=(m,T,k)=>(s._OrtCreateSession=et.Ma)(m,T,k),s._OrtReleaseSession=m=>(s._OrtReleaseSession=et.Na)(m),s._OrtGetInputOutputCount=(m,T,k)=>(s._OrtGetInputOutputCount=et.Oa)(m,T,k),s._OrtGetInputOutputMetadata=(m,T,k,D)=>(s._OrtGetInputOutputMetadata=et.Pa)(m,T,k,D),s._OrtFree=m=>(s._OrtFree=et.Qa)(m),s._OrtCreateTensor=(m,T,k,D,V,ie)=>(s._OrtCreateTensor=et.Ra)(m,T,k,D,V,ie),s._OrtGetTensorData=(m,T,k,D,V)=>(s._OrtGetTensorData=et.Sa)(m,T,k,D,V),s._OrtReleaseTensor=m=>(s._OrtReleaseTensor=et.Ta)(m),s._OrtCreateRunOptions=(m,T,k,D)=>(s._OrtCreateRunOptions=et.Ua)(m,T,k,D),s._OrtAddRunConfigEntry=(m,T,k)=>(s._OrtAddRunConfigEntry=et.Va)(m,T,k),s._OrtReleaseRunOptions=m=>(s._OrtReleaseRunOptions=et.Wa)(m),s._OrtCreateBinding=m=>(s._OrtCreateBinding=et.Xa)(m),s._OrtBindInput=(m,T,k)=>(s._OrtBindInput=et.Ya)(m,T,k),s._OrtBindOutput=(m,T,k,D)=>(s._OrtBindOutput=et.Za)(m,T,k,D),s._OrtClearBoundOutputs=m=>(s._OrtClearBoundOutputs=et._a)(m),s._OrtReleaseBinding=m=>(s._OrtReleaseBinding=et.$a)(m),s._OrtRunWithBinding=(m,T,k,D,V)=>(s._OrtRunWithBinding=et.ab)(m,T,k,D,V),s._OrtRun=(m,T,k,D,V,ie,Te,Oe)=>(s._OrtRun=et.bb)(m,T,k,D,V,ie,Te,Oe),s._OrtEndProfiling=m=>(s._OrtEndProfiling=et.cb)(m),s._JsepOutput=(m,T,k)=>(s._JsepOutput=et.db)(m,T,k),s._JsepGetNodeName=m=>(s._JsepGetNodeName=et.eb)(m);var an=()=>(an=et.fb)(),kr=s._free=m=>(kr=s._free=et.gb)(m),zs=s._malloc=m=>(zs=s._malloc=et.hb)(m),zn=(m,T,k,D,V,ie)=>(zn=et.kb)(m,T,k,D,V,ie),vo=()=>(vo=et.lb)(),Bn=(m,T,k,D,V)=>(Bn=et.mb)(m,T,k,D,V),xo=m=>(xo=et.nb)(m),Rn=m=>(Rn=et.ob)(m),Nn=(m,T)=>(Nn=et.pb)(m,T),To=()=>(To=et.qb)(),Eo=(m,T)=>(Eo=et.rb)(m,T),Bs=m=>(Bs=et.sb)(m),jn=m=>(jn=et.tb)(m),Vn=()=>(Vn=et.ub)(),Un=s.dynCall_ii=(m,T)=>(Un=s.dynCall_ii=et.vb)(m,T),Po=m=>(Po=et.wb)(m),Co=()=>(Co=et.xb)(),Wn=m=>(Wn=et.yb)(m),So=()=>(So=et.zb)();return s.stackSave=()=>Vn(),s.stackRestore=m=>Bs(m),s.stackAlloc=m=>jn(m),s.setValue=function(m,T,k="i8"){switch(k.endsWith("*")&&(k="*"),k){case"i1":case"i8":le()[m>>>0]=T;break;case"i16":F()[m>>>1>>>0]=T;break;case"i32":R()[m>>>2>>>0]=T;break;case"i64":J[m>>>3]=BigInt(T);break;case"float":be()[m>>>2>>>0]=T;break;case"double":de()[m>>>3>>>0]=T;break;case"*":ne()[m>>>2>>>0]=T;break;default:Ce(`invalid type for setValue: ${k}`)}},s.getValue=function(m,T="i8"){switch(T.endsWith("*")&&(T="*"),T){case"i1":case"i8":return le()[m>>>0];case"i16":return F()[m>>>1>>>0];case"i32":return R()[m>>>2>>>0];case"i64":return J[m>>>3];case"float":return be()[m>>>2>>>0];case"double":return de()[m>>>3>>>0];case"*":return ne()[m>>>2>>>0];default:Ce(`invalid type for getValue: ${T}`)}},s.UTF8ToString=Tt,s.stringToUTF8=yr,s.lengthBytesUTF8=Gr,function m(){if(0{Gu(),Il=typeof location>"u"?void 0:location.origin,Pu=import.meta.url>"file:"&&import.meta.url<"file;",Vh=()=>{{if(Pu){let e=URL;return new URL(new e("ort.bundle.min.mjs",import.meta.url).href,Il).href}return import.meta.url}},Ir=Vh(),Hw=()=>{if(Ir&&!Ir.startsWith("blob:"))return Ir.substring(0,Ir.lastIndexOf("/")+1)},Ri=(e,r)=>{try{let t=r??Ir;return(t?new URL(e,t):new URL(e)).origin===Il}catch{return!1}},Uh=(e,r)=>{let t=r??Ir;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},Wh=(e,r)=>`${r??"./"}${e}`,Al=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},Gh=async e=>(await import(e)).default,Fl=(jv(),Ko(Uw)).default,qw=async()=>{if(!Ir)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ri(Ir))return[void 0,Fl()];let e=await Al(Ir);return[e,Fl(e)]},Ol=(Vv(),Ko(Gw)).default,Xw=async(e,r,t)=>{if(!e&&!r&&Ol&&Ir&&Ri(Ir))return[void 0,Ol];{let s="ort-wasm-simd-threaded.jsep.mjs",n=e??Uh(s,r),o=t&&n&&!Ri(n,r),a=o?await Al(n):n??Wh(s,r);return[o?a:void 0,await Gh(a)]}}}),Dl,Ni,Ao,Ll,Kh,Hh,qh,Hu,Ft,xn=ze(()=>{Ku(),Ni=!1,Ao=!1,Ll=!1,Kh=()=>{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}},Hh=()=>{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}},qh=()=>{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}},Hu=async e=>{if(Ni)return Promise.resolve();if(Ao)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ll)throw new Error("previous call to 'initializeWebAssembly()' failed.");Ao=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!qh())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Hh())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=Kh();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,a=n?.mjs,i=a?.href??a,l=n?.wasm,c=l?.href??l,p=e.wasmBinary,[u,d]=await Xw(i,o,t>1),f=!1,_=[];if(r>0&&_.push(new Promise(P=>{setTimeout(()=>{f=!0,P()},r)})),_.push(new Promise((P,I)=>{let M={numThreads:t};if(p)M.wasmBinary=p;else if(c||o)M.locateFile=g=>c??o+g;else if(i&&i.indexOf("blob:")!==0)M.locateFile=g=>new URL(g,i).href;else if(u){let g=Hw();g&&(M.locateFile=S=>g+S)}d(M).then(g=>{Ao=!1,Ni=!0,Dl=g,P(),u&&URL.revokeObjectURL(u)},g=>{Ao=!1,Ll=!0,I(g)})})),await Promise.race(_),f)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},Ft=()=>{if(Ni&&Dl)return Dl;throw new Error("WebAssembly is not initialized yet.")}}),rs,sa,kt,qu=ze(()=>{xn(),rs=(e,r)=>{let t=Ft(),s=t.lengthBytesUTF8(e)+1,n=t._malloc(s);return t.stringToUTF8(e,n,s),r.push(n),n},sa=(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 a=r?r+n:n;if(typeof o=="object")sa(o,a+".",t,s);else if(typeof o=="string"||typeof o=="number")s(a,o.toString());else if(typeof o=="boolean")s(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},kt=e=>{let r=Ft(),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")),a=r.getValue(n+s,"*"),i=a?r.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${o}, ERROR_MESSAGE: ${i}`)}finally{r.stackRestore(t)}}}),Qw,Uv=ze(()=>{xn(),qu(),Qw=e=>{let r=Ft(),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=rs(e.tag,s)),t=r._OrtCreateRunOptions(n.logSeverityLevel,n.logVerbosityLevel,!!n.terminate,o),t===0&&kt("Can't create run options."),e?.extra!==void 0&&sa(e.extra,"",new WeakSet,(a,i)=>{let l=rs(a,s),c=rs(i,s);r._OrtAddRunConfigEntry(t,l,c)!==0&&kt(`Can't set a run config entry: ${a} - ${i}.`)}),[t,s]}catch(o){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(a=>r._free(a)),o}}}),Xh,Qh,Jh,Fo,Yh,Jw,Wv=ze(()=>{xn(),qu(),Xh=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}`)}},Qh=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Jh=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)},Fo=(e,r,t,s)=>{let n=rs(r,s),o=rs(t,s);Ft()._OrtAddSessionConfigEntry(e,n,o)!==0&&kt(`Can't set a session config entry: ${r} - ${t}.`)},Yh=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&&Fo(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}`);Fo(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${n}`)}let a=rs(n,t),i=o.length,l=0,c=0;if(i>0){l=Ft()._malloc(i*Ft().PTR_SIZE),t.push(l),c=Ft()._malloc(i*Ft().PTR_SIZE),t.push(c);for(let p=0;p{let r=Ft(),t=0,s=[],n=e||{};Jh(n);try{let o=Xh(n.graphOptimizationLevel??"all"),a=Qh(n.executionMode??"sequential"),i=typeof n.logId=="string"?rs(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"?rs(n.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(o,!!n.enableCpuMemArena,!!n.enableMemPattern,a,!!n.enableProfiling,0,i,l,c,p),t===0&&kt("Can't create session options."),n.executionProviders&&await Yh(t,n.executionProviders,s),n.enableGraphCapture!==void 0){if(typeof n.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${n.enableGraphCapture}`);Fo(t,"enableGraphCapture",n.enableGraphCapture.toString(),s)}if(n.freeDimensionOverrides)for(let[u,d]of Object.entries(n.freeDimensionOverrides)){if(typeof u!="string")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let f=rs(u,s);r._OrtAddFreeDimensionOverride(t,f,d)!==0&&kt(`Can't set a free dimension override: ${u} - ${d}.`)}return n.extra!==void 0&&sa(n.extra,"",new WeakSet,(u,d)=>{Fo(t,u,d,s)}),[t,s]}catch(o){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&kt("Can't release session options."),s.forEach(a=>r._free(a)),o}}}),Yn,Cs,wn,Xu,na,Qu,Ju,Cu,at=ze(()=>{Yn=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}`)}},Cs=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}`)}},wn=(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},Xu=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}`)}},na=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}`)}},Qu=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ju=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Cu=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}`)}}}),Yu,Yw=ze(()=>{Gu(),Yu=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(i){if(i instanceof RangeError){let l=Math.ceil(s/65536);o=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw i}let a=0;for(;;){let{done:i,value:l}=await n.read();if(i)break;let c=l.byteLength;new Uint8Array(o,a,c).set(l),a+=c}return new Uint8Array(o,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Zh,e_,t_,r_,Zu,s_,yt,Ss=ze(()=>{at(),Zh=["V","I","W","E","F"],e_=(e,r)=>{console.log(`[${Zh[e]},${new Date().toISOString()}]${r}`)},Zu=(e,r)=>{t_=e,r_=r},s_=(e,r)=>{let t=na(e),s=na(t_);t>=s&&e_(t,typeof r=="function"?r():r)},yt=(...e)=>{r_&&s_(...e)}}),n_,ro,we,oa,Zw,eM,tM,mt=ze(()=>{n_=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},ro=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),a=new Array(o);if(t){if(s<2||n<2)return;let i=n_.calcMatMulShape([e[s-2],e[s-1]],[r[n-2],r[n-1]]);if(i===void 0)return;[a[o-2],a[o-1]]=i}for(let i=t?3:1;i<=o;i++){let l=s-i<0?1:e[s-i],c=n-i<0?1:r[n-i];if(l!==c&&l>1&&c>1)return;let p=Math.max(l,c);if(l&&c)a[o-i]=Math.max(l,c);else{if(p>1)return;a[o-i]=0}}return a}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 ea{static size(r){return ea.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 ea.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 ea.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])}},oa=class Vo{static adjustPoolAttributes(r,t,s,n,o,a){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 i=0;i=s.length?s.push(t[i+2]):s[i]=t[i+2];for(let i=0;i=s[i]||a[i+s.length]>=s[i])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,n,o,a,i){if(i){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{at(),ec=(e,r)=>new(Xu(r))(e)}),Su,zl,o_,Bl,i_,Rl,Nl,jl,a_,sM,Gv=ze(()=>{Ss(),Su=(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||a<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${o}: ${a}`);n[o]=Number(a)}return r?new Uint8Array(n.buffer):n},zl=(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},o_=1,Bl=()=>o_++,i_=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Rl=(e,r)=>{let t=i_.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},Nl=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:r,context:t,tensor:s,dataType:n,shape:o,shouldConvertInt64toInt32:a=!1}=e;this.sessionId=r,this.mlContext=t,this.mlTensor=s,this.dataType=n,this.tensorShape=o,this.shouldConvertInt64toInt32=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Rl(this.dataType,this.tensorShape)}destroy(){yt("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=zl(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}},jl=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),a=n==="int64"&&!o.opSupportLimits().input.dataTypes.includes("int64");if(a&&(n="int32",yt("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!==Rl(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 i=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,n,t,i,!0,!0,a),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=Su(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else yt("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?zl(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)}},a_=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=Bl();return this.tensorTrackersById.set(e,new jl(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){yt("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){yt("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=Bl(),a=new Nl({sessionId:e,context:n,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(o,new jl(this,a)),this.externalTensors.add(a),o}async getCachedTensor(e,r,t,s,n,o,a=!1){let i=this.getMLContext(e);for(let[c,p]of this.freeTensors.entries())if(p.canReuseTensor(i,r,t)){yt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let u=this.freeTensors.splice(c,1)[0];return u.sessionId=e,u}yt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let l=await i.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:n,readable:o});return new Nl({sessionId:e,context:i,tensor:l,dataType:r,shape:t,shouldConvertInt64toInt32:a})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},sM=(...e)=>new a_(...e)}),ji,l_,nM,Kv=ze(()=>{at(),xn(),rM(),Gv(),Ss(),ji=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),l_=(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])},nM=class{constructor(e){this.tensorManager=sM(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Zu(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){yt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){yt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)yt("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=>l_(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){yt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,n){let o=ji.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){yt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=ji.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(!Ft().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");yt("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 ec(t,r)}}registerMLTensor(e,r,t,s){let n=ji.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let o=this.tensorManager.registerTensor(e,r,n,s);return yt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${n}, dimensions: ${s}} -> {tensorId: ${o}}`),o}registerMLConstant(e,r,t,s,n,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let i=e;e.startsWith("./")&&(i=e.substring(2));let l=o.get(i);if(!l)throw new Error(`File with name ${i} 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":a?(p=Su(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 yt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${n.dataType}, shape: ${n.shape}}} ${a?"(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(){}}}),tc=ze(()=>{}),Vl,Vi,Ui,u_,c_,Ul,$u,d_,oM,Hv=ze(()=>{Ss(),tc(),Vl=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]]),Vi=[],Ui=e=>Math.ceil(Number(e)/16)*16,u_=e=>{for(let r=0;rc_++,$u=async(e,r,t,s)=>{let n=Ui(t),o=e.device.createBuffer({size:n,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(r,0,o,0,n),e.flush(),await o.mapAsync(GPUMapMode.READ);let i=o.getMappedRange();if(s){let l=s();return l.set(new Uint8Array(i,0,t)),l}else return new Uint8Array(i.slice(0,t))}finally{o.destroy()}},d_=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 Vl)Vi.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=Ui(n),a=this.storageCache.get(e);if(!a)throw new Error("gpu data for uploading does not exist");if(Number(a.originalSize)!==n)throw new Error(`inconsistent data size. gpu data size=${a.originalSize}, data size=${n}`);let i=this.backend.device.createBuffer({mappedAtCreation:!0,size:o,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=i.getMappedRange();new Uint8Array(l).set(new Uint8Array(t,s,n)),i.unmap();let c=this.backend.device.createCommandEncoder();c.copyBufferToBuffer(i,0,a.gpuData.buffer,0,o),this.backend.device.queue.submit([c.finish()]),i.destroy(),yt("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=Ui(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 yt("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=Ul();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),yt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),yt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=u_(e),s,n=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,o=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(n||o){let i=(n?this.freeBuffers:this.freeUniformBuffers).get(t);i?i.length>0?s=i.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 a={id:Ul(),type:0,buffer:s};return this.storageCache.set(a.id,{gpuData:a,originalSize:Number(e)}),yt("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${a.id}`),a}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 yt("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 $u(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=Vl.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&&(yt("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},oM=(...e)=>new d_(...e)}),p_,Pt,Kt=ze(()=>{p_=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}},Pt=e=>new p_(e)}),so,Wi,hr,br,Ze,Wt,ku,eo,Ws,Je,Oo,Pe,Qe,iM,rc,m_,aM,ht=ze(()=>{at(),mt(),so=64,Wi=(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}`)}},hr=(e,r=1)=>{let t=Wi(e,r);return typeof t=="string"?t:t[0]},br=(e,r=1)=>{let t=Wi(e,r);return typeof t=="string"?t:t[1]},Ze=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:we.computeStrides(t)})}),r},Wt=e=>e%4===0?4:e%2===0?2:1,ku=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,eo=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,Ws=(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,Je=(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,Oo=(e,r,t,s,n)=>{let o=typeof t=="number",a=o?t:t.length,i=[...new Array(a).keys()],l=a<2?"u32":a<=4?`vec${a}`:`array`,c=Wi(r,n),p=typeof c=="string"?c:c[1],u=typeof c=="string"?c:c[0],d={indices:l,value:p,storage:u,tensor:r},f=N=>typeof N=="string"?N:`${N}u`,_={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},P=o?"uniforms.":"",I=`${P}${e}_shape`,M=`${P}${e}_strides`,g="";for(let N=0;N ${d.indices} { var indices: ${d.indices}; var current = offset; ${g} return indices; }`,E=N=>(_.offsetToIndices=!0,a<2?N:`o2i_${e}(${N})`),x=[];if(a>=2)for(let N=a-1;N>=0;N--)x.push(`${Je(M,N,a)} * (indices[${N}])`);let w=a<2?"":` fn i2o_${e}(indices: ${d.indices}) -> u32 { return ${x.join("+")}; }`,v=N=>(_.indicesToOffset=!0,a<2?N:`i2o_${e}(${N})`),$=(...N)=>a===0?"0u":`${d.indices}(${N.map(f).join(",")})`,O=(N,F)=>a<2?`${N}`:`${Je(N,F,a)}`,B=(N,F,G)=>a<2?`${N}=${G};`:`${Je(N,F,a)}=${G};`,H={},q=(N,F)=>{_.broadcastedIndicesToOffset=!0;let G=`${F.name}broadcastedIndicesTo${e}Offset`;if(G in H)return`${G}(${N})`;let R=[];for(let ne=a-1;ne>=0;ne--){let be=F.indicesGet("outputIndices",ne+F.rank-a);R.push(`${O(M,ne)} * (${be} % ${O(I,ne)})`)}return H[G]=`fn ${G}(outputIndices: ${F.type.indices}) -> u32 { return ${R.length>0?R.join("+"):"0u"}; }`,`${G}(${N})`},L=(N,F)=>(()=>{if(d.storage===d.value)return`${e}[${N}]=${F};`;if(d.storage==="vec2"&&d.value==="i32")return`${e}[${N}]=vec2(u32(${F}), select(0u, 0xFFFFFFFFu, ${F} < 0));`;if(d.storage==="vec2"&&d.value==="u32")return`${e}[${N}]=vec2(u32(${F}), 0u);`;if(d.storage==="u32"&&d.value==="vec4")return`${e}[${N}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${F}));`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),J=N=>(()=>{if(d.storage===d.value)return`${e}[${N}]`;if(d.storage==="vec2"&&d.value==="i32")return`i32(${e}[${N}].x)`;if(d.storage==="vec2"&&d.value==="u32")return`u32(${e}[${N}].x)`;if(d.storage==="u32"&&d.value==="vec4")return`vec4(bool(${e}[${N}] & 0xFFu), bool(${e}[${N}] & 0xFF00u), bool(${e}[${N}] & 0xFF0000u), bool(${e}[${N}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),X=a<2?"":` fn get_${e}ByIndices(indices: ${d.indices}) -> ${p} { return ${J(`i2o_${e}(indices)`)}; }`,Q=a<2?"":(()=>{let N=i.map(G=>`d${G}: u32`).join(", "),F=i.map(G=>`d${G}`).join(", ");return` fn get_${e}(${N}) -> ${p} { return get_${e}ByIndices(${$(F)}); }`})(),te=(...N)=>{if(N.length!==a)throw new Error(`indices length must be ${a}`);let F=N.map(f).join(",");return a===0?J("0u"):a===1?J(F[0]):(_.get=!0,_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}(${F})`)},re=N=>a<2?J(N):(_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}ByIndices(${N})`),ce=a<2?"":` fn set_${e}ByIndices(indices: ${d.indices}, value: ${p}) { ${L(`i2o_${e}(indices)`,"value")} }`,le=a<2?"":(()=>{let N=i.map(G=>`d${G}: u32`).join(", "),F=i.map(G=>`d${G}`).join(", ");return` fn set_${e}(${N}, value: ${p}) { set_${e}ByIndices(${$(F)}, value); }`})();return{impl:()=>{let N=[],F=!1;return _.offsetToIndices&&(N.push(S),F=!0),_.indicesToOffset&&(N.push(w),F=!0),_.broadcastedIndicesToOffset&&(Object.values(H).forEach(G=>N.push(G)),F=!0),_.set&&(N.push(le),F=!0),_.setByIndices&&(N.push(ce),F=!0),_.get&&(N.push(Q),F=!0),_.getByIndices&&(N.push(X),F=!0),!o&&F&&N.unshift(`const ${I} = ${d.indices}(${t.join(",")});`,`const ${M} = ${d.indices}(${we.computeStrides(t).join(",")});`),N.join(` `)},type:d,offsetToIndices:E,indicesToOffset:v,broadcastedIndicesToOffset:q,indices:$,indicesGet:O,indicesSet:B,set:(...N)=>{if(N.length!==a+1)throw new Error(`indices length must be ${a}`);let F=N[a];if(typeof F!="string")throw new Error("value must be string");let G=N.slice(0,a).map(f).join(",");return a===0?L("0u",F):a===1?L(G[0],F):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}(${G}, ${F})`)},setByOffset:L,setByIndices:(N,F)=>a<2?L(N,F):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}ByIndices(${N}, ${F});`),get:te,getByOffset:J,getByIndices:re,usage:s,name:e,strides:M,shape:I,rank:a}},Pe=(e,r,t,s=1)=>Oo(e,r,t,"input",s),Qe=(e,r,t,s=1)=>Oo(e,r,t,"output",s),iM=(e,r,t)=>Oo(e,r,t,"atomicOutput",1),rc=(e,r,t,s=1)=>Oo(e,r,t,"internal",s),m_=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=so){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`,a=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}) { ${a} `}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])}},aM=(e,r)=>new m_(e,r)}),h_,Wl,__,f_,g_,w_,Fr,lM,uM,Gs=ze(()=>{at(),mt(),Kt(),ht(),h_=(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}`)},Wl=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),__=(e,r)=>we.sortBasedOnPerm(e,Wl(e.length,r)),f_=(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=Wl(s,r),o=__(e.dims,n),a=e.dims,i=o,l=s<2||w_(n,e.dims),c;if(l)return c=_=>{let P=Pe("input",t,a,4),I=Qe("output",t,i,4);return` ${_.registerUniform("output_size","u32").declareVariables(P,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:u}=g_(e.dims,n),d=we.areEqual(u,[2,3,1]),f=we.areEqual(u,[3,1,2]);if(p.length===2||d||f){a=d?[p[0],p[1]*p[2]]:f?[p[0]*p[1],p[2]]:p,i=[a[1],a[0]];let _=16;return c=P=>{let I=Pe("a",t,a.length),M=Qe("output",t,i.length);return` ${P.registerUniform("output_size","u32").declareVariables(I,M)} var tile : array, ${_}>; ${P.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]) { ${M.setByIndices(`${M.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} } }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let P=we.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(i[1]/_),y:Math.ceil(i[0]/_)},programUniforms:[{type:12,data:P},...Ze(a,i)]}},getShaderSource:c}}return c=_=>{let P=Pe("a",t,a.length),I=Qe("output",t,i.length);return` ${_.registerUniform("output_size","u32").declareVariables(P,I)} ${f_(n,s,P,I)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${I.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${I.setByOffset("global_idx",P.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:_},...Ze(a,i)]}},getShaderSource:c}},lM=(e,r)=>{h_(e.inputs,r.perm),e.compute(Fr(e.inputs[0],r.perm))},uM=e=>Pt({perm:e.perm})}),M_,b_,y_,v_,x_,T_,E_,P_,C_,S_,Jr,cM,dM,pM,mM,hM,_M,fM,gM,wM,MM,qv=ze(()=>{at(),mt(),ht(),sc(),Gs(),M_={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"},b_={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"},y_={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},v_={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},x_=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let o=0;oe[o]);return[t,n]},E_=(e,r)=>{let t=e.length+r.length,s=[],n=0;for(let o=0;o{for(let t=0;t{let t=[];if(!P_(e,r)){for(let s=0;st.push(s))}return t},S_=(e,r,t,s,n,o,a)=>{let i=t[0].dims,l=we.size(o),c=we.size(a),p=Pe("_A",t[0].dataType,i),u=Qe("output",n,o),d=64;l===1&&(d=256);let f=` var aBestValues : array; `,_=P=>` ${P.registerUniform("reduceSize","u32").declareVariables(p,u)} ${f} fn DIV_CEIL(a : u32, b : u32) -> u32 { return ((a - 1u) / b + 1u); } ${P.mainStart(d)} let outputIndex = global_idx / ${d}; let offset = outputIndex * uniforms.reduceSize; var bestValue = f32(${y_[s]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${d}) { let candidate = f32(${p.getByOffset("offset + k")}); bestValue = ${M_[s]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); var reduceSize = min(Length, ${d}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 = ${b_[s]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; workgroupBarrier(); } if (local_idx == 0u) { ${u.setByOffset("outputIndex",`${s==="mean"?`${u.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${u.type.storage}(${v_[s]})`}`)}; } }`;return{name:e,shaderCache:{hint:`${r};${d}`,inputDependencies:["type"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:o,dataType:n}],dispatchGroup:{x:l},programUniforms:[{type:12,data:c}]})}},Jr=(e,r,t,s)=>{let n=e.inputs.length===1?t:Iu(e.inputs,t),o=n.axes;o.length===0&&!n.noopWithEmptyAxes&&(o=e.inputs[0].dims.map((f,_)=>_));let a=we.normalizeAxes(o,e.inputs[0].dims.length),i=a,l=e.inputs[0],c=C_(i,e.inputs[0].dims.length);c.length>0&&(l=e.compute(Fr(e.inputs[0],c),{inputs:[0],outputs:[-1]})[0],i=x_(i.length,l.dims.length));let[p,u]=T_(l.dims,i),d=p;n.keepDims&&(d=E_(p,a)),e.compute(S_(r,n.cacheKey,[l],s,e.inputs[0].dataType,d,u),{inputs:[l]})},cM=(e,r)=>{Jr(e,"ReduceMeanShared",r,"mean")},dM=(e,r)=>{Jr(e,"ReduceL1Shared",r,"l1")},pM=(e,r)=>{Jr(e,"ReduceL2Shared",r,"l2")},mM=(e,r)=>{Jr(e,"ReduceLogSumExpShared",r,"logSumExp")},hM=(e,r)=>{Jr(e,"ReduceMaxShared",r,"max")},_M=(e,r)=>{Jr(e,"ReduceMinShared",r,"min")},fM=(e,r)=>{Jr(e,"ReduceProdShared",r,"prod")},gM=(e,r)=>{Jr(e,"ReduceSumShared",r,"sum")},wM=(e,r)=>{Jr(e,"ReduceSumSquareShared",r,"sumSquare")},MM=(e,r)=>{Jr(e,"ReduceLogSumShared",r,"logSum")}}),Yr,$_,ia,Iu,Zr,k_,I_,A_,F_,O_,D_,L_,z_,B_,R_,es,bM,yM,vM,xM,TM,EM,PM,CM,SM,$M,sc=ze(()=>{at(),mt(),Kt(),ht(),qv(),Yr=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.")},$_=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],ia=(e,r,t,s,n,o,a=!1,i=!1)=>{let l=[],c=t[0].dims,p=c.length,u=we.normalizeAxes(n,p),d=!i&&u.length===0;c.forEach((P,I)=>{d||u.indexOf(I)>=0?a&&l.push(1):l.push(P)});let f=l.length,_=we.size(l);return{name:e,shaderCache:r,getShaderSource:P=>{let I=[],M=Pe("_A",t[0].dataType,p),g=Qe("output",o,f),S=s(M,g,u),E=S[2];for(let x=0,w=0;x=0?(a&&w++,E=`for(var j${x}: u32 = 0; j${x} < ${c[x]}; j${x}++) { ${S[2].includes("last_index")?`let last_index = j${x};`:""} ${M.indicesSet("input_indices",x,`j${x}`)} ${E} }`):(I.push(`${M.indicesSet("input_indices",x,g.indicesGet("output_indices",w))};`),w++);return` ${P.registerUniform("output_size","u32").declareVariables(M,g)} ${P.mainStart()} ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} var input_indices: ${M.type.indices}; let output_indices = ${g.offsetToIndices("global_idx")}; ${I.join(` `)} ${S[0]} // init ops for reduce max/min ${S[1]} ${E} ${S[3]} ${S.length===4?g.setByOffset("global_idx","value"):S.slice(4).join(` `)} }`},getRunData:()=>({outputs:[{dims:l,dataType:o}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...Ze(c,l)]})}},Iu=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),Pt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},Zr=(e,r,t,s)=>{let n=e.inputs,o=n.length===1?t:Iu(n,t);e.compute(ia(r,{hint:o.cacheKey,inputDependencies:["rank"]},[n[0]],o.noopWithEmptyAxes&&o.axes.length===0?$_:s,o.axes,n[0].dataType,o.keepDims,o.noopWithEmptyAxes),{inputs:[0]})},k_=(e,r)=>{Yr(e.inputs),Zr(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},I_=(e,r)=>{Yr(e.inputs),Zr(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},A_=(e,r)=>{Yr(e.inputs),Zr(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);"])},F_=(e,r)=>{Yr(e.inputs),Zr(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},O_=(e,r)=>{Yr(e.inputs),Zr(e,"ReduceMax",r,(t,s,n)=>{let o=[];for(let a=0;a=0||n.length===0)&&o.push(t.indicesSet("input_indices",a,0));return[`${o.join(` `)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},D_=(e,r)=>{Yr(e.inputs),Zr(e,"ReduceMean",r,(t,s,n)=>{let o=1;for(let a=0;a=0||n.length===0)&&(o*=e.inputs[0].dims[a]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${o});`]})},L_=(e,r)=>{Yr(e.inputs),Zr(e,"ReduceMin",r,(t,s,n)=>{let o=[];for(let a=0;a=0||n.length===0)&&o.push(`input_indices[${a}] = 0;`);return[`${o.join(` `)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},z_=(e,r)=>{Yr(e.inputs),Zr(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},B_=(e,r)=>{Yr(e.inputs),Zr(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},R_=(e,r)=>{Yr(e.inputs),Zr(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;`,""])},es=(e,r,t)=>{if(r.length===0)return t;let s=1,n=1;for(let o=0;o1024},bM=(e,r)=>{es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?D_(e,r):cM(e,r)},yM=(e,r)=>{es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?I_(e,r):dM(e,r)},vM=(e,r)=>{es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?A_(e,r):pM(e,r)},xM=(e,r)=>{es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?F_(e,r):mM(e,r)},TM=(e,r)=>{es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?O_(e,r):hM(e,r)},EM=(e,r)=>{es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?L_(e,r):_M(e,r)},PM=(e,r)=>{es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?z_(e,r):fM(e,r)},CM=(e,r)=>{es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?B_(e,r):gM(e,r)},SM=(e,r)=>{es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?R_(e,r):wM(e,r)},$M=(e,r)=>{es(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?k_(e,r):MM(e,r)}}),Gl,kM,IM,Au,Xv=ze(()=>{at(),Kt(),sc(),Gl=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.")},kM=(e,r)=>{Gl(e.inputs);let t=(s,n,o)=>{let a=[];for(let i=0;i=0||o.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.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(ia("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},IM=(e,r)=>{Gl(e.inputs);let t=(s,n,o)=>{let a=[];for(let i=0;i=0||o.length===0)&&a.push(`input_indices[${i}] = 0;`);return[`${a.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(ia("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Au=e=>Pt(e)}),N_,Gi,j_,V_,U_,qo,W_,AM,nc=ze(()=>{at(),mt(),tc(),ht(),N_=(e,r)=>{let t=e[0],s=e[1],n=e[2],o=e[3],a=e[4],i=e[5];if(a&&i)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 u=n.dims[0]/3,d=u,f=d;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let S of r.qkvHiddenSizes)if(S%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");u=r.qkvHiddenSizes[0],d=r.qkvHiddenSizes[1],f=r.qkvHiddenSizes[2]}let _=c;if(u!==d)throw new Error("qkv_hidden_sizes first element should be same as the second");if(n.dims[0]!==u+d+f)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let P=0;if(a){if(d!==f)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(a.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(a.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(a.dims[4]!==d/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(P=a.dims[3])}let I=_+P,M=-1,g=0;if(o)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");if(i){if(i.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(i.dims[0]!==l||i.dims[1]!==r.numHeads||i.dims[2]!==c||i.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:P,kvSequenceLength:_,totalSequenceLength:I,maxSequenceLength:M,inputHiddenSize:p,hiddenSize:u,vHiddenSize:f,headSize:Math.floor(u/r.numHeads),vHeadSize:Math.floor(f/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Gi=(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; `,j_=(e,r,t,s,n,o,a,i)=>{let l=Wt(a?1:o),c=64,p=o/l;p{let g=Qe("x",e.dataType,e.dims,l),S=[g],E=a?Pe("seq_lens",a.dataType,a.dims):void 0;E&&S.push(E);let x=i?Pe("total_sequence_length_input",i.dataType,i.dims):void 0;x&&S.push(x);let w=br(e.dataType),v=[{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; ${M.registerUniforms(v).declareVariables(...S)} ${M.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; ${Gi(E,x,!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 = ${a?"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] = ${g.type.value}(${w}(1.0) / ${w}(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] = ${g.type.value}(exp(f32input - max_value) / sum); } } ${a?` for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { x[offset + total_seq_id] = ${g.type.value}(${w}(0)); }`:""}; }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${c};${f};${l}`,inputDependencies:P},getShaderSource:I,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:n,z:r*t},programUniforms:d})}},V_=(e,r,t,s,n,o,a,i,l)=>{let c=a+o.kvSequenceLength,p=[o.batchSize,o.numHeads,o.sequenceLength,c],u=e>1&&s,d=o.kvNumHeads?o.kvNumHeads:o.numHeads,f=u?[o.batchSize,d,c,o.headSize]:void 0,_=o.nReps?o.nReps:1,P=o.scale===0?1/Math.sqrt(o.headSize):o.scale,I=Wt(o.headSize),M=o.headSize/I,g=12,S={x:Math.ceil(c/g),y:Math.ceil(o.sequenceLength/g),z:o.batchSize*o.numHeads},E=[{type:12,data:o.sequenceLength},{type:12,data:M},{type:12,data:c},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:1,data:P},{type:12,data:a},{type:12,data:o.kvSequenceLength},{type:12,data:_}],x=u&&s&&we.size(s.dims)>0,w=["type","type"];x&&w.push("type"),n&&w.push("type"),i&&w.push("type"),l&&w.push("type");let v=[{dims:p,dataType:r.dataType,gpuDataType:0}];u&&v.push({dims:f,dataType:r.dataType,gpuDataType:0});let $=O=>{let B=Pe("q",r.dataType,r.dims,I),H=Pe("key",t.dataType,t.dims,I),q=[B,H];if(x){let ce=Pe("past_key",s.dataType,s.dims,I);q.push(ce)}n&&q.push(Pe("attention_bias",n.dataType,n.dims));let L=i?Pe("seq_lens",i.dataType,i.dims):void 0;L&&q.push(L);let J=l?Pe("total_sequence_length_input",l.dataType,l.dims):void 0;J&&q.push(J);let X=Qe("output",r.dataType,p),Q=[X];u&&Q.push(Qe("present_key",r.dataType,f,I));let te=br(1,I),re=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${g}u; var tileQ: array<${B.type.storage}, ${g*g}>; var tileK: array<${B.type.storage}, ${g*g}>; ${O.registerUniforms(re).declareVariables(...q,...Q)} ${O.mainStart([g,g,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; ${Gi(L,J,!0)} let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; ${x&&u?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; ${u?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} var value = ${te}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; } if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${x&&u?` 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]; }`} ${u?`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 += ${te}(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:w},getRunData:()=>({outputs:v,dispatchGroup:S,programUniforms:E}),getShaderSource:$}},U_=(e,r,t,s,n,o,a=void 0,i=void 0)=>{let l=o+n.kvSequenceLength,c=n.nReps?n.nReps:1,p=n.vHiddenSize*c,u=e>1&&s,d=n.kvNumHeads?n.kvNumHeads:n.numHeads,f=u?[n.batchSize,d,l,n.headSize]:void 0,_=[n.batchSize,n.sequenceLength,p],P=12,I={x:Math.ceil(n.vHeadSize/P),y:Math.ceil(n.sequenceLength/P),z:n.batchSize*n.numHeads},M=[{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}],g=u&&s&&we.size(s.dims)>0,S=["type","type"];g&&S.push("type"),a&&S.push("type"),i&&S.push("type");let E=[{dims:_,dataType:r.dataType,gpuDataType:0}];u&&E.push({dims:f,dataType:r.dataType,gpuDataType:0});let x=w=>{let v=Pe("probs",r.dataType,r.dims),$=Pe("v",t.dataType,t.dims),O=[v,$];g&&O.push(Pe("past_value",s.dataType,s.dims));let B=a?Pe("seq_lens",a.dataType,a.dims):void 0;a&&O.push(B);let H=i?Pe("total_sequence_length_input",i.dataType,i.dims):void 0;i&&O.push(H);let q=[Qe("output",r.dataType,_)];u&&q.push(Qe("present_value",r.dataType,f));let L=[{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 = ${P}u; var tileQ: array<${v.type.value}, ${P*P}>; var tileV: array<${v.type.value}, ${P*P}>; ${w.registerUniforms(L).declareVariables(...O,...q)} ${w.mainStart([P,P,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; ${Gi(B,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 ${g&&u?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; ${u?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} var value = ${v.type.storage}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { var idx = TILE_SIZE * local_id.y + local_id.x; ${g&&u?` 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]; }`} ${u?` 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:S},getRunData:()=>({outputs:E,dispatchGroup:I,programUniforms:M}),getShaderSource:x}},qo=(e,r,t,s,n,o,a,i,l,c,p=void 0,u=void 0)=>{let d=Math.min(e.outputCount,1+(a?1:0)+(i?1:0)),f=d>1?c.pastSequenceLength:0,_=f+c.kvSequenceLength,P=l&&we.size(l.dims)>0?l:void 0,I=[r,t];d>1&&a&&we.size(a.dims)>0&&I.push(a),P&&I.push(P),p&&I.push(p),u&&I.push(u);let M=e.compute(V_(d,r,t,a,P,c,f,p,u),{inputs:I,outputs:d>1?[-1,1]:[-1]})[0];e.compute(j_(M,c.batchSize,c.numHeads,f,c.sequenceLength,_,p,u),{inputs:p&&u?[M,p,u]:[M],outputs:[]});let g=[M,s];d>1&&i&&we.size(i.dims)>0&&g.push(i),p&&g.push(p),u&&g.push(u),e.compute(U_(d,M,s,i,c,f,p,u),{inputs:g,outputs:d>1?[0,2]:[0]})},W_=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,n=r.inputHiddenSize,o=r.headSize,a=12,i={x:Math.ceil(r.headSize/a),y:Math.ceil(r.sequenceLength/a),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=u=>{let d=Qe("output_q",l[0].dataType,t),f=Qe("output_k",l[0].dataType,t),_=Qe("output_v",l[0].dataType,t),P=Pe("input",l[0].dataType,l[0].dims),I=Pe("weight",l[1].dataType,l[1].dims),M=Pe("bias",l[2].dataType,l[2].dims),g=P.type.storage,S=[{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 = ${a}u; var tileInput: array<${g}, ${a*a}>; var tileWeightQ: array<${g}, ${a*a}>; var tileWeightK: array<${g}, ${a*a}>; var tileWeightV: array<${g}, ${a*a}>; ${u.registerUniforms(S).declareVariables(P,I,M,d,f,_)} ${u.mainStart([a,a,1])} let batchIndex = workgroup_id.z / uniforms.num_heads; let headNumber = workgroup_id.z % uniforms.num_heads; let m = global_id.y; let n = global_id.x; let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; let biasOffsetQ = headNumber * uniforms.head_size; let biasOffsetK = uniforms.hidden_size + biasOffsetQ; let biasOffsetV = uniforms.hidden_size + biasOffsetK; var valueQ = ${g}(0); var valueK = ${g}(0); var valueV = ${g}(0); for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { if (m < uniforms.M && w + local_id.x < uniforms.K) { tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; } if (n < uniforms.N && w + local_id.y < uniforms.K) { let offset = n + (w + local_id.y) * uniforms.ldb; tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; } workgroupBarrier(); for (var k: u32 = 0u; k({outputs:[{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:i,programUniforms:c}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},AM=(e,r)=>{let t=N_(e.inputs,r),[s,n,o]=W_(e,t);return qo(e,s,n,o,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),G_,K_,H_,FM,Qv=ze(()=>{is(),at(),mt(),Kt(),ht(),G_=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,n,o)=>{let a=n.length;if(a!==s.length)throw new Error(`${o}: num dimensions != ${a}`);n.forEach((i,l)=>{if(i!==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")},K_=(e,r)=>{let{epsilon:t,spatial:s,format:n}=r,o=e[0].dims,a=s?Wt(o[o.length-1]):1,i=n==="NHWC"&&o.length>1?a:1,l=we.size(o)/a,c=s,p=c?o.length:o,u=Pe("x",e[0].dataType,e[0].dims,a),d=Pe("scale",e[1].dataType,e[1].dims,i),f=Pe("bias",e[2].dataType,e[2].dims,i),_=Pe("inputMean",e[3].dataType,e[3].dims,i),P=Pe("inputVar",e[4].dataType,e[4].dims,i),I=Qe("y",e[0].dataType,p,a),M=()=>{let S="";if(s)S=`let cOffset = ${o.length===1?"0u":n==="NHWC"?`outputIndices[${o.length-1}] / ${a}`:"outputIndices[1]"};`;else if(n==="NCHW")S=` ${I.indicesSet("outputIndices","0","0")} let cOffset = ${I.indicesToOffset("outputIndices")};`;else{S=`var cIndices = ${d.type.indices}(0); cIndices[0] = outputIndices[${o.length-1}];`;for(let E=1;E` const epsilon = ${t}; ${S.registerUniform("outputSize","u32").declareVariables(u,d,f,_,P,I)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${I.offsetToIndices(`global_idx * ${a}`)}; ${M()} let scale = ${d.getByOffset("cOffset")}; let bias = ${f.getByOffset("cOffset")}; let inputMean = ${_.getByOffset("cOffset")}; let inputVar = ${P.getByOffset("cOffset")}; let x = ${u.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}_${a}`,inputDependencies:c?["rank","type","type","type","type"]:void 0},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c?[{type:12,data:l},...Ze(o)]:[{type:12,data:l}]})}},H_=e=>Pt(e),FM=(e,r)=>{let{inputs:t,outputCount:s}=e,n=H_({...r,outputCount:s});if(Lt.webgpu.validateInputContent&&G_(t,n),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(K_(t,n))}}),q_,X_,OM,Jv=ze(()=>{mt(),ht(),q_=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")},X_=e=>{let r=e[0].dims,t=e[0].dims[2],s=we.size(r)/4,n=e[0].dataType,o=Pe("input",n,r,4),a=Pe("bias",n,[t],4),i=Pe("residual",n,r,4),l=Qe("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,a,i,l)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes(s)} let value = ${o.getByOffset("global_idx")} + ${a.getByOffset("global_idx % channels")} + ${i.getByOffset("global_idx")}; ${l.setByOffset("global_idx","value")} }`}},OM=e=>{q_(e.inputs),e.compute(X_(e.inputs))}}),Q_,xt,DM,LM,zM,BM,RM,NM,jM,VM,UM,J_,WM,GM,KM,HM,Uo,qM,ta,XM,QM,JM,YM,ZM,eb,tb,rb,sb,nb,ob,ib,ab,lb,ub,cb,Kl,db,Fu,Ou,pb,mb,hb,Y_,Z_,_b,oc=ze(()=>{at(),mt(),Kt(),ht(),Q_=(e,r,t,s,n,o,a)=>{let i=Math.ceil(r/4),l="";typeof n=="string"?l=`${n}(a)`:l=n("a");let c=Pe("inputData",t,[i],4),p=Qe("outputData",s,[i],4),u=[{name:"vec_size",type:"u32"}];return a&&u.push(...a),` ${e.registerUniforms(u).declareVariables(c,p)} ${o??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} let a = ${c.getByOffset("global_idx")}; ${p.setByOffset("global_idx",l)} }`},xt=(e,r,t,s,n,o=e.dataType,a,i)=>{let l=[{type:12,data:Math.ceil(we.size(e.dims)/4)}];return a&&l.push(...a),{name:r,shaderCache:{hint:n,inputDependencies:["type"]},getShaderSource:c=>Q_(c,we.size(e.dims),e.dataType,o,t,s,i),getRunData:c=>({outputs:[{dims:e.dims,dataType:o}],dispatchGroup:{x:Math.ceil(we.size(c[0].dims)/64/4)},programUniforms:l})}},DM=e=>{e.compute(xt(e.inputs[0],"Abs","abs"))},LM=e=>{e.compute(xt(e.inputs[0],"Acos","acos"))},zM=e=>{e.compute(xt(e.inputs[0],"Acosh","acosh"))},BM=e=>{e.compute(xt(e.inputs[0],"Asin","asin"))},RM=e=>{e.compute(xt(e.inputs[0],"Asinh","asinh"))},NM=e=>{e.compute(xt(e.inputs[0],"Atan","atan"))},jM=e=>{e.compute(xt(e.inputs[0],"Atanh","atanh"))},VM=e=>Pt(e),UM=(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(xt(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},J_=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 Pt({min:r,max:t})},WM=(e,r)=>{let t=r||J_(e.inputs),s=br(e.inputs[0].dataType);e.compute(xt(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]})},GM=e=>{e.compute(xt(e.inputs[0],"Ceil","ceil"))},KM=e=>{e.compute(xt(e.inputs[0],"Cos","cos"))},HM=e=>{e.compute(xt(e.inputs[0],"Cosh","cosh"))},Uo=e=>Pt(e),qM=(e,r)=>{let t=br(e.inputs[0].dataType);e.compute(xt(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))},ta=(e="f32")=>` const r0: ${e} = 0.3275911; const r1: ${e} = 0.254829592; const r2: ${e} = -0.284496736; const r3: ${e} = 1.421413741; const r4: ${e} = -1.453152027; const r5: ${e} = 1.061405429; fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> { let absv = abs(v); let x = 1.0 / (1.0 + r0 * absv); return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); }`,XM=e=>{let r=br(e.inputs[0].dataType);e.compute(xt(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,ta(r)))},QM=e=>{e.compute(xt(e.inputs[0],"Exp","exp"))},JM=e=>{e.compute(xt(e.inputs[0],"Floor","floor"))},YM=e=>{let r=br(e.inputs[0].dataType);e.compute(xt(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,ta(r)))},ZM=(e,r)=>{let t=br(e.inputs[0].dataType);e.compute(xt(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))},eb=e=>{e.compute(xt(e.inputs[0],"Not",r=>`!${r}`))},tb=e=>{e.compute(xt(e.inputs[0],"Neg",r=>`-${r}`))},rb=e=>{e.compute(xt(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},sb=e=>{let r=br(e.inputs[0].dataType);e.compute(xt(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},nb=e=>{e.compute(xt(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},ob=e=>Pt(e),ib=(e,r)=>{let t=br(e.inputs[0].dataType);e.compute(xt(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))},ab=e=>{e.compute(xt(e.inputs[0],"Sin","sin"))},lb=e=>{e.compute(xt(e.inputs[0],"Sinh","sinh"))},ub=e=>{e.compute(xt(e.inputs[0],"Sqrt","sqrt"))},cb=e=>{e.compute(xt(e.inputs[0],"Tan","tan"))},Kl=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,db=e=>{e.compute(xt(e.inputs[0],"Tanh",Kl))},Fu=(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 ${Kl("v")}; } `,Ou=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,pb=e=>{let r=br(e.inputs[0].dataType);e.compute(xt(e.inputs[0],"FastGelu",Ou,Fu(r),void 0,e.inputs[0].dataType))},mb=(e,r)=>{let t=br(e.inputs[0].dataType);return e.compute(xt(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},hb=e=>{e.compute(xt(e.inputs[0],"Log","log"))},Y_=(e,r)=>` const alpha = vec4<${e}>(${r}); const one = ${e}(1.0); const zero = ${e}(0.0); fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { let v = x *alpha; var x1 : vec4<${e}>; for (var i = 0; i < 4; i = i + 1) { if (v[i] >= zero) { x1[i] = one / (one + exp(-v[i])); } else { x1[i] = one - one / (one + exp(v[i])); } } return x * x1; } `,Z_=e=>`quick_gelu_impl(${e})`,_b=(e,r)=>{let t=br(e.inputs[0].dataType);e.compute(xt(e.inputs[0],"QuickGelu",Z_,Y_(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),ef,tf,fb,Yv=ze(()=>{mt(),ht(),oc(),ef=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")},tf=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=Pe("input",e[0].dataType,e[0].dims,4),s=Pe("bias",e[0].dataType,[e[0].dims[2]],4),n=Qe("output",e[0].dataType,r,4),o=we.size(r)/4,a=hr(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:i=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${i.declareVariables(t,s,n)} ${ta(a)} ${i.mainStart()} ${i.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")} }`}},fb=e=>{ef(e.inputs),e.compute(tf(e.inputs))}}),rf,sf,ts,gb,wb,Mb,bb,yb,vb,xb,Tb,Eb,Pb,Zv=ze(()=>{at(),mt(),ht(),rf=(e,r,t,s,n,o,a,i,l,c,p,u)=>{let d,f;typeof i=="string"?d=f=(g,S)=>`${i}((${g}),(${S}))`:typeof i=="function"?d=f=i:(d=i.scalar,f=i.vector);let _=Qe("outputData",p,s.length,4),P=Pe("aData",l,r.length,4),I=Pe("bData",c,t.length,4),M;if(n)if(o){let g=we.size(r)===1,S=we.size(t)===1,E=r.length>0&&r[r.length-1]%4===0,x=t.length>0&&t[t.length-1]%4===0;g||S?M=_.setByOffset("global_idx",f(g?`${P.type.value}(${P.getByOffset("0")}.x)`:P.getByOffset("global_idx"),S?`${I.type.value}(${I.getByOffset("0")}.x)`:I.getByOffset("global_idx"))):M=` let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; let offsetA = ${P.broadcastedIndicesToOffset("outputIndices",_)}; let offsetB = ${I.broadcastedIndicesToOffset("outputIndices",_)}; ${_.setByOffset("global_idx",f(a||E?P.getByOffset("offsetA / 4u"):`${P.type.value}(${P.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||x?I.getByOffset("offsetB / 4u"):`${I.type.value}(${I.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} `}else M=_.setByOffset("global_idx",f(P.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 g=(S,E,x="")=>{let w=`aData[indexA${E}][componentA${E}]`,v=`bData[indexB${E}][componentB${E}]`;return` let outputIndices${E} = ${_.offsetToIndices(`global_idx * 4u + ${E}u`)}; let offsetA${E} = ${P.broadcastedIndicesToOffset(`outputIndices${E}`,_)}; let offsetB${E} = ${I.broadcastedIndicesToOffset(`outputIndices${E}`,_)}; let indexA${E} = offsetA${E} / 4u; let indexB${E} = offsetB${E} / 4u; let componentA${E} = offsetA${E} % 4u; let componentB${E} = offsetB${E} % 4u; ${S}[${E}] = ${x}(${d(w,v)}); `};p===9?M=` var data = vec4(0); ${g("data",0,"u32")} ${g("data",1,"u32")} ${g("data",2,"u32")} ${g("data",3,"u32")} outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:M=` ${g("outputData[global_idx]",0)} ${g("outputData[global_idx]",1)} ${g("outputData[global_idx]",2)} ${g("outputData[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(P,I,_)} ${u??""} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${M} }`},sf=(e,r,t,s,n,o,a=t.dataType)=>{let i=t.dims.map(P=>Number(P)??1),l=s.dims.map(P=>Number(P)??1),c=!we.areEqual(i,l),p=i,u=we.size(i),d=!1,f=!1,_=[c];if(c){let P=ro.calcShape(i,l,!1);if(!P)throw new Error("Can't perform binary op on the given tensors");p=P.slice(),u=we.size(p);let I=we.size(i)===1,M=we.size(l)===1,g=i.length>0&&i[i.length-1]%4===0,S=l.length>0&&l[l.length-1]%4===0;_.push(I),_.push(M),_.push(g),_.push(S);let E=1;for(let x=1;xP.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:P=>rf(P,i,l,p,d,c,f,n,t.dataType,s.dataType,a,o),getRunData:()=>({outputs:[{dims:p,dataType:a}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(we.size(p)/4)},...Ze(i,l,p)]})}},ts=(e,r,t,s,n,o)=>{e.compute(sf(r,n??"",e.inputs[0],e.inputs[1],t,s,o))},gb=e=>{ts(e,"Add",(r,t)=>`${r}+${t}`)},wb=e=>{ts(e,"Div",(r,t)=>`${r}/${t}`)},Mb=e=>{ts(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},bb=e=>{ts(e,"Mul",(r,t)=>`${r}*${t}`)},yb=e=>{let r=Pe("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;ts(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)); } `)},vb=e=>{ts(e,"Sub",(r,t)=>`${r}-${t}`)},xb=e=>{ts(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},Tb=e=>{ts(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},Eb=e=>{ts(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},Pb=e=>{ts(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),nf,of,af,lf,Cb,Sb,ex=ze(()=>{at(),mt(),Kt(),ht(),nf=(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((a,i)=>{if(i!==t){if(a.dataType!==n)throw new Error("input tensors should be one type");if(a.dims.length!==o)throw new Error("input tensors should have the same shape");a.dims.forEach((l,c)=>{if(c!==r&&l!==s.dims[c])throw new Error("non concat dimensions must match")})}})},of=(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; }`,af=(e,r)=>{let t=e.length,s=[];for(let n=0;n{let n=we.size(t),o=new Array(e.length),a=new Array(e.length),i=0,l=[],c=[],p=[{type:12,data:n}];for(let P=0;P`uniforms.sizeInConcatAxis${P}`).join(","),_=P=>` ${(()=>{P.registerUniform("outputSize","u32");for(let I=0;I(${f}); ${d} -= sizeInConcatAxis[inputIndex - 1u]; } ${af(a,u)} }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}),getShaderSource:_}},Cb=(e,r)=>{let t=e.inputs,s=t[0].dims,n=we.normalizeAxis(r.axis,s.length);nf(t,n);let o=s.slice();o[n]=t.reduce((i,l)=>i+(l.dims.length>n?l.dims[n]:0),0);let a=t.filter(i=>we.size(i.dims)>0);e.compute(lf(a,n,o,t[0].dataType),{inputs:a})},Sb=e=>Pt({axis:e.axis})}),bn,yn,vn,ic,Tn=ze(()=>{at(),mt(),bn=(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}`)}},yn=(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})},vn=(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"})},ic=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||[eM,tM];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}}}),wr,$b,ac=ze(()=>{wr=(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.`)}},$b=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} `}),kb,tx=ze(()=>{kb=e=>` fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { return dot(coords, vec4( shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); } fn getOutputIndexFromCoords(coords : vec4) -> i32 { return dot(coords, vec4( i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); } `}),Go,lc,uc=ze(()=>{at(),mt(),ht(),Tn(),Go=(e,r,t,s,n)=>{let o=s-t;return` ${Array.from({length:t}).map((a,i)=>` if (${Je(r.shape,i,r.rank)} != 1) { ${r.indicesSet(e,i,Je(n,i+o,s))} } else { ${r.indicesSet(e,i,0)} }`).join("")} `},lc=(e,r,t,s,n=!1,o)=>{let a=e[0].dims,i=e[1].dims,l=a[a.length-2],c=i[i.length-1],p=a[a.length-1],u=Wt(c),d=Wt(p),f=Wt(l),_=we.size(t)/u/f,P=e.length>2,I=s?s.slice(0,-2):t.slice(0,-2),M=[we.size(I),l,c],g=[{type:12,data:_},{type:12,data:l},{type:12,data:c},{type:12,data:p}];yn(r,g),g.push(...Ze(I,a,i)),P&&g.push(...Ze(e[2].dims)),g.push(...Ze(M));let S=E=>{let x=rc("batch_dims",e[0].dataType,I.length),w=Pe("a",e[0].dataType,a.length,d),v=Pe("b",e[1].dataType,i.length,u),$=Qe("output",e[0].dataType,M.length,u),O=hr($.type.tensor),B=bn(r,$.type.value,O),H=[w,v],q="";if(P){let X=n?u:1;H.push(Pe("bias",e[2].dataType,e[2].dims.length,X)),q=`${n?`value += bias[col / ${X}];`:`value += ${$.type.value}(bias[row + i]);`}`}let L=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];vn(r,L);let J=()=>{let X=`var a_data: ${w.type.value};`;for(let Q=0;Q; for (var k: u32 = 0u; k < uniforms.K; k = k + ${d}) { ${J()} } for (var i = 0u; i < ${f}u; i++) { var value = values[i]; ${q} ${B} let cur_indices = ${$.type.indices}(batch, row + i, col); let offset = ${$.indicesToOffset("cur_indices")}; ${$.setByOffset(`offset / ${u}`,"value")}; } } `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${u};${d};${f};${n}`,inputDependencies:P?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:o?o(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:g}),getShaderSource:S}}}),uf,cf,Du,Hl,df,Lu,pf,aa,cc=ze(()=>{at(),mt(),ht(),Tn(),uc(),ac(),uf=(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":""}); `,cf=(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];"} }`,Du=(e,r,t="f32",s,n=!1,o=32,a=!1,i=32)=>{let l=r[1]*e[1],c=r[0]*e[0],p=n?l:o,u=n?o:l,d=p/r[0],f=o/r[1];if(!((n&&d===4&&e[1]===4||!n&&(d===3||d===4))&&p%r[0]===0&&o%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${n} is true, innerElementSize ${d} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${d} 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/d}>, ${u}>; var mm_Bsub: array, ${c/e[0]}>, ${o}>; const rowPerThread = ${e[1]}; const colPerThread = ${e[0]}; const innerElementSize = ${d}; 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 = ${a?"0":"i32(globalId.z)"}; ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} let globalRowStart = i32(workgroupId.y) * ${l}; let num_tiles = ${a?`${Math.ceil(i/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${a?`i32(globalId.z) * ${i}`:"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; ${uf(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]; ${d===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} ${cf(n,d)} } workgroupBarrier(); } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } }`},Hl=(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":""}); `,df=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Lu=(e,r,t="f32",s,n=!1,o=32,a=!1,i=32,l=!1)=>{let c=e[1]*r[1],p=e[0]*r[0],u=n?c:o,d=n?o:c;if(!(d%r[1]===0&&u%r[0]===0&&o%r[1]===0))throw new Error(`tileAHight ${d} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${r[0]}, tileInner ${o} must be divisible by workgroupSize[1]${r[1]}`);let f=d/r[1],_=u/r[0],P=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 < ${d}; inputRow = inputRow + ${r[1]}) { for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${r[0]}) { ${Hl(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) * ${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 innerRow = 0; innerRow < ${f}; innerRow = innerRow + 1) { for (var innerCol = 0; innerCol < ${_}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; ${Hl(n,s)} } } // Load one tile of B into local memory. for (var innerRow = 0; innerRow < ${P}; 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) { ${df(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, ${d}>; 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 = ${a?"0":"i32(globalId.z)"}; ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} let num_tiles = ${a?`${Math.ceil(i/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; var kStart = ${a?`i32(globalId.z) * ${i}`:"0"}; var acc : array, rowPerThread>; ${I} } `},pf=(e,r,t,s,n=!1)=>{let[o,a,i,l]=s,c=hr(s[0].type.tensor);return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${o.type.indices}) -> ${wr(e,c)} { var value = ${wr(e,c)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { var aIndices: ${a.type.indices}; ${Go("aIndices",a,a.rank-2,o.rank,"batchIndices")} ${a.indicesSet("aIndices",a.rank-2,"u32(row)")} ${a.indicesSet("aIndices",a.rank-1,"u32(colIn)")} value = ${a.getByIndices("aIndices")}; } return value; } fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${o.type.indices}) -> ${wr(e,c)} { var value = ${wr(e,c)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { var bIndices: ${i.type.indices}; ${Go("bIndices",i,i.rank-2,o.rank,"batchIndices")} ${i.indicesSet("bIndices",i.rank-2,"u32(row)")} ${i.indicesSet("bIndices",i.rank-1,"u32(colIn)")} value = ${i.getByIndices("bIndices")}; } return value; } fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${wr(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]":`${wr(e,c)}(bias[row])`};`:""} ${t} ${l.setByIndices("vec3(coords)","value")} } } `},aa=(e,r,t,s,n=!1,o)=>{let a=e[0].dims,i=e[1].dims,l=a.slice(0,-2),c=i.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),u=we.size(p),d=a[a.length-2],f=a[a.length-1],_=i[i.length-1],P=f%4===0&&_%4===0,I=d<=8?[4,1,1]:[4,4,1],M=[8,8,1],g=[Math.ceil(_/M[0]/I[0]),Math.ceil(d/M[1]/I[1]),Math.ceil(u/M[2]/I[2])],S=P?4:1,E=[...l,d,f/S],x=E.length,w=[...c,f,_/S],v=w.length,$=[u,d,_/S],O=[{type:6,data:d},{type:6,data:_},{type:6,data:f}];yn(r,O),O.push(...Ze(p,E,w));let B=["rank","rank"],H=e.length>2;H&&(O.push(...Ze(e[2].dims)),B.push("rank")),O.push(...Ze($));let q=L=>{let J=p.length,X=rc("batchDims",e[0].dataType,J,1),Q=hr(e[0].dataType),te=Pe("a",e[0].dataType,x,S),re=Pe("b",e[1].dataType,v,S),ce=Qe("result",e[0].dataType,$.length,S),le=[te,re];if(H){let ne=n?S:1;le.push(Pe("bias",e[2].dataType,e[2].dims.length,ne))}let N=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];vn(r,N);let F=hr(ce.type.tensor),G=bn(r,ce.type.value,F),R=pf(S,H,G,[X,te,re,ce],n);return` ${L.registerUniforms(N).registerInternalVariables(X).declareVariables(...le,ce)} ${R} ${P?Du(I,M,Q,X):Lu(I,M,Q,X)} `};return{name:"MatMul",shaderCache:{hint:`${I};${r.activation};${P};${n}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:o?o(t):t,dataType:e[0].dataType}],dispatchGroup:{x:g[0],y:g[1],z:g[2]},programUniforms:O}),getShaderSource:q}}}),mf,Ib,rx=ze(()=>{at(),Ss(),ht(),Tn(),ac(),tx(),cc(),mf=(e,r,t,s,n=!1,o,a=4,i=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.`)}},u=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.`)}},d=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])",P=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",I=e?"row":"col",M=e?"col":"row",g=` let inChannels = i32(uniforms.w_shape[2]); let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; let outRow = ${I} / outWidth; let outCol = ${I} % outWidth; let WRow = ${M} / (i32(uniforms.w_shape[1]) * inChannels); let WCol = ${M} / 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 = ${M} % inChannels; var resData = ${wr(a,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 < ${P}) { ${d} let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); ${p(a)} } return resData;`,S=e?r&&s?` let col = colIn * ${a}; ${g}`:` let col = colIn * ${a}; if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { ${g} } return ${wr(a,c)}(0.0);`:s&&t?` let col = colIn * ${a}; ${g}`:` let col = colIn * ${a}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${g} } return ${wr(a,c)}(0.0);`,E=e?s&&t?u(i):` let col = colIn * ${i}; if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { ${u(i)} } return ${wr(i,c)}(0.0);`:` let col = colIn * ${i}; if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { ${u(i)} } return ${wr(i,c)}(0.0);`,x=wr(l,c),w=wr(e?a:i,c),v=wr(e?i:a,c),$=bn(o,x,c);return` fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${w} { ${e?S:E} } fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${v} { ${e?E:S} } fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${x}) { 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} ${$b(n)} ${$} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } }`},Ib=(e,r,t,s,n,o,a,i,l)=>{let c=r.format==="NHWC",p=c?e[0].dims[3]:e[0].dims[1],u=t[0],d=c?t[2]:t[3],f=c?t[1]:t[2],_=c?t[3]:t[1],P=c&&(p%4===0||p%3===0)&&_%4===0,I=c?_:d*f,M=c?d*f:_,g=[8,8,1],S=s<=8?[4,1,1]:[4,4,1],E=[Math.ceil(I/g[0]/S[0]),Math.ceil(M/g[1]/S[1]),Math.ceil(u/g[2]/S[2])];yt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let x=P?c&&p%4!==0?3:4:1,w=g[1]*S[1],v=g[0]*S[0],$=Math.max(g[0]*x,g[1]),O=s%w===0,B=n%v===0,H=o%$===0,q=P?[x,4,4]:[1,1,1],L=[{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}];yn(r,L),L.push(...Ze(e[0].dims,e[1].dims));let J=["rank","rank"];a&&(L.push(...Ze(e[2].dims)),J.push("rank")),L.push(...Ze(t));let X=Q=>{let te=[{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}];vn(r,te);let re=P?4:1,ce=hr(e[0].dataType),le=` fn setOutputAtIndex(flatIndex : i32, value : ${P?`vec4<${ce}>`:ce}) { result[flatIndex] = ${P?`vec4<${ce}>`:ce}(value); } fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${P?`vec4<${ce}>`:ce}) { let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); setOutputAtIndex(flatIndex ${P?"/ 4":""}, value); }`,N=Pe("x",e[0].dataType,e[0].dims.length,x===3?1:x),F=Pe("w",e[1].dataType,e[1].dims.length,re),G=[N,F],R=Qe("result",e[0].dataType,t.length,re);if(a){let ne=Pe("bias",e[2].dataType,e[2].dims.length,re);G.push(ne),le+=` fn getBiasByOutputCoords(coords : vec4) -> ${P?`vec4<${ce}>`:ce} { return bias[coords.${c?"w":"y"}${P?"/ 4":""}]; }`}return` ${kb("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 }; ${Q.registerUniforms(te).declareVariables(...G,R)} ${le} ${mf(c,O,B,H,a,r,q[0],q[1],q[2],ce)} ${P?Du(S,g,ce,void 0,!c,$):Lu(S,g,ce,void 0,!c,$,!1,void 0,i)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${x};${P};${O};${B};${H};${w};${v};${$}`,inputDependencies:J},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:L}),getShaderSource:X}}}),hf,ql,Do,_f,Xl,ff,Ab,Fb,sx=ze(()=>{at(),Ss(),mt(),ht(),Tn(),ac(),hf=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,Do=(e,r)=>r<=1?e:e+(e-1)*(r-1),_f=(e,r,t,s=1)=>{let n=Do(r,s);return Math.floor((e[0]*(t-1)-t+n)/2)},Xl=(e,r,t,s,n)=>{n==null&&(n=_f(e,r[0],s[0]));let o=[0,0,0,t];for(let a=0;a<3;a++)e[a]+2*n>=r[a]&&(o[a]=Math.trunc((e[a]-r[a]+2*n)/s[a]+1));return o},ff=(e,r,t,s,n,o,a,i,l,c)=>{let p,u,d,f;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let _=Xl([r,t,s,1],[i,l,c],1,[n,o,a],e);u=_[0],d=_[1],f=_[2]}else if(Array.isArray(e)){if(!e.every((P,I,M)=>P===M[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 _=Xl([r,t,s,1],[i,l,c],1,[n,o,a],e[0]);u=_[0],d=_[1],f=_[2]}else if(e==="SAME_UPPER"){u=Math.ceil(r/n),d=Math.ceil(t/o),f=Math.ceil(s/a);let _=(u-1)*n+i-r,P=(d-1)*o+l-t,I=(f-1)*a+c-s,M=Math.floor(_/2),g=_-M,S=Math.floor(P/2),E=P-S,x=Math.floor(I/2),w=I-x;p={top:S,bottom:E,left:x,right:w,front:M,back:g}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:u,outHeight:d,outWidth:f}},Ab=(e,r,t,s,n,o=!1,a="channelsLast")=>{let i,l,c,p,u;if(a==="channelsLast")[i,l,c,p,u]=e;else if(a==="channelsFirst")[i,u,l,c,p]=e;else throw new Error(`Unknown dataFormat ${a}`);let[d,,f,_,P]=r,[I,M,g]=ql(t),[S,E,x]=ql(s),w=Do(f,S),v=Do(_,E),$=Do(P,x),{padInfo:O,outDepth:B,outHeight:H,outWidth:q}=ff(n,l,c,p,I,M,g,w,v,$),L=o?d*u:d,J=[0,0,0,0,0];return a==="channelsFirst"?J=[i,L,B,H,q]:a==="channelsLast"&&(J=[i,B,H,q,L]),{batchSize:i,dataFormat:a,inDepth:l,inHeight:c,inWidth:p,inChannels:u,outDepth:B,outHeight:H,outWidth:q,outChannels:L,padInfo:O,strideDepth:I,strideHeight:M,strideWidth:g,filterDepth:f,filterHeight:_,filterWidth:P,effectiveFilterDepth:w,effectiveFilterHeight:v,effectiveFilterWidth:$,dilationDepth:S,dilationHeight:E,dilationWidth:x,inShape:e,outShape:J,filterShape:r}},Fb=(e,r,t,s,n,o)=>{let a=o==="channelsLast";a?e[0].dims[3]:e[0].dims[1];let i=[64,1,1],l={x:t.map((I,M)=>M)},c=[Math.ceil(hf(l.x.map(I=>t[I]))/i[0]),1,1];yt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${c}`);let p=1,u=we.size(t),d=[{type:12,data:u},{type:12,data:s},{type:12,data:n},{type:12,data:r.strides},{type:12,data:r.dilations}];yn(r,d),d.push(...Ze(e[0].dims,e[1].dims));let f=["rank","rank"],_=e.length===3;_&&(d.push(...Ze(e[2].dims)),f.push("rank")),d.push(...Ze(t));let P=I=>{let M=[{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}];vn(r,M);let g=1,S=hr(e[0].dataType),E=Pe("x",e[0].dataType,e[0].dims.length,p),x=Pe("W",e[1].dataType,e[1].dims.length,g),w=[E,x],v=Qe("result",e[0].dataType,t.length,g),$="";if(_){let H=Pe("bias",e[2].dataType,e[2].dims.length,g);w.push(H),$+=` fn getBiasByOutputCoords(coords : array) -> ${S} { return bias[${a?Je("coords",4,5):Je("coords",1,5)}]; }`}let O=wr(p,S),B=bn(r,O,S);return` ${$} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${E.getByIndices("aIndices")}; } fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${x.getByIndices("aIndices")}; } ${I.registerUniforms(M).declareVariables(...w,v)} ${I.mainStart()} ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let coords = ${v.offsetToIndices("global_idx")}; let batch = ${Je("coords",0,E.rank)}; let d2 = ${a?Je("coords",E.rank-1,E.rank):Je("coords",1,E.rank)}; let xFRCCorner = vec3(${a?Je("coords",1,E.rank):Je("coords",2,E.rank)}, ${a?Je("coords",2,E.rank):Je("coords",3,E.rank)}, ${a?Je("coords",3,E.rank):Je("coords",4,E.rank)}) * uniforms.strides - uniforms.pads; let xFCorner = xFRCCorner.x; let xRCorner = xFRCCorner.y; let xCCorner = xFRCCorner.z; let xShapeY = ${a?Je("uniforms.x_shape",1,E.rank):Je("uniforms.x_shape",2,E.rank)}; let xShapeZ = ${a?Je("uniforms.x_shape",2,E.rank):Je("uniforms.x_shape",3,E.rank)}; let xShapeW = ${a?Je("uniforms.x_shape",3,E.rank):Je("uniforms.x_shape",4,E.rank)}; let xShapeU = ${a?Je("uniforms.x_shape",4,E.rank):Je("uniforms.x_shape",1,E.rank)}; let inputDepthNearestVec4 = (xShapeU / 4) * 4; let inputDepthVec4Remainder = xShapeU % 4; var value = 0.0; for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { let xF = xFCorner + wF * uniforms.dilations[0]; if (xF < 0 || xF >= xShapeY) { continue; } for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { let xR = xRCorner + wR * uniforms.dilations[1]; if (xR < 0 || xR >= xShapeZ) { continue; } for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { let xC = xCCorner + wC * uniforms.dilations[2]; if (xC < 0 || xC >= xShapeW) { continue; } for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { ${a?`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) { ${a?`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) { ${a?`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) { ${a?`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)":""}; ${B} result[global_idx] = f32(value); }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${a};${p};${_}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:c[0],y:c[1],z:c[2]},programUniforms:d}),getShaderSource:P}}}),Ob,Db,nx=ze(()=>{at(),mt(),ht(),Tn(),Ob=(e,r,t,s)=>{let n=e.length>2,o=n?"value += b[output_channel];":"",a=e[0].dims,i=e[1].dims,l=r.format==="NHWC",c=l?t[3]:t[1],p=c/r.group,u=l&&p>=4?Wt(c):1,d=we.size(t)/u,f=[{type:12,data:d},{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}];yn(r,f),f.push(...Ze(a,[i[0],i[1],i[2],i[3]/u]));let _=n?["rank","rank","rank"]:["rank","rank"];f.push(...Ze([t[0],t[1],t[2],t[3]/u]));let P=I=>{let M=Qe("output",e[0].dataType,t.length,u),g=hr(M.type.tensor),S=bn(r,M.type.value,g),E=Pe("x",e[0].dataType,a.length),x=Pe("w",e[1].dataType,i.length,u),w=[E,x];n&&w.push(Pe("b",e[2].dataType,e[2].dims,u));let v=[{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"}];vn(r,v);let $=l?` for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { continue; } for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; let xVal = ${E.get("batch","xHeight","xWidth","input_channel")}; let wVal = ${x.get("wHeight","wWidth","wInChannel","output_channel")}; value += xVal * wVal; } } } `:` for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { let input_channel = in_channel_offset + wInChannel; for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { continue; } for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { continue; } let xVal = ${E.get("batch","input_channel","xHeight","xWidth")}; let wVal = ${x.get("output_channel","wInChannel","wHeight","wWidth")}; value += xVal * wVal; } } } `;return` ${I.registerUniforms(v).declareVariables(...w,M)} ${I.mainStart()} ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${M.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 * ${u} / uniforms.output_channels_per_group; var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}]; var value: ${M.type.value} = ${M.type.value}(0); ${$} ${o} ${S} ${M.setByOffset("global_idx","value")} }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${u}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:f}),getShaderSource:P}},Db=(e,r,t,s)=>{let n=e.length>2,o=Wt(t[3]),a=Wt(t[2]),i=we.size(t)/o/a,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],u=[{type:12,data:i},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];yn(r,u),u.push(...Ze(l,c,p));let d=(a-1)*r.strides[1]+c[1],f=_=>{let P=Qe("output",e[0].dataType,p.length,o),I=hr(P.type.tensor),M=bn(r,P.type.value,I),g=Pe("x",e[0].dataType,l.length,o),S=Pe("w",e[1].dataType,c.length,o),E=[g,S];n&&E.push(Pe("b",e[2].dataType,e[2].dims,o));let x=n?"value += b[output_channel];":"",w=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return vn(r,w),` ${_.registerUniforms(w).declareVariables(...E,P)} ${_.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] / ${a}u; let col = (index1 % width1) * ${a}u; index1 = index1 / width1; let row = index1 % uniforms.output_shape[1]; let batch = index1 / uniforms.output_shape[1]; let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; var x_vals: array<${g.type.value}, ${d}>; var values: array<${P.type.value}, ${a}>; 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 < ${d}; i++) { let x_width = x_corner.y + i; if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { x_vals[i] = ${g.get("batch","u32(x_height)","u32(x_width)","input_channel")}; } else { x_vals[i] = ${g.type.value}(0); } } for (var w_width: u32 = 0u; w_width < ${c[1]}; w_width++) { let w_val = ${S.get("w_height","w_width","0","output_channel")}; for (var i = 0u; i < ${a}u; i++) { values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); } } } } for (var i = 0u; i < ${a}u; i++) { var value = values[i]; ${x} ${M} ${P.set("batch","row","col + i","output_channel","value")}; } }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${o};${a};${d};${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(i/64)},programUniforms:u}),getShaderSource:f}}}),gf,Ki,wf,Hi,zu,Ql,Mf,bf,Bu,ox=ze(()=>{mt(),rx(),sx(),cc(),nx(),Tn(),uc(),Gs(),gf=(e,r,t,s,n,o)=>{let a=e[0],i=e.slice(o?1:2,o?3:4),l=i.length,c=r[0],p=r.slice(2).map((d,f)=>d+(d-1)*(t[f]-1)),u=i.map((d,f)=>d+s[f]+s[f+l]).map((d,f)=>Math.floor((d-p[f]+n[f])/n[f]));return u.splice(0,0,a),u.splice(o?3:1,0,c),u},Ki=[2,3,1,0],wf=(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")},Hi=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=ic(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],n=e.dilations,o=e.group,a=e.kernel_shape,i=e.pads,l=e.strides,c=e.w_is_const();return{autoPad:s,format:t,dilations:n,group:o,kernelShape:a,pads:i,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},Ql=(e,r,t,s)=>{let n=t.format==="NHWC",o=gf(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,n);if(t.group!==1){let w=[r[0]];if(n){let v=e.kernelCustomData.wT??e.compute(Fr(r[1],Ki),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=v),w.push(v)}else w.push(r[1]);r.length===3&&w.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(Db(w,t,o,s),{inputs:w}):e.compute(Ob(w,t,o,s),{inputs:w});return}let a=r.length===3,i=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],u=r[1].dims[3],d=o[n?1:2],f=o[n?2:3],_=o[n?3:1],P=n&&p===i&&u===l&&t.pads[0]===0&&t.pads[1]===0;if(P||p===1&&u===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 w=o[0],v,$,O,B=[];if(n){let L=e.kernelCustomData.wT??e.compute(Fr(r[1],Ki),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=L),P){let J=i*l*c;v=r[0].reshape([1,w,J]),$=L.reshape([1,J,_]),O=[1,w,_]}else v=r[0].reshape([w,i*l,c]),$=L.reshape([1,c,_]),O=[w,d*f,_];B.push(v),B.push($)}else v=r[0].reshape([w,c,i*l]),$=r[1].reshape([1,_,c]),O=[w,_,d*f],B.push($),B.push(v);a&&B.push(r[2]);let H=O[2],q=B[0].dims[B[0].dims.length-1];H<8&&q<8?e.compute(lc(B,t,o,O,n,s),{inputs:B}):e.compute(aa(B,t,o,O,n,s),{inputs:B});return}let I=!0,M=e.kernelCustomData.wT??e.compute(Fr(r[1],Ki),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=M);let g=[r[0],M];a&&g.push(r[2]);let S=n?d*f:_,E=n?_:d*f,x=p*u*c;e.compute(Ib(g,t,o,S,E,x,a,I,s),{inputs:g})},Mf=(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),a=[1].concat(r.dilations),i=[1].concat(r.kernelShape),l=Hi({...r,pads:n,strides:o,dilations:a,kernelShape:i},s);Ql(e,s,l,c=>t?[c[0],c[2],c[3]]:[c[0],c[1],c[3]])},bf=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",n=Hi(t,r),o=t.autoPad==="NOTSET"?t.pads:t.autoPad,a=Ab(r[0].dims,r[1].dims,t.strides,t.dilations,o,!1,s);e.compute(Fb(r,n,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],s))},Bu=(e,r)=>{if(wf(e.inputs,r),e.inputs[0].dims.length===3)Mf(e,r);else if(e.inputs[0].dims.length===5)bf(e,e.inputs,r);else{let t=Hi(r,e.inputs);Ql(e,e.inputs,t)}}}),Lb,ix=ze(()=>{at(),Ss(),mt(),ht(),Lb=(e,r,t)=>{let s=e.length>2,n=r.outputShape,o=r.format==="NHWC",a=r.group,i=e[1].dims,l=i[2]/a,c=i[3],p=o?Wt(l):1,u=o&&c===1&&l>=4,d=u?Math.floor(l/4)*4:Math.floor(l/p)*p,f=l-d,_=o?Wt(c):1,P=o?c===1?p:_:1,I=we.size(n)/_,M=[Math.ceil(I/64),1,1];yt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${M}`);let g=["rank","rank"],S=[r.strides[0],r.strides[1]],E=[r.kernelShape[o?1:2],r.kernelShape[o?2:3]],x=[r.dilations[0],r.dilations[1]],w=[E[0]+(r.dilations[0]<=1?0:(r.kernelShape[o?1:2]-1)*(r.dilations[0]-1)),E[1]+(r.dilations[1]<=1?0:(r.kernelShape[o?2:3]-1)*(r.dilations[1]-1))],v=[w[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),w[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],$=[{type:12,data:I},{type:12,data:S},{type:12,data:E},{type:12,data:x},{type:12,data:w},{type:6,data:v},{type:12,data:d},{type:12,data:l},{type:12,data:c},...Ze(e[0].dims,e[1].dims)];s&&($.push(...Ze(e[2].dims)),g.push("rank")),$.push(...Ze(n));let O=B=>{let H=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:S.length},{name:"filter_dims",type:"u32",length:E.length},{name:"dilations",type:"u32",length:E.length},{name:"effective_filter_dims",type:"u32",length:w.length},{name:"pads",type:"i32",length:v.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],q=hr(e[0].dataType),L=o?1:2,J=o?2:3,X=o?3:1,Q=Pe("W",e[1].dataType,e[1].dims.length,P),te=Pe("Dy",e[0].dataType,e[0].dims.length,p),re=[te,Q];s&&re.push(Pe("bias",e[2].dataType,[n[X]].length,_));let ce=Qe("result",e[0].dataType,n.length,_),le=()=>{let G="";if(u)p===4?G+=` let xValue = ${te.getByOffset("x_offset")}; let wValue = ${Q.getByOffset("w_offset")}; dotProd = dotProd + dot(xValue, wValue); x_offset += 1u; w_offset += 1u;`:p===2?G+=` dotProd = dotProd + dot(vec4<${q}>(${te.getByOffset("x_offset")}, ${te.getByOffset("x_offset + 1u")}), vec4<${q}>(${Q.getByOffset("w_offset")}, ${Q.getByOffset("w_offset + 1u")})); x_offset += 2u; w_offset += 2u;`:p===1&&(G+=` dotProd = dotProd + dot(vec4<${q}>(${te.getByOffset("x_offset")}, ${te.getByOffset("x_offset + 1u")}, ${te.getByOffset("x_offset + 2u")}, ${te.getByOffset("x_offset + 3u")}), vec4<${q}>(${Q.getByOffset("w_offset")}, ${Q.getByOffset("w_offset + 1u")}, ${Q.getByOffset("w_offset + 2u")}, ${Q.getByOffset("w_offset + 3u")})); x_offset += 4u; w_offset += 4u;`);else if(G+=` let xValue = ${o?te.getByOffset(`${te.indicesToOffset(`${te.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):te.get("batch","inputChannel","idyR","idyC")}; `,p===1)G+=` let w_offset = ${Q.indicesToOffset(`${Q.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; let wValue = ${Q.getByOffset(`w_offset / ${P}`)}; dotProd = dotProd + xValue * wValue;`;else for(let R=0;R{if(f===0)return"";if(!u)throw new Error(`packInputAs4 ${u} is not true.`);let G="";if(p===1){G+="dotProd = dotProd";for(let R=0;R(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 = ${ce.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 = (${q}(dyRCorner) + ${q}(wR)) / ${q}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; if (dyR < 0.0 || dyR >= ${q}(uniforms.Dy_shape[${L}]) || 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 = (${q}(dyCCorner) + ${q}(wC)) / ${q}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; if (dyC < 0.0 || dyC >= ${q}(uniforms.Dy_shape[${J}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } let idyC: u32 = u32(dyC); var inputChannel = groupId * uniforms.input_channels_per_group; ${u?` var x_offset = ${te.indicesToOffset(`${te.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; var w_offset = ${Q.indicesToOffset(`${Q.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${P}; `:""} for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${u?4:p}) { ${le()} inputChannel = inputChannel + ${u?4:p}; } ${N()} wC = wC + uniforms.strides.y - 1; } wR = wR + uniforms.strides[0] - 1; } let value = dotProd${s?` + bias[d1 / ${_}]`:""}; ${ce.setByOffset("global_idx","value")}; `;return` ${B.registerUniforms(H).declareVariables(...re,ce)} ${B.mainStart()} ${B.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; ${F}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${P}${_}${u}${f}`,inputDependencies:g},getRunData:()=>({dispatchGroup:{x:M[0],y:M[1],z:M[2]},outputs:[{dims:t?t(n):n,dataType:e[0].dataType}],programUniforms:$}),getShaderSource:O}}}),yf,vf,xf,Jl,zb,Tf,Yl,Ef,Bb,ax=ze(()=>{ix(),Tn(),Gs(),yf=(e,r,t,s,n,o)=>(e-1)*r+t+(s-1)*n+1-o,vf=(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)},xf=(e,r,t,s,n,o,a,i,l,c)=>{let p=e.length-2,u=c.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((u,d)=>u*d,1)===0){t.length=0;for(let u=2;uu+d,0)===0){let u=r[0].dims.length-2;l=new Array(u).fill(1)}let c=e.strides.slice();if(c.reduce((u,d)=>u+d,0)===0){let u=r[0].dims.length-2;c=new Array(u).fill(1)}xf(i,t,l,e.autoPad,e.group,n,c,s,a,o);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:n,outputPadding:a,outputShape:o,dilations:l,strides:c}),p},zb=e=>{let r=ic(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],n=e.dilations,o=e.group,a=e.kernelShape,i=e.pads,l=e.strides,c=e.wIsConst(),p=e.outputPadding,u=e.outputShape;return{autoPad:s,format:t,dilations:n,group:o,kernelShape:a,outputPadding:p,outputShape:u,pads:i,strides:l,wIsConst:c,...r,cacheKey:`${e.format};${r.activation};`}},Tf=(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((a,i)=>a+i,0)>0&&r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.reduce((a,i)=>a+i,0)>0&&r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.reduce((a,i)=>a+i,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((a,i)=>a+i,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")},Yl=(e,r,t,s)=>{let n=e.kernelCustomData.wT??e.compute(Fr(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(Lb(o,t,s),{inputs:o})},Ef=(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 a=r.strides;(a.length===0||a[0]===0)&&(a=[1]);let i=r.pads;i.length===0&&(i=[0,0]),i=[0,i[0],0,i[1]],a=[1].concat(a),o=[1].concat(o),n=[1].concat(n);let l=r.outputPadding;l=[0].concat(l);let c=Jl({...r,pads:i,strides:a,dilations:o,kernelShape:n,outputPadding:l},s);Yl(e,s,c,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Bb=(e,r)=>{if(Tf(e.inputs,r),e.inputs[0].dims.length===3)Ef(e,r);else{let t=Jl(r,e.inputs);Yl(e,e.inputs,t)}}}),Pf,Rb,Nb,lx=ze(()=>{at(),mt(),Kt(),ht(),Pf=(e,r,t,s)=>{let n=we.size(r),o=r.length,a=Pe("input",e,o),i=Qe("output",e,o),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),c=we.normalizeAxis(l,o),p=u=>{let d=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,f=Je("uniforms.input_shape","uniforms.axis",o),_=s.reverse?d+(s.exclusive?" + 1":""):"0",P=s.reverse?f:d+(s.exclusive?"":" + 1");return` ${u.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,i)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var inputIndices = ${i.offsetToIndices("global_idx")}; var sum = ${i.type.value}(0); let first : i32 = ${_}; let last : i32 = ${P}; for (var i : i32 = first; i < last; i++) { ${a.indicesSet("inputIndices","uniforms.axis","u32(i)")}; sum = sum + ${a.getByIndices("inputIndices")}; } ${i.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},...Ze(r,r)]}),getShaderSource:p}},Rb=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,n=e.inputs[1];e.compute(Pf(s,t,n,r),{inputs:[0]})},Nb=e=>{let r=e.exclusive===1,t=e.reverse===1;return Pt({exclusive:r,reverse:t})}}),Cf,Sf,$f,jb,Vb,ux=ze(()=>{at(),mt(),Kt(),ht(),Cf=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.")},Sf=(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,a,i,l=r.format==="NHWC",c=r.blocksize,p=r.mode==="DCR";l?([t,s,n,o]=e.dims,a=p?[t,s,n,c,c,o/c**2]:[t,s,n,o/c**2,c,c],i=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]],a=p?[t,c,c,o/c**2,s,n]:[t,o/c**2,c,c,s,n],i=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let u=e.reshape(a),d=u.dims.length,f=e.dataType,_=Pe("a",f,d),P=Qe("output",f,d),I=M=>` ${M.registerUniform("output_size","u32").declareVariables(_,P)} ${Sf(i,d,_,P)} ${M.mainStart()} ${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${P.offsetToIndices("global_idx")}; let aIndices = perm(indices); ${P.setByOffset("global_idx",_.getByIndices("aIndices"))} }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:M=>{let g=l?[t,s*c,n*c,o/c**2]:[t,o/c**2,s*c,n*c],S=we.size(g),E=u.dims,x=we.sortBasedOnPerm(E,i);return{outputs:[{dims:g,dataType:M[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...Ze(E,x)]}},getShaderSource:I}},jb=(e,r)=>{Cf(e.inputs),e.compute($f(e.inputs[0],r))},Vb=e=>Pt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),qi,Lo,Zl,kf,If,Af,Ff,eu,Of,Ub,Wb,cx=ze(()=>{at(),mt(),Kt(),ht(),qi="[a-zA-Z]|\\.\\.\\.",Lo="("+qi+")+",Zl="^"+Lo+"$",kf="("+Lo+",)*"+Lo,If="^"+kf+"$",Af=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)}},Ff=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(If)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,o)=>{let a=e[o].dims.slice();if(!n.match(RegExp(Zl)))throw new Error("Invalid LHS term");let i=this.processTerm(n,!0,a,o);this.lhs.push(i)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,o])=>o.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(Lo)))throw new Error("Invalid RHS");s.match(RegExp(qi,"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,a=[],i=0;if(!e.match(RegExp(Zl))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(qi,"g")),c=new Af(s);return l?.forEach((p,u)=>{if(p==="..."){if(o)throw new Error("Only one ellipsis is allowed per input term");o=!0;let d=n-l.length+1;if(d<0)throw new Error("Ellipsis out of bounds");if(a=t.slice(i,i+d),this.hasEllipsis){if(this.ellipsisDims.length!==a.length||this.ellipsisDims.toString()!==a.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=a;else throw new Error("Ellipsis must be specified in the LHS");for(let f=0;fe+"_max",Of=(e,r,t,s)=>{let n=e.map(c=>c.length).map((c,p)=>Pe(`input${p}`,r,c)),o=we.size(s),a=Qe("output",r,s.length),i=[...t.symbolToInfo.keys()].filter(c=>!t.rhs.symbolToIndices.has(c)),l=c=>{let p=[],u="var prod = 1.0;",d="var sum = 0.0;",f="sum += prod;",_=[],P=[],I=[],M=[],g=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((E,x)=>{if(t.rhs.symbolToIndices.has(x)){let w=t.rhs.symbolToIndices.get(x)?.[0];w!==void 0&&t.lhs.forEach((v,$)=>{if(E.inputIndices.includes($)){let O=v.symbolToIndices.get(x);if(O===void 0)throw new Error("Invalid symbol error");O.forEach(B=>{p.push(`${n[$].indicesSet(`input${$}Indices`,B,a.indicesGet("outputIndices",w))}`)})}})}else t.lhs.forEach((w,v)=>{if(E.inputIndices.includes(v)){let $=w.symbolToIndices.get(x);if($===void 0)throw new Error("Invalid symbol error");$.forEach(O=>{_.push(`${n[v].indicesSet(`input${v}Indices`,O,`${x}`)}`)}),M.push(`prod *= ${n[v].getByIndices(`input${v}Indices`)};`)}}),P.push(`for(var ${x}: u32 = 0; ${x} < uniforms.${eu(x)}; ${x}++) {`),I.push("}")});let S=g?[...p,`let sum = ${n.map((E,x)=>E.getByIndices(`input${x}Indices`)).join(" * ")};`]:[...p,d,...P,..._,u,...M,f,...I];return` ${c.registerUniforms(i.map(E=>({name:`${eu(E)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...n,a)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} var outputIndices = ${a.offsetToIndices("global_idx")}; ${n.map((E,x)=>`var input${x}Indices: ${n[x].type.indices};`).join(` `)} ${S.join(` `)}; ${a.setByOffset("global_idx","sum")}; }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let c=i.filter(u=>t.symbolToInfo.has(u)).map(u=>({type:12,data:t.symbolToInfo.get(u)?.dimValue||0}));c.push({type:12,data:o});let p=e.map((u,d)=>[...Ze(u)]).reduce((u,d)=>u.concat(d),c);return p.push(...Ze(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}},getShaderSource:l}},Ub=(e,r)=>{let t=new Ff(e.inputs,r.equation),s=t.outputDims,n=e.inputs.map((o,a)=>o.dims);e.compute(Of(n,e.inputs[0].dataType,t,s))},Wb=e=>{let r=e.equation.replace(/\s+/g,"");return Pt({equation:r})}}),Df,tu,Lf,zf,Gb,dx=ze(()=>{at(),mt(),ht(),Df=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?tu(e,r):tu(r,e),zf=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=Lf(r,t),n=e[0].dataType,o=n===9||we.size(r)===1,a=n===9||r.length>0&&r[r.length-1]%4===0?4:1,i=o||s.length>0&&s[s.length-1]%4===0?4:1,l=Math.ceil(we.size(s)/i),c=u=>{let d=Pe("input",n,r.length,a),f=Qe("output",n,s.length,i),_;if(n===9){let P=(I,M,g="")=>` let outputIndices${M} = ${f.offsetToIndices(`outputOffset + ${M}u`)}; let offset${M} = ${d.broadcastedIndicesToOffset(`outputIndices${M}`,f)}; let index${M} = offset${M} / 4u; let component${M} = offset${M} % 4u; ${I}[${M}] = ${g}(${d.getByOffset(`index${M}`)}[component${M}]); `;_=` let outputOffset = global_idx * ${i}; var data = vec4(0); ${P("data",0,"u32")} ${P("data",1,"u32")} ${P("data",2,"u32")} ${P("data",3,"u32")} ${f.setByOffset("global_idx","data")} }`}else _=` let outputIndices = ${f.offsetToIndices(`global_idx * ${i}`)}; let inputOffset = ${d.broadcastedIndicesToOffset("outputIndices",f)}; let data = ${f.type.value}(${d.getByOffset(`inputOffset / ${a}`)}); ${f.setByOffset("global_idx","data")} }`;return` ${u.registerUniform("vec_size","u32").declareVariables(d,f)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${_}`},p=[{type:12,data:l},...Ze(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${a}${i}`,inputDependencies:["rank"]},getShaderSource:c,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},Gb=e=>{Df(e.inputs),e.compute(zf(e.inputs),{inputs:[0]})}}),Bf,Kb,px=ze(()=>{at(),mt(),ht(),oc(),Bf=e=>{let r=e[0].dataType,t=we.size(e[0].dims),s=we.size(e[1].dims),n=s%4===0,o=a=>{let i=Pe("x",r,[1],4),l=Pe("bias",r,[1],4),c=Qe("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],u=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];`,d=n?` let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${u(0)}${u(1)}${u(2)}${u(3)} let bias = ${i.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(p).declareVariables(i,l,c)} ${Fu(br(r))} ${a.mainStart(so)} ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} let x = ${i.getByOffset("global_idx")}; ${d} let x_in = x + bias; ${c.setByOffset("global_idx",Ou("x_in"))} }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${n}`,inputDependencies:["type","type"]},getShaderSource:o,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/so/4)}})}},Kb=e=>{e.inputs.length<2||we.size(e.inputs[1].dims)===0?pb(e):e.compute(Bf(e.inputs))}}),Rf,Nf,Hb,qb,mx=ze(()=>{at(),mt(),Kt(),ht(),Rf=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Nf=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t.length,o=we.normalizeAxis(r.axis,n),a=t.slice(0);a.splice(o,1,...s);let i=t[o],l=e[0].dataType===9?4:1,c=Math.ceil(we.size(a)/l),p=[{type:12,data:c},{type:6,data:i},{type:12,data:o},...Ze(e[0].dims,e[1].dims,a)],u=d=>{let f=Pe("data",e[0].dataType,e[0].dims.length,l),_=Pe("inputIndices",e[1].dataType,e[1].dims.length),P=Qe("output",e[0].dataType,a.length,l),I=g=>{let S=s.length,E=`var indicesIndices${g} = ${_.type.indices}(0);`;for(let x=0;x1?`indicesIndices${g}[${x}]`:`indicesIndices${g}`} = ${a.length>1?`outputIndices${g}[uniforms.axis + ${x}]`:`outputIndices${g}`};`;E+=` var idx${g} = ${_.getByIndices(`indicesIndices${g}`)}; if (idx${g} < 0) { idx${g} = idx${g} + uniforms.axisDimLimit; } var dataIndices${g} : ${f.type.indices}; `;for(let x=0,w=0;x1?`dataIndices${g}[${x}]`:`dataIndices${g}`} = u32(idx${g});`,w+=S):(E+=`${n>1?`dataIndices${g}[${x}]`:`dataIndices${g}`} = ${a.length>1?`outputIndices${g}[${w}]`:`outputIndices${g}`};`,w++);return E},M;if(e[0].dataType===9){let g=(S,E,x="")=>` let outputIndices${E} = ${P.offsetToIndices(`outputOffset + ${E}u`)}; ${I(E)}; let offset${E} = ${f.indicesToOffset(`dataIndices${E}`)}; let index${E} = offset${E} / 4u; let component${E} = offset${E} % 4u; ${S}[${E}] = ${x}(${f.getByOffset(`index${E}`)}[component${E}]); `;M=` let outputOffset = global_idx * ${l}; var value = vec4(0); ${g("value",0,"u32")} ${g("value",1,"u32")} ${g("value",2,"u32")} ${g("value",3,"u32")} ${P.setByOffset("global_idx","value")} `}else M=` let outputIndices = ${P.offsetToIndices("global_idx")}; ${I("")}; let value = ${f.getByIndices("dataIndices")}; ${P.setByOffset("global_idx","value")}; `;return` ${d.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(f,_,P)} ${d.mainStart()} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${M} }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:u}},Hb=e=>Pt({axis:e.axis}),qb=(e,r)=>{let t=e.inputs;Rf(t),e.compute(Nf(e.inputs,r))}}),jf,Xb,Qb,hx=ze(()=>{at(),mt(),ht(),jf=(e,r,t,s,n,o,a,i,l)=>{let c=[{type:12,data:o},{type:12,data:s},{type:12,data:n},{type:12,data:t},{type:12,data:a},{type:12,data:i},{type:12,data:l}],p=[o];c.push(...Ze(r.dims,p));let u=d=>{let f=Pe("indices_data",r.dataType,r.dims.length),_=Qe("input_slice_offsets_data",12,1,1),P=[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` ${d.registerUniforms(I).declareVariables(...P)} ${d.mainStart()} ${d.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:u},{inputs:[r],outputs:[-1]})[0]},Xb=(e,r)=>{let t=e.inputs,s=t[0].dims,n=t[0].dataType,o=t[1].dims,a=o[o.length-1],i=we.sizeToDimension(o,o.length-1),l=we.sizeFromDimension(s,r.batchDims+a),c=we.sizeToDimension(s,r.batchDims),p=we.sizeFromDimension(s,r.batchDims),u=i/c,d=new Array(a),f=l;for(let E=0;Es.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let I=o.slice(0,-1).concat(s.slice(P)),M=we.size(I),g=[{type:12,data:M},{type:12,data:l},...Ze(t[0].dims,_.dims,I)],S=E=>{let x=Pe("data",t[0].dataType,t[0].dims.length),w=Pe("slice_offsets",12,_.dims.length),v=Qe("output",t[0].dataType,I.length);return` ${E.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(x,w,v)} ${E.mainStart()} ${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; }`};e.compute({name:"GatherND",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:I,dataType:n}],dispatchGroup:{x:Math.ceil(M/64)},programUniforms:g}),getShaderSource:S},{inputs:[t[0],_]})},Qb=e=>({batchDims:e.batch_dims,cacheKey:""})}),Vf,Uf,Jb,Yb,_x=ze(()=>{at(),mt(),Kt(),ht(),Vf=(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],a=e.length===4?e[3]:void 0;if(o.dims.length!==n.dims.length||!n.dims.map((i,l)=>l===t?Math.ceil(i/s)===o.dims[l]:i===o.dims[l]).reduce((i,l)=>i&&l,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(a){if(a.dataType!==n.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(a.dims.length!==o.dims.length||!a.dims.map((i,l)=>i===o.dims[l]).reduce((i,l)=>i&&l,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Uf=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t.length,o=we.normalizeAxis(r.gatherAxis,n),a=we.normalizeAxis(r.quantizeAxis,n),i=t.slice(0);i.splice(o,1,...s);let l=we.size(i),c=e[2].dataType,p=e[0].dataType===22,u=[{type:12,data:l},{type:12,data:a},{type:12,data:o},{type:12,data:r.blockSize},...Ze(...e.map((f,_)=>f.dims),i)],d=f=>{let _=Pe("data",e[0].dataType,e[0].dims.length),P=Pe("inputIndices",e[1].dataType,e[1].dims.length),I=Pe("scales",e[2].dataType,e[2].dims.length),M=e.length>3?Pe("zeroPoint",e[3].dataType,e[3].dims.length):void 0,g=Qe("output",c,i.length),S=[_,P,I];M&&S.push(M);let E=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${f.registerUniforms(E).declareVariables(...S,g)} ${f.mainStart()} let output_indices = ${g.offsetToIndices("global_idx")}; var indices_indices = ${P.type.indices}(0); ${s.length>1?` for (var i: u32 = 0; i < ${s.length}; i++) { let index = ${g.indicesGet("output_indices","uniforms.gather_axis + i")}; ${P.indicesSet("indices_indices","i","index")}; }`:`indices_indices = ${g.indicesGet("output_indices","uniforms.gather_axis")};`}; var data_indices = ${_.type.indices}(0); for (var i: u32 = 0; i < uniforms.gather_axis; i++) { let index = ${g.indicesGet("output_indices","i")}; ${_.indicesSet("data_indices","i","index")}; } var index_from_indices = ${P.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 < ${i.length}; i++) { let index = ${g.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")}; ${M?` let zero_point_indices = scale_indices; let zero_point_offset = ${M.indicesToOffset("zero_point_indices")}; let zero_point_index = zero_point_offset % 8; let packed_4bit_zero_points = ${M.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 = ${br(c)}(quantized_data - zero_point) * scale; ${g.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:i,dataType:c}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:d}},Jb=(e,r)=>{let t=e.inputs;Vf(t,r),e.compute(Uf(e.inputs,r))},Yb=e=>Pt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Wf,Gf,Zb,ey,fx=ze(()=>{at(),mt(),Kt(),ht(),Wf=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.`)},Gf=(e,r)=>{let t=e[0].dims,s=e[0].dataType,n=t.length,o=e[1].dims,a=e[1].dataType,i=we.normalizeAxis(r.axis,n),l=t[i],c=o.slice(0),p=we.size(c),u=Pe("input",s,n),d=Pe("indicesInput",a,o.length),f=Qe("output",s,c.length),_=[{type:12,data:p},{type:6,data:l},{type:12,data:i}];return _.push(...Ze(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:P=>` ${P.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(u,d,f)} ${P.mainStart()} ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let outputIndices = ${f.offsetToIndices("global_idx")}; var idx = ${d.getByOffset("global_idx")}; if (idx < 0) { idx = idx + uniforms.axisDimLimit; } var inputIndices = ${u.type.indices}(outputIndices); ${u.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; let value = ${u.getByIndices("inputIndices")}; ${f.setByOffset("global_idx","value")}; }`}},Zb=e=>Pt({axis:e.axis}),ey=(e,r)=>{let t=e.inputs;Wf(t),e.compute(Gf(e.inputs,r))}}),Kf,Hf,ty,ry,gx=ze(()=>{at(),mt(),ht(),Kf=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")},Hf=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[n,o,a]=Zw.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),i=[n,o];if(!i)throw new Error("Can't use gemm on the given tensors");let l=16,c=Math.ceil(o/l),p=Math.ceil(n/l),u=!0,d=we.size(i),f=[{type:12,data:u?c:d},{type:12,data:n},{type:12,data:o},{type:12,data:a},{type:1,data:r.alpha},{type:1,data:r.beta}],_=["type","type"];e.length===3&&(f.push(...Ze(e[2].dims)),_.push("rank")),f.push(...Ze(i));let P=M=>{let g="";r.transA&&r.transB?g="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?g="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?g="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(g="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let S=r.alpha===1?"":"value *= uniforms.alpha;",E=Pe("a",e[0].dataType,e[0].dims),x=Pe("b",e[1].dataType,e[1].dims),w=E.type.value,v=null,$=[E,x];e.length===3&&(v=Pe("c",e[2].dataType,e[2].dims.length),$.push(v));let O=Qe("output",e[0].dataType,i.length);$.push(O);let B=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` ${M.registerUniforms(B).declareVariables(...$)} ${M.mainStart()} ${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let m = global_idx / uniforms.N; let n = global_idx % uniforms.N; var value = ${w}(0); for (var k: u32 = 0u; k < uniforms.K; k++) { ${g} } ${S} ${v!=null?`let cOffset = ${v.broadcastedIndicesToOffset("vec2(m, n)",O)}; value += ${w}(uniforms.beta) * ${v.getByOffset("cOffset")};`:""} output[global_idx] = value; }`},I=M=>{let g=Pe("a",e[0].dataType,e[0].dims),S=Pe("b",e[1].dataType,e[1].dims),E=null,x=[g,S];e.length===3&&(E=Pe("c",e[2].dataType,e[2].dims.length),x.push(E));let w=Qe("output",e[0].dataType,i.length);x.push(w);let v=[{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"}],$="",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] = ${g.type.value}(0); } col = k_start + local_id.x; row = tile_col_start + local_id.y; if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { tile_b[local_id.y][local_id.x] = ${S.type.value}(0); } `,$="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] = ${g.type.value}(0); } col = tile_col_start + local_id.x; row = k_start + local_id.y; if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { tile_b[local_id.y][local_id.x] = ${S.type.value}(0); } `,$="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] = ${g.type.value}(0); } col = k_start + local_id.x; row = tile_col_start + local_id.y; if (col < uniforms.K && row < uniforms.N) { tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; } else { tile_b[local_id.y][local_id.x] = ${S.type.value}(0); } `,$="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] = ${g.type.value}(0); } col = tile_col_start + local_id.x; row = k_start + local_id.y; if (col < uniforms.N && row < uniforms.K) { tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; } else { tile_b[local_id.y][local_id.x] = ${S.type.value}(0); } `,$="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let B=r.alpha===1?"":"value *= uniforms.alpha;";return` ${M.registerUniforms(v).declareVariables(...x)} var tile_a: array, ${l}>; var tile_b: array, ${l}>; ${M.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 = ${w.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++) { ${$} } workgroupBarrier(); } ${B} let m = tile_row_start + local_id.y; let n = tile_col_start + local_id.x; ${E!=null?`let cOffset = ${E.broadcastedIndicesToOffset("vec2(m, n)",w)}; value += ${w.type.value}(uniforms.beta) * ${E.getByOffset("cOffset")};`:""} if (m < uniforms.M && n < uniforms.N) { output[m * uniforms.N + n] = value; } }`};return u?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:c*p},programUniforms:f}),getShaderSource:I}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:f}),getShaderSource:P}},ty=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}`}},ry=(e,r)=>{Kf(e.inputs),e.compute(Hf(e.inputs,r))}}),_s,Ps,pn,mn,qf,Xf,Qf,Jf,Yf,Zf,eg,tg,sy,ny,wx=ze(()=>{at(),mt(),Kt(),ht(),[_s,Ps,pn,mn]=[0,1,2,3],qf=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")},Xf=` 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; } `,Qf=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; } `,Jf=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)); `} } `,Yf=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); }`:""} `,Zf=(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[${_s}] = batch; indices[${Ps}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` if (r >= 0 && r < H && c >=0 && c < W) { indices[${pn}] = u32(r); indices[${mn}] = u32(c); } else { return ${r}(0); } `;case"border":return` indices[${pn}] = u32(clamp(r, 0, H - 1)); indices[${mn}] = u32(clamp(c, 0, W - 1)); `;case"reflection":return` indices[${pn}] = gs_reflect(r, border[1], border[3]); indices[${mn}] = gs_reflect(c, border[0], border[2]); `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` return ${e.getByIndices("indices")}; } `,eg=(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[${_s}], indices[${Ps}], 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[${_s}], indices[${Ps}], border); let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${_s}], indices[${Ps}], border); let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${_s}], indices[${Ps}], border); let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${_s}], indices[${Ps}], 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[${_s}], indices[${Ps}], 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")}`,tg=(e,r)=>{let t=Pe("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],n=Pe("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]],[_s,Ps,pn,mn]=[0,3,1,2]);let a=Qe("output",e[0].dataType,o.length),i=t.type.value,l=we.size(o),c=[{type:12,data:l},...Ze(e[0].dims,s,o)],p=u=>` ${u.registerUniform("output_size","u32").declareVariables(t,n,a)} ${Xf} ${Qf(i)} ${Jf(r)} ${Yf(r)} ${Zf(t,i,r)} ${u.mainStart()} ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let H_in = i32(uniforms.x_shape[${pn}]); let W_in = i32(uniforms.x_shape[${mn}]); ${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 = ${a.offsetToIndices("global_idx")}; var grid_indices = vec3(indices[${_s}], indices[${pn}], indices[${mn}]); let nxy = ${n.getByIndices("grid_indices")}; var x = gs_denormalize(f32(nxy[0]), W_in); var y = gs_denormalize(f32(nxy[1]), H_in); ${eg(a,i,r)} }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:u=>{let d=we.size(o);return{outputs:[{dims:o,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c}},getShaderSource:p}},sy=(e,r)=>{qf(e.inputs),e.compute(tg(e.inputs,r))},ny=e=>Pt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Pr,rg,oy,ru,sg,Wo,iy,ay=ze(()=>{at(),mt(),Kt(),tc(),nc(),ht(),Gs(),Pr=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,rg=(e,r)=>{let t=e[0],s=Pr(e,1),n=Pr(e,2),o=Pr(e,3),a=Pr(e,4),i=Pr(e,5),l=Pr(e,6),c=Pr(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],u=t.dims[1],d=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],f=u,_=0,P=0,I=Math.floor(d/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],P=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 M;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)');M=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.');M=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');M=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');M=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 g=_+f,S=0;if(a&&we.size(a.dims)>0){S=8;let v=a.dims;throw v.length===1?v[0]===p?S=1:v[0]===3*p+2&&(S=3):v.length===2&&v[0]===p&&v[1]===g&&(S=5),S===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let E=!1,x=d;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)');x=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)');x=n.dims[1]*n.dims[3],E=!0}}let w=!1;if(a&&we.size(a.dims)>0)throw new Error("Key padding mask is not supported");if(i&&we.size(i.dims)>0){if(i.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(i.dims[0]!==p||i.dims[1]!==r.numHeads||i.dims[2]!==u||i.dims[3]!==g)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:u,pastSequenceLength:_,kvSequenceLength:f,totalSequenceLength:g,maxSequenceLength:P,inputHiddenSize:0,hiddenSize:d,vHiddenSize:x,headSize:I,vHeadSize:Math.floor(x/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:S,scale:r.scale,broadcastResPosBias:w,passPastInKv:E,qkvFormat:M}},oy=e=>Pt({...e}),ru=Pt({perm:[0,2,1,3]}),sg=(e,r,t,s,n,o,a)=>{let i=[s,n,o],l=we.size(i),c=[{type:12,data:l},{type:12,data:a},{type:12,data:o}],p=u=>{let d=Qe("qkv_with_bias",r.dataType,i),f=Pe("qkv",r.dataType,i),_=Pe("bias",t.dataType,i),P=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${u.registerUniforms(P).declareVariables(f,_,d)} ${u.mainStart()} ${u.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:i,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},Wo=(e,r,t,s,n,o,a,i)=>{let l=o;if(a&&we.size(a.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=sg(e,o,a,r,s,t*n,i),l=l.reshape([r,s,t,n]),t===1||s===1?l:e.compute(Fr(l,ru.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(Fr(l,ru.perm),{inputs:[l],outputs:[-1]})[0]},iy=(e,r)=>{let t=rg(e.inputs,r),s=e.inputs[0],n=Pr(e.inputs,1),o=Pr(e.inputs,2),a=Pr(e.inputs,3),i=Pr(e.inputs,4),l=Pr(e.inputs,5),c=Pr(e.inputs,6),p=Pr(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 u=n&&o&&n.dims.length===4&&o.dims.length===4,d=Wo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,a,0);if(u)return qo(e,d,n,o,i,void 0,c,p,l,t);if(!n||!o)throw new Error("key and value must be provided");let f=Wo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,n,a,t.hiddenSize),_=Wo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,o,a,2*t.hiddenSize);qo(e,d,f,_,i,void 0,c,p,l,t)}}),ng,og,ig,ag,Ru,ly,uy,cy=ze(()=>{at(),mt(),Kt(),ht(),ng=e=>{if(!e||e.length<1)throw new Error("too few inputs")},og=(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),Pt({numOutputs:s,axis:r.axis,splitSizes:t})},ig=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${Je("uniforms.size_in_split_axis","i",e)}) { return i; } } return ${e}u; }`,ag=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),a=new Array(r.numOutputs),i=Pe("input",n,t.length),l=new Array(r.numOutputs),c=[],p=[],u=0,d=[{type:12,data:s}];for(let _=0;_` ${_.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(i,...a)} ${ig(l.length)} ${ag(a)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} var indices = ${i.offsetToIndices("global_idx")}; var index = ${i.indicesGet("indices",o)}; let output_number = calculateOutputIndex(index); if (output_number != 0) { index -= ${Je("uniforms.size_in_split_axis","output_number - 1u",l.length)}; ${i.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:d})}},ly=(e,r)=>{ng(e.inputs);let t=e.inputs.length===1?r:og(e.inputs,r);e.compute(Ru(e.inputs,t),{inputs:[0]})},uy=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 Pt({axis:r,numOutputs:s,splitSizes:t})}}),lg,la,dy,py=ze(()=>{at(),mt(),Kt(),ht(),lg=(e,r)=>{let[t,s,n,o]=e,{numHeads:a,rotaryEmbeddingDim:i}=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(i>0&&a===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],u=we.sizeFromDimension(t.dims,1)/c,d=i===0?n.dims[1]*2:u/a;if(i>d)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(d/2!==n.dims[1]&&i/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")},la=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:n,scale:o}=r,a=e[0].dims[0],i=we.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],c=i/l,p=e[2].dims[1],u=n===0?p*2:c/s,d=new Array(a,l,c/u,u-p),f=we.computeStrides(d),_=[{type:1,data:o},{type:12,data:d},{type:12,data:f},...e[0].dims.length===3?new Array({type:12,data:[i,c,u,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[i,u,l*u,1]}):[],...Ze(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],P=I=>{let M=Pe("input",e[0].dataType,e[0].dims.length),g=Pe("position_ids",e[1].dataType,e[1].dims.length),S=Pe("cos_cache",e[2].dataType,e[2].dims.length),E=Pe("sin_cache",e[3].dataType,e[3].dims.length),x=Qe("output",e[0].dataType,e[0].dims.length);return I.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:d.length},{name:"global_strides",type:"u32",length:f.length},{name:"input_output_strides",type:"u32",length:f.length}]),` ${I.declareVariables(M,g,S,E,x)} ${I.mainStart(so)} let half_rotary_emb_dim = uniforms.${S.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 = ${g.broadcastedIndicesToOffset("bsnh.xy",Qe("",g.type.tensor,2))}; let position_id = u32(${g.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${t}); let j = i + select(half_rotary_emb_dim, 1, ${t}); let re = ${M.getByOffset("i")} * ${S.get("position_id","bsnh[3]")} - ${M.getByOffset("j")} * ${E.get("position_id","bsnh[3]")}; ${x.setByOffset("i","re")} let im = ${M.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} + ${M.getByOffset("j")} * ${S.get("position_id","bsnh[3]")}; ${x.setByOffset("j","im")} } else { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${x.setByOffset("k",M.getByOffset("k"))} } }`};return{name:"RotaryEmbedding",shaderCache:{hint:Pt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:P,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(we.size(d)/so)},programUniforms:_})}},dy=(e,r)=>{lg(e.inputs,r),e.compute(la(e.inputs,r))}}),ug,cg,su,dg,my,Mx=ze(()=>{Kt(),at(),nc(),ay(),cy(),Gs(),py(),ht(),ug=(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],a=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 i=!1,l=t.dims[0],c=t.dims[1],p=t.dims.length===3?i?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],u=c,d=0,f=!s||s.dims.length===0,_=Math.floor(f?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);f&&(p=_*r.numHeads);let P=o&&o.dims.length!==0,I=a&&a.dims.length!==0;if(P&&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(P&&I){if(o.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(a.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');d=o.dims[2]}else if(P||I)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let M=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"');u=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.');u=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');u=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');M=3}let g=0,S=!1,E=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(u!==n.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');E=n.dims[2]}else{if(u!==n.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');E=n.dims[1]*n.dims[3],S=!0}}let x=e.length>4?e[5]:void 0;if(x&&x.dims.length!==1&&x.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:d,kvSequenceLength:u,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:E,headSize:_,vHeadSize:Math.floor(E/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:S,qkvFormat:M}},cg=Pt({perm:[0,2,1,3]}),su=(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(Fr(s,cg.perm),{inputs:[s],outputs:[-1]})[0]),s},dg=(e,r,t,s)=>{let n=7,o=["type","type"],a=[e*r],i=e*r,l=[{type:12,data:i},{type:12,data:r},{type:12,data:e}],c=p=>{let u=Pe("seq_lens",t.dataType,t.dims),d=Pe("total_seq_lens",s.dataType,s.dims),f=Qe("pos_ids",n,a),_=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` ${p.registerUniforms(_).declareVariables(u,d,f)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let total_sequence_length = u32(${d.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 = ${u.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:a,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:l}),getShaderSource:c}},my=(e,r)=>{let t=ug(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,a=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,i=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,u=Pt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[d,f,_]=!n&&!o?e.compute(Ru([s],u),{inputs:[s],outputs:[-1,-1,-1]}):[s,n,o],P,I;if(r.doRotary){let E=e.compute(dg(t.batchSize,t.sequenceLength,l,c),{inputs:[l,c],outputs:[-1]})[0],x=e.inputs[7],w=e.inputs[8],v=Pt({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),$=[d,E,x,w],O=[-1];P=e.compute(la($,v),{inputs:$,outputs:O})[0],$.splice(0,1,f);let B=Pt({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});I=e.compute(la($,B),{inputs:$,outputs:O})[0]}let M=Wo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?P:d,void 0,0),g=su(e,r.doRotary?I:f,t),S=su(e,_,t);qo(e,M,g,S,void 0,void 0,a,i,void 0,t,l,c)}}),nu,pg,mg,hy,bx=ze(()=>{at(),mt(),Gs(),ht(),nu=(e,r,t,s,n,o,a,i)=>{let l=Wt(o),c=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,u=n*a,d=64;u===1&&(d=256);let f=[n,a,o/l],_=[n,a,2],P=["rank","type","type"],I=[];I.push(...Ze(f,_));let M=g=>{let S=Pe("x",r.dataType,3,l),E=Pe("scale",t.dataType,t.dims),x=Pe("bias",s.dataType,s.dims),w=Qe("output",1,3,2),v=[S,E,x,w];return` var workgroup_shared : array<${p}, ${d}>; const workgroup_size = ${d}u; ${g.declareVariables(...v)} ${g.mainStart(d)} 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}(${S.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 = ${Ws("workgroup_shared[0][0]",l)} / f32(hight * ${l}); let squared_sum_final = ${Ws("workgroup_shared[0][1]",l)} / f32(hight * ${l}); let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${i})); 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};${i};${d}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:_,dataType:1}],dispatchGroup:{x:u},programUniforms:I}),getShaderSource:M},{inputs:[r,t,s],outputs:[-1]})[0]},pg=(e,r,t)=>{let s=r[0].dims,n=s,o=2,a=s[0],i=s[1],l=we.sizeFromDimension(s,o),c=Wt(l),p=we.size(n)/c,u=nu(e,r[0],r[1],r[2],a,l,i,t.epsilon),d=[a,i,l/c],f=[a,i],_=["type","none"],P=I=>{let M=Pe("x",r[0].dataType,d.length,c),g=Pe("scale_shift",1,f.length,2),S=Qe("output",r[0].dataType,d.length,c),E=[M,g,S];return` ${I.registerUniform("output_size","u32").declareVariables(...E)} ${I.mainStart()} ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let outputIndices = ${S.offsetToIndices("global_idx")}; let batch = outputIndices[0]; let channel = outputIndices[1]; let scale_shift = ${g.getByIndices("vec2(batch, channel)")}; let value = ${M.getByOffset("global_idx")} * ${S.type.value}(scale_shift.x) + ${S.type.value}(scale_shift.y); ${S.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},...Ze(d,f,d)]}),getShaderSource:P},{inputs:[r[0],u]})},mg=(e,r,t)=>{let s=r[0].dims,n=s,o=s[0],a=s[s.length-1],i=we.sizeFromDimension(s,1)/a,l=Wt(a),c=we.size(n)/l,p=[{type:12,data:i},{type:12,data:Math.floor(a/l)}],u=["type","type"],d=!1,f=[0,s.length-1];for(let M=0;Ms[f[g]])),P=nu(e,_,r[1],r[2],o,i,a,t.epsilon),I=M=>{let g=hr(r[0].dataType),S=l===1?"vec2f":`mat${l}x2f`,E=v=>{let $=v===0?"x":"y",O=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${g}(${O}(scale.${$}))`;case 2:return`vec2<${g}>(${O}(scale[0].${$}, scale[1].${$}))`;case 4:return`vec4<${g}>(${O}(scale[0].${$}, scale[1].${$}, scale[2].${$}, scale[3].${$}))`;default:throw new Error(`Not supported compoents ${l}`)}},x=Pe("input",r[0].dataType,r[0].dims,l),w=Qe("output",r[0].dataType,n,l);return` @group(0) @binding(0) var input : array<${x.type.storage}>; @group(0) @binding(1) var scale_input : array<${S}>; @group(0) @binding(2) var output : array<${w.type.storage}>; struct Uniforms {H: u32, C : u32}; @group(0) @binding(3) var uniforms: Uniforms; ${M.mainStart()} let current_image_number = global_idx / (uniforms.C * uniforms.H); let current_channel_number = global_idx % uniforms.C; let scale_offset = current_image_number * uniforms.C + current_channel_number; let scale = scale_input[scale_offset]; output[global_idx] = fma(input[global_idx], ${E(0)}, ${E(1)}); }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:n,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:p}),getShaderSource:I},{inputs:[r[0],P]})},hy=(e,r)=>{r.format==="NHWC"?mg(e,e.inputs,r):pg(e,e.inputs,r)}}),hg,_g,_y,yx=ze(()=>{at(),mt(),ht(),hg=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},_g=(e,r,t)=>{let s=r.simplified,n=e[0].dims,o=e[1],a=!s&&e[2],i=n,l=we.normalizeAxis(r.axis,n.length),c=we.sizeToDimension(n,l),p=we.sizeFromDimension(n,l),u=we.size(o.dims),d=a?we.size(a.dims):0;if(u!==p||a&&d!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. Size of scale and bias (if provided) must match this. Got scale size of ${u} and bias size of ${d}`);let f=[];for(let x=0;x1,g=t>2,S=x=>{let w=hr(e[0].dataType),v=[Pe("x",e[0].dataType,e[0].dims,_),Pe("scale",o.dataType,o.dims,_)];a&&v.push(Pe("bias",a.dataType,a.dims,_)),v.push(Qe("output",e[0].dataType,i,_)),M&&v.push(Qe("mean_data_output",1,f)),g&&v.push(Qe("inv_std_output",1,f));let $=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${x.registerUniforms($).declareVariables(...v)} ${x.mainStart()} ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; var mean_vector = ${ku("f32",_)}; var mean_square_vector = ${ku("f32",_)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${eo(w,_,"x[h + offset]")}; mean_vector += value; mean_square_vector += value * value; } let mean = ${Ws("mean_vector",_)} / uniforms.norm_size; let inv_std_dev = inverseSqrt(${Ws("mean_square_vector",_)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { let f32input = ${eo(w,_,"x[j + offset]")}; let f32scale = ${eo(w,_,"scale[j]")}; output[j + offset] = ${v[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale ${a?`+ ${eo(w,_,"bias[j]")}`:""} ); } ${M?"mean_data_output[global_idx] = mean":""}; ${g?"inv_std_output[global_idx] = inv_std_dev":""}; }`},E=[{dims:i,dataType:e[0].dataType}];return M&&E.push({dims:f,dataType:1}),g&&E.push({dims:f,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${t};${s}`,inputDependencies:P},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(c/64)},programUniforms:I}),getShaderSource:S}},_y=(e,r)=>{hg(e.inputs),e.compute(_g(e.inputs,r,e.outputCount))}}),fg,fy,vx=ze(()=>{mt(),uc(),cc(),fg=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.")},fy=e=>{fg(e.inputs);let r=ro.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(lc(e.inputs,{activation:""},r));else{let n=r[r.length-2],o=we.size(e.inputs[0].dims.slice(0,-2)),a=we.size(e.inputs[1].dims.slice(0,-2));if(o!==1&&n===1&&a===1){let i=e.inputs[0].reshape([1,o,s]),l=e.inputs[1].reshape([1,s,t]),c=[1,o,t],p=[i,l];e.compute(aa(p,{activation:""},r,c),{inputs:p})}else e.compute(aa(e.inputs,{activation:""},r))}}}),gg,wg,Mg,gy,wy,xx=ze(()=>{at(),mt(),Kt(),ht(),gg=(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,a=e[1];if(!we.areEqual(a.dims,[r.n,n,o]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let i=e[2].dims;if(we.size(i)!==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.")}},wg=(e,r)=>{let t=e[0].dims,s=t.length,n=t[s-2],o=r.k,a=r.n,i=t.slice(0,s-2),l=we.size(i),c=e[1].dims[2]/4,p=e[0].dataType,u=Wt(r.k),d=Wt(c),f=Wt(a),_=i.concat([n,a]),P=n>1&&a/f%2===0?2:1,I=we.size(_)/f/P,M=64,g=[],S=[l,n,o/u],E=we.convertShape(e[1].dims).slice();E.splice(-1,1,c/d),g.push(...Ze(S)),g.push(...Ze(E)),g.push(...Ze(e[2].dims)),e.length===4&&g.push(...Ze(we.convertShape(e[3].dims)));let x=[l,n,a/f];g.push(...Ze(x));let w=v=>{let $=S.length,O=Pe("a",e[0].dataType,$,u),B=Pe("b",12,E.length,d),H=Pe("scales",e[2].dataType,e[2].dims.length),q=[O,B,H],L=e.length===4?Pe("zero_points",12,e[3].dims.length):void 0;L&&q.push(L);let J=x.length,X=Qe("output",e[0].dataType,J,f),Q=hr(e[0].dataType),te=(()=>{switch(u){case 1:return`array<${Q}, 8>`;case 2:return`mat4x2<${Q}>`;case 4:return`mat2x4<${Q}>`;default:throw new Error(`${u}-component is not supported.`)}})(),re=()=>{let N=` // reuse a data var input_offset = ${O.indicesToOffset(`${O.type.indices}(batch, row, word_offset)`)}; var a_data: ${te}; for (var j: u32 = 0; j < ${8/u}; j++) { a_data[j] = ${O.getByOffset("input_offset")}; input_offset++; } `;for(let F=0;F> 4) & b_mask); b_quantized_values = ${te}(${Array.from({length:4},(G,R)=>`${Q}(b_value_lower[${R}]), ${Q}(b_value_upper[${R}])`).join(", ")}); b_dequantized_values = ${u===1?`${te}(${Array.from({length:8},(G,R)=>`(b_quantized_values[${R}] - ${L?`zero_point${F}`:"zero_point"}) * scale${F}`).join(", ")});`:`(b_quantized_values - ${te}(${Array(8).fill(`${L?`zero_point${F}`:"zero_point"}`).join(",")})) * scale${F};`}; workgroup_shared[local_id.x * ${P} + ${Math.floor(F/f)}]${f>1?`[${F%f}]`:""} += ${Array.from({length:8/u},(G,R)=>`${u===1?`a_data[${R}] * b_dequantized_values[${R}]`:`dot(a_data[${R}], b_dequantized_values[${R}])`}`).join(" + ")}; `;return N},ce=()=>{let N=` var col_index = col * ${f}; ${L?` 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 = ${Q}(8);`} `;for(let F=0;F> 0x1u); zero_point_word_index = zero_point_byte_count >> 0x2u; zero_point_byte_offset = zero_point_byte_count & 0x3u; zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); zero_point_word = ${L.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${F} = ${Q}((zero_point_word) & 0xFu);`:""} col_index += 1;`;return N},le=()=>{let N=`col_index = col * ${f};`;for(let F=0;F; var b_value_upper: vec4; var b_quantized_values: ${te}; var b_dequantized_values: ${te};`,N};return` var workgroup_shared: array<${X.type.value}, ${P*M}>; ${v.declareVariables(...q,X)} ${v.mainStart([M,1,1])} let output_indices = ${X.offsetToIndices(`(global_idx / ${M}) * ${P}`)}; 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 += ${M}) { //process one block var word_offset: u32 = block * ${r.blockSize/u}; ${ce()} for (var word: u32 = 0; word < ${c}; word += ${d}) { ${le()} for (var i: u32 = 0; i < ${d}; i++) { ${re()} word_offset += ${8/u}; } } } workgroupBarrier(); if (local_id.x < ${P}) { var output_value: ${X.type.value} = ${X.type.value}(0); var workgroup_shared_offset: u32 = local_id.x; for (var b: u32 = 0u; b < ${M}u; b++) { output_value += workgroup_shared[workgroup_shared_offset]; workgroup_shared_offset += ${P}; } ${X.setByIndices(`${X.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${u};${d};${f};${P};${M}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:I},programUniforms:g}),getShaderSource:w}},Mg=(e,r)=>{let t=e[0].dims,s=t.length,n=t[s-2],o=r.k,a=r.n,i=t.slice(0,s-2),l=we.size(i),c=e[1].dims[2]/4,p=e[0].dataType,u=Wt(r.k),d=Wt(c),f=i.concat([n,a]),_=128,P=a%8===0?8:a%4===0?4:1,I=_/P,M=I*d*8,g=M/u,S=M/r.blockSize,E=we.size(f)/P,x=[],w=[l,n,o/u],v=we.convertShape(e[1].dims).slice();v.splice(-1,1,c/d),x.push(...Ze(w)),x.push(...Ze(v)),x.push(...Ze(e[2].dims)),e.length===4&&x.push(...Ze(we.convertShape(e[3].dims)));let $=[l,n,a];x.push(...Ze($));let O=B=>{let H=w.length,q=Pe("a",e[0].dataType,H,u),L=Pe("b",12,v.length,d),J=Pe("scales",e[2].dataType,e[2].dims.length),X=[q,L,J],Q=e.length===4?Pe("zero_points",12,e[3].dims.length):void 0;Q&&X.push(Q);let te=$.length,re=Qe("output",e[0].dataType,te),ce=hr(e[0].dataType),le=()=>{switch(u){case 1:return` let a_data0 = vec4<${ce}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${ce}>(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<${ce}>(sub_a[word_offset], sub_a[word_offset + 1]); let a_data1 = vec4<${ce}>(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(`${u}-component is not supported.`)}};return` var sub_a: array<${q.type.value}, ${g}>; var inter_results: array, ${P}>; ${B.declareVariables(...X,re)} ${B.mainStart([I,P,1])} let output_indices = ${re.offsetToIndices(`workgroup_index * ${P}`)}; 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) / ${S} + 1; // Loop over shared dimension. for (var tile: u32 = 0; tile < num_tiles; tile += 1) { let a_col_start = tile * ${g}; // load one tile A data into shared memory. for (var a_offset = local_idx; a_offset < ${g}; a_offset += ${_}) { let a_col = a_col_start + a_offset; if (a_col < uniforms.a_shape[2]) { sub_a[a_offset] = ${q.getByIndices(`${q.type.indices}(batch, row, a_col)`)}; } else { sub_a[a_offset] = ${q.type.value}(0); } } workgroupBarrier(); // each thread process one block let b_row = col + local_id.y; let block = tile * ${S} + local_id.x; ${Q?` 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 = ${Q.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point = ${ce}((zero_point_word) & 0xFu);`:` // The default zero point is 8 for unsigned 4-bit quantization. let zero_point = ${ce}(8);`} let scale = ${J.getByOffset("b_row * n_blocks_per_col + block")}; let b_data = ${L.getByIndices(`${L.type.indices}(b_row, block, 0)`)}; var word_offset = local_id.x * ${r.blockSize/u}; for (var i: u32 = 0; i < ${d}; i++) { ${le()} let b_value = ${d===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<${ce}>(${Array.from({length:4},(N,F)=>`${ce}(b_value_lower[${F}]), ${ce}(b_value_upper[${F}])`).join(", ")}); let b_dequantized_values = (b_quantized_values - mat2x4<${ce}>(${Array(8).fill("zero_point").join(",")})) * scale; inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(N,F)=>`${`dot(a_data${F}, b_dequantized_values[${F}])`}`).join(" + ")}; word_offset += ${8/u}; } workgroupBarrier(); } if (local_idx < ${P}) { var output_value: ${re.type.value} = ${re.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]) { ${re.setByIndices(`${re.type.indices}(batch, row, col + local_idx)`,"output_value")} } } }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${u};${d};${I};${P}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:E},programUniforms:x}),getShaderSource:O}},gy=(e,r)=>{gg(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(Mg(e.inputs,r)):e.compute(wg(e.inputs,r))},wy=e=>Pt(e)}),bg,yg,vg,xg,Tg,Eg,Pg,Cg,My,Tx=ze(()=>{at(),mt(),ht(),bg=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].")}},yg=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${Je("uniforms.pads",n,t)}; if (k < 0) { break; } if (k >= i32(${Je("uniforms.x_shape",n,r)})) { break; } offset += k * i32(${Je("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]; } `},vg=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${Je("uniforms.pads",n,t)}; if (k < 0) { k = -k; } { let _2n_1 = 2 * (i32(${Je("uniforms.x_shape",n,r)}) - 1); k = k % _2n_1; if(k >= i32(${Je("uniforms.x_shape",n,r)})) { k = _2n_1 - k; } } offset += k * i32(${Je("uniforms.x_strides",n,r)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},xg=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${Je("uniforms.pads",n,t)}; if (k < 0) { k = 0; } if (k >= i32(${Je("uniforms.x_shape",n,r)})) { k = i32(${Je("uniforms.x_shape",n,r)}) - 1; } offset += k * i32(${Je("uniforms.x_strides",n,r)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},Tg=(e,r,t)=>{let s="";for(let n=r-1;n>=0;--n)s+=` k = i32(${e.indicesGet("indices",n)}) - ${Je("uniforms.pads",n,t)}; if (k < 0) { k += i32(${Je("uniforms.x_shape",n,r)}]); } if (k >= i32(${Je("uniforms.x_shape",n,r)})) { k -= i32(${Je("uniforms.x_shape",n,r)}); } offset += k * i32(${Je("uniforms.x_strides",n,r)}); `;return` var offset = 0; var k = 0; ${s} value = x[offset]; `},Eg=(e,r,t)=>{switch(t.mode){case 0:return yg(e,r,t.pads.length);case 1:return vg(e,r,t.pads.length);case 2:return xg(e,r,t.pads.length);case 3:return Tg(e,r,t.pads.length);default:throw new Error("Invalid mode")}},Pg=(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}],a=e.length>=3&&e[2].data;r.mode===0&&o.push({type:a?e[2].dataType:1,data:r.value}),o.push(...Ze(e[0].dims,t));let i=["rank"],l=c=>{let p=Qe("output",e[0].dataType,t.length),u=Pe("x",e[0].dataType,s.length),d=u.type.value,f=Eg(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:a?d:"f32"}),` ${c.registerUniforms(_).declareVariables(u,p)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let indices = ${p.offsetToIndices("global_idx")}; var value = ${d}(0); ${f} output[global_idx] = value; }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${a}`,inputDependencies:i},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(we.size(t)/64)},programUniforms:o}),getShaderSource:l}},Cg=(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 i=e[3].getBigInt64Array();for(let l=0;lo[Number(l)]=Number(i));let a=[];return o.forEach(i=>a.push(i)),{mode:r.mode,value:s,pads:a}}else return r},My=(e,r)=>{bg(e.inputs);let t=Cg(e.inputs,r);e.compute(Pg(e.inputs,t),{inputs:[0]})}}),zo,ou,iu,au,lu,Sg,$g,uu,cu,by,yy,du,vy,xy,pu,Ty,Ey,Py,Cy,Ex=ze(()=>{is(),at(),mt(),ht(),zo=e=>{if(Lt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},ou=(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"),a=r.kernelShape.slice(),i=r.strides.slice(),l=o?r.dilations.slice():[],c=r.pads.slice();oa.adjustPoolAttributes(t,n,a,i,l,c);let p=oa.computePoolOutputShape(t,n,i,l,a,c,r.autoPad),u=Object.assign({},r);o?Object.assign(u,{kernelShape:a,strides:i,pads:c,dilations:l,cacheKey:r.cacheKey}):Object.assign(u,{kernelShape:a,strides:i,pads:c,cacheKey:r.cacheKey});let d=p.slice();return d.push(d.splice(1,1)[0]),[u,s?d:p]},iu=(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}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let i=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],u=!!(c+p);o.push({type:12,data:i},{type:12,data:l},{type:12,data:c},{type:12,data:p}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let d=!1;if(r.kernelShape.length===2){let f=r.kernelShape[r.kernelShape.length-2],_=r.strides[r.strides.length-2],P=r.pads[r.pads.length/2-2],I=r.pads[r.pads.length-2];d=!!(P+I),o.push({type:12,data:f},{type:12,data:_},{type:12,data:P},{type:12,data:I}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[o,a,!0,u,d]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let i=we.computeStrides(r.kernelShape);o.push({type:12,data:i},{type:12,data:r.pads},{type:12,data:r.strides}),a.push({name:"kernelStrides",type:"u32",length:i.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,a,!!l,!1,!1]}},au=(e,r,t,s,n,o,a,i,l,c,p,u)=>{let d=n.format==="NHWC",f=r.type.value,_=Qe("output",r.type.tensor,s);if(n.kernelShape.length<=2){let P="",I="",M="",g=t-(d?2:1);if(p?P=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${g}] < 0 || xIndices[${g}] >= uniforms.x_shape[${g}]) { pad++; continue; } let x_val = x[${r.indicesToOffset("xIndices")}]; ${o} }`:P=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; let x_val = x[${r.indicesToOffset("xIndices")}]; ${o} }`,n.kernelShape.length===2){let S=t-(d?3:2);u?I=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${S}] = indices[${S}] * uniforms.sh - uniforms.phStart + j; if (xIndices[${S}] < 0 || xIndices[${S}] >= uniforms.x_shape[${S}]) { pad += i32(uniforms.kw); continue; } `:I=` for (var j: u32 = 0u; j < uniforms.kh; j++) { xIndices[${S}] = indices[${S}] * uniforms.sh - uniforms.phStart + j; `,M=` } `}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}(${i}); var pad = 0; ${I} ${P} ${M} ${a} output[global_idx] = value; }`}else{if(d)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let P=n.kernelShape.length,I=n.pads.length,M="";return c?M=` if (xIndices[j] >= uniforms.x_shape[j]) { pad++; isPad = true; break; } } if (!isPad) { let x_val = x[${r.indicesToOffset("xIndices")}]; ${o} }`:M=` } 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}(${i}); var pad = 0; var isPad = false; for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { var offset = i; for (var j = 0u; j < ${P-1}u; j++) { offsets[j] = offset / ${Je("uniforms.kernelStrides","j",P)}; offset -= offsets[j] * ${Je("uniforms.kernelStrides","j",P)}; } offsets[${P-1}] = offset; isPad = false; for (var j = ${t-P}u; j < ${t}u; j++) { xIndices[j] = indices[j] * ${Je("uniforms.strides",`j - ${t-P}u`,P)} + offsets[j - ${t-P}u] - ${Je("uniforms.pads","j - 2u",I)}; ${M} } ${a} output[global_idx] = value; }`}},lu=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Sg=e=>`${lu(e)};${e.countIncludePad}`,$g=e=>`${lu(e)};${e.storageOrder};${e.dilations}`,uu=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}),cu=(e,r,t,s)=>{let[n,o]=ou(r,s,t),a=Pe("x",r.dataType,r.dims.length),i=a.type.value,l="value += x_val;",c="";n.countIncludePad?c+=`value /= ${i}(uniforms.kernelSize);`:c+=`value /= ${i}(i32(uniforms.kernelSize) - pad);`;let[p,u,d,f,_]=iu(o,n);p.push(...Ze(r.dims,o));let P=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${d};${f};${_}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:o,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(we.size(o)/64)},programUniforms:p}),getShaderSource:I=>au(I,a,r.dims.length,o.length,n,l,c,0,u,d,f,_)}},by=e=>{let r=e.count_include_pad!==0,t=uu(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:Sg(s)}},yy=(e,r)=>{zo(e.inputs),e.compute(cu("AveragePool",e.inputs[0],!1,r))},du={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},vy=e=>{let r=e.format;return{format:r,...du,cacheKey:r}},xy=(e,r)=>{zo(e.inputs),e.compute(cu("GlobalAveragePool",e.inputs[0],!0,r))},pu=(e,r,t,s)=>{let[n,o]=ou(r,s,t),a=` value = max(x_val, value); `,i="",l=Pe("x",r.dataType,r.dims.length),c=["rank"],[p,u,d,f,_]=iu(o,n);return p.push(...Ze(r.dims,o)),{name:e,shaderCache:{hint:`${s.cacheKey};${d};${f};${_}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:o,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(we.size(o)/64)},programUniforms:p}),getShaderSource:P=>au(P,l,r.dims.length,o.length,n,a,i,r.dataType===10?-65504:-1e5,u,d,f,_)}},Ty=(e,r)=>{zo(e.inputs),e.compute(pu("MaxPool",e.inputs[0],!1,r))},Ey=e=>{let r=e.storage_order,t=e.dilations,s=uu(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:$g(n)}},Py=e=>{let r=e.format;return{format:r,...du,cacheKey:r}},Cy=(e,r)=>{zo(e.inputs),e.compute(pu("GlobalMaxPool",e.inputs[0],!0,r))}}),kg,Ig,Sy,$y,Px=ze(()=>{at(),mt(),Kt(),ht(),kg=(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)].")}},Ig=(e,r)=>{let t=we.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,n=s===3,o=e[0].dims,a=e[1].dataType,i=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,u=e.length>2?e[2]:void 0,d=u?l?[Math.ceil(we.size(u.dims)/4)]:u.dims:void 0,f=p.length===0||p.length===1&&p[0]===1,_=f===!1&&p.length===1,P=Wt(i),I=f&&(!l||P===4),M=I?P:1,g=I&&!l?P:1,S=Pe("input",l?12:s,c.length,g),E=Pe("scale",a,p.length),x=u?Pe("zero_point",l?12:s,d.length):void 0,w=Qe("output",a,o.length,M),v=[S,E];x&&v.push(x);let $=[c,p];u&&$.push(d);let O=[{type:12,data:i/M},{type:12,data:t},{type:12,data:r.blockSize},...Ze(...$,o)],B=H=>{let q=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${H.registerUniforms(q).declareVariables(...v,w)} ${H.mainStart()} ${H.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${w.offsetToIndices("global_idx")}; // Set input x ${l?` let input = ${S.getByOffset("global_idx / 4")}; let x_vec = ${n?"unpack4xI8(input)":"unpack4xU8(input)"}; let x_value = ${M===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${S.getByOffset("global_idx")};`}; // Set scale input ${f?`let scale_value= ${E.getByOffset("0")}`:_?` let scale_index = ${w.indicesGet("output_indices","uniforms.axis")}; let scale_value= ${E.getByOffset("scale_index")};`:` var scale_indices: ${E.type.indices} = output_indices; let index = ${E.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; ${E.indicesSet("scale_indices","uniforms.axis","index")}; let scale_value= ${E.getByIndices("scale_indices")};`}; // Set zero-point input ${x?f?l?` let zero_point_input = ${x.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 = ${x.getByOffset("0")}`:_?l?` let zero_point_index = ${w.indicesGet("output_indices","uniforms.axis")}; let zero_point_input = ${x.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 = ${w.indicesGet("output_indices","uniforms.axis")}; let zero_point_value = ${x.getByOffset("zero_point_index")};`:l?` let zero_point_offset = ${E.indicesToOffset("scale_indices")}; let zero_point_input = ${x.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 = ${x.getByIndices("scale_indices")};`:`let zero_point_value = ${l?n?"i32":"u32":S.type.value}(0);`}; // Compute and write output ${w.setByOffset("global_idx",`${w.type.value}(x_value - zero_point_value) * scale_value`)}; }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:x?["rank","rank","rank"]:["rank","rank"]},getShaderSource:B,getRunData:()=>({outputs:[{dims:o,dataType:a}],dispatchGroup:{x:Math.ceil(i/M/64),y:1,z:1},programUniforms:O})}},Sy=(e,r)=>{kg(e.inputs,r),e.compute(Ig(e.inputs,r))},$y=e=>Pt({axis:e.axis,blockSize:e.blockSize})}),Ag,Fg,ky,Cx=ze(()=>{is(),at(),ht(),Ag=(e,r,t)=>{let s=e===r,n=er&&t>0;if(s||n||o)throw new Error("Range these inputs' contents are invalid.")},Fg=(e,r,t,s)=>{let n=Math.abs(Math.ceil((r-e)/t)),o=[n],a=n,i=[{type:12,data:a},{type:s,data:e},{type:s,data:t},...Ze(o)],l=c=>{let p=Qe("output",s,o.length),u=p.type.value,d=[{name:"outputSize",type:"u32"},{name:"start",type:u},{name:"delta",type:u}];return` ${c.registerUniforms(d).declareVariables(p)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${u}(global_idx) * uniforms.delta; }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:o,dataType:s}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:i})}},ky=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]),Lt.webgpu.validateInputContent&&Ag(r,t,s),e.compute(Fg(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),Og,mu,hu,Dg,Iy,Ay,Sx=ze(()=>{at(),mt(),Kt(),ht(),Og=(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.`)}},mu=(e,r)=>`${e===1?` let element_count_dim = uniforms.output_strides; let dim_value = uniforms.output_shape;`:` let element_count_dim = uniforms.output_strides[${r?"i - indices_start":"i"}]; let dim_value = uniforms.output_shape[${r?"i - indices_start":"i"} + uniforms.last_index_dimension];`} if (index >= 0) { if (index >= i32(dim_value)) { index = i32(dim_value - 1); } } else { if (index < -i32(dim_value)) { index = 0; } else { index += i32(dim_value); } } data_offset += u32((u32(index) * element_count_dim));`,hu=(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]; ${Og(e.reduction,"output[data_offset + i]","value",r)} }`,Dg=(e,r)=>{let t=e[0].dims,s=e[1].dims,n=t,o=1,a=Math.ceil(we.size(s)/o),i=s[s.length-1],l=we.sizeFromDimension(t,i),c=we.sizeFromDimension(s,0)/i,p=[{type:12,data:a},{type:12,data:i},{type:12,data:l},...Ze(e[1].dims,e[2].dims,n)],u=d=>{let f=Pe("indices",e[1].dataType,e[1].dims.length),_=Pe("updates",e[2].dataType,e[2].dims.length,o),P=r.reduction!=="none"&&r.reduction!==""?iM("output",e[0].dataType,n.length):Qe("output",e[0].dataType,n.length,o);return` ${d.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(f,_,P)} ${d.mainStart()} ${d.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); ${mu(t.length,!1)} } ${hu(r,P.type.value,!1)} } return; } var data_offset = 0u; var indices_start = uniforms.last_index_dimension * global_idx; var indices_end = indices_start + uniforms.last_index_dimension; for (var i = indices_start; i < indices_end; i++) { var index = i32(indices[i].x); ${mu(t.length,!0)} } ${hu(r,P.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(a/64)},programUniforms:p}),getShaderSource:u}},Iy=e=>Pt({reduction:e.reduction}),Ay=(e,r)=>{e.compute(Dg(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Lg,zg,Bg,_u,Rg,Ng,jg,Vg,Ug,Wg,Gg,Kg,fu,Hg,qg,Xg,Qg,Jg,Fy,Oy,$x=ze(()=>{at(),mt(),Kt(),ht(),Lg=(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")}},zg=(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},Bg=(e,r,t,s,n,o)=>{let[a,i,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],c=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].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(i>0&&e.length>i&&e[i].dims.length===1&&e[i].dims[0]>0){if(e[i].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");Lg(s,r),r.axes.length>0&&zg(s,r.axes,c).forEach((p,u)=>s[u]=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")},_u=(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; `,Rg=(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 { ${_u("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 { ${_u("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`)}})()+"}",Ng=(e,r,t)=>`fn getNearestPixelFromOriginal(xOriginal: ${t}, isDownSample: bool) -> ${t} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(r<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",jg=(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,a)=>{s[o]=n[a],s[a+t]=n[r.length+a]}),s):n},Vg=(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,a)=>n[o]=t[a])}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,a)=>Math.round(o*r[a]))}return n},Ug=(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,a)=>n[a]=Math.round(o*r[a]))),n},Wg=(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 = ${Je("uniforms.scales","i",s)}; var roi_low = ${Je("uniforms.roi","i",n)}; var roi_hi = ${Je("uniforms.roi",`i + ${r.length}`,n)}; if (scale == 1.0) { original_indices[i] = ${e.type.value}(output_index); } else { var input_shape_i = ${Je("uniforms.input_shape","i",r.length)}; var output_shape_i = ${Je("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; }`,Gg=(e,r,t,s,n,o,a)=>` 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 = ${Je("uniforms.scales","i",n)}; if (scale == 1.0) { input_index = output_index; } else { var roi_low = ${Je("uniforms.roi","i",o)}; var roi_hi = ${Je("uniforms.roi",`i + ${t.length}`,o)}; var input_shape_i = ${Je("uniforms.input_shape","i",t.length)}; var output_shape_i = ${Je("uniforms.output_shape","i",s.length)}; var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, input_shape_i, roi_low, roi_hi); if (!${a} || (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; }`,Kg=(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 >= ${Je("uniforms.input_shape","i",r.length)}) { return false; } } return true; }`,fu=(e,r,t,s)=>e.rank>s?` ${e.indicesSet("input_indices",r,"channel")}; ${e.indicesSet("input_indices",t,"batch")}; `:"",Hg=(e,r,t,s,n)=>{let[o,a,i,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",a,`max(0, min(row, ${t[a]} - 1))`)}; ${e.indicesSet("input_indices",i,`max(0, min(col, ${t[i]} - 1))`)}; ${fu(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[${a}]; var col:${c} = originalIndices[${i}]; ${s?`if (row < 0 || row > (${t[a]} - 1) || col < 0 || col > (${t[i]} - 1)) { return ${n}; }`:""}; row = max(0, min(row, ${t[a]} - 1)); col = max(0, min(col, ${t[i]} - 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); }`},qg=(e,r,t,s,n,o,a,i,l,c)=>{let p=t.length===2,[u,d]=p?[0,1]:[2,3],f=e.type.value,_=P=>{let I=P===u?"row":"col";return` fn ${I}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${f} { var output_index = ${r.indicesGet("output_indices",P)}; var originalIdx: ${f} = getOriginalCoordinateFromResizedCoordinate(output_index, ${n[P]}, ${s[P]}, ${t[P]}, ${o[P]}, ${o[P]} + ${t.length}); var fractOriginalIdx: ${f} = originalIdx - floor(originalIdx); var coefs = getCubicInterpolationCoefs(fractOriginalIdx); if (${i} && (originalIdx < 0 || originalIdx > (${t[P]} - 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[P]}) { ${c?`coefs[i + 1] = 0.0; continue;`:i?`return ${l};`:`${I} = max(0, min(${I}, ${t[P]} - 1));`}; } var input_indices_copy: ${e.type.indices} = input_indices; ${e.indicesSet("input_indices_copy",P,`u32(${I})`)}; data[i + 1] = ${P===u?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; } return cubicInterpolation1D(data, coefs); }`};return` ${_(u)}; ${_(d)}; 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] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a}; coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1; coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a}; 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); } `},Xg=(e,r,t,s,n)=>{let[o,a,i,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",a,`max(0, min(depth, ${t[a]} - 1))`)}; ${e.indicesSet("input_indices",i,`max(0, min(height, ${t[i]} - 1))`)}; ${e.indicesSet("input_indices",l,`max(0, min(width, ${t[l]} - 1))`)}; ${fu(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[${a}]; var height:${p} = originalIndices[${i}]; var width:${p} = originalIndices[${l}]; ${s?`if (depth < 0 || depth > (${t[a]} - 1) || height < 0 || height > (${t[i]} - 1) || width < 0 || (width > ${t[l]} - 1)) { return ${n}; }`:""}; depth = max(0, min(depth, ${t[a]} - 1)); height = max(0, min(height, ${t[i]} - 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); }`},Qg=(e,r,t,s,n,o)=>{let a=e.dims,i=jg(o,r.axes,a.length),l=Vg(a,s,n,r.axes),c=s.slice();s.length===0&&(c=a.map((g,S)=>g===0?1:l[S]/g),r.keepAspectRatioPolicy!=="stretch"&&(l=Ug(a,c,r)));let p=Qe("output",e.dataType,l.length),u=Pe("input",e.dataType,a.length),d=we.size(l),f=a.length===l.length&&a.every((g,S)=>g===l[S]),_=r.coordinateTransformMode==="tf_crop_and_resize",P=r.extrapolationValue,I=u.type.value,M=g=>` ${f?"":` ${Rg(r.coordinateTransformMode,I)}; ${(()=>{switch(r.mode){case"nearest":return` ${Kg(u,a)}; ${Ng(r.nearestMode,t,I)}; ${Gg(u,p,a,l,c.length,i.length,_)}; `;case"linear":return` ${Wg(p,a,l,c.length,i.length)}; ${(()=>{if(a.length===2||a.length===4)return`${Hg(u,p,a,_,P)}`;if(a.length===3||a.length===5)return`${Xg(u,p,a,_,P)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; `;case"cubic":return` ${(()=>{if(a.length===2||a.length===4)return`${qg(u,p,a,l,c,i,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")}})()}; `} ${g.registerUniform("output_size","u32").registerUniform("scales","f32",c.length).registerUniform("roi","f32",i.length).declareVariables(u,p)} ${g.mainStart()} ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} ${f?"output[global_idx] = input[global_idx];":` let output_indices = ${p.offsetToIndices("global_idx")}; var input_indices: ${u.type.indices}; ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); if (checkInputIndices(input_indices)) { output[global_idx] = ${u.getByIndices("input_indices")}; } else { output[global_idx] = ${r.extrapolationValue}; }`;case"linear":return`output[global_idx] = ${a.length===2||a.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:""}|${i.length>0?i:""}|${f}|${r.mode==="nearest"?a.length:a}`,inputDependencies:["rank"]},getShaderSource:M,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},{type:1,data:c},{type:1,data:i},...Ze(a,l)]})}},Jg=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},Fy=(e,r)=>{let t=[],s=[],n=[],o=Jg(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Bg(e.inputs,r,o,t,s,n),e.compute(Qg(e.inputs[0],r,o,t,s,n),{inputs:[0]})},Oy=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,n=e.cubicCoeffA,o=e.excludeOutside!==0,a=e.extrapolationValue,i=e.keepAspectRatioPolicy,l=e.mode,c=e.nearestMode===""?"simple":e.nearestMode;return Pt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:n,excludeOutside:o,extrapolationValue:a,keepAspectRatioPolicy:i,mode:l,nearestMode:c})}}),Yg,Zg,Dy,kx=ze(()=>{at(),mt(),ht(),Yg=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 a=e[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==n)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error("Bias must be 1D");if(a.dims[a.dims.length-1]!==n)throw new Error("Bias must have the same hidden size as input")}},Zg=(e,r,t,s)=>{let n=r.simplified,o=e[0].dims,a=we.size(o),i=o,l=a,c=o.slice(-1)[0],p=s?o.slice(0,-1).concat(1):[],u=!n&&e.length>3,d=e.length>4,f=s&&t>1,_=s&&t>2,P=t>3,I=64,M=Wt(c),g=[{type:12,data:l},{type:12,data:M},{type:12,data:c},{type:1,data:r.epsilon}],S=x=>{let w=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],v=[Pe("x",e[0].dataType,e[0].dims,M),Pe("skip",e[1].dataType,e[1].dims,M),Pe("gamma",e[2].dataType,e[2].dims,M)];u&&v.push(Pe("beta",e[3].dataType,e[3].dims,M)),d&&v.push(Pe("bias",e[4].dataType,e[4].dims,M)),v.push(Qe("output",e[0].dataType,i,M)),f&&v.push(Qe("mean_output",1,p)),_&&v.push(Qe("inv_std_output",1,p)),P&&v.push(Qe("input_skip_bias_sum",e[0].dataType,i,M));let $=hr(e[0].dataType),O=hr(1,M);return` ${x.registerUniforms(w).declareVariables(...v)} var sum_shared : array<${O}, ${I}>; var sum_squared_shared : array<${O}, ${I}>; ${x.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 = ${d?"bias[offset1d + i]":$+"(0.0)"}; let input_value = x[offset + i]; let value = input_value + skip_value + bias_value; ${P?"input_skip_bias_sum[offset + i] = value;":""} output[offset + i] = value; let f32_value = ${eo($,M,"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 = ${Ws("sum",M)} / f32(uniforms.hidden_size); let inv_std_dev = inverseSqrt(${Ws("square_sum",M)} / 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?"":`- ${$}(mean)`}) * ${$}(inv_std_dev) * gamma[offset1d + i] ${u?"+ beta[offset1d + i]":""}; } }`},E=[{dims:i,dataType:e[0].dataType}];return t>1&&E.push({dims:p,dataType:1}),t>2&&E.push({dims:p,dataType:1}),t>3&&E.push({dims:o,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${M};${f};${_};${P}`,inputDependencies:e.map((x,w)=>"type")},getShaderSource:S,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/c)},programUniforms:g})}},Dy=(e,r)=>{Yg(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(Zg(e.inputs,r,e.outputCount,!1),{outputs:t})}}),ew,Bo,tw,gu,rw,sw,Ly,zy,Ix=ze(()=>{at(),mt(),Kt(),ht(),ew=(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`)})},Bo=(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},tw=(e,r)=>{if(e.length>1){let t=Bo(e,1),s=Bo(e,2),n=Bo(e,3);return n.length===0&&(n=[...Array(e[0].dims.length).keys()]),Pt({starts:t,ends:s,axes:n})}else return r},gu=(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]]))},rw=(e,r,t)=>`fn calculateInputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${t.length}; i >= 0; i--) { let input_shape_i = ${Je("uniforms.input_shape","i",t.length)}; let steps_i = ${Je("uniforms.steps","i",t.length)}; let signs_i = ${Je("uniforms.signs","i",t.length)}; let starts_i = ${Je("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; }`,sw=(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=Bo(e,4);o.forEach(M=>M!==0||(()=>{throw new Error("step cannot be 0")})),o.length===0&&(o=Array(n.length).fill(1));let a=r.starts.map((M,g)=>gu(M,g,t,n,o)),i=r.ends.map((M,g)=>gu(M,g,t,n,o));if(n.length!==a.length||n.length!==i.length)throw new Error("start, ends and axes should have the same number of elements");if(n.length!==t.length)for(let M=0;MMath.sign(M));o.forEach((M,g,S)=>{if(M<0){let E=(i[g]-a[g])/M,x=a[g],w=x+E*o[g];a[g]=w,i[g]=x,S[g]=-M}});let c=t.slice(0);n.forEach((M,g)=>{c[M]=Math.ceil((i[M]-a[M])/o[M])});let p={dims:c,dataType:e[0].dataType},u=Qe("output",e[0].dataType,c.length),d=Pe("input",e[0].dataType,e[0].dims.length),f=we.size(c),_=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:o.length}],P=[{type:12,data:f},{type:12,data:a},{type:6,data:l},{type:12,data:o},...Ze(e[0].dims,c)],I=M=>` ${M.registerUniforms(_).declareVariables(d,u)} ${rw(d,u,t)} ${M.mainStart()} ${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${u.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${u.setByOffset("global_idx",d.getByIndices("input_indices"))} }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${a.length}_${o.length}`,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:P})}},Ly=(e,r)=>{ew(e.inputs,r);let t=tw(e.inputs,r);e.compute(sw(e.inputs,t),{inputs:[0]})},zy=e=>{let r=e.starts,t=e.ends,s=e.axes;return Pt({starts:r,ends:t,axes:s})}}),nw,ow,By,Ry,Ax=ze(()=>{at(),mt(),Kt(),Gs(),ht(),nw=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},ow=(e,r)=>{let t=e.inputs[0],s=t.dims,n=we.size(s),o=s.length,a=we.normalizeAxis(r.axis,o),i=a$),c[a]=o-1,c[o-1]=a,l=e.compute(Fr(t,c),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,u=p[o-1],d=n/u,f=Wt(u),_=u/f,P=64;d===1&&(P=256);let I=(v,$)=>$===4?`max(max(${v}.x, ${v}.y), max(${v}.z, ${v}.w))`:$===2?`max(${v}.x, ${v}.y)`:$===3?`max(max(${v}.x, ${v}.y), ${v}.z)`:v,M=Pe("x",l.dataType,l.dims,f),g=Qe("result",l.dataType,l.dims,f),S=M.type.value,E=hr(l.dataType)==="f32"?`var threadMax = ${S}(-3.402823e+38f);`:`var threadMax = ${S}(-65504.0h);`,x=v=>` var rowMaxShared : ${S}; var rowSumShared : ${S}; var threadShared : array<${S}, ${P}>; fn getValue(row: i32, col: i32, row_stride: i32) -> ${S} { let index = row * row_stride + col; return x[index]; } fn setValue(row: i32, col: i32, row_stride: i32, value: ${S}) { let index = row * row_stride + col; result[index] = value; } ${v.registerUniform("packedCols","i32").declareVariables(M,g)} ${v.mainStart(P)} let gindex = i32(global_idx); let lindex = i32(local_idx); const wg = ${P}; let row = gindex / wg; let cols = uniforms.packedCols; let row_stride : i32 = uniforms.packedCols; // find the rows max ${E} for (var col = lindex; col < cols; col += wg) { let value = getValue(row, col, row_stride); threadMax = max(threadMax, value); } if (lindex < cols) { threadShared[lindex] = threadMax; } workgroupBarrier(); var reduceSize = min(cols, wg); for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { reduceSize = currSize + (reduceSize & 1); if (lindex < currSize) { threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); } workgroupBarrier(); } if (lindex == 0) { rowMaxShared = ${S}(${I("threadShared[0]",f)}); } workgroupBarrier(); // find the rows sum var threadSum = ${S}(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 = ${S}(${Ws("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); } }`,w=e.compute({name:"Softmax",shaderCache:{hint:`${f};${P}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:d},programUniforms:[{type:6,data:_}]}),getShaderSource:x},{inputs:[l],outputs:[i?-1:0]})[0];i&&e.compute(Fr(w,c),{inputs:[w]})},By=(e,r)=>{nw(e.inputs),ow(e,r)},Ry=e=>Pt({axis:e.axis})}),wu,iw,aw,lw,Ny,Fx=ze(()=>{at(),mt(),ht(),wu=e=>Array.from(e.getBigInt64Array(),Number),iw=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(wu(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")},aw=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??wu(e[1]),n=aw(t,s),o=we.size(n),a=e[0].dataType,i=Pe("input",a,t.length),l=Qe("output",a,n.length),c=p=>` const inputShape = ${i.indices(...t)}; ${p.registerUniform("output_size","u32").declareVariables(i,l)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${l.offsetToIndices("global_idx")}; var input_indices: ${i.type.indices}; for (var i = 0; i < ${t.length}; i++) { let input_dim_i = ${i.indicesGet("uniforms.input_shape","i")}; let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i; ${i.indicesSet("input_indices","i","input_dim_value")} } ${l.setByOffset("global_idx",i.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},...Ze(e[0].dims,n)]}),getShaderSource:c}},Ny=e=>{iw(e.inputs),e.compute(lw(e.inputs),{inputs:[0]})}}),uw,cw,jy,Ox=ze(()=>{at(),mt(),ht(),uw=(e,r,t,s,n)=>{let o=Qe("output_data",n,t.length,4),a=Pe("a_data",r[1].dataType,r[1].dims.length,4),i=Pe("b_data",r[2].dataType,r[2].dims.length,4),l=Pe("c_data",r[0].dataType,r[0].dims.length,4),c,p=(u,d,f)=>`select(${d}, ${u}, ${f})`;if(!s)c=o.setByOffset("global_idx",p(a.getByOffset("global_idx"),i.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let u=(d,f,_="")=>{let P=`a_data[index_a${f}][component_a${f}]`,I=`b_data[index_b${f}][component_b${f}]`,M=`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} = ${a.broadcastedIndicesToOffset(`output_indices${f}`,o)}; let offset_b${f} = ${i.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; ${d}[${f}] = ${_}(${p(P,I,M)}); `};n===9?c=` var data = vec4(0); ${u("data",0,"u32")} ${u("data",1,"u32")} ${u("data",2,"u32")} ${u("data",3,"u32")} output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:c=` ${u("output_data[global_idx]",0)} ${u("output_data[global_idx]",1)} ${u("output_data[global_idx]",2)} ${u("output_data[global_idx]",3)} `}return` ${e.registerUniform("vec_size","u32").declareVariables(l,a,i,o)} ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${c} }`},cw=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)),a=r,i=we.size(r);if(o){let c=ro.calcShape(ro.calcShape(r,t,!1),s,!1);if(!c)throw new Error("Can't perform where op on the given tensors");a=c,i=we.size(a)}let l=Math.ceil(i/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:c=>uw(c,e,a,o,n),getRunData:()=>({outputs:[{dims:a,dataType:n}],dispatchGroup:{x:Math.ceil(i/64/4)},programUniforms:[{type:12,data:l},...Ze(s,r,t,a)]})}},jy=e=>{e.compute(cw(e.inputs))}}),Vy,Dx=ze(()=>{Xv(),nc(),Qv(),Jv(),Yv(),Zv(),ex(),ox(),ax(),lx(),ux(),cx(),dx(),px(),mx(),hx(),_x(),fx(),gx(),wx(),Mx(),bx(),yx(),vx(),xx(),ay(),Tx(),Ex(),Px(),Cx(),Sx(),sc(),$x(),py(),kx(),Ix(),Ax(),cy(),Fx(),Gs(),oc(),Ox(),Vy=new Map([["Abs",[DM]],["Acos",[LM]],["Acosh",[zM]],["Add",[gb]],["ArgMax",[IM,Au]],["ArgMin",[kM,Au]],["Asin",[BM]],["Asinh",[RM]],["Atan",[NM]],["Atanh",[jM]],["Attention",[AM]],["AveragePool",[yy,by]],["BatchNormalization",[FM]],["BiasAdd",[OM]],["BiasSplitGelu",[fb]],["Cast",[UM,VM]],["Ceil",[GM]],["Clip",[WM]],["Concat",[Cb,Sb]],["Conv",[Bu,zu]],["ConvTranspose",[Bb,zb]],["Cos",[KM]],["Cosh",[HM]],["CumSum",[Rb,Nb]],["DepthToSpace",[jb,Vb]],["DequantizeLinear",[Sy,$y]],["Div",[wb]],["Einsum",[Ub,Wb]],["Elu",[qM,Uo]],["Equal",[Mb]],["Erf",[XM]],["Exp",[QM]],["Expand",[Gb]],["FastGelu",[Kb]],["Floor",[JM]],["FusedConv",[Bu,zu]],["Gather",[qb,Hb]],["GatherElements",[ey,Zb]],["GatherBlockQuantized",[Jb,Yb]],["GatherND",[Xb,Qb]],["Gelu",[YM]],["Gemm",[ry,ty]],["GlobalAveragePool",[xy,vy]],["GlobalMaxPool",[Cy,Py]],["Greater",[xb]],["GreaterOrEqual",[Eb]],["GridSample",[sy,ny]],["GroupQueryAttention",[my]],["HardSigmoid",[ib,ob]],["InstanceNormalization",[hy]],["LayerNormalization",[_y]],["LeakyRelu",[ZM,Uo]],["Less",[Tb]],["LessOrEqual",[Pb]],["Log",[hb]],["MatMul",[fy]],["MatMulNBits",[gy,wy]],["MaxPool",[Ty,Ey]],["Mul",[bb]],["MultiHeadAttention",[iy,oy]],["Neg",[tb]],["Not",[eb]],["Pad",[My]],["Pow",[yb]],["QuickGelu",[_b,Uo]],["Range",[ky]],["Reciprocal",[rb]],["ReduceMin",[EM]],["ReduceMean",[bM]],["ReduceMax",[TM]],["ReduceSum",[CM]],["ReduceProd",[PM]],["ReduceL1",[yM]],["ReduceL2",[vM]],["ReduceLogSum",[$M]],["ReduceLogSumExp",[xM]],["ReduceSumSquare",[SM]],["Relu",[sb]],["Resize",[Fy,Oy]],["RotaryEmbedding",[dy]],["ScatterND",[Ay,Iy]],["Sigmoid",[nb]],["Sin",[ab]],["Sinh",[lb]],["Slice",[Ly,zy]],["SkipLayerNormalization",[Dy]],["Split",[ly,uy]],["Sqrt",[ub]],["Softmax",[By,Ry]],["Sub",[vb]],["Tan",[cb]],["Tanh",[db]],["ThresholdedRelu",[mb,Uo]],["Tile",[Ny]],["Transpose",[lM,uM]],["Where",[jy]]])}),Uy,Lx=ze(()=>{is(),Ss(),ht(),Uy=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){os(e.programInfo.name);let o=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let i=[];for(let c of r)i.push({binding:i.length,resource:{buffer:c.buffer}});for(let c of t)i.push({binding:i.length,resource:{buffer:c.buffer}});n&&i.push({binding:i.length,resource:n});let l=o.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:i,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)}a.setPipeline(e.computePipeline),a.setBindGroup(0,l),a.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(),Vr(e.programInfo.name)}dispose(){}build(e,r){os(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=aM(r,this.backend.device.limits),o=e.getShaderSource(n),a=`${s.join(` `)} ${n.additionalImplementations} ${o}`,i=t.createShaderModule({code:a,label:e.name});yt("verbose",()=>`[WebGPU] ${e.name} shader code: ${a}`);let l=t.createComputePipeline({compute:{module:i,entryPoint:"main"},layout:"auto",label:e.name});return Vr(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,a=Math.ceil(Math.sqrt(o));if(a>n){if(a=Math.ceil(Math.cbrt(o)),a>n)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),Wy={};no(Wy,{WebGpuBackend:()=>Gy});var dw,pw,mw,Gy,zx=ze(()=>{is(),at(),Ss(),rM(),Hv(),Dx(),Lx(),dw=(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+`:${dw(r,e.shaderCache?.inputDependencies??new Array(r.length).fill("dims"))}`,s},mw=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},Gy=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 mw(r.info||await r.requestAdapterInfo()),this.gpuDataManager=oM(this),this.programManager=new Uy(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Zu(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;os(),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=d);let _=Number(d-this.queryTimeBase),P=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(_)||!Number.isSafeInteger(P))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:Cs(I.dataType)})),outputsMetadata:u.map(I=>({dims:I.dims,dataType:Cs(I.dataType)})),kernelId:o,kernelType:i,kernelName:l,programName:c,startTime:_,endTime:P});else{let I="";p.forEach((g,S)=>{I+=`input[${S}]: [${g.dims}] | ${Cs(g.dataType)}, `});let M="";u.forEach((g,S)=>{M+=`output[${S}]: [${g.dims}] | ${Cs(g.dataType)}, `}),console.log(`[profiling] kernel "${o}|${i}|${l}|${c}" ${I}${M}execution time: ${P-_} ns`)}Ho("GPU",`${c}::${d}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),Vr()}run(e,r,t,s,n,o){os(e.name);let a=[];for(let g=0;gS):t;if(p.length!==i.length)throw new Error(`Output size ${p.length} must be equal to ${i.length}.`);let u=[],d=[];for(let g=0;g=o)throw new Error(`Invalid output index: ${p[g]}`);if(p[g]===-3)continue;let S=p[g]===-1,E=p[g]===-2,x=S||E?n(i[g].dataType,i[g].dims):s(p[g],i[g].dataType,i[g].dims);if(u.push(x),x.data===0)continue;let w=this.gpuDataManager.get(x.data);if(!w)throw new Error(`no GPU data for output: ${x.data}`);if(S&&this.temporaryData.push(w),E){let v=this.kernelPersistentData.get(this.currentKernelId);v||(v=[],this.kernelPersistentData.set(this.currentKernelId,v)),v.push(w)}d.push(w)}if(a.length!==r.length||d.length!==u.length){if(d.length===0)return Vr(e.name),u;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 g=0,S=[];c.forEach(v=>{let $=typeof v.data=="number"?[v.data]:v.data;if($.length===0)return;let O=v.type===10?2:4,B,H;v.type===10?(H=$.length>4?16:$.length>2?8:$.length*O,B=$.length>4?16:O*$.length):(H=$.length<=2?$.length*O:16,B=16),g=Math.ceil(g/H)*H,S.push(g);let q=v.type===10?8:4;g+=$.length>4?Math.ceil($.length/q)*B:$.length*O});let E=16;g=Math.ceil(g/E)*E;let x=new ArrayBuffer(g);c.forEach((v,$)=>{let O=S[$],B=typeof v.data=="number"?[v.data]:v.data;if(v.type===6)new Int32Array(x,O,B.length).set(B);else if(v.type===12)new Uint32Array(x,O,B.length).set(B);else if(v.type===10)new Uint16Array(x,O,B.length).set(B);else if(v.type===1)new Float32Array(x,O,B.length).set(B);else throw new Error(`Unsupported uniform type: ${Cs(v.type)}`)});let w=this.gpuDataManager.create(g,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(w.buffer,0,x,0,g),this.gpuDataManager.release(w.id),f={offset:0,size:g,buffer:w.buffer}}let _=this.programManager.normalizeDispatchGroupSize(l),P=_[1]===1&&_[2]===1,I=pw(e,r,P),M=this.programManager.getArtifact(I);if(M||(M=this.programManager.build(e,_),this.programManager.setArtifact(I,M),yt("info",()=>`[artifact] key: ${I}, programName: ${e.name}`)),c&&M.uniformVariablesInfo){if(c.length!==M.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${M.uniformVariablesInfo.length}, got ${c.length} in program "${M.programInfo.name}".`);for(let g=0;g`[ProgramManager] run "${e.name}" (key=${I}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let g={kernelId:this.currentKernelId,programName:M.programInfo.name,inputTensorViews:r,outputTensorViews:u};this.pendingKernels.push(g),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(g)}return this.programManager.run(M,a,d,_,f),Vr(e.name),u}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=Vy.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,a=s.kernelEntry,i=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${n}] ${o}" is not allowed to be called recursively`);this.currentKernelId=e,i[0]&&(i[1]=i[0](i[1]),i[0]=void 0),yt("info",()=>`[WebGPU] Start to run kernel "[${n}] ${o}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),a(r,i[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),a=this.gpuDataManager.registerExternalBuffer(t,s,o);return n.set(r,[a,t]),a}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 $u(this,e,r);return ec(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(){yt("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(){yt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){yt("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()}}}),Ky={};no(Ky,{init:()=>Hy});var Xi,hw,Hy,Bx=ze(()=>{at(),Ss(),mt(),Kv(),Xi=class qy{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 qy(this.module,this.dataType,this.data,r)}},hw=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 a=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 i=[];for(let l=0;ltypeof a=="number"?this.inputs[a]:a)??this.inputs,s=r?.outputs??[],n=(a,i,l)=>new Xi(this.module,i,this.output(a,l),l),o=(a,i)=>{let l=wn(a,i);if(!l)throw new Error(`Unsupported data type: ${a}`);let c=l>0?this.backend.gpuDataManager.create(l).id:0;return new Xi(this.module,a,c,i)};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 a=0;a{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=(zx(),Ko(Wy)).WebGpuBackend,a=new o;await a.initialize(t,s),n("webgpu",[a,i=>a.alloc(Number(i)),i=>a.free(i),(i,l,c,p=!1)=>{if(p)yt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(i)}, dst=${Number(l)}, size=${Number(c)}`),a.memcpy(Number(i),Number(l));else{yt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(i)}, gpuDataId=${Number(l)}, size=${Number(c)}`);let u=r.HEAPU8.subarray(Number(i>>>0),Number(i>>>0)+Number(c));a.upload(Number(l),u)}},async(i,l,c)=>{yt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${i}, dataOffset=${l}, size=${c}`),await a.download(Number(i),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+c)>>>0))},(i,l,c)=>a.createKernel(i,Number(l),c,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),i=>a.releaseKernel(i),(i,l,c,p)=>{yt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${c}, kernel=${i}, contextDataOffset=${l}`);let u=new hw(r,a,Number(l));return a.computeKernel(Number(i),u,p)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let o=new nM(t);n("webnn",[o,()=>o.reserveTensorId(),a=>o.releaseTensorId(a),async(a,i,l,c,p)=>o.ensureTensor(a,i,l,c,p),(a,i)=>{o.uploadTensor(a,i)},async(a,i)=>o.downloadTensor(a,i)])}}}),_w,dc,pc,Vs,fw,Mu,ua,mc,hc,bu,_c,fc,gc,Xy=ze(()=>{Uv(),Wv(),at(),xn(),qu(),Yw(),_w=(e,r)=>{Ft()._OrtInit(e,r)!==0&&kt("Can't initialize onnxruntime.")},dc=async e=>{_w(e.wasm.numThreads,na(e.logLevel))},pc=async(e,r)=>{Ft().asyncInit?.();{let t=(Bx(),Ko(Ky)).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",Ft(),e,s)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await t("webnn",Ft(),e)}}},Vs=new Map,fw=e=>{let r=Ft(),t=r.stackSave();try{let s=r.PTR_SIZE,n=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,n,n+s)!==0&&kt("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)}},Mu=(e,r)=>{let t=Ft(),s=t.stackSave(),n=0;try{let o=t.PTR_SIZE,a=t.stackAlloc(2*o);t._OrtGetInputOutputMetadata(e,r,a,a+o)!==0&&kt("Can't get session input/output metadata.");let i=Number(t.getValue(a,"*"));n=Number(t.getValue(a+o,"*"));let l=t.HEAP32[n/4];if(l===0)return[i,0];let c=t.HEAPU32[n/4+1],p=[];for(let u=0;u{let r=Ft(),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]},mc=async(e,r)=>{let t,s,n=Ft();Array.isArray(e)?[t,s]=e:e.buffer===n.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=ua(e);let o=0,a=0,i=0,l=[],c=[],p=[];try{if([a,l]=await Jw(r),r?.externalData&&n.mountExternalData){let E=[];for(let x of r.externalData){let w=typeof x=="string"?x:x.path;E.push(Yu(typeof x=="string"?x:x.data).then(v=>{n.mountExternalData(w,v)}))}await Promise.all(E)}for(let E of r?.executionProviders??[])if((typeof E=="string"?E:E.name)==="webnn"){if(n.shouldTransferToMLTensor=!1,typeof E!="string"){let x=E,w=x?.context,v=x?.gpuDevice,$=x?.deviceType,O=x?.powerPreference;w?n.currentContext=w:v?n.currentContext=await n.webnnCreateMLContext(v):n.currentContext=await n.webnnCreateMLContext({deviceType:$,powerPreference:O})}else n.currentContext=await n.webnnCreateMLContext();break}o=await n._OrtCreateSession(t,s,a),n.webgpuOnCreateSession?.(o),o===0&&kt("Can't create a session."),n.jsepOnCreateSession?.(),n.currentContext&&(n.webnnRegisterMLContext(o,n.currentContext),n.currentContext=void 0,n.shouldTransferToMLTensor=!0);let[u,d]=fw(o),f=!!r?.enableGraphCapture,_=[],P=[],I=[],M=[],g=[];for(let E=0;EE==="gpu-buffer"||E==="ml-tensor")&&(i=n._OrtCreateBinding(o),i===0&&kt("Can't create IO binding."),S={handle:i,outputPreferredLocations:g,outputPreferredLocationsEncoded:g.map(E=>Cu(E))}),Vs.set(o,[o,c,p,S,f,!1]),[o,_,P,I,M]}catch(u){throw c.forEach(d=>n._OrtFree(d)),p.forEach(d=>n._OrtFree(d)),i!==0&&n._OrtReleaseBinding(i)!==0&&kt("Can't release IO binding."),o!==0&&n._OrtReleaseSession(o)!==0&&kt("Can't release session."),u}finally{n._free(t),a!==0&&n._OrtReleaseSessionOptions(a)!==0&&kt("Can't release session options."),l.forEach(u=>n._free(u)),n.unmountExternalData?.()}},hc=e=>{let r=Ft(),t=Vs.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,n,o,a,i]=t;a&&(i&&r._OrtClearBoundOutputs(a.handle)!==0&&kt("Can't clear bound outputs."),r._OrtReleaseBinding(a.handle)!==0&&kt("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&&kt("Can't release session."),Vs.delete(e)},bu=async(e,r,t,s,n,o,a=!1)=>{if(!e){r.push(0);return}let i=Ft(),l=i.PTR_SIZE,c=e[0],p=e[1],u=e[3],d=u,f,_;if(c==="string"&&(u==="gpu-buffer"||u==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&u!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(u==="gpu-buffer"){let M=e[2].gpuBuffer;_=wn(Yn(c),p);{let g=i.jsepRegisterBuffer;if(!g)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');f=g(s,o,M,_)}}else if(u==="ml-tensor"){let M=e[2].mlTensor;_=wn(Yn(c),p);let g=i.webnnRegisterMLTensor;if(!g)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');f=g(s,M,Yn(c),p)}else{let M=e[2];if(Array.isArray(M)){_=l*M.length,f=i._malloc(_),t.push(f);for(let g=0;gi.setValue(I+S*l,g,l===4?"i32":"i64"));let M=i._OrtCreateTensor(Yn(c),f,_,I,p.length,Cu(d));M===0&&kt(`Can't create tensor for input/output. session=${s}, index=${o}.`),r.push(M)}finally{i.stackRestore(P)}},_c=async(e,r,t,s,n,o)=>{let a=Ft(),i=a.PTR_SIZE,l=Vs.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let c=l[0],p=l[1],u=l[2],d=l[3],f=l[4],_=l[5],P=r.length,I=s.length,M=0,g=[],S=[],E=[],x=[],w=a.stackSave(),v=a.stackAlloc(P*i),$=a.stackAlloc(P*i),O=a.stackAlloc(I*i),B=a.stackAlloc(I*i);try{[M,g]=Qw(o);for(let L=0;Lde*ve,1);re=Cs(N);let be=d?.outputPreferredLocations[s[L]];if(re==="string"){if(be==="gpu-buffer"||be==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let de=[];for(let ve=0;ve0){let de=a.jsepGetBuffer;if(!de)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ve=de(ce),je=wn(N,ne);if(je===void 0||!Qu(re))throw new Error(`Unsupported data type: ${re}`);te=!0,q.push([re,R,{gpuBuffer:ve,download:a.jsepCreateDownloader(ve,je,re),dispose:()=>{a._OrtReleaseTensor(J)!==0&&kt("Can't release tensor.")}},"gpu-buffer"])}else if(be==="ml-tensor"&&ne>0){let de=a.webnnEnsureTensor,ve=a.webnnIsInt64Supported;if(!de||!ve)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(wn(N,ne)===void 0||!Ju(re))throw new Error(`Unsupported data type: ${re}`);if(re==="int64"&&!ve(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let je=await de(e,ce,N,R,!1);te=!0,q.push([re,R,{mlTensor:je,download:a.webnnCreateMLTensorDownloader(ce,re),dispose:()=>{a.webnnReleaseTensorId(ce),a._OrtReleaseTensor(J)}},"ml-tensor"])}else{let de=Xu(re),ve=new de(ne);new Uint8Array(ve.buffer,ve.byteOffset,ve.byteLength).set(a.HEAPU8.subarray(ce,ce+ve.byteLength)),q.push([re,R,ve,"cpu"])}}finally{a.stackRestore(X),re==="string"&&ce&&a._free(ce),te||a._OrtReleaseTensor(J),a.webnnOnRunEnd?.(c)}}return d&&!f&&(a._OrtClearBoundOutputs(d.handle)!==0&&kt("Can't clear bound outputs."),Vs.set(e,[c,p,u,d,f,!1])),q}finally{a.stackRestore(w),S.forEach(H=>a._OrtReleaseTensor(H)),E.forEach(H=>a._OrtReleaseTensor(H)),x.forEach(H=>a._free(H)),M!==0&&a._OrtReleaseRunOptions(M),g.forEach(H=>a._free(H))}},fc=e=>{let r=Ft(),t=Vs.get(e);if(!t)throw new Error("invalid session id");let s=t[0],n=r._OrtEndProfiling(s);n===0&&kt("Can't get an profile file name."),r._OrtFree(n)},gc=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),Us,Rr,Qn,Ro,No,Qi,yu,Ji,hn,_n,gw,Qy,Jy,Yy,Zy,e0,t0,r0,s0=ze(()=>{is(),Xy(),xn(),Ku(),Us=()=>!!Lt.wasm.proxy&&typeof document<"u",Qn=!1,Ro=!1,No=!1,Ji=new Map,hn=(e,r)=>{let t=Ji.get(e);t?t.push(r):Ji.set(e,[r])},_n=()=>{if(Qn||!Ro||No||!Rr)throw new Error("worker not ready")},gw=e=>{switch(e.data.type){case"init-wasm":Qn=!1,e.data.err?(No=!0,yu[1](e.data.err)):(Ro=!0,yu[0]()),Qi&&(URL.revokeObjectURL(Qi),Qi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=Ji.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},Qy=async()=>{if(!Ro){if(Qn)throw new Error("multiple calls to 'initWasm()' detected.");if(No)throw new Error("previous call to 'initWasm()' failed.");if(Qn=!0,Us())return new Promise((e,r)=>{Rr?.terminate(),qw().then(([t,s])=>{try{Rr=s,Rr.onerror=o=>r(o),Rr.onmessage=gw,yu=[e,r];let n={type:"init-wasm",in:Lt};!n.in.wasm.wasmPaths&&(t||Pu)&&(n.in.wasm.wasmPaths={wasm:new URL(""+new URL("ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",import.meta.url).href,import.meta.url).href}),Rr.postMessage(n),Qi=t}catch(n){r(n)}},r)});try{await Hu(Lt.wasm),await dc(Lt),Ro=!0}catch(e){throw No=!0,e}finally{Qn=!1}}},Jy=async e=>{if(Us())return _n(),new Promise((r,t)=>{hn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Lt}};Rr.postMessage(s)});await pc(Lt,e)},Yy=async e=>Us()?(_n(),new Promise((r,t)=>{hn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};Rr.postMessage(s,[e.buffer])})):ua(e),Zy=async(e,r)=>{if(Us()){if(r?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return _n(),new Promise((t,s)=>{hn("create",[t,s]);let n={type:"create",in:{model:e,options:{...r}}},o=[];e instanceof Uint8Array&&o.push(e.buffer),Rr.postMessage(n,o)})}else return mc(e,r)},e0=async e=>{if(Us())return _n(),new Promise((r,t)=>{hn("release",[r,t]);let s={type:"release",in:e};Rr.postMessage(s)});hc(e)},t0=async(e,r,t,s,n,o)=>{if(Us()){if(t.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(n.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return _n(),new Promise((a,i)=>{hn("run",[a,i]);let l=t,c={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:o}};Rr.postMessage(c,gc(l))})}else return _c(e,r,t,s,n,o)},r0=async e=>{if(Us())return _n(),new Promise((r,t)=>{hn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};Rr.postMessage(s)});fc(e)}}),vu,ww,n0,Rx=ze(()=>{is(),s0(),at(),Gu(),Yw(),vu=(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()}`)}},ww=e=>{switch(e[3]){case"cpu":return new ss(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!Qu(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:n}=e[2];return ss.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:n})}case"ml-tensor":{let r=e[0];if(!Ju(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:n}=e[2];return ss.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:n})}default:throw new Error(`invalid data location: ${e[3]}`)}},n0=class{async fetchModelAndCopyToWasmMemory(e){return Yy(await Yu(e))}async loadModel(e,r){os();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Zy(t,r),Vr()}async dispose(){return e0(this.sessionId)}async run(e,r,t){os();let s=[],n=[];Object.entries(e).forEach(u=>{let d=u[0],f=u[1],_=this.inputNames.indexOf(d);if(_===-1)throw new Error(`invalid input '${d}'`);s.push(f),n.push(_)});let o=[],a=[];Object.entries(r).forEach(u=>{let d=u[0],f=u[1],_=this.outputNames.indexOf(d);if(_===-1)throw new Error(`invalid output '${d}'`);o.push(f),a.push(_)});let i=s.map((u,d)=>vu(u,()=>`input "${this.inputNames[n[d]]}"`)),l=o.map((u,d)=>u?vu(u,()=>`output "${this.outputNames[a[d]]}"`):null),c=await t0(this.sessionId,n,i,a,l,t),p={};for(let u=0;uju,initializeFlags:()=>Nu,wasmBackend:()=>i0});var Nu,ju,i0,Nx=ze(()=>{is(),s0(),Rx(),Nu=()=>{(typeof Lt.wasm.initTimeout!="number"||Lt.wasm.initTimeout<0)&&(Lt.wasm.initTimeout=0);let e=Lt.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.`),Lt.wasm.simd=!1),typeof Lt.wasm.proxy!="boolean"&&(Lt.wasm.proxy=!1),typeof Lt.wasm.trace!="boolean"&&(Lt.wasm.trace=!1),typeof Lt.wasm.numThreads!="number"||!Number.isInteger(Lt.wasm.numThreads)||Lt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Lt.wasm.numThreads=1;else{let r=typeof navigator>"u"?Pv("node:os").cpus().length:navigator.hardwareConcurrency;Lt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},ju=class{async init(e){Nu(),await Qy(),await Jy(e)}async createInferenceSessionHandler(e,r){let t=new n0;return await t.loadModel(e,r),t}},i0=new ju});is();is();is();var jx="1.22.0-dev.20250409-89f8206ba4",Vx=Vw;{let e=(Nx(),Ko(o0)).wasmBackend;Mn("webgpu",e,5),Mn("webnn",e,5),Mn("cpu",e,10),Mn("wasm",e,10)}Object.defineProperty(Lt.versions,"web",{value:jx,enumerable:!0});/** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= *//** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */var Ux=Object.freeze({__proto__:null,get InferenceSession(){return Wu},get TRACE(){return Ho},get TRACE_FUNC_BEGIN(){return os},get TRACE_FUNC_END(){return Vr},get Tensor(){return ss},default:Vx,get env(){return Lt},get registerBackend(){return Mn}}),xu={},Wx={"onnxruntime-common":e=>{e.exports=vv},"onnxruntime-web":e=>{e.exports=Ux},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,r,t)=>{t.r(r),t.d(r,{Environment:()=>Ce,Interpreter:()=>$e,Template:()=>Ne,parse:()=>N,tokenize:()=>u});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndSet:"EndSet",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),n=Object.freeze({set:s.Set,for:s.For,in:s.In,is:s.Is,if:s.If,else:s.Else,endset:s.EndSet,endif:s.EndIf,elif:s.ElseIf,endfor:s.EndFor,and:s.And,or:s.Or,not:s.Not,"not in":s.NotIn,macro:s.Macro,endmacro:s.EndMacro,true:s.BooleanLiteral,false:s.BooleanLiteral,none:s.NullLiteral,True:s.BooleanLiteral,False:s.BooleanLiteral,None:s.NullLiteral}),o=class{constructor(A,Y){this.value=A,this.type=Y}};function a(A){return/\w/.test(A)}function i(A){return/[0-9]/.test(A)}var l=[["{%",s.OpenStatement],["%}",s.CloseStatement],["{{",s.OpenExpression],["}}",s.CloseExpression],["(",s.OpenParen],[")",s.CloseParen],["{",s.OpenCurlyBracket],["}",s.CloseCurlyBracket],["[",s.OpenSquareBracket],["]",s.CloseSquareBracket],[",",s.Comma],[".",s.Dot],[":",s.Colon],["|",s.Pipe],["<=",s.ComparisonBinaryOperator],[">=",s.ComparisonBinaryOperator],["==",s.ComparisonBinaryOperator],["!=",s.ComparisonBinaryOperator],["<",s.ComparisonBinaryOperator],[">",s.ComparisonBinaryOperator],["+",s.AdditiveBinaryOperator],["-",s.AdditiveBinaryOperator],["*",s.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],c=new Map([["n",` `],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function p(A,Y={}){return A.endsWith(` `)&&(A=A.slice(0,-1)),A=A.replace(/{#.*?#}/gs,"{##}"),Y.lstrip_blocks&&(A=A.replace(/^[ \t]*({[#%])/gm,"$1")),Y.trim_blocks&&(A=A.replace(/([#%]})\n/g,"$1")),A.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function u(A,Y={}){const z=[],ee=p(A,Y);let oe=0;const he=Ee=>{let Fe="";for(;Ee(ee[oe]);){if(ee[oe]==="\\"){if(++oe,oe>=ee.length)throw new SyntaxError("Unexpected end of input");const Me=ee[oe++],ke=c.get(Me);if(ke===void 0)throw new SyntaxError(`Unexpected escaped character: ${Me}`);Fe+=ke;continue}if(Fe+=ee[oe++],oe>=ee.length)throw new SyntaxError("Unexpected end of input")}return Fe};e:for(;oe0){z.push(new o(Me,s.Text));continue}}he(Me=>/\s/.test(Me));const Fe=ee[oe];if(Fe==="-"||Fe==="+"){const Me=z.at(-1)?.type;if(Me===s.Text||Me===void 0)throw new SyntaxError(`Unexpected character: ${Fe}`);switch(Me){case s.Identifier:case s.NumericLiteral:case s.BooleanLiteral:case s.NullLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++oe;const ke=he(i);z.push(new o(`${Fe}${ke}`,ke.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[Me,ke]of l)if(ee.slice(oe,oe+Me.length)===Me){z.push(new o(Me,ke)),oe+=Me.length;continue e}if(Fe==="'"||Fe==='"'){++oe;const Me=he(ke=>ke!==Fe);z.push(new o(Me,s.StringLiteral)),++oe;continue}if(i(Fe)){const Me=he(i);z.push(new o(Me,s.NumericLiteral));continue}if(a(Fe)){const Me=he(a),ke=Object.hasOwn(n,Me)?n[Me]:s.Identifier;ke===s.In&&z.at(-1)?.type===s.Not?(z.pop(),z.push(new o("not in",s.NotIn))):z.push(new o(Me,ke));continue}throw new SyntaxError(`Unexpected character: ${Fe}`)}return z}var d=class{type="Statement"},f=class extends d{constructor(A){super(),this.body=A}type="Program"},_=class extends d{constructor(A,Y,z){super(),this.test=A,this.body=Y,this.alternate=z}type="If"},P=class extends d{constructor(A,Y,z,ee){super(),this.loopvar=A,this.iterable=Y,this.body=z,this.defaultBlock=ee}type="For"},I=class extends d{constructor(A,Y,z){super(),this.assignee=A,this.value=Y,this.body=z}type="Set"},M=class extends d{constructor(A,Y,z){super(),this.name=A,this.args=Y,this.body=z}type="Macro"},g=class extends d{type="Expression"},S=class extends g{constructor(A,Y,z){super(),this.object=A,this.property=Y,this.computed=z}type="MemberExpression"},E=class extends g{constructor(A,Y){super(),this.callee=A,this.args=Y}type="CallExpression"},x=class extends g{constructor(A){super(),this.value=A}type="Identifier"},w=class extends g{constructor(A){super(),this.value=A}type="Literal"},v=class extends w{type="NumericLiteral"},$=class extends w{type="StringLiteral"},O=class extends w{type="BooleanLiteral"},B=class extends w{type="NullLiteral"},H=class extends w{type="ArrayLiteral"},q=class extends w{type="TupleLiteral"},L=class extends w{type="ObjectLiteral"},J=class extends g{constructor(A,Y,z){super(),this.operator=A,this.left=Y,this.right=z}type="BinaryExpression"},X=class extends g{constructor(A,Y){super(),this.operand=A,this.filter=Y}type="FilterExpression"},Q=class extends g{constructor(A,Y){super(),this.iterable=A,this.test=Y}type="SelectExpression"},te=class extends g{constructor(A,Y,z){super(),this.operand=A,this.negate=Y,this.test=z}type="TestExpression"},re=class extends g{constructor(A,Y){super(),this.operator=A,this.argument=Y}type="UnaryExpression"},ce=class extends g{constructor(A=void 0,Y=void 0,z=void 0){super(),this.start=A,this.stop=Y,this.step=z}type="SliceExpression"},le=class extends g{constructor(A,Y){super(),this.key=A,this.value=Y}type="KeywordArgumentExpression"};function N(A){const Y=new f([]);let z=0;function ee(De,He){const Ye=A[z++];if(!Ye||Ye.type!==De)throw new Error(`Parser Error: ${He}. ${Ye.type} !== ${De}.`);return Ye}function oe(){switch(A[z].type){case s.Text:return Fe();case s.OpenStatement:return Me();case s.OpenExpression:return ke();default:throw new SyntaxError(`Unexpected token type: ${A[z].type}`)}}function he(...De){return z+De.length<=A.length&&De.some((He,Ye)=>He!==A[z+Ye].type)}function Ee(...De){return z+De.length<=A.length&&De.every((He,Ye)=>He===A[z+Ye].type)}function Fe(){return new $(ee(s.Text,"Expected text token").value)}function Me(){ee(s.OpenStatement,"Expected opening statement token");let De;switch(A[z].type){case s.Set:++z,De=st(),ee(s.CloseStatement,"Expected closing statement token");break;case s.If:++z,De=ut(),ee(s.OpenStatement,"Expected {% token"),ee(s.EndIf,"Expected endif token"),ee(s.CloseStatement,"Expected %} token");break;case s.Macro:++z,De=_t(),ee(s.OpenStatement,"Expected {% token"),ee(s.EndMacro,"Expected endmacro token"),ee(s.CloseStatement,"Expected %} token");break;case s.For:++z,De=er(),ee(s.OpenStatement,"Expected {% token"),ee(s.EndFor,"Expected endfor token"),ee(s.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${A[z].type}`)}return De}function ke(){ee(s.OpenExpression,"Expected opening expression token");const De=It();return ee(s.CloseExpression,"Expected closing expression token"),De}function st(){const De=It();if(Ee(s.Equals)){++z;const He=It();return new I(De,He,[])}else{const He=[];for(ee(s.CloseStatement,"Expected %} token");!(A[z]?.type===s.OpenStatement&&A[z+1]?.type===s.EndSet);){const Ye=oe();He.push(Ye)}return ee(s.OpenStatement,"Expected {% token"),ee(s.EndSet,"Expected endset token"),new I(De,null,He)}}function ut(){const De=It();ee(s.CloseStatement,"Expected closing statement token");const He=[],Ye=[];for(;!(A[z]?.type===s.OpenStatement&&(A[z+1]?.type===s.ElseIf||A[z+1]?.type===s.Else||A[z+1]?.type===s.EndIf));)He.push(oe());if(A[z]?.type===s.OpenStatement&&A[z+1]?.type!==s.EndIf)if(++z,Ee(s.ElseIf))ee(s.ElseIf,"Expected elseif token"),Ye.push(ut());else for(ee(s.Else,"Expected else token"),ee(s.CloseStatement,"Expected closing statement token");!(A[z]?.type===s.OpenStatement&&A[z+1]?.type===s.EndIf);)Ye.push(oe());return new _(De,He,Ye)}function _t(){const De=ur();if(De.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const He=Ur();ee(s.CloseStatement,"Expected closing statement token");const Ye=[];for(;he(s.OpenStatement,s.EndMacro);)Ye.push(oe());return new M(De,He,Ye)}function gt(De=!1){const He=De?ur:It,Ye=[He()],cr=Ee(s.Comma);for(;cr&&(++z,Ye.push(He()),!!Ee(s.Comma)););return cr?new q(Ye):Ye[0]}function er(){const De=gt(!0);if(!(De instanceof x||De instanceof q))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${De.type} instead`);ee(s.In,"Expected `in` keyword following loop variable");const He=It();ee(s.CloseStatement,"Expected closing statement token");const Ye=[];for(;he(s.OpenStatement,s.EndFor)&&he(s.OpenStatement,s.Else);)Ye.push(oe());const cr=[];if(Ee(s.OpenStatement,s.Else))for(++z,++z,ee(s.CloseStatement,"Expected closing statement token");he(s.OpenStatement,s.EndFor);)cr.push(oe());return new P(De,He,Ye,cr)}function It(){return lr()}function lr(){const De=as();if(Ee(s.If)){++z;const He=as();if(Ee(s.Else)){++z;const Ye=as();return new _(He,[De],[Ye])}else return new Q(De,He)}return De}function as(){let De=fs();for(;Ee(s.Or);){const He=A[z];++z;const Ye=fs();De=new J(He,De,Ye)}return De}function fs(){let De=Cr();for(;Ee(s.And);){const He=A[z];++z;const Ye=Cr();De=new J(He,De,Ye)}return De}function Cr(){let De;for(;Ee(s.Not);){const He=A[z];++z;const Ye=Cr();De=new re(He,Ye)}return De??$s()}function $s(){let De=ls();for(;Ee(s.ComparisonBinaryOperator)||Ee(s.In)||Ee(s.NotIn);){const He=A[z];++z;const Ye=ls();De=new J(He,De,Ye)}return De}function ls(){let De=Gr();for(;Ee(s.AdditiveBinaryOperator);){const He=A[z];++z;const Ye=Gr();De=new J(He,De,Ye)}return De}function gs(){const De=Wr(ur());return Ee(s.OpenParen)?nt(De):De}function nt(De){let He=new E(De,Ur());return He=Wr(He),Ee(s.OpenParen)&&(He=nt(He)),He}function Ur(){ee(s.OpenParen,"Expected opening parenthesis for arguments list");const De=Tt();return ee(s.CloseParen,"Expected closing parenthesis for arguments list"),De}function Tt(){const De=[];for(;!Ee(s.CloseParen);){let He=It();if(Ee(s.Equals)){if(++z,!(He instanceof x))throw new SyntaxError("Expected identifier for keyword argument");const Ye=It();He=new le(He,Ye)}De.push(He),Ee(s.Comma)&&++z}return De}function us(){const De=[];let He=!1;for(;!Ee(s.CloseSquareBracket);)Ee(s.Colon)?(De.push(void 0),++z,He=!0):(De.push(It()),Ee(s.Colon)&&(++z,He=!0));if(De.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(He){if(De.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new ce(...De)}return De[0]}function Wr(De){for(;Ee(s.Dot)||Ee(s.OpenSquareBracket);){const He=A[z];++z;let Ye;const cr=He.type!==s.Dot;if(cr)Ye=us(),ee(s.CloseSquareBracket,"Expected closing square bracket");else if(Ye=ur(),Ye.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");De=new S(De,Ye,cr)}return De}function Gr(){let De=yr();for(;Ee(s.MultiplicativeBinaryOperator);){const He=A[z];++z;const Ye=yr();De=new J(He,De,Ye)}return De}function yr(){let De=cs();for(;Ee(s.Is);){++z;const He=Ee(s.Not);He&&++z;let Ye=ur();if(Ye instanceof O?Ye=new x(Ye.value.toString()):Ye instanceof B&&(Ye=new x("none")),!(Ye instanceof x))throw new SyntaxError("Expected identifier for the test");De=new te(De,He,Ye)}return De}function cs(){let De=gs();for(;Ee(s.Pipe);){++z;let He=ur();if(!(He instanceof x))throw new SyntaxError("Expected identifier for the filter");Ee(s.OpenParen)&&(He=nt(He)),De=new X(De,He)}return De}function ur(){const De=A[z];switch(De.type){case s.NumericLiteral:return++z,new v(Number(De.value));case s.StringLiteral:return++z,new $(De.value);case s.BooleanLiteral:return++z,new O(De.value.toLowerCase()==="true");case s.NullLiteral:return++z,new B(null);case s.Identifier:return++z,new x(De.value);case s.OpenParen:{++z;const He=gt();if(A[z].type!==s.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${A[z].type} instead`);return++z,He}case s.OpenSquareBracket:{++z;const He=[];for(;!Ee(s.CloseSquareBracket);)He.push(It()),Ee(s.Comma)&&++z;return++z,new H(He)}case s.OpenCurlyBracket:{++z;const He=new Map;for(;!Ee(s.CloseCurlyBracket);){const Ye=It();ee(s.Colon,"Expected colon between key and value in object literal");const cr=It();He.set(Ye,cr),Ee(s.Comma)&&++z}return++z,new L(He)}default:throw new SyntaxError(`Unexpected token: ${De.type}`)}}for(;z=0?(Y=(Y??=0)<0?Math.max(A.length+Y,0):Math.min(Y,A.length),z=(z??=A.length)<0?Math.max(A.length+z,0):Math.min(z,A.length)):(Y=(Y??=A.length-1)<0?Math.max(A.length+Y,-1):Math.min(Y,A.length-1),z=(z??=-1)<-1?Math.max(A.length+z,-1):Math.min(z,A.length-1));const he=[];for(let Ee=Y;oe*EeY.toUpperCase())}var ne=class{type="RuntimeValue";value;builtins=new Map;constructor(A=void 0){this.value=A}__bool__(){return new ve(!!this.value)}},be=class extends ne{type="NumericValue"},de=class extends ne{type="StringValue";builtins=new Map([["upper",new pe(()=>new de(this.value.toUpperCase()))],["lower",new pe(()=>new de(this.value.toLowerCase()))],["strip",new pe(()=>new de(this.value.trim()))],["title",new pe(()=>new de(R(this.value)))],["length",new be(this.value.length)],["rstrip",new pe(()=>new de(this.value.trimEnd()))],["lstrip",new pe(()=>new de(this.value.trimStart()))],["split",new pe(A=>{const Y=A[0]??new ye;if(!(Y instanceof de||Y instanceof ye))throw new Error("sep argument must be a string or null");const z=A[1]??new be(-1);if(!(z instanceof be))throw new Error("maxsplit argument must be a number");let ee=[];if(Y instanceof ye){const oe=this.value.trimStart();for(const{0:he,index:Ee}of oe.matchAll(/\S+/g)){if(z.value!==-1&&ee.length>=z.value&&Ee!==void 0){ee.push(he+oe.slice(Ee+he.length));break}ee.push(he)}}else{if(Y.value==="")throw new Error("empty separator");ee=this.value.split(Y.value),z.value!==-1&&ee.length>z.value&&ee.push(ee.splice(z.value).join(Y.value))}return new K(ee.map(oe=>new de(oe)))})]])},ve=class extends ne{type="BooleanValue"},je=class extends ne{type="ObjectValue";__bool__(){return new ve(this.value.size>0)}builtins=new Map([["get",new pe(([A,Y])=>{if(!(A instanceof de))throw new Error(`Object key must be a string: got ${A.type}`);return this.value.get(A.value)??Y??new ye})],["items",new pe(()=>new K(Array.from(this.value.entries()).map(([A,Y])=>new K([new de(A),Y]))))]])},fe=class extends je{type="KeywordArgumentsValue"},K=class extends ne{type="ArrayValue";builtins=new Map([["length",new be(this.value.length)]]);__bool__(){return new ve(this.value.length>0)}},U=class extends K{type="TupleValue"},pe=class extends ne{type="FunctionValue"},ye=class extends ne{type="NullValue"},xe=class extends ne{type="UndefinedValue"},Ce=class{constructor(A){this.parent=A}variables=new Map([["namespace",new pe(A=>{if(A.length===0)return new je(new Map);if(A.length!==1||!(A[0]instanceof je))throw new Error("`namespace` expects either zero arguments or a single object argument");return A[0]})]]);tests=new Map([["boolean",A=>A.type==="BooleanValue"],["callable",A=>A instanceof pe],["odd",A=>{if(A.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${A.type}`);return A.value%2!==0}],["even",A=>{if(A.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${A.type}`);return A.value%2===0}],["false",A=>A.type==="BooleanValue"&&!A.value],["true",A=>A.type==="BooleanValue"&&A.value],["none",A=>A.type==="NullValue"],["string",A=>A.type==="StringValue"],["number",A=>A.type==="NumericValue"],["integer",A=>A.type==="NumericValue"&&Number.isInteger(A.value)],["iterable",A=>A.type==="ArrayValue"||A.type==="StringValue"],["mapping",A=>A.type==="ObjectValue"],["lower",A=>{const Y=A.value;return A.type==="StringValue"&&Y===Y.toLowerCase()}],["upper",A=>{const Y=A.value;return A.type==="StringValue"&&Y===Y.toUpperCase()}],["none",A=>A.type==="NullValue"],["defined",A=>A.type!=="UndefinedValue"],["undefined",A=>A.type==="UndefinedValue"],["equalto",(A,Y)=>A.value===Y.value],["eq",(A,Y)=>A.value===Y.value]]);set(A,Y){return this.declareVariable(A,Ae(Y))}declareVariable(A,Y){if(this.variables.has(A))throw new SyntaxError(`Variable already declared: ${A}`);return this.variables.set(A,Y),Y}setVariable(A,Y){return this.variables.set(A,Y),Y}resolve(A){if(this.variables.has(A))return this;if(this.parent)return this.parent.resolve(A);throw new Error(`Unknown variable: ${A}`)}lookupVariable(A){try{return this.resolve(A).variables.get(A)??new xe}catch{return new xe}}},$e=class{global;constructor(A){this.global=A??new Ce}run(A){return this.evaluate(A,this.global)}evaluateBinaryExpression(A,Y){const z=this.evaluate(A.left,Y);switch(A.operator.value){case"and":return z.__bool__().value?this.evaluate(A.right,Y):z;case"or":return z.__bool__().value?z:this.evaluate(A.right,Y)}const ee=this.evaluate(A.right,Y);switch(A.operator.value){case"==":return new ve(z.value==ee.value);case"!=":return new ve(z.value!=ee.value)}if(z instanceof xe||ee instanceof xe)throw new Error("Cannot perform operation on undefined values");if(z instanceof ye||ee instanceof ye)throw new Error("Cannot perform operation on null values");if(z instanceof be&&ee instanceof be)switch(A.operator.value){case"+":return new be(z.value+ee.value);case"-":return new be(z.value-ee.value);case"*":return new be(z.value*ee.value);case"/":return new be(z.value/ee.value);case"%":return new be(z.value%ee.value);case"<":return new ve(z.value":return new ve(z.value>ee.value);case">=":return new ve(z.value>=ee.value);case"<=":return new ve(z.value<=ee.value)}else if(z instanceof K&&ee instanceof K)switch(A.operator.value){case"+":return new K(z.value.concat(ee.value))}else if(ee instanceof K){const oe=ee.value.find(he=>he.value===z.value)!==void 0;switch(A.operator.value){case"in":return new ve(oe);case"not in":return new ve(!oe)}}if(z instanceof de||ee instanceof de)switch(A.operator.value){case"+":return new de(z.value.toString()+ee.value.toString())}if(z instanceof de&&ee instanceof de)switch(A.operator.value){case"in":return new ve(ee.value.includes(z.value));case"not in":return new ve(!ee.value.includes(z.value))}if(z instanceof de&&ee instanceof je)switch(A.operator.value){case"in":return new ve(ee.value.has(z.value));case"not in":return new ve(!ee.value.has(z.value))}throw new SyntaxError(`Unknown operator "${A.operator.value}" between ${z.type} and ${ee.type}`)}evaluateArguments(A,Y){const z=[],ee=new Map;for(const oe of A)if(oe.type==="KeywordArgumentExpression"){const he=oe;ee.set(he.key.value,this.evaluate(he.value,Y))}else{if(ee.size>0)throw new Error("Positional arguments must come before keyword arguments");z.push(this.evaluate(oe,Y))}return[z,ee]}evaluateFilterExpression(A,Y){const z=this.evaluate(A.operand,Y);if(A.filter.type==="Identifier"){const ee=A.filter;if(ee.value==="tojson")return new de(Re(z));if(z instanceof K)switch(ee.value){case"list":return z;case"first":return z.value[0];case"last":return z.value[z.value.length-1];case"length":return new be(z.value.length);case"reverse":return new K(z.value.reverse());case"sort":return new K(z.value.sort((oe,he)=>{if(oe.type!==he.type)throw new Error(`Cannot compare different types: ${oe.type} and ${he.type}`);switch(oe.type){case"NumericValue":return oe.value-he.value;case"StringValue":return oe.value.localeCompare(he.value);default:throw new Error(`Cannot compare type: ${oe.type}`)}}));case"join":return new de(z.value.map(oe=>oe.value).join(""));case"string":return new de(Re(z));default:throw new Error(`Unknown ArrayValue filter: ${ee.value}`)}else if(z instanceof de)switch(ee.value){case"length":return new be(z.value.length);case"upper":return new de(z.value.toUpperCase());case"lower":return new de(z.value.toLowerCase());case"title":return new de(R(z.value));case"capitalize":return new de(z.value.charAt(0).toUpperCase()+z.value.slice(1));case"trim":return new de(z.value.trim());case"indent":return new de(z.value.split(` `).map((oe,he)=>he===0||oe.length===0?oe:" "+oe).join(` `));case"join":case"string":return z;default:throw new Error(`Unknown StringValue filter: ${ee.value}`)}else if(z instanceof be)switch(ee.value){case"abs":return new be(Math.abs(z.value));default:throw new Error(`Unknown NumericValue filter: ${ee.value}`)}else if(z instanceof je)switch(ee.value){case"items":return new K(Array.from(z.value.entries()).map(([oe,he])=>new K([new de(oe),he])));case"length":return new be(z.value.size);default:throw new Error(`Unknown ObjectValue filter: ${ee.value}`)}throw new Error(`Cannot apply filter "${ee.value}" to type: ${z.type}`)}else if(A.filter.type==="CallExpression"){const ee=A.filter;if(ee.callee.type!=="Identifier")throw new Error(`Unknown filter: ${ee.callee.type}`);const oe=ee.callee.value;if(oe==="tojson"){const[,he]=this.evaluateArguments(ee.args,Y),Ee=he.get("indent")??new ye;if(!(Ee instanceof be||Ee instanceof ye))throw new Error("If set, indent must be a number");return new de(Re(z,Ee.value))}else if(oe==="join"){let he;if(z instanceof de)he=Array.from(z.value);else if(z instanceof K)he=z.value.map(ke=>ke.value);else throw new Error(`Cannot apply filter "${oe}" to type: ${z.type}`);const[Ee,Fe]=this.evaluateArguments(ee.args,Y),Me=Ee.at(0)??Fe.get("separator")??new de("");if(!(Me instanceof de))throw new Error("separator must be a string");return new de(he.join(Me.value))}if(z instanceof K){switch(oe){case"selectattr":case"rejectattr":{const he=oe==="selectattr";if(z.value.some(ut=>!(ut instanceof je)))throw new Error(`\`${oe}\` can only be applied to array of objects`);if(ee.args.some(ut=>ut.type!=="StringLiteral"))throw new Error(`arguments of \`${oe}\` must be strings`);const[Ee,Fe,Me]=ee.args.map(ut=>this.evaluate(ut,Y));let ke;if(Fe){const ut=Y.tests.get(Fe.value);if(!ut)throw new Error(`Unknown test: ${Fe.value}`);ke=ut}else ke=(...ut)=>ut[0].__bool__().value;const st=z.value.filter(ut=>{const _t=ut.value.get(Ee.value),gt=_t?ke(_t,Me):!1;return he?gt:!gt});return new K(st)}case"map":{const[,he]=this.evaluateArguments(ee.args,Y);if(he.has("attribute")){const Ee=he.get("attribute");if(!(Ee instanceof de))throw new Error("attribute must be a string");const Fe=he.get("default"),Me=z.value.map(ke=>{if(!(ke instanceof je))throw new Error("items in map must be an object");return ke.value.get(Ee.value)??Fe??new xe});return new K(Me)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${oe}`)}else if(z instanceof de){switch(oe){case"indent":{const[he,Ee]=this.evaluateArguments(ee.args,Y),Fe=he.at(0)??Ee.get("width")??new be(4);if(!(Fe instanceof be))throw new Error("width must be a number");const Me=he.at(1)??Ee.get("first")??new ve(!1),ke=he.at(2)??Ee.get("blank")??new ve(!1),st=z.value.split(` `),ut=" ".repeat(Fe.value),_t=st.map((gt,er)=>!Me.value&&er===0||!ke.value&>.length===0?gt:ut+gt);return new de(_t.join(` `))}}throw new Error(`Unknown StringValue filter: ${oe}`)}else throw new Error(`Cannot apply filter "${oe}" to type: ${z.type}`)}throw new Error(`Unknown filter: ${A.filter.type}`)}evaluateTestExpression(A,Y){const z=this.evaluate(A.operand,Y),ee=Y.tests.get(A.test.value);if(!ee)throw new Error(`Unknown test: ${A.test.value}`);const oe=ee(z);return new ve(A.negate?!oe:oe)}evaluateUnaryExpression(A,Y){const z=this.evaluate(A.argument,Y);switch(A.operator.value){case"not":return new ve(!z.value);default:throw new SyntaxError(`Unknown operator: ${A.operator.value}`)}}evalProgram(A,Y){return this.evaluateBlock(A.body,Y)}evaluateBlock(A,Y){let z="";for(const ee of A){const oe=this.evaluate(ee,Y);oe.type!=="NullValue"&&oe.type!=="UndefinedValue"&&(z+=oe.value)}return new de(z)}evaluateIdentifier(A,Y){return Y.lookupVariable(A.value)}evaluateCallExpression(A,Y){const[z,ee]=this.evaluateArguments(A.args,Y);ee.size>0&&z.push(new fe(ee));const oe=this.evaluate(A.callee,Y);if(oe.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${oe.type}`);return oe.value(z,Y)}evaluateSliceExpression(A,Y,z){if(!(A instanceof K||A instanceof de))throw new Error("Slice object must be an array or string");const ee=this.evaluate(Y.start,z),oe=this.evaluate(Y.stop,z),he=this.evaluate(Y.step,z);if(!(ee instanceof be||ee instanceof xe))throw new Error("Slice start must be numeric or undefined");if(!(oe instanceof be||oe instanceof xe))throw new Error("Slice stop must be numeric or undefined");if(!(he instanceof be||he instanceof xe))throw new Error("Slice step must be numeric or undefined");return A instanceof K?new K(G(A.value,ee.value,oe.value,he.value)):new de(G(Array.from(A.value),ee.value,oe.value,he.value).join(""))}evaluateMemberExpression(A,Y){const z=this.evaluate(A.object,Y);let ee;if(A.computed){if(A.property.type==="SliceExpression")return this.evaluateSliceExpression(z,A.property,Y);ee=this.evaluate(A.property,Y)}else ee=new de(A.property.value);let oe;if(z instanceof je){if(!(ee instanceof de))throw new Error(`Cannot access property with non-string: got ${ee.type}`);oe=z.value.get(ee.value)??z.builtins.get(ee.value)}else if(z instanceof K||z instanceof de)if(ee instanceof be)oe=z.value.at(ee.value),z instanceof de&&(oe=new de(z.value.at(ee.value)));else if(ee instanceof de)oe=z.builtins.get(ee.value);else throw new Error(`Cannot access property with non-string/non-number: got ${ee.type}`);else{if(!(ee instanceof de))throw new Error(`Cannot access property with non-string: got ${ee.type}`);oe=z.builtins.get(ee.value)}return oe instanceof ne?oe:new xe}evaluateSet(A,Y){const z=A.value?this.evaluate(A.value,Y):this.evaluateBlock(A.body,Y);if(A.assignee.type==="Identifier"){const ee=A.assignee.value;Y.setVariable(ee,z)}else if(A.assignee.type==="MemberExpression"){const ee=A.assignee,oe=this.evaluate(ee.object,Y);if(!(oe instanceof je))throw new Error("Cannot assign to member of non-object");if(ee.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");oe.value.set(ee.property.value,z)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(A.assignee)}`);return new ye}evaluateIf(A,Y){const z=this.evaluate(A.test,Y);return this.evaluateBlock(z.__bool__().value?A.body:A.alternate,Y)}evaluateFor(A,Y){const z=new Ce(Y);let ee,oe;if(A.iterable.type==="SelectExpression"){const ke=A.iterable;oe=this.evaluate(ke.iterable,z),ee=ke.test}else oe=this.evaluate(A.iterable,z);if(!(oe instanceof K))throw new Error(`Expected iterable type in for loop: got ${oe.type}`);const he=[],Ee=[];for(let ke=0;kegt.setVariable(A.loopvar.value,ut);else if(A.loopvar.type==="TupleLiteral"){const gt=A.loopvar;if(ut.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${ut.type}`);const er=ut;if(gt.value.length!==er.value.length)throw new Error(`Too ${gt.value.length>er.value.length?"few":"many"} items to unpack`);_t=It=>{for(let lr=0;lr0?he[ke-1]:new xe],["nextitem",ke{const oe=new Ce(ee);z=z.slice();let he;z.at(-1)?.type==="KeywordArgumentsValue"&&(he=z.pop());for(let Ee=0;Eethis.evaluate(z,Y)));case"TupleLiteral":return new U(A.value.map(z=>this.evaluate(z,Y)));case"ObjectLiteral":{const z=new Map;for(const[ee,oe]of A.value){const he=this.evaluate(ee,Y);if(!(he instanceof de))throw new Error(`Object keys must be strings: got ${he.type}`);z.set(he.value,this.evaluate(oe,Y))}return new je(z)}case"Identifier":return this.evaluateIdentifier(A,Y);case"CallExpression":return this.evaluateCallExpression(A,Y);case"MemberExpression":return this.evaluateMemberExpression(A,Y);case"UnaryExpression":return this.evaluateUnaryExpression(A,Y);case"BinaryExpression":return this.evaluateBinaryExpression(A,Y);case"FilterExpression":return this.evaluateFilterExpression(A,Y);case"TestExpression":return this.evaluateTestExpression(A,Y);default:throw new SyntaxError(`Unknown node type: ${A.type}`)}}};function Ae(A){switch(typeof A){case"number":return new be(A);case"string":return new de(A);case"boolean":return new ve(A);case"undefined":return new xe;case"object":return A===null?new ye:Array.isArray(A)?new K(A.map(Ae)):new je(new Map(Object.entries(A).map(([Y,z])=>[Y,Ae(z)])));case"function":return new pe((Y,z)=>{const ee=A(...Y.map(oe=>oe.value))??null;return Ae(ee)});default:throw new Error(`Cannot convert to runtime value: ${A}`)}}function Re(A,Y,z){const ee=z??0;switch(A.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(A.value);case"ArrayValue":case"ObjectValue":{const oe=Y?" ".repeat(Y):"",he=` `+oe.repeat(ee),Ee=he+oe;if(A.type==="ArrayValue"){const Fe=A.value.map(Me=>Re(Me,Y,ee+1));return Y?`[${Ee}${Fe.join(`,${Ee}`)}${he}]`:`[${Fe.join(", ")}]`}else{const Fe=Array.from(A.value.entries()).map(([Me,ke])=>{const st=`"${Me}": ${Re(ke,Y,ee+1)}`;return Y?`${Ee}${st}`:st});return Y?`{${Fe.join(",")}${he}}`:`{${Fe.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${A.type}`)}}var Ne=class{parsed;constructor(A){const Y=u(A,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=N(Y)}render(A){const Y=new Ce;if(Y.set("false",!1),Y.set("true",!0),Y.set("raise_exception",oe=>{throw new Error(oe)}),Y.set("range",F),A)for(const[oe,he]of Object.entries(A))Y.set(oe,he);return new $e(Y).run(this.parsed).value}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>i.Tensor,createInferenceSession:()=>I,deviceToExecutionProviders:()=>_,isONNXProxy:()=>S,isONNXTensor:()=>M});var n=t("./src/env.js"),o=t("?2ce3"),a=t("onnxruntime-web"),i=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,u;const d=Symbol.for("onnxruntime");if(d in globalThis)u=globalThis[d];else if(n.apis.IS_NODE_ENV){switch(u=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 u=a,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=u.InferenceSession;function _(E=null){if(!E)return p;switch(E){case"auto":return c;case"gpu":return c.filter(x=>["webgpu","cuda","dml","webnn-gpu"].includes(x))}if(c.includes(E))return[l[E]??E];throw new Error(`Unsupported device: "${E}". Should be one of: ${c.join(", ")}.`)}let P=null;async function I(E,x,w){P&&await P;const v=f.create(E,x);P??=v;const $=await v;return $.config=w,$}function M(E){return E instanceof u.Tensor}const g=u?.env;g?.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!g.wasm.wasmPaths&&(g.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${n.env.version}/dist/`),g.wasm.proxy=!1),g?.webgpu&&(g.webgpu.powerPreference="high-performance");function S(){return g?.wasm?.proxy}n.env.backends.onnx=g},"./src/base/feature_extraction_utils.js":(e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>a,validate_audio_inputs:()=>i});var s=t("./src/utils/constants.js"),n=t("./src/utils/generic.js"),o=t("./src/utils/hub.js");class a extends n.Callable{constructor(c){super(),this.config=c}static async from_pretrained(c,p){const u=await(0,o.getModelJSON)(c,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(u)}}function i(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:()=>E,center_to_corners_format:()=>u,post_process_instance_segmentation:()=>S,post_process_object_detection:()=>d,post_process_panoptic_segmentation:()=>g,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 a=t("./src/utils/core.js"),i=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function c(x,w,v=0,$=null){const O=x/w;let B=(0,o.bankers_round)(O)*w;return $!==null&&B>$&&(B=Math.floor(O)*w),Bw&&F.push(R)}else{let R=(0,o.max)(N.data)[1];if(R===L-1||(G=(0,o.softmax)(N.data),G[R]be*Q[(de+1)%2])),te.boxes.push(ne),te.classes.push(R),te.scores.push(G[R])}}J.push(te)}return J}function f(x,w=null){const v=x.logits,$=v.dims[0];if(w!==null&&w.length!==$)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const O=[];for(let B=0;B<$;++B){const H=w!==null?w[B]:null;let q=v[B];H!==null&&(q=(0,n.interpolate)(q,H,"bilinear",!1));const[L,J]=H??q.dims.slice(-2),X=new n.Tensor("int32",new Int32Array(L*J),[L,J]),Q=q[0].data,te=X.data;for(let le=1;leQ[F]&&(Q[F]=N[F],te[F]=le)}const re=new Array(q.dims[0]);for(let le=0;lele!==void 0);O.push({segmentation:X,labels:ce})}return O}function _(x,w,v,$){const O=[],B=[],H=[];for(let q=0;qv&&(O.push(J),B.push(te),H.push(X))}return[O,B,H]}function P(x,w,v,$=.5,O=.8){const B=[];let H=0,q=0;const L=w[v].data;for(let X=0;X=$&&++q;let J=H>0&&q>0;return J&&(J=H/q>O),[J,B]}function I(x,w,v,$,O,B=null,H=null){const[q,L]=H??x[0].dims,J=new n.Tensor("int32",new Int32Array(q*L),[q,L]),X=[];if(H!==null)for(let le=0;lete[G]&&(Q[G]=le,te[G]=F[G])}let re=0;const ce=J.data;for(let le=0;le200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(x,w)/Math.min(x,w)}`);let B=Math.round(x/v)*v,H=Math.round(w/v)*v;if(B*H>O){const q=Math.sqrt(x*w/O);B=Math.floor(x/q/v)*v,H=Math.floor(w/q/v)*v}else if(B*H<$){const q=Math.sqrt($/(x*w));B=Math.ceil(x*q/v)*v,H=Math.ceil(w*q/v)*v}return[B,H]}function g(x,w=.5,v=.5,$=.8,O=null,B=null){O===null&&(console.warn("`label_ids_to_fuse` unset. No instance will be fused."),O=new Set);const H=x.class_queries_logits??x.logits,L=(x.masks_queries_logits??x.pred_masks).sigmoid();let[J,X,Q]=H.dims;if(Q-=1,B!==null&&B.length!==J)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let te=[];for(let re=0;reB?J=Math.floor(B*L/O):B>O&&(L=Math.floor(O*J/B)),await w.resize(J,L,{resample:$}))}async crop_margin(w,v=200){const $=w.clone().grayscale(),O=(0,o.min)($.data)[0],H=(0,o.max)($.data)[0]-O;if(H===0)return w;const q=v/255;let L=$.width,J=$.height,X=0,Q=0;const te=$.data;for(let re=0;re<$.height;++re){const ce=re*$.width;for(let le=0;le<$.width;++le)(te[ce+le]-O)/Hthis.preprocess(B)));return{pixel_values:(0,n.stack)($.map(B=>B.pixel_values),0),original_sizes:$.map(B=>B.original_size),reshaped_input_sizes:$.map(B=>B.reshaped_input_size)}}static async from_pretrained(w,v){const $=await(0,i.getModelJSON)(w,l.IMAGE_PROCESSOR_NAME,!0,v);return new this($)}}},"./src/base/processing_utils.js":(e,r,t)=>{t.r(r),t.d(r,{Processor:()=>a});var s=t("./src/utils/constants.js"),n=t("./src/utils/generic.js"),o=t("./src/utils/hub.js");class a extends n.Callable{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;constructor(l,c){super(),this.config=l,this.components=c}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,...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,u]=await Promise.all([this.uses_processor_config?(0,o.getModelJSON)(l,s.PROCESSOR_NAME,!0,c):{},Promise.all(this.classes.filter(d=>d in this).map(async d=>{const f=await this[d].from_pretrained(l,c);return[d.replace(/_class$/,""),f]})).then(Object.fromEntries)]);return new this(p,u)}}},"./src/configs.js":(e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>c,PretrainedConfig:()=>l,getKeyValueShapes:()=>i});var s=t("./src/utils/core.js"),n=t("./src/utils/hub.js");async function o(p,u){return await(0,n.getModelJSON)(p,"config.json",!0,u)}function a(p){const u={};let d={};switch(p.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":d=a(p.text_config);break;case"moondream1":d=a(p.phi_config);break;case"musicgen":d=a(p.decoder);break;case"multi_modality":d=a(p.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":u.num_heads="num_attention_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":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";break;case"gemma":case"gemma2":case"gemma3_text":case"glm":case"helium":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 _=a(p.decoder),P="num_decoder_layers"in _,I=(0,s.pick)(p,["model_type","is_encoder_decoder"]);return P?(I.num_decoder_layers=_.num_decoder_layers,I.num_decoder_heads=_.num_decoder_heads,I.decoder_hidden_size=_.decoder_hidden_size,I.num_encoder_layers=_.num_encoder_layers,I.num_encoder_heads=_.num_encoder_heads,I.encoder_hidden_size=_.encoder_hidden_size):(I.num_layers=_.num_layers,I.num_heads=_.num_heads,I.hidden_size=_.hidden_size),I}const f={...d,...(0,s.pick)(p,["model_type","multi_query","is_encoder_decoder"])};for(const _ in u)f[_]=p[u[_]];return f}function i(p,{prefix:u="past_key_values",batch_size:d=1}={}){const f={},_=p.normalized_config;if(_.is_encoder_decoder&&"num_encoder_heads"in _&&"num_decoder_heads"in _){const P=_.encoder_dim_kv??_.encoder_hidden_size/_.num_encoder_heads,I=_.decoder_dim_kv??_.decoder_hidden_size/_.num_decoder_heads,M=[d,_.num_encoder_heads,0,P],g=[d,_.num_decoder_heads,0,I];for(let S=0;S<_.num_decoder_layers;++S)f[`${u}.${S}.encoder.key`]=M,f[`${u}.${S}.encoder.value`]=M,f[`${u}.${S}.decoder.key`]=g,f[`${u}.${S}.decoder.value`]=g}else{const P=_.num_heads,I=_.num_layers,M=_.dim_kv??_.hidden_size/(_.num_attention_heads??P);if(_.model_type==="falcon"){const g=[d*P,0,M];for(let S=0;S{t.r(r),t.d(r,{apis:()=>I,env:()=>w});var s=t("?569f"),n=t("?3f59"),o=t("?154a");const a="3.5.0",i=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&self.constructor?.name==="DedicatedWorkerGlobalScope",c=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,u=typeof navigator<"u"&&"ml"in navigator,d=typeof process<"u",f=d&&process?.release?.name==="node",_=!v(s),P=!v(n),I=Object.freeze({IS_BROWSER_ENV:i,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:c,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:u,IS_PROCESS_AVAILABLE:d,IS_NODE_ENV:f,IS_FS_AVAILABLE:_,IS_PATH_AVAILABLE:P}),M=_&&P;let g="./";if(M){const $=Object(import.meta).url;$?g=n.dirname(n.dirname(o.fileURLToPath($))):typeof __dirname<"u"&&(g=n.dirname(__dirname))}const S=M?n.join(g,"/.cache/"):null,E="/models/",x=M?n.join(g,E):E,w={version:a,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co./",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(i||l),localModelPath:x,useFS:_,useBrowserCache:c,useFSCache:_,cacheDir:S,useCustomCache:!1,customCache:null};function v($){return Object.keys($).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(a){Object.assign(this,(0,s.pick)(a,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>M,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>c,LogitsProcessor:()=>o,LogitsProcessorList:()=>i,LogitsWarper:()=>a,MinLengthLogitsProcessor:()=>_,MinNewTokensLengthLogitsProcessor:()=>P,NoBadWordsLogitsProcessor:()=>I,NoRepeatNGramLogitsProcessor:()=>d,RepetitionPenaltyLogitsProcessor:()=>f,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>g,TopKLogitsWarper:()=>E,TopPLogitsWarper:()=>S,WhisperTimeStampLogitsProcessor:()=>u});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(w,v){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{_call(w,v){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{constructor(){super(),this.processors=[]}push(w){this.processors.push(w)}extend(w){this.processors.push(...w)}_call(w,v){let $=v;for(const O of this.processors)$=O(w,$);return $}[Symbol.iterator](){return this.processors.values()}}class l extends o{constructor(w){super(),this.bos_token_id=w}_call(w,v){for(let $=0;$=1&&B[B.length-1]>=this.timestamp_begin,q=B.length<2||B[B.length-2]>=this.timestamp_begin;if(H&&(q?O.subarray(this.timestamp_begin).fill(-1/0):O.subarray(0,this.eos_token_id).fill(-1/0)),w[$].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Q=this.timestamp_begin+this.max_initial_timestamp_index;O.subarray(Q+1).fill(-1/0)}const L=(0,n.log_softmax)(O),J=Math.log(L.subarray(this.timestamp_begin).map(Math.exp).reduce((Q,te)=>Q+te)),X=(0,n.max)(L.subarray(0,this.timestamp_begin))[0];J>X&&O.subarray(0,this.timestamp_begin).fill(-1/0)}return v}}class d extends o{constructor(w){super(),this.no_repeat_ngram_size=w}getNgrams(w){const v=w.length,$=[];for(let B=0;B1 to use the classifier free guidance processor, got guidance scale ${w}.`);this.guidance_scale=w}_call(w,v){if(v.dims[0]!==2*w.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 ${v.dims[0]} for the logits and ${w.length} for the input ids.`);const $=w.length,O=v.slice([0,$],null),B=v.slice([$,v.dims[0]],null);for(let H=0;H1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${w}`);if(!Number.isInteger($)||$<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${$}`);this.top_p=w,this.filter_value=v,this.min_tokens_to_keep=$}}class E extends a{constructor(w,{filter_value:v=-1/0,min_tokens_to_keep:$=1}={}){if(super(),!Number.isInteger(w)||w<0)throw new Error(`\`top_k\` must be a positive integer, but is ${w}`);this.top_k=Math.max(w,$),this.filter_value=v}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>a});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 a extends s.Callable{constructor(u){super(),this.generation_config=u}async _call(u){return this.sample(u)}async sample(u){throw Error("sample should be implemented in subclasses.")}getLogits(u,d){let f=u.dims.at(-1),_=u.data;if(d===-1)_=_.slice(-f);else{let P=d*f;_=_.slice(P,P+f)}return _}randomSelect(u){let d=0;for(let _=0;_1)return new c(u);if(u.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${u.num_return_sequences}.`);return new i(u)}}class i extends a{async sample(u){const d=(0,o.max)(u.data)[1];return[[BigInt(d),0]]}}class l extends a{async sample(u){let d=u.dims.at(-1);this.generation_config.top_k>0&&(d=Math.min(this.generation_config.top_k,d));const[f,_]=await(0,n.topk)(u,d),P=(0,o.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},()=>{const I=this.randomSelect(P);return[_.data[I],Math.log(P[I])]})}}class c extends a{async sample(u){let d=u.dims.at(-1);this.generation_config.top_k>0&&(d=Math.min(this.generation_config.top_k,d));const[f,_]=await(0,n.topk)(u,d),P=(0,o.softmax)(f.data);return Array.from({length:this.generation_config.num_beams},(I,M)=>[_.data[M],Math.log(P[M])])}}},"./src/generation/stopping_criteria.js":(e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>i,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>a,StoppingCriteria:()=>n,StoppingCriteriaList:()=>o});var s=t("./src/utils/generic.js");class n extends s.Callable{_call(p,u){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,u){const d=new Array(p.length).fill(!1);for(const f of this.criteria){const _=f(p,u);for(let P=0;Pu.length>=this.max_length)}}class i extends n{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,u){return p.map(d=>{const f=d.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,u){return new Array(p.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>a,TextStreamer:()=>l,WhisperTextStreamer:()=>c});var s=t("./src/utils/core.js"),n=t("./src/tokenizers.js"),o=t("./src/env.js");class a{put(u){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const i=o.apis.IS_PROCESS_AVAILABLE?p=>process.stdout.write(p):p=>console.log(p);class l extends a{constructor(u,{skip_prompt:d=!1,callback_function:f=null,token_callback_function:_=null,skip_special_tokens:P=!0,decode_kwargs:I={},...M}={}){super(),this.tokenizer=u,this.skip_prompt=d,this.callback_function=f??i,this.token_callback_function=_,this.decode_kwargs={skip_special_tokens:P,...I,...M},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(u){if(u.length>1)throw Error("TextStreamer only supports batch size of 1");const d=this.next_tokens_are_prompt;if(d&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const f=u[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 P;d||_.endsWith(` `)?(P=_.slice(this.print_len),this.token_cache=[],this.print_len=0):_.length>0&&(0,n.is_chinese_char)(_.charCodeAt(_.length-1))?(P=_.slice(this.print_len),this.print_len+=P.length):(P=_.slice(this.print_len,_.lastIndexOf(" ")+1),this.print_len+=P.length),this.on_finalized_text(P,!1)}end(){let u;this.token_cache.length>0?(u=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):u="",this.next_tokens_are_prompt=!0,this.on_finalized_text(u,!0)}on_finalized_text(u,d){u.length>0&&this.callback_function?.(u),d&&this.callback_function===i&&o.apis.IS_PROCESS_AVAILABLE&&this.callback_function?.(` `)}}class c extends l{constructor(u,{skip_prompt:d=!1,callback_function:f=null,token_callback_function:_=null,on_chunk_start:P=null,on_chunk_end:I=null,on_finalize:M=null,time_precision:g=.02,skip_special_tokens:S=!0,decode_kwargs:E={}}={}){super(u,{skip_prompt:d,skip_special_tokens:S,callback_function:f,token_callback_function:_,decode_kwargs:E}),this.timestamp_begin=u.timestamp_begin,this.on_chunk_start=P,this.on_chunk_end=I,this.on_finalize=M,this.time_precision=g,this.waiting_for_timestamp=!1}put(u){if(u.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const d=u[0];if(d.length===1){const f=Number(d[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,u=[[]]}}return super.put(u)}end(){super.end(),this.on_finalize?.()}}},"./src/models.js":(e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>si,ASTModel:()=>ri,ASTPreTrainedModel:()=>io,AlbertForMaskedLM:()=>W,AlbertForQuestionAnswering:()=>C,AlbertForSequenceClassification:()=>ue,AlbertModel:()=>En,AlbertPreTrainedModel:()=>ps,AutoModel:()=>y0,AutoModelForAudioClassification:()=>N0,AutoModelForAudioFrameClassification:()=>V0,AutoModelForAudioTextToText:()=>J0,AutoModelForCTC:()=>R0,AutoModelForCausalLM:()=>S0,AutoModelForDepthEstimation:()=>K0,AutoModelForDocumentQuestionAnswering:()=>U0,AutoModelForImageClassification:()=>A0,AutoModelForImageFeatureExtraction:()=>X0,AutoModelForImageMatting:()=>W0,AutoModelForImageSegmentation:()=>F0,AutoModelForImageTextToText:()=>Q0,AutoModelForImageToImage:()=>G0,AutoModelForMaskGeneration:()=>B0,AutoModelForMaskedLM:()=>$0,AutoModelForNormalEstimation:()=>H0,AutoModelForObjectDetection:()=>L0,AutoModelForPoseEstimation:()=>q0,AutoModelForQuestionAnswering:()=>k0,AutoModelForSemanticSegmentation:()=>O0,AutoModelForSeq2SeqLM:()=>T0,AutoModelForSequenceClassification:()=>v0,AutoModelForSpeechSeq2Seq:()=>E0,AutoModelForTextToSpectrogram:()=>P0,AutoModelForTextToWaveform:()=>C0,AutoModelForTokenClassification:()=>x0,AutoModelForUniversalSegmentation:()=>D0,AutoModelForVision2Seq:()=>I0,AutoModelForXVector:()=>j0,AutoModelForZeroShotObjectDetection:()=>z0,BartForConditionalGeneration:()=>rr,BartForSequenceClassification:()=>Nt,BartModel:()=>zt,BartPretrainedModel:()=>lt,BaseModelOutput:()=>ye,BeitForImageClassification:()=>wd,BeitModel:()=>gd,BeitPreTrainedModel:()=>Da,BertForMaskedLM:()=>$e,BertForQuestionAnswering:()=>Ne,BertForSequenceClassification:()=>Ae,BertForTokenClassification:()=>Re,BertModel:()=>Ce,BertPreTrainedModel:()=>xe,BlenderbotForConditionalGeneration:()=>nr,BlenderbotModel:()=>Dt,BlenderbotPreTrainedModel:()=>Lr,BlenderbotSmallForConditionalGeneration:()=>Br,BlenderbotSmallModel:()=>zr,BlenderbotSmallPreTrainedModel:()=>dr,BloomForCausalLM:()=>Nc,BloomModel:()=>Rc,BloomPreTrainedModel:()=>xa,CLIPModel:()=>di,CLIPPreTrainedModel:()=>xs,CLIPSegForImageSegmentation:()=>_i,CLIPSegModel:()=>Mo,CLIPSegPreTrainedModel:()=>On,CLIPTextModel:()=>pa,CLIPTextModelWithProjection:()=>pi,CLIPVisionModel:()=>ma,CLIPVisionModelWithProjection:()=>sn,CamembertForMaskedLM:()=>Wr,CamembertForQuestionAnswering:()=>cs,CamembertForSequenceClassification:()=>Gr,CamembertForTokenClassification:()=>yr,CamembertModel:()=>us,CamembertPreTrainedModel:()=>Tt,CausalLMOutput:()=>ln,CausalLMOutputWithPast:()=>Z0,ChineseCLIPModel:()=>Fn,ChineseCLIPPreTrainedModel:()=>An,ClapAudioModelWithProjection:()=>fm,ClapModel:()=>hm,ClapPreTrainedModel:()=>Ei,ClapTextModelWithProjection:()=>_m,CodeGenForCausalLM:()=>Vn,CodeGenModel:()=>jn,CodeGenPreTrainedModel:()=>Bs,CohereForCausalLM:()=>vc,CohereModel:()=>yc,CoherePreTrainedModel:()=>_a,ConvBertForMaskedLM:()=>It,ConvBertForQuestionAnswering:()=>fs,ConvBertForSequenceClassification:()=>lr,ConvBertForTokenClassification:()=>as,ConvBertModel:()=>er,ConvBertPreTrainedModel:()=>gt,ConvNextForImageClassification:()=>cp,ConvNextModel:()=>up,ConvNextPreTrainedModel:()=>Xa,ConvNextV2ForImageClassification:()=>pp,ConvNextV2Model:()=>dp,ConvNextV2PreTrainedModel:()=>Qa,DPTForDepthEstimation:()=>Gd,DPTModel:()=>Wd,DPTPreTrainedModel:()=>Ka,DacDecoderModel:()=>nh,DacDecoderOutput:()=>th,DacEncoderModel:()=>sh,DacEncoderOutput:()=>eh,DacModel:()=>rh,DacPreTrainedModel:()=>Ai,DebertaForMaskedLM:()=>He,DebertaForQuestionAnswering:()=>ks,DebertaForSequenceClassification:()=>Ye,DebertaForTokenClassification:()=>cr,DebertaModel:()=>De,DebertaPreTrainedModel:()=>ur,DebertaV2ForMaskedLM:()=>As,DebertaV2ForQuestionAnswering:()=>Sr,DebertaV2ForSequenceClassification:()=>ws,DebertaV2ForTokenClassification:()=>Fs,DebertaV2Model:()=>Is,DebertaV2PreTrainedModel:()=>Or,DecisionTransformerModel:()=>zm,DecisionTransformerPreTrainedModel:()=>Lm,DeiTForImageClassification:()=>Od,DeiTModel:()=>Fd,DeiTPreTrainedModel:()=>Va,DepthAnythingForDepthEstimation:()=>Hd,DepthAnythingPreTrainedModel:()=>Kd,DepthProForDepthEstimation:()=>Yd,DepthProPreTrainedModel:()=>Jd,DetrForObjectDetection:()=>bd,DetrForSegmentation:()=>La,DetrModel:()=>Md,DetrObjectDetectionOutput:()=>za,DetrPreTrainedModel:()=>wi,DetrSegmentationOutput:()=>yd,Dinov2ForImageClassification:()=>hp,Dinov2Model:()=>mp,Dinov2PreTrainedModel:()=>Ja,Dinov2WithRegistersForImageClassification:()=>fp,Dinov2WithRegistersModel:()=>_p,Dinov2WithRegistersPreTrainedModel:()=>Ya,DistilBertForMaskedLM:()=>Os,DistilBertForQuestionAnswering:()=>vr,DistilBertForSequenceClassification:()=>Ms,DistilBertForTokenClassification:()=>bs,DistilBertModel:()=>_r,DistilBertPreTrainedModel:()=>Kr,DonutSwinModel:()=>lp,DonutSwinPreTrainedModel:()=>ap,EfficientNetForImageClassification:()=>xm,EfficientNetModel:()=>vm,EfficientNetPreTrainedModel:()=>ll,ElectraForMaskedLM:()=>ls,ElectraForQuestionAnswering:()=>Ur,ElectraForSequenceClassification:()=>gs,ElectraForTokenClassification:()=>nt,ElectraModel:()=>$s,ElectraPreTrainedModel:()=>Cr,EsmForMaskedLM:()=>Ks,EsmForSequenceClassification:()=>ys,EsmForTokenClassification:()=>xr,EsmModel:()=>$r,EsmPreTrainedModel:()=>ds,ExaoneForCausalLM:()=>Te,ExaoneModel:()=>ie,ExaonePreTrainedModel:()=>V,FalconForCausalLM:()=>mm,FalconModel:()=>pm,FalconPreTrainedModel:()=>ol,FastViTForImageClassification:()=>id,FastViTModel:()=>od,FastViTPreTrainedModel:()=>ka,Florence2ForConditionalGeneration:()=>li,Florence2PreTrainedModel:()=>ai,GLPNForDepthEstimation:()=>ip,GLPNModel:()=>op,GLPNPreTrainedModel:()=>qa,GPT2LMHeadModel:()=>on,GPT2Model:()=>bo,GPT2PreTrainedModel:()=>Dn,GPTBigCodeForCausalLM:()=>Eo,GPTBigCodeModel:()=>To,GPTBigCodePreTrainedModel:()=>Nn,GPTJForCausalLM:()=>Rn,GPTJModel:()=>xo,GPTJPreTrainedModel:()=>Bn,GPTNeoForCausalLM:()=>kr,GPTNeoModel:()=>an,GPTNeoPreTrainedModel:()=>Ln,GPTNeoXForCausalLM:()=>vo,GPTNeoXModel:()=>zn,GPTNeoXPreTrainedModel:()=>zs,Gemma2ForCausalLM:()=>Pc,Gemma2Model:()=>Ec,Gemma2PreTrainedModel:()=>ga,Gemma3ForCausalLM:()=>Sc,Gemma3Model:()=>Cc,Gemma3PreTrainedModel:()=>wa,GemmaForCausalLM:()=>Tc,GemmaModel:()=>xc,GemmaPreTrainedModel:()=>fa,GlmForCausalLM:()=>D,GlmModel:()=>k,GlmPreTrainedModel:()=>T,GraniteForCausalLM:()=>bc,GraniteModel:()=>Mc,GranitePreTrainedModel:()=>ha,GroundingDinoForObjectDetection:()=>wp,GroundingDinoPreTrainedModel:()=>gp,GroupViTModel:()=>nd,GroupViTPreTrainedModel:()=>sd,HeliumForCausalLM:()=>m,HeliumModel:()=>So,HeliumPreTrainedModel:()=>Wn,HieraForImageClassification:()=>Ld,HieraModel:()=>Dd,HieraPreTrainedModel:()=>Ua,HubertForCTC:()=>qp,HubertForSequenceClassification:()=>Xp,HubertModel:()=>Hp,HubertPreTrainedModel:()=>l0,IJepaForImageClassification:()=>qc,IJepaModel:()=>Hc,IJepaPreTrainedModel:()=>Ca,Idefics3ForConditionalGeneration:()=>In,Idefics3PreTrainedModel:()=>po,ImageMattingOutput:()=>Dh,JAISLMHeadModel:()=>yo,JAISModel:()=>fi,JAISPreTrainedModel:()=>et,JinaCLIPModel:()=>fo,JinaCLIPPreTrainedModel:()=>nn,JinaCLIPTextModel:()=>go,JinaCLIPVisionModel:()=>wo,LiteWhisperForConditionalGeneration:()=>lo,LlamaForCausalLM:()=>Co,LlamaModel:()=>Po,LlamaPreTrainedModel:()=>Un,LlavaForConditionalGeneration:()=>hs,LlavaOnevisionForConditionalGeneration:()=>ii,LlavaPreTrainedModel:()=>uo,LongT5ForConditionalGeneration:()=>Ge,LongT5Model:()=>Ue,LongT5PreTrainedModel:()=>Se,M2M100ForConditionalGeneration:()=>Sp,M2M100Model:()=>Cp,M2M100PreTrainedModel:()=>tl,MBartForCausalLM:()=>sr,MBartForConditionalGeneration:()=>Ht,MBartForSequenceClassification:()=>ms,MBartModel:()=>Ot,MBartPreTrainedModel:()=>jt,MPNetForMaskedLM:()=>Xs,MPNetForQuestionAnswering:()=>Ys,MPNetForSequenceClassification:()=>Qs,MPNetForTokenClassification:()=>Js,MPNetModel:()=>qs,MPNetPreTrainedModel:()=>Hr,MT5ForConditionalGeneration:()=>Mt,MT5Model:()=>Ve,MT5PreTrainedModel:()=>Ke,MarianMTModel:()=>Pp,MarianModel:()=>Ep,MarianPreTrainedModel:()=>el,MaskFormerForInstanceSegmentation:()=>np,MaskFormerModel:()=>sp,MaskFormerPreTrainedModel:()=>Ha,MaskedLMOutput:()=>gr,Metric3DForDepthEstimation:()=>ep,Metric3DPreTrainedModel:()=>Zd,Metric3Dv2ForDepthEstimation:()=>rp,Metric3Dv2PreTrainedModel:()=>tp,MgpstrForSceneTextRecognition:()=>Vm,MgpstrModelOutput:()=>Nm,MgpstrPreTrainedModel:()=>jm,MimiDecoderModel:()=>Zm,MimiDecoderOutput:()=>Qm,MimiEncoderModel:()=>Ym,MimiEncoderOutput:()=>Xm,MimiModel:()=>Jm,MimiPreTrainedModel:()=>Ii,MistralForCausalLM:()=>um,MistralModel:()=>lm,MistralPreTrainedModel:()=>sl,MobileBertForMaskedLM:()=>fr,MobileBertForQuestionAnswering:()=>Hs,MobileBertForSequenceClassification:()=>vs,MobileBertModel:()=>tr,MobileBertPreTrainedModel:()=>Dr,MobileLLMForCausalLM:()=>Xe,MobileLLMModel:()=>We,MobileLLMPreTrainedModel:()=>Oe,MobileNetV1ForImageClassification:()=>Em,MobileNetV1ForSemanticSegmentation:()=>Pm,MobileNetV1Model:()=>Tm,MobileNetV1PreTrainedModel:()=>Ci,MobileNetV2ForImageClassification:()=>Sm,MobileNetV2ForSemanticSegmentation:()=>$m,MobileNetV2Model:()=>Cm,MobileNetV2PreTrainedModel:()=>Si,MobileNetV3ForImageClassification:()=>Im,MobileNetV3ForSemanticSegmentation:()=>Am,MobileNetV3Model:()=>km,MobileNetV3PreTrainedModel:()=>$i,MobileNetV4ForImageClassification:()=>Om,MobileNetV4ForSemanticSegmentation:()=>Dm,MobileNetV4Model:()=>Fm,MobileNetV4PreTrainedModel:()=>ki,MobileViTForImageClassification:()=>cd,MobileViTModel:()=>ud,MobileViTPreTrainedModel:()=>Ia,MobileViTV2ForImageClassification:()=>pd,MobileViTV2Model:()=>dd,MobileViTV2PreTrainedModel:()=>Aa,ModelOutput:()=>pe,ModernBertForMaskedLM:()=>z,ModernBertForSequenceClassification:()=>ee,ModernBertForTokenClassification:()=>oe,ModernBertModel:()=>Y,ModernBertPreTrainedModel:()=>A,Moondream1ForConditionalGeneration:()=>co,MoonshineForConditionalGeneration:()=>oi,MoonshineModel:()=>da,MoonshinePreTrainedModel:()=>Sn,MptForCausalLM:()=>Vc,MptModel:()=>jc,MptPreTrainedModel:()=>Ta,MultiModalityCausalLM:()=>Rm,MultiModalityPreTrainedModel:()=>Bm,MusicgenForCausalLM:()=>p0,MusicgenForConditionalGeneration:()=>cl,MusicgenModel:()=>d0,MusicgenPreTrainedModel:()=>ul,NomicBertModel:()=>Ee,NomicBertPreTrainedModel:()=>he,OPTForCausalLM:()=>Wc,OPTModel:()=>Uc,OPTPreTrainedModel:()=>Ea,Olmo2ForCausalLM:()=>gi,Olmo2Model:()=>Es,Olmo2PreTrainedModel:()=>Jt,OlmoForCausalLM:()=>Ct,OlmoModel:()=>bt,OlmoPreTrainedModel:()=>ct,OpenELMForCausalLM:()=>kc,OpenELMModel:()=>$c,OpenELMPreTrainedModel:()=>Ma,OwlViTForObjectDetection:()=>hd,OwlViTModel:()=>md,OwlViTPreTrainedModel:()=>Fa,Owlv2ForObjectDetection:()=>fd,Owlv2Model:()=>_d,Owlv2PreTrainedModel:()=>Oa,PaliGemmaForConditionalGeneration:()=>kn,PaliGemmaPreTrainedModel:()=>ui,PatchTSMixerForPrediction:()=>Km,PatchTSMixerModel:()=>Gm,PatchTSMixerPreTrainedModel:()=>pl,PatchTSTForPrediction:()=>Wm,PatchTSTModel:()=>Um,PatchTSTPreTrainedModel:()=>dl,Phi3ForCausalLM:()=>Bc,Phi3Model:()=>zc,Phi3PreTrainedModel:()=>va,Phi3VForCausalLM:()=>ho,Phi3VPreTrainedModel:()=>ci,PhiForCausalLM:()=>Lc,PhiModel:()=>Dc,PhiPreTrainedModel:()=>ya,PreTrainedModel:()=>U,PretrainedMixin:()=>St,PvtForImageClassification:()=>Yc,PvtModel:()=>Jc,PvtPreTrainedModel:()=>Sa,PyAnnoteForAudioFrameClassification:()=>Op,PyAnnoteModel:()=>Fp,PyAnnotePreTrainedModel:()=>rl,QuestionAnsweringModelOutput:()=>Mr,Qwen2ForCausalLM:()=>Ac,Qwen2Model:()=>Ic,Qwen2PreTrainedModel:()=>ba,Qwen2VLForConditionalGeneration:()=>Oc,Qwen2VLPreTrainedModel:()=>Fc,RFDetrForObjectDetection:()=>Sd,RFDetrModel:()=>Cd,RFDetrObjectDetectionOutput:()=>$d,RFDetrPreTrainedModel:()=>Na,RTDetrForObjectDetection:()=>xd,RTDetrModel:()=>vd,RTDetrObjectDetectionOutput:()=>Mi,RTDetrPreTrainedModel:()=>Ba,RTDetrV2ForObjectDetection:()=>Ed,RTDetrV2Model:()=>Td,RTDetrV2ObjectDetectionOutput:()=>Pd,RTDetrV2PreTrainedModel:()=>Ra,ResNetForImageClassification:()=>Bd,ResNetModel:()=>zd,ResNetPreTrainedModel:()=>Wa,RoFormerForMaskedLM:()=>ke,RoFormerForQuestionAnswering:()=>_t,RoFormerForSequenceClassification:()=>st,RoFormerForTokenClassification:()=>ut,RoFormerModel:()=>Me,RoFormerPreTrainedModel:()=>Fe,RobertaForMaskedLM:()=>or,RobertaForQuestionAnswering:()=>Xt,RobertaForSequenceClassification:()=>Gt,RobertaForTokenClassification:()=>Rt,RobertaModel:()=>Tr,RobertaPreTrainedModel:()=>qt,SamImageSegmentationOutput:()=>Tp,SamModel:()=>xp,SamPreTrainedModel:()=>vp,SapiensForDepthEstimation:()=>Xd,SapiensForNormalEstimation:()=>Qd,SapiensForSemanticSegmentation:()=>qd,SapiensPreTrainedModel:()=>yi,SegformerForImageClassification:()=>wm,SegformerForSemanticSegmentation:()=>Mm,SegformerModel:()=>c0,SegformerPreTrainedModel:()=>Pi,Seq2SeqLMOutput:()=>Y0,SequenceClassifierOutput:()=>dt,SiglipModel:()=>_o,SiglipPreTrainedModel:()=>Ts,SiglipTextModel:()=>mi,SiglipVisionModel:()=>hi,SmolVLMForConditionalGeneration:()=>mo,SnacDecoderModel:()=>ah,SnacEncoderModel:()=>ih,SnacModel:()=>oh,SnacPreTrainedModel:()=>Fi,SpeechT5ForSpeechToText:()=>sm,SpeechT5ForTextToSpeech:()=>nm,SpeechT5HifiGan:()=>om,SpeechT5Model:()=>u0,SpeechT5PreTrainedModel:()=>Ti,SqueezeBertForMaskedLM:()=>en,SqueezeBertForQuestionAnswering:()=>rn,SqueezeBertForSequenceClassification:()=>tn,SqueezeBertModel:()=>Zs,SqueezeBertPreTrainedModel:()=>qr,StableLmForCausalLM:()=>ym,StableLmModel:()=>bm,StableLmPreTrainedModel:()=>al,Starcoder2ForCausalLM:()=>dm,Starcoder2Model:()=>cm,Starcoder2PreTrainedModel:()=>nl,StyleTextToSpeech2Model:()=>rm,StyleTextToSpeech2PreTrainedModel:()=>tm,Swin2SRForImageSuperResolution:()=>Ud,Swin2SRModel:()=>Vd,Swin2SRPreTrainedModel:()=>Ga,SwinForImageClassification:()=>Nd,SwinForSemanticSegmentation:()=>jd,SwinModel:()=>Rd,SwinPreTrainedModel:()=>bi,T5ForConditionalGeneration:()=>_e,T5Model:()=>se,T5PreTrainedModel:()=>Z,TableTransformerForObjectDetection:()=>Id,TableTransformerModel:()=>kd,TableTransformerObjectDetectionOutput:()=>Ad,TableTransformerPreTrainedModel:()=>ja,TokenClassifierOutput:()=>pr,TrOCRForCausalLM:()=>am,TrOCRPreTrainedModel:()=>im,UltravoxModel:()=>qm,UltravoxPreTrainedModel:()=>Hm,UniSpeechForCTC:()=>Bp,UniSpeechForSequenceClassification:()=>Rp,UniSpeechModel:()=>zp,UniSpeechPreTrainedModel:()=>vi,UniSpeechSatForAudioFrameClassification:()=>Up,UniSpeechSatForCTC:()=>jp,UniSpeechSatForSequenceClassification:()=>Vp,UniSpeechSatModel:()=>Np,UniSpeechSatPreTrainedModel:()=>$o,ViTForImageClassification:()=>Kc,ViTMAEModel:()=>ed,ViTMAEPreTrainedModel:()=>Zc,ViTMSNForImageClassification:()=>rd,ViTMSNModel:()=>td,ViTMSNPreTrainedModel:()=>$a,ViTModel:()=>Gc,ViTPreTrainedModel:()=>Pa,VisionEncoderDecoderModel:()=>$n,VitMatteForImageMatting:()=>ld,VitMattePreTrainedModel:()=>ad,VitPoseForPoseEstimation:()=>Qc,VitPosePreTrainedModel:()=>Xc,VitsModel:()=>il,VitsModelOutput:()=>Lh,VitsPreTrainedModel:()=>gm,Wav2Vec2BertForCTC:()=>Gp,Wav2Vec2BertForSequenceClassification:()=>Kp,Wav2Vec2BertModel:()=>Wp,Wav2Vec2BertPreTrainedModel:()=>xi,Wav2Vec2ForAudioFrameClassification:()=>Ap,Wav2Vec2ForCTC:()=>kp,Wav2Vec2ForSequenceClassification:()=>Ip,Wav2Vec2Model:()=>$p,Wav2Vec2PreTrainedModel:()=>Rs,WavLMForAudioFrameClassification:()=>em,WavLMForCTC:()=>Jp,WavLMForSequenceClassification:()=>Yp,WavLMForXVector:()=>Zp,WavLMModel:()=>Qp,WavLMPreTrainedModel:()=>Gn,WeSpeakerResNetModel:()=>Lp,WeSpeakerResNetPreTrainedModel:()=>Dp,WhisperForConditionalGeneration:()=>Cn,WhisperModel:()=>ni,WhisperPreTrainedModel:()=>ao,XLMForQuestionAnswering:()=>Qo,XLMForSequenceClassification:()=>Xo,XLMForTokenClassification:()=>oo,XLMModel:()=>Ds,XLMPreTrainedModel:()=>ir,XLMRobertaForMaskedLM:()=>Yo,XLMRobertaForQuestionAnswering:()=>ti,XLMRobertaForSequenceClassification:()=>Zo,XLMRobertaForTokenClassification:()=>ei,XLMRobertaModel:()=>Jo,XLMRobertaPreTrainedModel:()=>Ls,XLMWithLMHeadModel:()=>Pn,XVectorOutput:()=>Oh,YolosForObjectDetection:()=>bp,YolosModel:()=>Mp,YolosObjectDetectionOutput:()=>yp,YolosPreTrainedModel:()=>Za});var s=t("./src/configs.js"),n=t("./src/backends/onnx.js"),o=t("./src/utils/dtypes.js"),a=t("./src/utils/generic.js"),i=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),c=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),u=t("./src/generation/configuration_utils.js"),d=t("./src/utils/tensor.js"),f=t("./src/utils/image.js"),_=t("./src/utils/maths.js"),P=t("./src/generation/stopping_criteria.js"),I=t("./src/generation/logits_sampler.js"),M=t("./src/env.js"),g=t("./src/models/whisper/generation_whisper.js"),S=t("./src/models/whisper/common_whisper.js");const E={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11},x=new Map,w=new Map,v=new Map;async function $(b,y,j){let ae=j.config?.["transformers.js_config"]??{},me=j.device??ae.device;me&&typeof me!="string"&&(me.hasOwnProperty(y)?me=me[y]:(console.warn(`device not specified for "${y}". Using the default device.`),me=null));const ge=me??(M.apis.IS_NODE_ENV?"cpu":"wasm"),Ie=(0,n.deviceToExecutionProviders)(ge),Le=ae.device_config??{};Le.hasOwnProperty(ge)&&(ae={...ae,...Le[ge]});let Be=j.dtype??ae.dtype;if(typeof Be!="string"&&(Be&&Be.hasOwnProperty(y)?Be=Be[y]:(Be=o.DEFAULT_DEVICE_DTYPE_MAPPING[ge]??o.DATA_TYPES.fp32,console.warn(`dtype not specified for "${y}". Using the default dtype (${Be}) for this device (${ge}).`))),Be===o.DATA_TYPES.auto){let wt=ae.dtype;typeof wt!="string"&&(wt=wt?.[y]),wt&&wt!==o.DATA_TYPES.auto&&o.DATA_TYPES.hasOwnProperty(wt)?Be=wt:Be=o.DEFAULT_DEVICE_DTYPE_MAPPING[ge]??o.DATA_TYPES.fp32}const qe=Be;if(o.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(qe)){if(qe===o.DATA_TYPES.fp16&&ge==="webgpu"&&!await(0,o.isWebGpuFp16Supported)())throw new Error(`The device (${ge}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${qe}. Should be one of: ${Object.keys(o.DATA_TYPES).join(", ")}`);const pt=ae.kv_cache_dtype,ft=pt?typeof pt=="string"?pt:pt[qe]??"float32":void 0;if(ft&&!["float32","float16"].includes(ft))throw new Error(`Invalid kv_cache_dtype: ${ft}. Should be one of: float32, float16`);const ot={dtype:qe,kv_cache_dtype:ft},rt=o.DEFAULT_DTYPE_SUFFIX_MAPPING[qe],$t=`${y}${rt}.onnx`,it=`${j.subfolder??""}/${$t}`,tt={...j.session_options};tt.executionProviders??=Ie;const vt=ae.free_dimension_overrides;vt?tt.freeDimensionOverrides??=vt:ge.startsWith("webnn")&&!tt.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${ge}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const At=M.apis.IS_NODE_ENV&&M.env.useFSCache,Vt=(0,l.getModelFile)(b,it,!0,j,At),Yt=j.use_external_data_format??ae.use_external_data_format;let Zt=[];if(Yt){let wt;typeof Yt=="object"?Yt.hasOwnProperty($t)?wt=Yt[$t]:Yt.hasOwnProperty(y)?wt=Yt[y]:wt=!1:wt=Yt;const Ut=+wt;if(Ut>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${Ut}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let mr=0;mr{const qn=await(0,l.getModelFile)(b,Er,!0,j,At);Xr(qn instanceof Uint8Array?{path:un,data:qn}:un)}))}}else tt.externalData!==void 0&&(Zt=tt.externalData.map(async wt=>{if(typeof wt.data=="string"){const Ut=await(0,l.getModelFile)(b,wt.data,!0,j);return{...wt,data:Ut}}return wt}));if(Zt.length>0){const wt=await Promise.all(Zt);M.apis.IS_NODE_ENV||(tt.externalData=wt)}if(ge==="webgpu"){const wt=(0,s.getKeyValueShapes)(j.config,{prefix:"present"});if(Object.keys(wt).length>0&&!(0,n.isONNXProxy)()){const Ut={};for(const mr in wt)Ut[mr]="gpu-buffer";tt.preferredOutputLocation=Ut}}return{buffer_or_path:await Vt,session_options:tt,session_config:ot}}async function O(b,y,j){return Object.fromEntries(await Promise.all(Object.keys(y).map(async ae=>{const{buffer_or_path:me,session_options:ge,session_config:Ie}=await $(b,y[ae],j),Le=await(0,n.createInferenceSession)(me,ge,Ie);return[ae,Le]})))}async function B(b,y,j){return Object.fromEntries(await Promise.all(Object.keys(y).map(async ae=>{const me=await(0,l.getModelJSON)(b,y[ae],!1,j);return[ae,me]})))}function H(b,y){const j=Object.create(null),ae=[];for(const Ie of b.inputNames){const Le=y[Ie];if(!(Le instanceof d.Tensor)){ae.push(Ie);continue}j[Ie]=(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(y).length,ge=b.inputNames.length;if(me>ge){let Ie=Object.keys(y).filter(Le=>!b.inputNames.includes(Le));console.warn(`WARNING: Too many inputs were provided (${me} > ${ge}). The following inputs will be ignored: "${Ie.join(", ")}".`)}return j}async function q(b,y){const j=H(b,y);try{const ae=Object.fromEntries(Object.entries(j).map(([ge,Ie])=>[ge,Ie.ort_tensor]));let me=await b.run(ae);return me=L(me),me}catch(ae){const me=Object.fromEntries(Object.entries(j).map(([ge,{type:Ie,dims:Le,data:Be}])=>[ge,{type:Ie,dims:Le,data:Be}]));throw console.error(`An error occurred during model execution: "${ae}".`),console.error("Inputs given to model:",me),ae}}function L(b){for(let y in b)(0,n.isONNXTensor)(b[y])?b[y]=new d.Tensor(b[y]):typeof b[y]=="object"&&L(b[y]);return b}function J(b){if(b instanceof d.Tensor)return b;if(b.length===0)throw Error("items must be non-empty");if(Array.isArray(b[0])){if(b.some(y=>y.length!==b[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 d.Tensor("int64",BigInt64Array.from(b.flat().map(y=>BigInt(y))),[b.length,b[0].length])}else return new d.Tensor("int64",BigInt64Array.from(b.map(y=>BigInt(y))),[1,b.length])}function X(b){return new d.Tensor("bool",[b],[1])}async function Q(b,y){let{encoder_outputs:j,input_ids:ae,decoder_input_ids:me,...ge}=y;if(!j){const Le=(0,i.pick)(y,b.sessions.model.inputNames);j=(await te(b,Le)).last_hidden_state}return ge.input_ids=me,ge.encoder_hidden_states=j,b.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(ge.encoder_attention_mask=y.attention_mask),await ce(b,ge,!0)}async function te(b,y){const j=b.sessions.model,ae=(0,i.pick)(y,j.inputNames);if(j.inputNames.includes("inputs_embeds")&&!ae.inputs_embeds){if(!y.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ae.inputs_embeds=await b.encode_text({input_ids:y.input_ids})}if(j.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,d.zeros_like)(ae.input_ids)}if(j.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,d.ones)([me[0],me[2],me[3]])}return await q(j,ae)}async function re(b,y){const j=await b.encode(y);return await b.decode(j)}async function ce(b,y,j=!1){const ae=b.sessions[j?"decoder_model_merged":"model"],{past_key_values:me,...ge}=y;if(ae.inputNames.includes("use_cache_branch")&&(ge.use_cache_branch=X(!!me)),ae.inputNames.includes("position_ids")&&ge.attention_mask&&!ge.position_ids){const Le=["paligemma","gemma3_text","gemma3"].includes(b.config.model_type)?1:0;ge.position_ids=de(ge,me,Le)}b.addPastKeyValues(ge,me);const Ie=(0,i.pick)(ge,ae.inputNames);return await q(ae,Ie)}function le({modality_token_id:b,inputs_embeds:y,modality_features:j,input_ids:ae,attention_mask:me}){const ge=ae.tolist().map(qe=>qe.reduce((pt,ft,ot)=>(ft==b&&pt.push(ot),pt),[])),Ie=ge.reduce((qe,pt)=>qe+pt.length,0),Le=j.dims[0];if(Ie!==Le)throw new Error(`Number of tokens and features do not match: tokens: ${Ie}, features ${Le}`);let Be=0;for(let qe=0;qege.dims[1])){if(meLe==b.config.image_token_index)){const Le=b.config.num_image_tokens;if(!Le)throw new Error("`num_image_tokens` is missing in the model configuration.");const Be=ge.dims[1]-(me-Le);j.input_ids=ge.slice(null,[-Be,null]),j.attention_mask=(0,d.ones)([1,me+Be])}}}return j}function je(b,y,j,ae){return j.past_key_values&&(y=y.map(me=>[me.at(-1)])),{...j,decoder_input_ids:J(y)}}function fe(b,...y){return b.config.is_encoder_decoder?je(b,...y):ve(b,...y)}function K(b,y,j,ae){const me=!!j.past_key_values;return ae.guidance_scale!==null&&ae.guidance_scale>1&&(me?j.input_ids=(0,d.cat)([j.input_ids,j.input_ids],0):(j.input_ids=(0,d.cat)([j.input_ids,(0,d.full_like)(j.input_ids,BigInt(ae.pad_token_id))],0),j.attention_mask=(0,d.cat)([j.attention_mask,(0,d.full_like)(j.attention_mask,0n)],0))),(me||!j.pixel_values)&&(j.pixel_values=(0,d.full)([0,0,3,384,384],1)),me&&(j.images_seq_mask=new d.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),j.images_emb_mask=new d.Tensor("bool",new Array(0).fill(!1),[1,1,0])),j}class U extends a.Callable{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];constructor(y,j,ae){super(),this.config=y,this.sessions=j,this.configs=ae;const me=v.get(this.constructor),ge=x.get(me);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,ge){case E.DecoderOnly:this.can_generate=!0,this._forward=ce,this._prepare_inputs_for_generation=ve;break;case E.Seq2Seq:case E.Vision2Seq:case E.Musicgen:this.can_generate=!0,this._forward=Q,this._prepare_inputs_for_generation=je;break;case E.EncoderDecoder:this._forward=Q;break;case E.ImageTextToText:this.can_generate=!0,this._forward=ne,this._prepare_inputs_for_generation=fe;break;case E.AudioTextToText:this.can_generate=!0,this._forward=R,this._prepare_inputs_for_generation=fe;break;case E.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=fe;break;case E.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=K;break;case E.AutoEncoder:this._forward=re;break;default:this._forward=te;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){const y=[];for(const j of Object.values(this.sessions))j?.handler?.dispose&&y.push(j.handler.dispose());return await Promise.all(y)}static async from_pretrained(y,{progress_callback:j=null,config:ae=null,cache_dir:me=null,local_files_only:ge=!1,revision:Ie="main",model_file_name:Le=null,subfolder:Be="onnx",device:qe=null,dtype:pt=null,use_external_data_format:ft=null,session_options:ot={}}={}){let rt={progress_callback:j,config:ae,cache_dir:me,local_files_only:ge,revision:Ie,model_file_name:Le,subfolder:Be,device:qe,dtype:pt,use_external_data_format:ft,session_options:ot};const $t=v.get(this),it=x.get($t);ae=rt.config=await s.AutoConfig.from_pretrained(y,rt);let tt;if(it===E.DecoderOnly)tt=await Promise.all([O(y,{model:rt.model_file_name??"model"},rt),B(y,{generation_config:"generation_config.json"},rt)]);else if(it===E.Seq2Seq||it===E.Vision2Seq)tt=await Promise.all([O(y,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},rt),B(y,{generation_config:"generation_config.json"},rt)]);else if(it===E.MaskGeneration)tt=await Promise.all([O(y,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},rt)]);else if(it===E.EncoderDecoder)tt=await Promise.all([O(y,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},rt)]);else if(it===E.ImageTextToText){const vt={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};ae.is_encoder_decoder&&(vt.model="encoder_model"),tt=await Promise.all([O(y,vt,rt),B(y,{generation_config:"generation_config.json"},rt)])}else if(it===E.AudioTextToText){const vt={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};tt=await Promise.all([O(y,vt,rt),B(y,{generation_config:"generation_config.json"},rt)])}else if(it===E.Musicgen)tt=await Promise.all([O(y,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},rt),B(y,{generation_config:"generation_config.json"},rt)]);else if(it===E.MultiModality)tt=await Promise.all([O(y,{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"},rt),B(y,{generation_config:"generation_config.json"},rt)]);else if(it===E.Phi3V)tt=await Promise.all([O(y,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},rt),B(y,{generation_config:"generation_config.json"},rt)]);else if(it===E.AutoEncoder)tt=await Promise.all([O(y,{encoder_model:"encoder_model",decoder_model:"decoder_model"},rt)]);else{if(it!==E.EncoderOnly){const vt=$t??ae?.model_type;vt!=="custom"&&console.warn(`Model type for '${vt}' not found, assuming encoder-only architecture. Please report this at ${c.GITHUB_ISSUE_URL}.`)}tt=await Promise.all([O(y,{model:rt.model_file_name??"model"},rt)])}return new this(ae,...tt)}async _call(y){return await this.forward(y)}async forward(y){return await this._forward(this,y)}get generation_config(){return this.configs?.generation_config??null}_get_logits_warper(y){const j=new p.LogitsProcessorList;return y.temperature!==null&&y.temperature!==1&&j.push(new p.TemperatureLogitsWarper(y.temperature)),y.top_k!==null&&y.top_k!==0&&j.push(new p.TopKLogitsWarper(y.top_k)),y.top_p!==null&&y.top_p<1&&j.push(new p.TopPLogitsWarper(y.top_p)),j}_get_logits_processor(y,j,ae=null){const me=new p.LogitsProcessorList;if(y.repetition_penalty!==null&&y.repetition_penalty!==1&&me.push(new p.RepetitionPenaltyLogitsProcessor(y.repetition_penalty)),y.no_repeat_ngram_size!==null&&y.no_repeat_ngram_size>0&&me.push(new p.NoRepeatNGramLogitsProcessor(y.no_repeat_ngram_size)),y.bad_words_ids!==null&&me.push(new p.NoBadWordsLogitsProcessor(y.bad_words_ids,y.eos_token_id)),y.min_length!==null&&y.eos_token_id!==null&&y.min_length>0&&me.push(new p.MinLengthLogitsProcessor(y.min_length,y.eos_token_id)),y.min_new_tokens!==null&&y.eos_token_id!==null&&y.min_new_tokens>0&&me.push(new p.MinNewTokensLengthLogitsProcessor(j,y.min_new_tokens,y.eos_token_id)),y.forced_bos_token_id!==null&&me.push(new p.ForcedBOSTokenLogitsProcessor(y.forced_bos_token_id)),y.forced_eos_token_id!==null&&me.push(new p.ForcedEOSTokenLogitsProcessor(y.max_length,y.forced_eos_token_id)),y.begin_suppress_tokens!==null){const ge=j>1||y.forced_bos_token_id===null?j:j+1;me.push(new p.SuppressTokensAtBeginLogitsProcessor(y.begin_suppress_tokens,ge))}return y.guidance_scale!==null&&y.guidance_scale>1&&me.push(new p.ClassifierFreeGuidanceLogitsProcessor(y.guidance_scale)),ae!==null&&me.extend(ae),me}_prepare_generation_config(y,j,ae=u.GenerationConfig){const me={...this.config};for(const Ie of["decoder","generator","text_config"])Ie in me&&Object.assign(me,me[Ie]);const ge=new ae(me);return Object.assign(ge,this.generation_config??{}),y&&Object.assign(ge,y),j&&Object.assign(ge,(0,i.pick)(j,Object.getOwnPropertyNames(ge))),ge}_get_stopping_criteria(y,j=null){const ae=new P.StoppingCriteriaList;return y.max_length!==null&&ae.push(new P.MaxLengthCriteria(y.max_length,this.config.max_position_embeddings??null)),y.eos_token_id!==null&&ae.push(new P.EosTokenCriteria(y.eos_token_id)),j&&ae.extend(j),ae}_validate_model_class(){if(!this.can_generate){const y=[_l,fl,hl,ml],j=v.get(this.constructor),ae=new Set,me=this.config.model_type;for(const Ie of y){const Le=Ie.get(me);Le&&ae.add(Le[0])}let ge=`The current model class (${j}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ae.size>0&&(ge+=` Please use the following class instead: ${[...ae].join(", ")}`),Error(ge)}}prepare_inputs_for_generation(...y){return this._prepare_inputs_for_generation(this,...y)}_update_model_kwargs_for_generation({generated_input_ids:y,outputs:j,model_inputs:ae,is_encoder_decoder:me}){return ae.past_key_values=this.getPastKeyValues(j,ae.past_key_values),ae.input_ids=new d.Tensor("int64",y.flat(),[y.length,1]),me||(ae.attention_mask=(0,d.cat)([ae.attention_mask,(0,d.ones)([ae.attention_mask.dims[0],1])],1)),ae.position_ids=null,ae}_prepare_model_inputs({inputs:y,bos_token_id:j,model_kwargs:ae}){const me=(0,i.pick)(ae,this.forward_params),ge=this.main_input_name;if(ge in me){if(y)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[ge]=y;return{inputs_tensor:me[ge],model_inputs:me,model_input_name:ge}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:y,model_inputs:j,model_input_name:ae,generation_config:me}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!j.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Ie,pixel_values:Le,attention_mask:Be,...qe}=j,pt=await this._prepare_inputs_embeds(j);j={...qe,...(0,i.pick)(pt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:ge}=await te(this,j);if(me.guidance_scale!==null&&me.guidance_scale>1)ge=(0,d.cat)([ge,(0,d.full_like)(ge,0)],0),"attention_mask"in j&&(j.attention_mask=(0,d.cat)([j.attention_mask,(0,d.zeros_like)(j.attention_mask)],0));else if(j.decoder_input_ids){const Ie=J(j.decoder_input_ids).dims[0];if(Ie!==ge.dims[0]){if(ge.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${ge.dims[0]}) than the decoder inputs (${Ie}).`);ge=(0,d.cat)(Array.from({length:Ie},()=>ge),0)}}return j.encoder_outputs=ge,j}_prepare_decoder_input_ids_for_generation({batch_size:y,model_input_name:j,model_kwargs:ae,decoder_start_token_id:me,bos_token_id:ge,generation_config:Ie}){let{decoder_input_ids:Le,...Be}=ae;if(!(Le instanceof d.Tensor)){if(Le)Array.isArray(Le[0])||(Le=Array.from({length:y},()=>Le));else if(me??=ge,this.config.model_type==="musicgen")Le=Array.from({length:y*this.config.decoder.num_codebooks},()=>[me]);else if(Array.isArray(me)){if(me.length!==y)throw new Error(`\`decoder_start_token_id\` expcted to have length ${y} but got ${me.length}`);Le=me}else Le=Array.from({length:y},()=>[me]);Le=J(Le)}return ae.decoder_attention_mask=(0,d.ones_like)(Le),{input_ids:Le,model_inputs:Be}}async generate({inputs:y=null,generation_config:j=null,logits_processor:ae=null,stopping_criteria:me=null,streamer:ge=null,...Ie}){this._validate_model_class(),j=this._prepare_generation_config(j,Ie);let{inputs_tensor:Le,model_inputs:Be,model_input_name:qe}=this._prepare_model_inputs({inputs:y,model_kwargs:Ie});const pt=this.config.is_encoder_decoder;pt&&("encoder_outputs"in Be||(Be=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Le,model_inputs:Be,model_input_name:qe,generation_config:j})));let ft;pt?{input_ids:ft,model_inputs:Be}=this._prepare_decoder_input_ids_for_generation({batch_size:Be[qe].dims.at(0),model_input_name:qe,model_kwargs:Be,decoder_start_token_id:j.decoder_start_token_id,bos_token_id:j.bos_token_id,generation_config:j}):ft=Be[qe];let ot=ft.dims.at(-1);j.max_new_tokens!==null&&(j.max_length=ot+j.max_new_tokens);const rt=this._get_logits_processor(j,ot,ae),$t=this._get_stopping_criteria(j,me),it=Be[qe].dims.at(0),tt=I.LogitsSampler.getSampler(j),vt=new Array(it).fill(0),At=ft.tolist();ge&&ge.put(At);let Vt,Yt={};for(;;){if(Be=this.prepare_inputs_for_generation(At,Be,j),Vt=await this.forward(Be),j.output_attentions&&j.return_dict_in_generate){const Er=this.getAttentions(Vt);for(const Xr in Er)Xr in Yt||(Yt[Xr]=[]),Yt[Xr].push(Er[Xr])}const wt=Vt.logits.slice(null,-1,null),Ut=rt(At,wt),mr=[];for(let Er=0;ErEr))break;Be=this._update_model_kwargs_for_generation({generated_input_ids:mr,outputs:Vt,model_inputs:Be,is_encoder_decoder:pt})}ge&&ge.end();const Zt=this.getPastKeyValues(Vt,Be.past_key_values,!0),Qt=new d.Tensor("int64",At.flat(),[At.length,At[0].length]);if(j.return_dict_in_generate)return{sequences:Qt,past_key_values:Zt,...Yt};for(const wt of Object.values(Vt))wt.location==="gpu-buffer"&&wt.dispose();return Qt}getPastKeyValues(y,j,ae=!1){const me=Object.create(null);for(const ge in y)if(ge.startsWith("present")){const Ie=ge.replace("present","past_key_values"),Le=ge.includes("encoder");if(Le&&j?me[Ie]=j[Ie]:me[Ie]=y[ge],j&&(!Le||ae)){const Be=j[Ie];Be.location==="gpu-buffer"&&Be.dispose()}}return me}getAttentions(y){const j={};for(const ae of["cross_attentions","encoder_attentions","decoder_attentions"])for(const me in y)me.startsWith(ae)&&(ae in j||(j[ae]=[]),j[ae].push(y[me]));return j}addPastKeyValues(y,j){if(j)Object.assign(y,j);else{const me=(this.sessions.decoder_model_merged??this.sessions.model)?.config?.kv_cache_dtype??"float32",ge=me==="float16"?new d.DataTypeMap.float16:[],Ie=(y[this.main_input_name]??y.attention_mask)?.dims?.[0]??1,Le=(0,s.getKeyValueShapes)(this.config,{batch_size:Ie});for(const Be in Le)y[Be]=new d.Tensor(me,ge,Le[Be])}}async encode_image({pixel_values:y}){const j=(await q(this.sessions.vision_encoder,{pixel_values:y})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${j.dims[1]}).`),this.config.num_image_tokens=j.dims[1]),j}async encode_text({input_ids:y}){return(await q(this.sessions.embed_tokens,{input_ids:y})).inputs_embeds}async encode_audio({audio_values:y}){return(await q(this.sessions.audio_encoder,{audio_values:y})).audio_features}}class pe{}class ye extends pe{constructor({last_hidden_state:y,hidden_states:j=null,attentions:ae=null}){super(),this.last_hidden_state=y,this.hidden_states=j,this.attentions=ae}}class xe extends U{}class Ce extends xe{}class $e extends xe{async _call(y){return new gr(await super._call(y))}}class Ae extends xe{async _call(y){return new dt(await super._call(y))}}class Re extends xe{async _call(y){return new pr(await super._call(y))}}class Ne extends xe{async _call(y){return new Mr(await super._call(y))}}class A extends U{}class Y extends A{}class z extends A{async _call(y){return new gr(await super._call(y))}}class ee extends A{async _call(y){return new dt(await super._call(y))}}class oe extends A{async _call(y){return new pr(await super._call(y))}}class he extends U{}class Ee extends he{}class Fe extends U{}class Me extends Fe{}class ke extends Fe{async _call(y){return new gr(await super._call(y))}}class st extends Fe{async _call(y){return new dt(await super._call(y))}}class ut extends Fe{async _call(y){return new pr(await super._call(y))}}class _t extends Fe{async _call(y){return new Mr(await super._call(y))}}class gt extends U{}class er extends gt{}class It extends gt{async _call(y){return new gr(await super._call(y))}}class lr extends gt{async _call(y){return new dt(await super._call(y))}}class as extends gt{async _call(y){return new pr(await super._call(y))}}class fs extends gt{async _call(y){return new Mr(await super._call(y))}}class Cr extends U{}class $s extends Cr{}class ls extends Cr{async _call(y){return new gr(await super._call(y))}}class gs extends Cr{async _call(y){return new dt(await super._call(y))}}class nt extends Cr{async _call(y){return new pr(await super._call(y))}}class Ur extends Cr{async _call(y){return new Mr(await super._call(y))}}class Tt extends U{}class us extends Tt{}class Wr extends Tt{async _call(y){return new gr(await super._call(y))}}class Gr extends Tt{async _call(y){return new dt(await super._call(y))}}class yr extends Tt{async _call(y){return new pr(await super._call(y))}}class cs extends Tt{async _call(y){return new Mr(await super._call(y))}}class ur extends U{}class De extends ur{}class He extends ur{async _call(y){return new gr(await super._call(y))}}class Ye extends ur{async _call(y){return new dt(await super._call(y))}}class cr extends ur{async _call(y){return new pr(await super._call(y))}}class ks extends ur{async _call(y){return new Mr(await super._call(y))}}class Or extends U{}class Is extends Or{}class As extends Or{async _call(y){return new gr(await super._call(y))}}class ws extends Or{async _call(y){return new dt(await super._call(y))}}class Fs extends Or{async _call(y){return new pr(await super._call(y))}}class Sr extends Or{async _call(y){return new Mr(await super._call(y))}}class Kr extends U{}class _r extends Kr{}class Ms extends Kr{async _call(y){return new dt(await super._call(y))}}class bs extends Kr{async _call(y){return new pr(await super._call(y))}}class vr extends Kr{async _call(y){return new Mr(await super._call(y))}}class Os extends Kr{async _call(y){return new gr(await super._call(y))}}class ds extends U{}class $r extends ds{}class Ks extends ds{async _call(y){return new gr(await super._call(y))}}class ys extends ds{async _call(y){return new dt(await super._call(y))}}class xr extends ds{async _call(y){return new pr(await super._call(y))}}class Dr extends U{}class tr extends Dr{}class fr extends Dr{async _call(y){return new gr(await super._call(y))}}class vs extends Dr{async _call(y){return new dt(await super._call(y))}}class Hs extends Dr{async _call(y){return new Mr(await super._call(y))}}class Hr extends U{}class qs extends Hr{}class Xs extends Hr{async _call(y){return new gr(await super._call(y))}}class Qs extends Hr{async _call(y){return new dt(await super._call(y))}}class Js extends Hr{async _call(y){return new pr(await super._call(y))}}class Ys extends Hr{async _call(y){return new Mr(await super._call(y))}}class qr extends U{}class Zs extends qr{}class en extends qr{async _call(y){return new gr(await super._call(y))}}class tn extends qr{async _call(y){return new dt(await super._call(y))}}class rn extends qr{async _call(y){return new Mr(await super._call(y))}}class ps extends U{}class En extends ps{}class ue extends ps{async _call(y){return new dt(await super._call(y))}}class C extends ps{async _call(y){return new Mr(await super._call(y))}}class W extends ps{async _call(y){return new gr(await super._call(y))}}class Z extends U{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]}class se extends Z{}class _e extends Z{}class Se extends U{}class Ue extends Se{}class Ge extends Se{}class Ke extends U{}class Ve extends Ke{}class Mt extends Ke{}class lt extends U{}class zt extends lt{}class rr extends lt{}class Nt extends lt{async _call(y){return new dt(await super._call(y))}}class jt extends U{}class Ot extends jt{}class Ht extends jt{}class ms extends jt{async _call(y){return new dt(await super._call(y))}}class sr extends jt{}class Lr extends U{}class Dt extends Lr{}class nr extends Lr{}class dr extends U{}class zr extends dr{}class Br extends dr{}class qt extends U{}class Tr extends qt{}class or extends qt{async _call(y){return new gr(await super._call(y))}}class Gt extends qt{async _call(y){return new dt(await super._call(y))}}class Rt extends qt{async _call(y){return new pr(await super._call(y))}}class Xt extends qt{async _call(y){return new Mr(await super._call(y))}}class ir extends U{}class Ds extends ir{}class Pn extends ir{async _call(y){return new gr(await super._call(y))}}class Xo extends ir{async _call(y){return new dt(await super._call(y))}}class oo extends ir{async _call(y){return new pr(await super._call(y))}}class Qo extends ir{async _call(y){return new Mr(await super._call(y))}}class Ls extends U{}class Jo extends Ls{}class Yo extends Ls{async _call(y){return new gr(await super._call(y))}}class Zo extends Ls{async _call(y){return new dt(await super._call(y))}}class ei extends Ls{async _call(y){return new pr(await super._call(y))}}class ti extends Ls{async _call(y){return new Mr(await super._call(y))}}class io extends U{}class ri extends io{}class si extends io{}class ao extends U{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 ni extends ao{}class Cn extends ao{_prepare_generation_config(y,j){return super._prepare_generation_config(y,j,g.WhisperGenerationConfig)}_retrieve_init_tokens(y){const j=[y.decoder_start_token_id];let ae=y.language;const me=y.task;if(y.is_multilingual){ae||(console.warn("No language specified - defaulting to English (en)."),ae="en");const Ie=`<|${(0,S.whisper_language_to_code)(ae)}|>`;j.push(y.lang_to_id[Ie]),j.push(y.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!y.return_timestamps&&y.no_timestamps_token_id&&j.at(-1)!==y.no_timestamps_token_id?j.push(y.no_timestamps_token_id):y.return_timestamps&&j.at(-1)===y.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),j.pop()),j.filter(ge=>ge!=null)}async generate({inputs:y=null,generation_config:j=null,logits_processor:ae=null,stopping_criteria:me=null,...ge}){j=this._prepare_generation_config(j,ge);const Ie=ge.decoder_input_ids??this._retrieve_init_tokens(j);if(j.return_timestamps&&(ae??=new p.LogitsProcessorList,ae.push(new p.WhisperTimeStampLogitsProcessor(j,Ie))),j.begin_suppress_tokens&&(ae??=new p.LogitsProcessorList,ae.push(new p.SuppressTokensAtBeginLogitsProcessor(j.begin_suppress_tokens,Ie.length))),j.return_token_timestamps){if(!j.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.");j.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),j.output_attentions=!0,j.return_dict_in_generate=!0}const Le=await super.generate({inputs:y,generation_config:j,logits_processor:ae,decoder_input_ids:Ie,...ge});return j.return_token_timestamps&&(Le.token_timestamps=this._extract_token_timestamps(Le,j.alignment_heads,j.num_frames)),Le}_extract_token_timestamps(y,j,ae=null,me=.02){if(!y.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 ge=this.config.median_filter_width;ge===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),ge=7);const Ie=y.cross_attentions,Le=Array.from({length:this.config.decoder_layers},(it,tt)=>(0,d.cat)(Ie.map(vt=>vt[tt]),2)),Be=(0,d.stack)(j.map(([it,tt])=>{if(it>=Le.length)throw new Error(`Layer index ${it} is out of bounds for cross attentions (length ${Le.length}).`);return ae?Le[it].slice(null,tt,null,[0,ae]):Le[it].slice(null,tt)})).transpose(1,0,2,3),[qe,pt]=(0,d.std_mean)(Be,-2,0,!0),ft=Be.clone();for(let it=0;itvt[wt+1]-vt[wt]),Yt=(0,i.mergeArrays)([1],Vt).map(Qt=>!!Qt),Zt=[];for(let Qt=0;Qtot.findIndex(rt=>rt==ge)),Be=Le.every(ot=>ot===-1),qe=Le.every(ot=>ot!==-1);if(!Be&&!qe)throw new Error("Every input should contain either 0 or 1 image token.");if(Be)return{inputs_embeds:y,attention_mask:me};const pt=[],ft=[];for(let ot=0;otArray.from({length:y.dims[0]},Vt=>Array.from({length:y.dims[1]},Yt=>1))),$t=j?j.tolist():[],it=ae?ae.tolist():[];let tt=0,vt=0;for(let At=0;Atot[At][ar]==1),Zt=Vt.reduce((Bt,ar,Ns)=>(ar==Be&&Bt.push(Ns),Bt),[]).map(Bt=>Vt[Bt+1]),Qt=Zt.filter(Bt=>Bt==Ie).length,wt=Zt.filter(Bt=>Bt==Le).length;let Ut=[],mr=0,un=Qt,Er=wt;for(let Bt=0;BtQr>mr&&dn==Ie),Ns=Vt.findIndex((dn,Qr)=>Qr>mr&&dn==Le),cn=un>0&&ar!==-1?ar:Vt.length+1,Xn=Er>0&&Ns!==-1?Ns:Vt.length+1;let Di,gl,wl,Ml;cn0?(0,_.max)(Ut.at(-1))[0]+1:0;Ut.push(Array.from({length:3*yl},(dn,Qr)=>zh+Qr%yl));const vl=yl+zh,zi=tv*bl*Li,rv=Array.from({length:zi},(dn,Qr)=>vl+Math.floor(Qr/(bl*Li))),sv=Array.from({length:zi},(dn,Qr)=>vl+Math.floor(Qr/Li)%bl),nv=Array.from({length:zi},(dn,Qr)=>vl+Qr%Li);Ut.push([rv,sv,nv].flat()),mr=Di+zi}if(mr0?(0,_.max)(Ut.at(-1))[0]+1:0,ar=Vt.length-mr;Ut.push(Array.from({length:3*ar},(Ns,cn)=>Bt+cn%ar))}const Xr=Ut.reduce((Bt,ar)=>Bt+ar.length,0),Hn=new Array(Xr);let qn=0;for(let Bt=0;Bt<3;++Bt)for(let ar=0;arft[tt%ft.length]),$t=Array.from({length:ot[0]},(it,tt)=>(0,_.max)(ft.subarray(ot[1]*tt,ot[1]*(tt+1)))[0]+1n+BigInt(ot[1]));return[new d.Tensor("int64",rt,[3,...ot]),new d.Tensor("int64",$t,[$t.length,1])]}else{const[ft,ot]=y.dims,rt=BigInt64Array.from({length:3*ft*ot},($t,it)=>BigInt(Math.floor(it%ot/ft)));return[new d.Tensor("int64",rt,[3,...y.dims]),(0,d.zeros)([ft,1])]}}async encode_image({pixel_values:y,image_grid_thw:j}){return(await q(this.sessions.vision_encoder,{pixel_values:y,grid_thw:j})).image_features}_merge_input_ids_with_image_features(y){return N({image_token_id:this.config.image_token_id,...y})}prepare_inputs_for_generation(y,j,ae){if(j.attention_mask&&!j.position_ids)if(!j.past_key_values)[j.position_ids,j.rope_deltas]=this.get_rope_index(j.input_ids,j.image_grid_thw,j.video_grid_thw,j.attention_mask);else{j.pixel_values=null;const me=BigInt(Object.values(j.past_key_values)[0].dims.at(-2)),ge=j.rope_deltas.map(Ie=>me+Ie);j.position_ids=(0,d.stack)([ge,ge,ge],0)}return j}}class ya extends U{}class Dc extends ya{}class Lc extends ya{}class va extends U{}class zc extends va{}class Bc extends va{}class xa extends U{}class Rc extends xa{}class Nc extends xa{}class Ta extends U{}class jc extends Ta{}class Vc extends Ta{}class Ea extends U{}class Uc extends Ea{}class Wc extends Ea{}class Pa extends U{}class Gc extends Pa{}class Kc extends Pa{async _call(y){return new dt(await super._call(y))}}class Ca extends U{}class Hc extends Ca{}class qc extends Ca{async _call(y){return new dt(await super._call(y))}}class Xc extends U{}class Qc extends Xc{}class Sa extends U{}class Jc extends Sa{}class Yc extends Sa{async _call(y){return new dt(await super._call(y))}}class Zc extends U{}class ed extends Zc{}class $a extends U{}class td extends $a{}class rd extends $a{async _call(y){return new dt(await super._call(y))}}class sd extends U{}class nd extends sd{}class ka extends U{}class od extends ka{}class id extends ka{async _call(y){return new dt(await super._call(y))}}class ad extends U{}class ld extends ad{async _call(y){return new Dh(await super._call(y))}}class Ia extends U{}class ud extends Ia{}class cd extends Ia{async _call(y){return new dt(await super._call(y))}}class Aa extends U{}class dd extends Aa{}class pd extends Aa{async _call(y){return new dt(await super._call(y))}}class Fa extends U{}class md extends Fa{}class hd extends Fa{}class Oa extends U{}class _d extends Oa{}class fd extends Oa{}class Da extends U{}class gd extends Da{}class wd extends Da{async _call(y){return new dt(await super._call(y))}}class wi extends U{}class Md extends wi{}class bd extends wi{async _call(y){return new za(await super._call(y))}}class La extends wi{async _call(y){return new yd(await super._call(y))}}class za extends pe{constructor({logits:y,pred_boxes:j}){super(),this.logits=y,this.pred_boxes=j}}class yd extends pe{constructor({logits:y,pred_boxes:j,pred_masks:ae}){super(),this.logits=y,this.pred_boxes=j,this.pred_masks=ae}}class Ba extends U{}class vd extends Ba{}class xd extends Ba{async _call(y){return new Mi(await super._call(y))}}class Mi extends pe{constructor({logits:y,pred_boxes:j}){super(),this.logits=y,this.pred_boxes=j}}class Ra extends U{}class Td extends Ra{}class Ed extends Ra{async _call(y){return new Pd(await super._call(y))}}class Pd extends Mi{}class Na extends U{}class Cd extends Na{}class Sd extends Na{async _call(y){return new $d(await super._call(y))}}class $d extends Mi{}class ja extends U{}class kd extends ja{}class Id extends ja{async _call(y){return new Ad(await super._call(y))}}class Ad extends za{}class Va extends U{}class Fd extends Va{}class Od extends Va{async _call(y){return new dt(await super._call(y))}}class Ua extends U{}class Dd extends Ua{}class Ld extends Ua{async _call(y){return new dt(await super._call(y))}}class Wa extends U{}class zd extends Wa{}class Bd extends Wa{async _call(y){return new dt(await super._call(y))}}class bi extends U{}class Rd extends bi{}class Nd extends bi{async _call(y){return new dt(await super._call(y))}}class jd extends bi{}class Ga extends U{}class Vd extends Ga{}class Ud extends Ga{}class Ka extends U{}class Wd extends Ka{}class Gd extends Ka{}class Kd extends U{}class Hd extends Kd{}class yi extends U{}class qd extends yi{}class Xd extends yi{}class Qd extends yi{}class Jd extends U{}class Yd extends Jd{}class Zd extends U{}class ep extends Zd{}class tp extends U{}class rp extends tp{}class Ha extends U{}class sp extends Ha{}class np extends Ha{}class qa extends U{}class op extends qa{}class ip extends qa{}class ap extends U{}class lp extends ap{}class Xa extends U{}class up extends Xa{}class cp extends Xa{async _call(y){return new dt(await super._call(y))}}class Qa extends U{}class dp extends Qa{}class pp extends Qa{async _call(y){return new dt(await super._call(y))}}class Ja extends U{}class mp extends Ja{}class hp extends Ja{async _call(y){return new dt(await super._call(y))}}class Ya extends U{}class _p extends Ya{}class fp extends Ya{async _call(y){return new dt(await super._call(y))}}class gp extends U{}class wp extends gp{}class Za extends U{}class Mp extends Za{}class bp extends Za{async _call(y){return new yp(await super._call(y))}}class yp extends pe{constructor({logits:y,pred_boxes:j}){super(),this.logits=y,this.pred_boxes=j}}class vp extends U{}class xp extends vp{async get_image_embeddings({pixel_values:y}){return await te(this,{pixel_values:y})}async forward(y){if((!y.image_embeddings||!y.image_positional_embeddings)&&(y={...y,...await this.get_image_embeddings(y)}),!y.input_labels&&y.input_points){const ae=y.input_points.dims.slice(0,-1),me=ae.reduce((ge,Ie)=>ge*Ie,1);y.input_labels=new d.Tensor("int64",new BigInt64Array(me).fill(1n),ae)}const j={image_embeddings:y.image_embeddings,image_positional_embeddings:y.image_positional_embeddings};return y.input_points&&(j.input_points=y.input_points),y.input_labels&&(j.input_labels=y.input_labels),y.input_boxes&&(j.input_boxes=y.input_boxes),await q(this.sessions.prompt_encoder_mask_decoder,j)}async _call(y){return new Tp(await super._call(y))}}class Tp extends pe{constructor({iou_scores:y,pred_masks:j}){super(),this.iou_scores=y,this.pred_masks=j}}class el extends U{}class Ep extends el{}class Pp extends el{}class tl extends U{}class Cp extends tl{}class Sp extends tl{}class Rs extends U{}class $p extends Rs{}class kp extends Rs{async _call(y){return new ln(await super._call(y))}}class Ip extends Rs{async _call(y){return new dt(await super._call(y))}}class Ap extends Rs{async _call(y){return new pr(await super._call(y))}}class rl extends U{}class Fp extends rl{}class Op extends rl{async _call(y){return new pr(await super._call(y))}}class Dp extends U{}class Lp extends Dp{}class vi extends U{}class zp extends vi{}class Bp extends vi{async _call(y){return new ln(await super._call(y))}}class Rp extends vi{async _call(y){return new dt(await super._call(y))}}class $o extends U{}class Np extends $o{}class jp extends $o{async _call(y){return new ln(await super._call(y))}}class Vp extends $o{async _call(y){return new dt(await super._call(y))}}class Up extends $o{async _call(y){return new pr(await super._call(y))}}class xi extends U{}class Wp extends xi{}class Gp extends xi{async _call(y){return new ln(await super._call(y))}}class Kp extends xi{async _call(y){return new dt(await super._call(y))}}class l0 extends U{}class Hp extends Rs{}class qp extends Rs{async _call(y){return new ln(await super._call(y))}}class Xp extends Rs{async _call(y){return new dt(await super._call(y))}}class Gn extends U{}class Qp extends Gn{}class Jp extends Gn{async _call(y){return new ln(await super._call(y))}}class Yp extends Gn{async _call(y){return new dt(await super._call(y))}}class Zp extends Gn{async _call(y){return new Oh(await super._call(y))}}class em extends Gn{async _call(y){return new pr(await super._call(y))}}class tm extends U{}class rm extends tm{}class Ti extends U{}class u0 extends Ti{}class sm extends Ti{}class nm extends Ti{async generate_speech(y,j,{threshold:ae=.5,minlenratio:me=0,maxlenratio:ge=20,vocoder:Ie=null}={}){const Le={input_ids:y},{encoder_outputs:Be,encoder_attention_mask:qe}=await te(this,Le),pt=Be.dims[1]/this.config.reduction_factor,ft=Math.floor(pt*ge),ot=Math.floor(pt*me),rt=this.config.num_mel_bins;let $t=[],it=null,tt=null,vt=0;for(;;){++vt;const Yt=X(!!tt);let Zt;tt?Zt=tt.output_sequence_out:Zt=new d.Tensor("float32",new Float32Array(rt),[1,1,rt]);let Qt={use_cache_branch:Yt,output_sequence:Zt,encoder_attention_mask:qe,speaker_embeddings:j,encoder_hidden_states:Be};this.addPastKeyValues(Qt,it),tt=await q(this.sessions.decoder_model_merged,Qt),it=this.getPastKeyValues(tt,it);const{prob:wt,spectrum:Ut}=tt;if($t.push(Ut),vt>=ot&&(Array.from(wt.data).filter(mr=>mr>=ae).length>0||vt>=ft))break}const At=(0,d.cat)($t),{waveform:Vt}=await q(Ie.sessions.model,{spectrogram:At});return{spectrogram:At,waveform:Vt}}}class om extends U{main_input_name="spectrogram"}class im extends U{}class am extends im{}class sl extends U{}class lm extends sl{}class um extends sl{}class nl extends U{}class cm extends nl{}class dm extends nl{}class ol extends U{}class pm extends ol{}class mm extends ol{}class Ei extends U{}class hm extends Ei{}class _m extends Ei{static async from_pretrained(y,j={}){return super.from_pretrained(y,{...j,model_file_name:j.model_file_name??"text_model"})}}class fm extends Ei{static async from_pretrained(y,j={}){return super.from_pretrained(y,{...j,model_file_name:j.model_file_name??"audio_model"})}}class gm extends U{}class il extends gm{async _call(y){return new Lh(await super._call(y))}}class Pi extends U{}class c0 extends Pi{}class wm extends Pi{}class Mm extends Pi{}class al extends U{}class bm extends al{}class ym extends al{}class ll extends U{}class vm extends ll{}class xm extends ll{async _call(y){return new dt(await super._call(y))}}class ul extends U{}class d0 extends ul{}class p0 extends ul{}class cl extends U{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(y){const[j,ae]=y.dims,me=this.config.decoder.num_codebooks,ge=ae-me;let Ie=0;for(let qe=0;qe0&&ot<=ge&&(y.data[Ie++]=y.data[qe])}const Le=Math.floor(j/me),Be=Ie/(Le*me);return new d.Tensor(y.type,y.data.slice(0,Ie),[Le,me,Be])}prepare_inputs_for_generation(y,j,ae){let me=structuredClone(y);for(let Ie=0;Ie=Le&&(me[Ie][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,j,ae)}async generate(y){const j=await super.generate(y),ae=this._apply_and_filter_by_delay_pattern_mask(j).unsqueeze_(0),{audio_values:me}=await q(this.sessions.encodec_decode,{audio_codes:ae});return me}}class Ci extends U{}class Tm extends Ci{}class Em extends Ci{async _call(y){return new dt(await super._call(y))}}class Pm extends Ci{}class Si extends U{}class Cm extends Si{}class Sm extends Si{async _call(y){return new dt(await super._call(y))}}class $m extends Si{}class $i extends U{}class km extends $i{}class Im extends $i{async _call(y){return new dt(await super._call(y))}}class Am extends $i{}class ki extends U{}class Fm extends ki{}class Om extends ki{async _call(y){return new dt(await super._call(y))}}class Dm extends ki{}class Lm extends U{}class zm extends Lm{}class Bm extends U{}class Rm extends Bm{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...y){super(...y),this._generation_mode="text"}async forward(y){const j=this._generation_mode??"text";let ae;if(j==="text"||!y.past_key_values){const Be=this.sessions.prepare_inputs_embeds,qe=(0,i.pick)(y,Be.inputNames);ae=await q(Be,qe)}else{const Be=this.sessions.gen_img_embeds,qe=(0,i.pick)({image_ids:y.input_ids},Be.inputNames);ae=await q(Be,qe)}const me={...y,...ae},ge=await ce(this,me),Ie=this.sessions[j==="text"?"lm_head":"gen_head"];if(!Ie)throw new Error(`Unable to find "${Ie}" generation head`);const Le=await q(Ie,(0,i.pick)(ge,Ie.inputNames));return{...ae,...ge,...Le}}async generate(y){return this._generation_mode="text",super.generate(y)}async generate_images(y){this._generation_mode="image";const j=(y.inputs??y[this.main_input_name]).dims[1],me=(await super.generate(y)).slice(null,[j,null]),ge=this.sessions.image_decode,{decoded_image:Ie}=await q(ge,{generated_tokens:me}),Le=Ie.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Be=[];for(const qe of Le){const pt=f.RawImage.fromTensor(qe);Be.push(pt)}return Be}}class Nm extends pe{constructor({char_logits:y,bpe_logits:j,wp_logits:ae}){super(),this.char_logits=y,this.bpe_logits=j,this.wp_logits=ae}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class jm extends U{}class Vm extends jm{async _call(y){return new Nm(await super._call(y))}}class dl extends U{}class Um extends dl{}class Wm extends dl{}class pl extends U{}class Gm extends pl{}class Km extends pl{}class Hm extends U{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]}class qm extends Hm{_merge_input_ids_with_audio_features(y){const j=y.audio_features.dims.at(-1),ae=y.audio_features.view(-1,j);return F({audio_token_id:this.config.ignore_index,...y,audio_features:ae})}}class Ii extends U{main_input_name="input_values";forward_params=["input_values"]}class Xm extends pe{constructor({audio_codes:y}){super(),this.audio_codes=y}}class Qm extends pe{constructor({audio_values:y}){super(),this.audio_values=y}}class Jm extends Ii{async encode(y){return new Xm(await q(this.sessions.encoder_model,y))}async decode(y){return new Qm(await q(this.sessions.decoder_model,y))}}class Ym extends Ii{static async from_pretrained(y,j={}){return super.from_pretrained(y,{...j,model_file_name:j.model_file_name??"encoder_model"})}}class Zm extends Ii{static async from_pretrained(y,j={}){return super.from_pretrained(y,{...j,model_file_name:j.model_file_name??"decoder_model"})}}class Ai extends U{main_input_name="input_values";forward_params=["input_values"]}class eh extends pe{constructor({audio_codes:y}){super(),this.audio_codes=y}}class th extends pe{constructor({audio_values:y}){super(),this.audio_values=y}}class rh extends Ai{async encode(y){return new eh(await q(this.sessions.encoder_model,y))}async decode(y){return new th(await q(this.sessions.decoder_model,y))}}class sh extends Ai{static async from_pretrained(y,j={}){return super.from_pretrained(y,{...j,model_file_name:j.model_file_name??"encoder_model"})}}class nh extends Ai{static async from_pretrained(y,j={}){return super.from_pretrained(y,{...j,model_file_name:j.model_file_name??"decoder_model"})}}class Fi extends U{main_input_name="input_values";forward_params=["input_values"]}class oh extends Fi{async encode(y){return await q(this.sessions.encoder_model,y)}async decode(y){return await q(this.sessions.decoder_model,y)}}class ih extends Fi{static async from_pretrained(y,j={}){return super.from_pretrained(y,{...j,model_file_name:j.model_file_name??"encoder_model"})}}class ah extends Fi{static async from_pretrained(y,j={}){return super.from_pretrained(y,{...j,model_file_name:j.model_file_name??"decoder_model"})}}class St{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static async from_pretrained(y,{progress_callback:j=null,config:ae=null,cache_dir:me=null,local_files_only:ge=!1,revision:Ie="main",model_file_name:Le=null,subfolder:Be="onnx",device:qe=null,dtype:pt=null,use_external_data_format:ft=null,session_options:ot={}}={}){const rt={progress_callback:j,config:ae,cache_dir:me,local_files_only:ge,revision:Ie,model_file_name:Le,subfolder:Be,device:qe,dtype:pt,use_external_data_format:ft,session_options:ot};if(rt.config=await s.AutoConfig.from_pretrained(y,rt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const $t=rt.config.model_type;for(const it of this.MODEL_CLASS_MAPPINGS){let tt=it.get($t);if(!tt){for(const vt of it.values())if(vt[0]===$t){tt=vt;break}if(!tt)continue}return await tt[1].from_pretrained(y,rt)}if(this.BASE_IF_FAIL)return Fh.has($t)||console.warn(`Unknown model class "${$t}", attempting to construct from base class.`),await U.from_pretrained(y,rt);throw Error(`Unsupported model type: ${$t}`)}}const m0=new Map([["bert",["BertModel",Ce]],["modernbert",["ModernBertModel",Y]],["nomic_bert",["NomicBertModel",Ee]],["roformer",["RoFormerModel",Me]],["electra",["ElectraModel",$s]],["esm",["EsmModel",$r]],["convbert",["ConvBertModel",er]],["camembert",["CamembertModel",us]],["deberta",["DebertaModel",De]],["deberta-v2",["DebertaV2Model",Is]],["mpnet",["MPNetModel",qs]],["albert",["AlbertModel",En]],["distilbert",["DistilBertModel",_r]],["roberta",["RobertaModel",Tr]],["xlm",["XLMModel",Ds]],["xlm-roberta",["XLMRobertaModel",Jo]],["clap",["ClapModel",hm]],["clip",["CLIPModel",di]],["clipseg",["CLIPSegModel",Mo]],["chinese_clip",["ChineseCLIPModel",Fn]],["siglip",["SiglipModel",_o]],["jina_clip",["JinaCLIPModel",fo]],["mobilebert",["MobileBertModel",tr]],["squeezebert",["SqueezeBertModel",Zs]],["wav2vec2",["Wav2Vec2Model",$p]],["wav2vec2-bert",["Wav2Vec2BertModel",Wp]],["unispeech",["UniSpeechModel",zp]],["unispeech-sat",["UniSpeechSatModel",Np]],["hubert",["HubertModel",Hp]],["wavlm",["WavLMModel",Qp]],["audio-spectrogram-transformer",["ASTModel",ri]],["vits",["VitsModel",il]],["pyannote",["PyAnnoteModel",Fp]],["wespeaker-resnet",["WeSpeakerResNetModel",Lp]],["detr",["DetrModel",Md]],["rt_detr",["RTDetrModel",vd]],["rt_detr_v2",["RTDetrV2Model",Td]],["rf_detr",["RFDetrModel",Cd]],["table-transformer",["TableTransformerModel",kd]],["vit",["ViTModel",Gc]],["ijepa",["IJepaModel",Hc]],["pvt",["PvtModel",Jc]],["vit_msn",["ViTMSNModel",td]],["vit_mae",["ViTMAEModel",ed]],["groupvit",["GroupViTModel",nd]],["fastvit",["FastViTModel",od]],["mobilevit",["MobileViTModel",ud]],["mobilevitv2",["MobileViTV2Model",dd]],["owlvit",["OwlViTModel",md]],["owlv2",["Owlv2Model",_d]],["beit",["BeitModel",gd]],["deit",["DeiTModel",Fd]],["hiera",["HieraModel",Dd]],["convnext",["ConvNextModel",up]],["convnextv2",["ConvNextV2Model",dp]],["dinov2",["Dinov2Model",mp]],["dinov2_with_registers",["Dinov2WithRegistersModel",_p]],["resnet",["ResNetModel",zd]],["swin",["SwinModel",Rd]],["swin2sr",["Swin2SRModel",Vd]],["donut-swin",["DonutSwinModel",lp]],["yolos",["YolosModel",Mp]],["dpt",["DPTModel",Wd]],["glpn",["GLPNModel",op]],["hifigan",["SpeechT5HifiGan",om]],["efficientnet",["EfficientNetModel",vm]],["decision_transformer",["DecisionTransformerModel",zm]],["patchtst",["PatchTSTForPrediction",Um]],["patchtsmixer",["PatchTSMixerForPrediction",Gm]],["mobilenet_v1",["MobileNetV1Model",Tm]],["mobilenet_v2",["MobileNetV2Model",Cm]],["mobilenet_v3",["MobileNetV3Model",km]],["mobilenet_v4",["MobileNetV4Model",Fm]],["maskformer",["MaskFormerModel",sp]],["mgp-str",["MgpstrForSceneTextRecognition",Vm]],["style_text_to_speech_2",["StyleTextToSpeech2Model",rm]]]),h0=new Map([["t5",["T5Model",se]],["longt5",["LongT5Model",Ue]],["mt5",["MT5Model",Ve]],["bart",["BartModel",zt]],["mbart",["MBartModel",Ot]],["marian",["MarianModel",Ep]],["whisper",["WhisperModel",ni]],["m2m_100",["M2M100Model",Cp]],["blenderbot",["BlenderbotModel",Dt]],["blenderbot-small",["BlenderbotSmallModel",zr]]]),_0=new Map([["mimi",["MimiModel",Jm]],["dac",["DacModel",rh]],["snac",["SnacModel",oh]]]),f0=new Map([["bloom",["BloomModel",Rc]],["jais",["JAISModel",fi]],["gpt2",["GPT2Model",bo]],["gptj",["GPTJModel",xo]],["gpt_bigcode",["GPTBigCodeModel",To]],["gpt_neo",["GPTNeoModel",an]],["gpt_neox",["GPTNeoXModel",zn]],["codegen",["CodeGenModel",jn]],["llama",["LlamaModel",Po]],["exaone",["ExaoneModel",ie]],["olmo",["OlmoModel",bt]],["olmo2",["Olmo2Model",Es]],["mobilellm",["MobileLLMModel",We]],["granite",["GraniteModel",Mc]],["cohere",["CohereModel",yc]],["gemma",["GemmaModel",xc]],["gemma2",["Gemma2Model",Ec]],["gemma3_text",["Gemma3Model",Cc]],["helium",["HeliumModel",So]],["glm",["GlmModel",k]],["openelm",["OpenELMModel",$c]],["qwen2",["Qwen2Model",Ic]],["phi",["PhiModel",Dc]],["phi3",["Phi3Model",zc]],["mpt",["MptModel",jc]],["opt",["OPTModel",Uc]],["mistral",["MistralModel",lm]],["starcoder2",["Starcoder2Model",cm]],["falcon",["FalconModel",pm]],["stablelm",["StableLmModel",bm]]]),ml=new Map([["speecht5",["SpeechT5ForSpeechToText",sm]],["whisper",["WhisperForConditionalGeneration",Cn]],["lite-whisper",["LiteWhisperForConditionalGeneration",lo]],["moonshine",["MoonshineForConditionalGeneration",oi]]]),lh=new Map([["speecht5",["SpeechT5ForTextToSpeech",nm]]]),uh=new Map([["vits",["VitsModel",il]],["musicgen",["MusicgenForConditionalGeneration",cl]]]),ch=new Map([["bert",["BertForSequenceClassification",Ae]],["modernbert",["ModernBertForSequenceClassification",ee]],["roformer",["RoFormerForSequenceClassification",st]],["electra",["ElectraForSequenceClassification",gs]],["esm",["EsmForSequenceClassification",ys]],["convbert",["ConvBertForSequenceClassification",lr]],["camembert",["CamembertForSequenceClassification",Gr]],["deberta",["DebertaForSequenceClassification",Ye]],["deberta-v2",["DebertaV2ForSequenceClassification",ws]],["mpnet",["MPNetForSequenceClassification",Qs]],["albert",["AlbertForSequenceClassification",ue]],["distilbert",["DistilBertForSequenceClassification",Ms]],["roberta",["RobertaForSequenceClassification",Gt]],["xlm",["XLMForSequenceClassification",Xo]],["xlm-roberta",["XLMRobertaForSequenceClassification",Zo]],["bart",["BartForSequenceClassification",Nt]],["mbart",["MBartForSequenceClassification",ms]],["mobilebert",["MobileBertForSequenceClassification",vs]],["squeezebert",["SqueezeBertForSequenceClassification",tn]]]),dh=new Map([["bert",["BertForTokenClassification",Re]],["modernbert",["ModernBertForTokenClassification",oe]],["roformer",["RoFormerForTokenClassification",ut]],["electra",["ElectraForTokenClassification",nt]],["esm",["EsmForTokenClassification",xr]],["convbert",["ConvBertForTokenClassification",as]],["camembert",["CamembertForTokenClassification",yr]],["deberta",["DebertaForTokenClassification",cr]],["deberta-v2",["DebertaV2ForTokenClassification",Fs]],["mpnet",["MPNetForTokenClassification",Js]],["distilbert",["DistilBertForTokenClassification",bs]],["roberta",["RobertaForTokenClassification",Rt]],["xlm",["XLMForTokenClassification",oo]],["xlm-roberta",["XLMRobertaForTokenClassification",ei]]]),hl=new Map([["t5",["T5ForConditionalGeneration",_e]],["longt5",["LongT5ForConditionalGeneration",Ge]],["mt5",["MT5ForConditionalGeneration",Mt]],["bart",["BartForConditionalGeneration",rr]],["mbart",["MBartForConditionalGeneration",Ht]],["marian",["MarianMTModel",Pp]],["m2m_100",["M2M100ForConditionalGeneration",Sp]],["blenderbot",["BlenderbotForConditionalGeneration",nr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Br]]]),_l=new Map([["bloom",["BloomForCausalLM",Nc]],["gpt2",["GPT2LMHeadModel",on]],["jais",["JAISLMHeadModel",yo]],["gptj",["GPTJForCausalLM",Rn]],["gpt_bigcode",["GPTBigCodeForCausalLM",Eo]],["gpt_neo",["GPTNeoForCausalLM",kr]],["gpt_neox",["GPTNeoXForCausalLM",vo]],["codegen",["CodeGenForCausalLM",Vn]],["llama",["LlamaForCausalLM",Co]],["exaone",["ExaoneForCausalLM",Te]],["olmo",["OlmoForCausalLM",Ct]],["olmo2",["Olmo2ForCausalLM",gi]],["mobilellm",["MobileLLMForCausalLM",Xe]],["granite",["GraniteForCausalLM",bc]],["cohere",["CohereForCausalLM",vc]],["gemma",["GemmaForCausalLM",Tc]],["gemma2",["Gemma2ForCausalLM",Pc]],["gemma3_text",["Gemma3ForCausalLM",Sc]],["helium",["HeliumForCausalLM",m]],["glm",["GlmForCausalLM",D]],["openelm",["OpenELMForCausalLM",kc]],["qwen2",["Qwen2ForCausalLM",Ac]],["phi",["PhiForCausalLM",Lc]],["phi3",["Phi3ForCausalLM",Bc]],["mpt",["MptForCausalLM",Vc]],["opt",["OPTForCausalLM",Wc]],["mbart",["MBartForCausalLM",sr]],["mistral",["MistralForCausalLM",um]],["starcoder2",["Starcoder2ForCausalLM",dm]],["falcon",["FalconForCausalLM",mm]],["trocr",["TrOCRForCausalLM",am]],["stablelm",["StableLmForCausalLM",ym]],["phi3_v",["Phi3VForCausalLM",ho]]]),g0=new Map([["multi_modality",["MultiModalityCausalLM",Rm]]]),ph=new Map([["bert",["BertForMaskedLM",$e]],["modernbert",["ModernBertForMaskedLM",z]],["roformer",["RoFormerForMaskedLM",ke]],["electra",["ElectraForMaskedLM",ls]],["esm",["EsmForMaskedLM",Ks]],["convbert",["ConvBertForMaskedLM",It]],["camembert",["CamembertForMaskedLM",Wr]],["deberta",["DebertaForMaskedLM",He]],["deberta-v2",["DebertaV2ForMaskedLM",As]],["mpnet",["MPNetForMaskedLM",Xs]],["albert",["AlbertForMaskedLM",W]],["distilbert",["DistilBertForMaskedLM",Os]],["roberta",["RobertaForMaskedLM",or]],["xlm",["XLMWithLMHeadModel",Pn]],["xlm-roberta",["XLMRobertaForMaskedLM",Yo]],["mobilebert",["MobileBertForMaskedLM",fr]],["squeezebert",["SqueezeBertForMaskedLM",en]]]),mh=new Map([["bert",["BertForQuestionAnswering",Ne]],["roformer",["RoFormerForQuestionAnswering",_t]],["electra",["ElectraForQuestionAnswering",Ur]],["convbert",["ConvBertForQuestionAnswering",fs]],["camembert",["CamembertForQuestionAnswering",cs]],["deberta",["DebertaForQuestionAnswering",ks]],["deberta-v2",["DebertaV2ForQuestionAnswering",Sr]],["mpnet",["MPNetForQuestionAnswering",Ys]],["albert",["AlbertForQuestionAnswering",C]],["distilbert",["DistilBertForQuestionAnswering",vr]],["roberta",["RobertaForQuestionAnswering",Xt]],["xlm",["XLMForQuestionAnswering",Qo]],["xlm-roberta",["XLMRobertaForQuestionAnswering",ti]],["mobilebert",["MobileBertForQuestionAnswering",Hs]],["squeezebert",["SqueezeBertForQuestionAnswering",rn]]]),fl=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",$n]],["idefics3",["Idefics3ForConditionalGeneration",In]],["smolvlm",["SmolVLMForConditionalGeneration",mo]]]),hh=new Map([["llava",["LlavaForConditionalGeneration",hs]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",ii]],["moondream1",["Moondream1ForConditionalGeneration",co]],["florence2",["Florence2ForConditionalGeneration",li]],["qwen2-vl",["Qwen2VLForConditionalGeneration",Oc]],["idefics3",["Idefics3ForConditionalGeneration",In]],["smolvlm",["SmolVLMForConditionalGeneration",mo]],["paligemma",["PaliGemmaForConditionalGeneration",kn]]]),_h=new Map([["ultravox",["UltravoxModel",qm]]]),w0=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",$n]]]),fh=new Map([["vit",["ViTForImageClassification",Kc]],["ijepa",["IJepaForImageClassification",qc]],["pvt",["PvtForImageClassification",Yc]],["vit_msn",["ViTMSNForImageClassification",rd]],["fastvit",["FastViTForImageClassification",id]],["mobilevit",["MobileViTForImageClassification",cd]],["mobilevitv2",["MobileViTV2ForImageClassification",pd]],["beit",["BeitForImageClassification",wd]],["deit",["DeiTForImageClassification",Od]],["hiera",["HieraForImageClassification",Ld]],["convnext",["ConvNextForImageClassification",cp]],["convnextv2",["ConvNextV2ForImageClassification",pp]],["dinov2",["Dinov2ForImageClassification",hp]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",fp]],["resnet",["ResNetForImageClassification",Bd]],["swin",["SwinForImageClassification",Nd]],["segformer",["SegformerForImageClassification",wm]],["efficientnet",["EfficientNetForImageClassification",xm]],["mobilenet_v1",["MobileNetV1ForImageClassification",Em]],["mobilenet_v2",["MobileNetV2ForImageClassification",Sm]],["mobilenet_v3",["MobileNetV3ForImageClassification",Im]],["mobilenet_v4",["MobileNetV4ForImageClassification",Om]]]),gh=new Map([["detr",["DetrForObjectDetection",bd]],["rt_detr",["RTDetrForObjectDetection",xd]],["rt_detr_v2",["RTDetrV2ForObjectDetection",Ed]],["rf_detr",["RFDetrForObjectDetection",Sd]],["table-transformer",["TableTransformerForObjectDetection",Id]],["yolos",["YolosForObjectDetection",bp]]]),wh=new Map([["owlvit",["OwlViTForObjectDetection",hd]],["owlv2",["Owlv2ForObjectDetection",fd]],["grounding-dino",["GroundingDinoForObjectDetection",wp]]]),Kn=new Map([["detr",["DetrForSegmentation",La]],["clipseg",["CLIPSegForImageSegmentation",_i]]]),Mh=new Map([["segformer",["SegformerForSemanticSegmentation",Mm]],["sapiens",["SapiensForSemanticSegmentation",qd]],["swin",["SwinForSemanticSegmentation",jd]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",Pm]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",$m]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Am]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Dm]]]),bh=new Map([["detr",["DetrForSegmentation",La]],["maskformer",["MaskFormerForInstanceSegmentation",np]]]),yh=new Map([["sam",["SamModel",xp]]]),vh=new Map([["wav2vec2",["Wav2Vec2ForCTC",kp]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Gp]],["unispeech",["UniSpeechForCTC",Bp]],["unispeech-sat",["UniSpeechSatForCTC",jp]],["wavlm",["WavLMForCTC",Jp]],["hubert",["HubertForCTC",qp]]]),xh=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Ip]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Kp]],["unispeech",["UniSpeechForSequenceClassification",Rp]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Vp]],["wavlm",["WavLMForSequenceClassification",Yp]],["hubert",["HubertForSequenceClassification",Xp]],["audio-spectrogram-transformer",["ASTForAudioClassification",si]]]),Th=new Map([["wavlm",["WavLMForXVector",Zp]]]),Eh=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Up]],["wavlm",["WavLMForAudioFrameClassification",em]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Ap]],["pyannote",["PyAnnoteForAudioFrameClassification",Op]]]),Ph=new Map([["vitmatte",["VitMatteForImageMatting",ld]]]),M0=new Map([["patchtst",["PatchTSTForPrediction",Wm]],["patchtsmixer",["PatchTSMixerForPrediction",Km]]]),Ch=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Ud]]]),Sh=new Map([["dpt",["DPTForDepthEstimation",Gd]],["depth_anything",["DepthAnythingForDepthEstimation",Hd]],["glpn",["GLPNForDepthEstimation",ip]],["sapiens",["SapiensForDepthEstimation",Xd]],["depth_pro",["DepthProForDepthEstimation",Yd]],["metric3d",["Metric3DForDepthEstimation",ep]],["metric3dv2",["Metric3Dv2ForDepthEstimation",rp]]]),$h=new Map([["sapiens",["SapiensForNormalEstimation",Qd]]]),kh=new Map([["vitpose",["VitPoseForPoseEstimation",Qc]]]),Ih=new Map([["clip",["CLIPVisionModelWithProjection",sn]],["siglip",["SiglipVisionModel",hi]],["jina_clip",["JinaCLIPVisionModel",wo]]]),Ah=[[m0,E.EncoderOnly],[h0,E.EncoderDecoder],[f0,E.DecoderOnly],[_0,E.AutoEncoder],[ch,E.EncoderOnly],[dh,E.EncoderOnly],[hl,E.Seq2Seq],[ml,E.Seq2Seq],[_l,E.DecoderOnly],[g0,E.MultiModality],[ph,E.EncoderOnly],[mh,E.EncoderOnly],[fl,E.Vision2Seq],[hh,E.ImageTextToText],[_h,E.AudioTextToText],[fh,E.EncoderOnly],[Kn,E.EncoderOnly],[bh,E.EncoderOnly],[Mh,E.EncoderOnly],[Ph,E.EncoderOnly],[M0,E.EncoderOnly],[Ch,E.EncoderOnly],[Sh,E.EncoderOnly],[$h,E.EncoderOnly],[kh,E.EncoderOnly],[gh,E.EncoderOnly],[wh,E.EncoderOnly],[yh,E.MaskGeneration],[vh,E.EncoderOnly],[xh,E.EncoderOnly],[lh,E.Seq2Seq],[uh,E.EncoderOnly],[Th,E.EncoderOnly],[Eh,E.EncoderOnly],[Ih,E.EncoderOnly]];for(const[b,y]of Ah)for(const[j,ae]of b.values())x.set(j,y),v.set(ae,j),w.set(j,ae);const b0=[["MusicgenForConditionalGeneration",cl,E.Musicgen],["Phi3VForCausalLM",ho,E.Phi3V],["CLIPTextModelWithProjection",pi,E.EncoderOnly],["SiglipTextModel",mi,E.EncoderOnly],["JinaCLIPTextModel",go,E.EncoderOnly],["ClapTextModelWithProjection",_m,E.EncoderOnly],["ClapAudioModelWithProjection",fm,E.EncoderOnly],["DacEncoderModel",sh,E.EncoderOnly],["DacDecoderModel",nh,E.EncoderOnly],["MimiEncoderModel",Ym,E.EncoderOnly],["MimiDecoderModel",Zm,E.EncoderOnly],["SnacEncoderModel",ih,E.EncoderOnly],["SnacDecoderModel",ah,E.EncoderOnly]];for(const[b,y,j]of b0)x.set(b,j),v.set(y,b),w.set(b,y);const Fh=new Map([["modnet",Kn],["birefnet",Kn],["isnet",Kn],["ben",Kn]]);for(const[b,y]of Fh.entries())y.set(b,["PreTrainedModel",U]),x.set(b,E.EncoderOnly),v.set(U,b),w.set(b,U);class y0 extends St{static MODEL_CLASS_MAPPINGS=Ah.map(y=>y[0]);static BASE_IF_FAIL=!0}class v0 extends St{static MODEL_CLASS_MAPPINGS=[ch]}class x0 extends St{static MODEL_CLASS_MAPPINGS=[dh]}class T0 extends St{static MODEL_CLASS_MAPPINGS=[hl]}class E0 extends St{static MODEL_CLASS_MAPPINGS=[ml]}class P0 extends St{static MODEL_CLASS_MAPPINGS=[lh]}class C0 extends St{static MODEL_CLASS_MAPPINGS=[uh]}class S0 extends St{static MODEL_CLASS_MAPPINGS=[_l]}class $0 extends St{static MODEL_CLASS_MAPPINGS=[ph]}class k0 extends St{static MODEL_CLASS_MAPPINGS=[mh]}class I0 extends St{static MODEL_CLASS_MAPPINGS=[fl]}class A0 extends St{static MODEL_CLASS_MAPPINGS=[fh]}class F0 extends St{static MODEL_CLASS_MAPPINGS=[Kn]}class O0 extends St{static MODEL_CLASS_MAPPINGS=[Mh]}class D0 extends St{static MODEL_CLASS_MAPPINGS=[bh]}class L0 extends St{static MODEL_CLASS_MAPPINGS=[gh]}class z0 extends St{static MODEL_CLASS_MAPPINGS=[wh]}class B0 extends St{static MODEL_CLASS_MAPPINGS=[yh]}class R0 extends St{static MODEL_CLASS_MAPPINGS=[vh]}class N0 extends St{static MODEL_CLASS_MAPPINGS=[xh]}class j0 extends St{static MODEL_CLASS_MAPPINGS=[Th]}class V0 extends St{static MODEL_CLASS_MAPPINGS=[Eh]}class U0 extends St{static MODEL_CLASS_MAPPINGS=[w0]}class W0 extends St{static MODEL_CLASS_MAPPINGS=[Ph]}class G0 extends St{static MODEL_CLASS_MAPPINGS=[Ch]}class K0 extends St{static MODEL_CLASS_MAPPINGS=[Sh]}class H0 extends St{static MODEL_CLASS_MAPPINGS=[$h]}class q0 extends St{static MODEL_CLASS_MAPPINGS=[kh]}class X0 extends St{static MODEL_CLASS_MAPPINGS=[Ih]}class Q0 extends St{static MODEL_CLASS_MAPPINGS=[hh]}class J0 extends St{static MODEL_CLASS_MAPPINGS=[_h]}class Y0 extends pe{constructor({logits:y,past_key_values:j,encoder_outputs:ae,decoder_attentions:me=null,cross_attentions:ge=null}){super(),this.logits=y,this.past_key_values=j,this.encoder_outputs=ae,this.decoder_attentions=me,this.cross_attentions=ge}}class dt extends pe{constructor({logits:y,...j}){super(),this.logits=y;const ae=Object.values(j);ae.length>0&&(this.attentions=ae)}}class Oh extends pe{constructor({logits:y,embeddings:j}){super(),this.logits=y,this.embeddings=j}}class pr extends pe{constructor({logits:y}){super(),this.logits=y}}class gr extends pe{constructor({logits:y}){super(),this.logits=y}}class Mr extends pe{constructor({start_logits:y,end_logits:j}){super(),this.start_logits=y,this.end_logits=j}}class ln extends pe{constructor({logits:y}){super(),this.logits=y}}class Z0 extends pe{constructor({logits:y,past_key_values:j}){super(),this.logits=y,this.past_key_values=j}}class Dh extends pe{constructor({alphas:y}){super(),this.alphas=y}}class Lh extends pe{constructor({waveform:y,spectrogram:j}){super(),this.waveform=y,this.spectrogram=j}}},"./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(i){super(i);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(i,l){return(0,n.spectrogram)(i,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(i){(0,s.validate_audio_inputs)(i,"ASTFeatureExtractor");const l=await this._extract_fbank_features(i,this.config.max_length);if(this.config.do_normalize){const c=this.std*2,p=l.data;for(let u=0;u{t.r(r),t.d(r,{AutoFeatureExtractor:()=>a});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 a{static async from_pretrained(l,c={}){const p=await(0,n.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,c),u=p.feature_extractor_type,d=o[u];if(!d)throw new Error(`Unknown feature_extractor_type: '${u}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new d(p)}}},"./src/models/auto/image_processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoImageProcessor:()=>i});var s=t("./src/utils/constants.js"),n=t("./src/utils/hub.js"),o=t("./src/base/image_processors_utils.js"),a=t("./src/models/image_processors.js");class i{static async from_pretrained(c,p={}){const u=await(0,n.getModelJSON)(c,s.IMAGE_PROCESSOR_NAME,!0,p),d=u.image_processor_type??u.feature_extractor_type;let f=a[d];return f||(d!==void 0&&console.warn(`Image processor type '${d}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),f=o.ImageProcessor),new f(u)}}},"./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"),a=t("./src/models/processors.js"),i=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class c{static async from_pretrained(u,d={}){const f=await(0,n.getModelJSON)(u,s.IMAGE_PROCESSOR_NAME,!0,d),{image_processor_type:_,feature_extractor_type:P,processor_class:I}=f;if(I&&a[I])return a[I].from_pretrained(u,d);if(!_&&!P)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const M={};if(_){const S=i[_];if(!S)throw new Error(`Unknown image_processor_type: '${_}'.`);M.image_processor=new S(f)}if(P){const S=i[P];if(S)M.image_processor=new S(f);else{const E=l[P];if(!E)throw new Error(`Unknown feature_extractor_type: '${P}'.`);M.feature_extractor=new E(f)}}const g={};return new o.Processor(g,M)}}},"./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(i){super(i),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(i,l,c,p){let u;const d=i.length-l;if(d>0)if(c==="rand_trunc"){const f=Math.floor(Math.random()*(d+1));i=i.subarray(f,f+l),u=await this._extract_fbank_features(i,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${c}" not implemented`);else{if(d<0){let f=new Float64Array(l);if(f.set(i),p==="repeat")for(let _=i.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(i){super(i),this.crop_pct=this.config.crop_pct??224/256}async resize(i){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,u]=this.get_resize_output_image_size(i,{shortest_edge:c});i=await i.resize(p,u,{resample:this.resample}),i=await i.center_crop(l,l)}else i=await i.resize(l,l,{resample:this.resample});return i}}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:()=>a,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],u=(0,n.full)(p,1n);return{...c,pixel_mask:u}}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 a extends o{}},"./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(i,l,c,p={}){const[u,d,f]=l;let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(f).fill(_));let P=this.image_std;Array.isArray(P)||(P=new Array(f).fill(_));const I=_.map((M,g)=>-M/P[g]);return super.pad_image(i,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(a){super(a),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(i=>i*i))}}},"./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(i){(0,s.validate_audio_inputs)(i,"EncodecFeatureExtractor"),i instanceof Float64Array&&(i=new Float32Array(i));const l=this.config.feature_size;if(i.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,i.length/l];return{input_values:new n.Tensor("float32",i,c)}}}},"./src/models/feature_extractors.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>o.ClapFeatureExtractor,DacFeatureExtractor:()=>a.DacFeatureExtractor,EncodecFeatureExtractor:()=>n.EncodecFeatureExtractor,ImageFeatureExtractor:()=>P.ImageProcessor,MoonshineFeatureExtractor:()=>i.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>l.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>c.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>p.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>u.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>d.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>f.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>_.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"),a=t("./src/models/dac/feature_extraction_dac.js"),i=t("./src/models/moonshine/feature_extraction_moonshine.js"),l=t("./src/models/pyannote/feature_extraction_pyannote.js"),c=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),p=t("./src/models/snac/feature_extraction_snac.js"),u=t("./src/models/speecht5/feature_extraction_speecht5.js"),d=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),f=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),_=t("./src/models/whisper/feature_extraction_whisper.js"),P=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>a});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class a extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;constructor(l,c){super(l,c);const{tasks_answer_post_processing_type:p,task_prompts_without_inputs:u,task_prompts_with_input:d}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(p??{})),this.task_prompts_without_inputs=new Map(Object.entries(u??{})),this.task_prompts_with_input=new Map(Object.entries(d??{})),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[u,d]of this.task_prompts_with_input)if(p.includes(u)){c.push(d.replaceAll("{input}",p).replaceAll(u,""));break}c.length!==l.length&&c.push(p)}return c}post_process_generation(l,c,p){const u=this.tasks_answer_post_processing_type.get(c)??"pure_text";l=l.replaceAll("","").replaceAll("","");let d;switch(u){case"pure_text":d=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const f=u==="ocr"?"quad_boxes":"bboxes",_=l.matchAll(this.regexes[f]),P=[],I=[];for(const[M,g,...S]of _)P.push(g?g.trim():P.at(-1)??""),I.push(S.map((E,x)=>(Number(E)+.5)/this.size_per_bin*p[x%2]));d={labels:P,[f]:I};break;default:throw new Error(`Task "${c}" (of type "${u}") not yet implemented.`)}return{[c]:d}}async _call(l,c=null,p={}){if(!l&&!c)throw new Error("Either text or images must be provided");const u=await this.image_processor(l,p),d=c?this.tokenizer(c,p):{};return{...u,...d}}}},"./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(i){const l=await super._call(i),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"),a=t("./src/base/image_processors_utils.js");function i(c,p){const d=c.dims.at(-1)-1,f=c.tolist();f.fill(!1,0,1),f.fill(!1,d);const _=p.tolist();return f.map((P,I)=>P?I:null).filter(P=>P!==null).map(P=>_[P])}class l extends s.Processor{static tokenizer_class=o.AutoTokenizer;static image_processor_class=n.AutoImageProcessor;async _call(p,u,d={}){const f=p?await this.image_processor(p,d):{};return{...u?this.tokenizer(u,d):{},...f}}post_process_grounded_object_detection(p,u,{box_threshold:d=.25,text_threshold:f=.25,target_sizes:_=null}={}){const{logits:P,pred_boxes:I}=p,M=P.dims[0];if(_!==null&&_.length!==M)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const g=P.dims.at(1),S=P.sigmoid(),E=S.max(-1).tolist(),x=I.tolist().map(v=>v.map($=>(0,a.center_to_corners_format)($))),w=[];for(let v=0;vL.map((J,X)=>J*$[(X+1)%2])));const O=E[v],B=[],H=[],q=[];for(let L=0;L{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(i){super(i),this.do_image_splitting=i.do_image_splitting??!0,this.max_image_size=i.max_image_size}get_resize_for_vision_encoder(i,l){let[c,p]=i.dims.slice(-2);const u=p/c;return p>=c?(p=Math.ceil(p/l)*l,c=Math.floor(p/u),c=Math.ceil(c/l)*l):(c=Math.ceil(c/l)*l,p=Math.floor(c*u),p=Math.ceil(p/l)*l),{height:c,width:p}}async _call(i,{do_image_splitting:l=null,return_row_col_info:c=!1}={}){let p;if(!Array.isArray(i))p=[[i]];else{if(i.length===0||!i[0])throw new Error("No images provided.");Array.isArray(i[0])?p=i:p=[i]}let u=[],d=[],f=[];const _=[],P=[];for(const v of p){let $=await Promise.all(v.map(H=>this.preprocess(H)));_.push(...$.map(H=>H.original_size)),P.push(...$.map(H=>H.reshaped_input_size)),$.forEach(H=>H.pixel_values.unsqueeze_(0));const{longest_edge:O}=this.max_image_size;let B;if(l??this.do_image_splitting){let H=new Array($.length),q=new Array($.length);B=await Promise.all($.map(async(L,J)=>{const X=this.get_resize_for_vision_encoder(L.pixel_values,O),Q=await(0,n.interpolate_4d)(L.pixel_values,{size:[X.height,X.width]}),{frames:te,num_splits_h:re,num_splits_w:ce}=await this.split_image(Q,this.max_image_size);return H[J]=re,q[J]=ce,(0,n.cat)(te,0)})),d.push(H),f.push(q)}else{const H=[O,O];B=await Promise.all($.map(q=>(0,n.interpolate_4d)(q.pixel_values,{size:H}))),d.push(new Array($.length).fill(0)),f.push(new Array($.length).fill(0))}u.push((0,n.cat)(B,0))}const I=u.length,[M,g,S,E]=u[0].dims;let x,w;if(I===1)x=u[0].unsqueeze_(0),w=(0,n.full)([I,M,S,E],!0);else{const v=Math.max(...u.map(B=>B.dims.at(0)));w=(0,n.full)([I,v,S,E],!0);const $=w.data,O=v*S*E;for(let B=0;Bc||f>p){_=Math.ceil(d/c),P=Math.ceil(f/p);const I=Math.ceil(d/_),M=Math.ceil(f/P);for(let E=0;E<_;++E)for(let x=0;x{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 a=t("./src/utils/core.js");function i(u,d,f,_,P,I){let M="";for(let g=0;g`+P.repeat(u);M+=` `}return M+=` ${_}${I}`+P.repeat(u)+`${_}`,M}function l(u,d,f,_){return`${d}${_}`+f.repeat(u)+`${d}`}function c(u,d,f,_,P,I){return u===0&&d===0?l(f,_,P,I):i(f,u,d,_,P,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(d,f=null,_={}){_.return_row_col_info??=!0;let P;f&&(P=await this.image_processor(f,_)),Array.isArray(d)||(d=[d]);const I=P.rows??[new Array(d.length).fill(0)],M=P.cols??[new Array(d.length).fill(0)],g=this.config.image_seq_len,S=[],E=[];for(let w=0;wc(L,O[J],g,this.fake_image_token,this.image_token,this.global_img_token)),H=v.split(this.image_token);if(H.length===0)throw new Error("The image token should be present in the text.");let q=H[0];for(let L=0;L{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>n.BitImageProcessor,CLIPFeatureExtractor:()=>a.CLIPFeatureExtractor,CLIPImageProcessor:()=>a.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>o.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>i.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>i.ConvNextImageProcessor,DPTFeatureExtractor:()=>u.DPTFeatureExtractor,DPTImageProcessor:()=>u.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>c.DetrFeatureExtractor,DetrImageProcessor:()=>c.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>d.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>f.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>P.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>M.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>g.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>S.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>E.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>E.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>x.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>x.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>w.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>w.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>v.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>v.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>$.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>$.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>O.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>O.MobileViTImageProcessor,NougatImageProcessor:()=>B.NougatImageProcessor,OwlViTFeatureExtractor:()=>q.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>q.OwlViTImageProcessor,Owlv2ImageProcessor:()=>H.Owlv2ImageProcessor,Phi3VImageProcessor:()=>L.Phi3VImageProcessor,PvtImageProcessor:()=>J.PvtImageProcessor,Qwen2VLImageProcessor:()=>X.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Q.RTDetrImageProcessor,SamImageProcessor:()=>te.SamImageProcessor,SegformerFeatureExtractor:()=>re.SegformerFeatureExtractor,SegformerImageProcessor:()=>re.SegformerImageProcessor,SiglipImageProcessor:()=>ce.SiglipImageProcessor,SmolVLMImageProcessor:()=>le.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>N.Swin2SRImageProcessor,VLMImageProcessor:()=>I.VLMImageProcessor,ViTFeatureExtractor:()=>F.ViTFeatureExtractor,ViTImageProcessor:()=>F.ViTImageProcessor,VitMatteImageProcessor:()=>G.VitMatteImageProcessor,VitPoseImageProcessor:()=>R.VitPoseImageProcessor,YolosFeatureExtractor:()=>ne.YolosFeatureExtractor,YolosImageProcessor:()=>ne.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"),a=t("./src/models/clip/image_processing_clip.js"),i=t("./src/models/convnext/image_processing_convnext.js"),l=t("./src/models/deit/image_processing_deit.js"),c=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/donut/image_processing_donut.js"),u=t("./src/models/dpt/image_processing_dpt.js"),d=t("./src/models/efficientnet/image_processing_efficientnet.js"),f=t("./src/models/glpn/image_processing_glpn.js"),_=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),P=t("./src/models/idefics3/image_processing_idefics3.js"),I=t("./src/models/janus/image_processing_janus.js"),M=t("./src/models/jina_clip/image_processing_jina_clip.js"),g=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),S=t("./src/models/mask2former/image_processing_mask2former.js"),E=t("./src/models/maskformer/image_processing_maskformer.js"),x=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),w=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),v=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),$=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),O=t("./src/models/mobilevit/image_processing_mobilevit.js"),B=t("./src/models/nougat/image_processing_nougat.js"),H=t("./src/models/owlv2/image_processing_owlv2.js"),q=t("./src/models/owlvit/image_processing_owlvit.js"),L=t("./src/models/phi3_v/image_processing_phi3_v.js"),J=t("./src/models/pvt/image_processing_pvt.js"),X=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Q=t("./src/models/rt_detr/image_processing_rt_detr.js"),te=t("./src/models/sam/image_processing_sam.js"),re=t("./src/models/segformer/image_processing_segformer.js"),ce=t("./src/models/siglip/image_processing_siglip.js"),le=t("./src/models/smolvlm/image_processing_smolvlm.js"),N=t("./src/models/swin2sr/image_processing_swin2sr.js"),F=t("./src/models/vit/image_processing_vit.js"),G=t("./src/models/vitmatte/image_processing_vitmatte.js"),R=t("./src/models/vitpose/image_processing_vitpose.js"),ne=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(a){super({do_pad:!0,pad_size:{width:a.image_size,height:a.image_size},...a}),this.constant_values=this.config.background_color.map(i=>i*this.rescale_factor)}pad_image(a,i,l,c){return super.pad_image(a,i,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"),a=t("./src/utils/core.js"),i=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(u,d){super(u,d),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(u,{images:d=null,chat_template:f="default"}={}){d?Array.isArray(d)||(d=[d]):d=await Promise.all(u.filter(B=>B.images).flatMap(B=>B.images).map(B=>l.RawImage.read(B)));const _=this.tokenizer,P=_.apply_chat_template(u,{tokenize:!1,add_generation_prompt:!0,chat_template:f}),I=B=>_.encode(B,{add_special_tokens:!1}),M=P.split(this.image_tag),g=M.length-1;if(d.length!==g)throw new Error(`Number of images provided (${d.length}) does not match number of "${this.image_tag}" image tags (${g})`);const[S,E,x]=_.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let w=I(M[0]),v=new Array(w.length).fill(!1);for(let B=1;B0){const B=await this.image_processor(d);return B.pixel_values.unsqueeze_(0),{...O,...B}}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(a){const{resize_mode:i,fill_color:l,interpolation:c,size:p,...u}=a,d=i==="squash"?{width:p,height:p}:i==="shortest"?{shortest_edge:p}:{longest_edge:p},f=c==="bicubic"?3:2;super({...u,size:d,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:()=>a});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class a 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 u=l?this.tokenizer(l,p):{},d=c?await this.image_processor(c,p):{};return{...u,...d}}}},"./src/models/llava_onevision/image_processing_llava_onevision.js":(e,r,t)=>{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(...i){return(0,s.post_process_panoptic_segmentation)(...i)}post_process_instance_segmentation(...i){return(0,s.post_process_instance_segmentation)(...i)}}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"),a=t("./src/utils/maths.js");const i={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,u){if(!i.hasOwnProperty(u))throw new Error(`Format ${u} is not supported.`);const[d,f]=i[u],_=this[d].bind(this),[P,I]=p.dims,M=[],g=[],S=p.tolist();for(let x=0;x0?$.reduce((B,H)=>B*H,1):0;g.push(v),M.push(O)}return[_(g),M]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(u=>u.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(u=>u.replaceAll(" ",""))}batch_decode([p,u,d]){const[f,_]=this._decode_helper(p,"char"),[P,I]=this._decode_helper(u,"bpe"),[M,g]=this._decode_helper(d,"wp"),S=[],E=[];for(let x=0;x{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(i){(0,s.validate_audio_inputs)(i,"MoonshineFeatureExtractor"),i instanceof Float64Array&&(i=new Float32Array(i));const l=[1,i.length];return{input_values:new n.Tensor("float32",i,l)}}}},"./src/models/moonshine/processing_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>a});var s=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class a 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(...i){return(0,s.post_process_object_detection)(...i)}}class o extends n{}},"./src/models/owlvit/processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>a});var s=t("./src/base/processing_utils.js"),n=t("./src/models/auto/image_processing_auto.js"),o=t("./src/tokenizers.js");class a 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 a="";function i(c,p,u,d,f){return`${d.repeat(u*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,u=null,d={}){u||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),u=""),Array.isArray(p)||(p=[p]),Array.isArray(u)||(u=[u]);const f=this.tokenizer.bos_token,_=this.image_processor.config.image_seq_length;let P;u.some(g=>g.includes(a))?P=u.map(g=>{const S=g.replaceAll(a,a.repeat(_)),E=S.lastIndexOf(a),x=E===-1?0:E+a.length;return S.slice(0,x)+f+S.slice(x)+` `}):(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."),P=u.map(g=>i(g,f,_,a,p.length)));const I=this.tokenizer(P,d);return{...await this.image_processor(p,d),...I}}}},"./src/models/phi3_v/image_processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VImageProcessor:()=>p});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/tensor.js");const o=336,a=[2,3],{ceil:i,floor:l,sqrt:c}=Math;class p extends s.ImageProcessor{constructor(d){super({...d,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=d.num_crops}calc_num_image_tokens_from_image_size(d,f){const{num_img_tokens:_}=this.config;return l((l(f/o)*l(d/o)+1)*_+1+(l(f/o)+1)*c(_))}get_resize_output_image_size(d,f){const _=this._num_crops,[P,I]=d.size;let M=P/I,g=1;for(;g*Math.ceil(g/M)<=_;)g+=1;g-=1;const S=Math.floor(g*336),E=Math.floor(S/M);return[S,E]}pad_image(d,f,_,P={}){const[I,M]=f,g=o*i(I/o),S=o*i(M/o),E=[1,1,1].map((x,w)=>(x-this.image_mean[w])/this.image_std[w]);return super.pad_image(d,f,{width:S,height:g},{center:!0,constant_values:E,...P})}async _call(d,{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(d)||(d=[d]);const _=d.length,P=await Promise.all(d.map(v=>this.preprocess(v))),I=P.map(v=>v.original_size),M=P.map(v=>v.reshaped_input_size),g=[];for(const{pixel_values:v}of P){v.unsqueeze_(0);const[$,O]=v.dims.slice(-2),B=await(0,n.interpolate_4d)(v,{size:[o,o],mode:"bicubic"});if(f>0){const H=[],q=c(f),L=l(O/q),J=l($/q);for(let Q=0;Qv.map($=>o*i($/o))),x=new n.Tensor("int64",E.flat(),[_,2]),w=E.map(([v,$])=>this.calc_num_image_tokens_from_image_size($,v));return{pixel_values:S,original_sizes:I,reshaped_input_sizes:M,image_sizes:x,num_img_tokens:w}}}},"./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 a="<|image|>",i=/<\|image_\d+\|>/g;class l extends s.Processor{static image_processor_class=n.AutoImageProcessor;static tokenizer_class=o.AutoTokenizer;async _call(p,u=null,{padding:d=!0,truncation:f=!0,num_crops:_=null}={}){Array.isArray(p)||(p=[p]);let P,I;if(u){I=await this.image_processor(u,{num_crops:_});const{num_img_tokens:M}=I,g=p.map((E,x)=>E.split(i).join(a.repeat(M[x])));P=this.tokenizer(g,{padding:d,truncation:f});const S=this.tokenizer.model.convert_tokens_to_ids([a])[0];P.input_ids.map_(E=>E==S?-E:E)}else P=this.tokenizer(p);return{...P,...I}}}},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,GroundingDinoProcessor:()=>n.GroundingDinoProcessor,Idefics3Processor:()=>o.Idefics3Processor,JinaCLIPProcessor:()=>i.JinaCLIPProcessor,MgpstrProcessor:()=>l.MgpstrProcessor,MoonshineProcessor:()=>c.MoonshineProcessor,OwlViTProcessor:()=>p.OwlViTProcessor,PaliGemmaProcessor:()=>d.PaliGemmaProcessor,Phi3VProcessor:()=>u.Phi3VProcessor,PyAnnoteProcessor:()=>f.PyAnnoteProcessor,Qwen2VLProcessor:()=>_.Qwen2VLProcessor,SamProcessor:()=>P.SamProcessor,SmolVLMProcessor:()=>I.SmolVLMProcessor,SpeechT5Processor:()=>M.SpeechT5Processor,UltravoxProcessor:()=>g.UltravoxProcessor,VLChatProcessor:()=>a.VLChatProcessor,Wav2Vec2Processor:()=>S.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>E.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>x.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),n=t("./src/models/grounding_dino/processing_grounding_dino.js"),o=t("./src/models/idefics3/processing_idefics3.js"),a=t("./src/models/janus/processing_janus.js"),i=t("./src/models/jina_clip/processing_jina_clip.js"),l=t("./src/models/mgp_str/processing_mgp_str.js"),c=t("./src/models/moonshine/processing_moonshine.js"),p=t("./src/models/owlvit/processing_owlvit.js"),u=t("./src/models/phi3_v/processing_phi3_v.js"),d=t("./src/models/paligemma/processing_paligemma.js"),f=t("./src/models/pyannote/processing_pyannote.js"),_=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),P=t("./src/models/sam/processing_sam.js"),I=t("./src/models/smolvlm/processing_smolvlm.js"),M=t("./src/models/speecht5/processing_speecht5.js"),g=t("./src/models/ultravox/processing_ultravox.js"),S=t("./src/models/wav2vec2/processing_wav2vec2.js"),E=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),x=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:()=>a});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/maths.js");class a 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,u=[];for(const d of l.tolist()){const f=[];let _=-1;for(let P=0;P({id:P,start:I*p,end:M*p,confidence:g/(M-I)})))}return u}}},"./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(i){return await this.feature_extractor(i)}post_process_speaker_diarization(...i){return this.feature_extractor.post_process_speaker_diarization(...i)}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(i,...l){const{pixel_values:c,original_sizes:p,reshaped_input_sizes:u}=await super._call(i,...l);let d=c;const{temporal_patch_size:f,merge_size:_,patch_size:P}=this.config;d.dims[0]===1&&(d=(0,n.cat)(Array.from({length:f},()=>d),0));const I=d.dims[0]/f,M=d.dims[1],g=Math.floor(d.dims[2]/P),S=Math.floor(d.dims[3]/P),E=d.view(I,f,M,Math.floor(g/_),_,P,Math.floor(S/_),_,P).permute(0,3,6,4,7,2,1,5,8).view(I*g*S,M*f*P*P),x=new n.Tensor("int64",[I,g,S],[1,3]);return{pixel_values:E,image_grid_thw:x,original_sizes:p,reshaped_input_sizes:u}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>a});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 a 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 u,d;if(c&&(u=await this.image_processor(c),d=u.image_grid_thw),d){let _=this.image_processor.config.merge_size**2,P=0;const I=d.tolist();l=l.map(M=>{for(;M.includes("<|image_pad|>");){const g=Number(I[P++].reduce((S,E)=>S*E,1n));M=M.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(g/_)))}return M.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...u}}}},"./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(...a){return(0,s.post_process_object_detection)(...a)}}},"./src/models/sam/image_processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>a});var s=t("./src/base/image_processors_utils.js"),n=t("./src/utils/core.js"),o=t("./src/utils/tensor.js");class a extends s.ImageProcessor{reshape_input_points(l,c,p,u=!1){l=structuredClone(l);let d=(0,n.calculateDimensions)(l);if(d.length===3)u||(d=[1,...d]),l=[l];else if(d.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;fu!==c.dims[d]))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:u=null}={}){const d=await super._call(l);if(c&&(d.input_points=this.reshape_input_points(c,d.original_sizes,d.reshaped_input_sizes)),p){if(!d.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");d.input_labels=this.add_input_labels(p,d.input_points)}return u&&(d.input_boxes=this.reshape_input_points(u,d.original_sizes,d.reshaped_input_sizes,!0)),d}async post_process_masks(l,c,p,{mask_threshold:u=0,binarize:d=!0,pad_size:f=null}={}){const _=[];f=f??this.pad_size;const P=[f.height,f.width];for(let I=0;Iu&&(x[w]=1);S=new o.Tensor("bool",x,S.dims)}_.push(S)}return _}generate_crop_boxes(l,c,{crop_n_layers:p=0,overlap_ratio:u=512/1500,points_per_crop:d=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(...i){return await this.image_processor(...i)}post_process_masks(...i){return this.image_processor.post_process_masks(...i)}reshape_input_points(...i){return this.image_processor.reshape_input_points(...i)}}},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>a});var s=t("./src/base/feature_extraction_utils.js"),n=t("./src/utils/tensor.js"),o=t("./src/utils/audio.js");class a 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:u=!0,return_attention_mask:d=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let f=await this._extract_fbank_features(l,this.config.max_length);if(u){const[x,w]=f.dims,v=f.data;for(let $=0;$0){const O=new Float32Array(w*(x+$));O.set(v),O.fill(this.config.padding_value,v.length);const B=x+$;f=new n.Tensor(f.type,O,[B,w]),d&&(_=new n.Tensor("int64",new BigInt64Array(B),[1,B]),_.data.fill(1n,0,x))}}const[P,I]=f.dims,M=this.config.stride;if(P%M!==0)throw new Error(`The number of frames (${P}) must be a multiple of the stride (${M}).`);const S=f.view(1,Math.floor(P/M),I*M),E={input_features:S};if(d){const x=S.dims[1],w=new BigInt64Array(x);if(_){const v=_.data;for(let $=1,O=0;${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(...i){return(0,s.post_process_semantic_segmentation)(...i)}}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:()=>a});var s=t("./src/base/processing_utils.js"),n=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js");class a 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(a,i,l,c={}){const[p,u,d]=i;return super.pad_image(a,i,{width:u+(l-u%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:()=>a});var s=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class a 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 u={};if(c){const f=c.length,{input_features:_}=await this.feature_extractor(c,{...p,max_length:f}),P=Math.round(f/this.config.encoder_ds_factor+1e-4),I=1+Math.ceil(P/this.config.stack_factor);u.audio_token_len=[I],u.audio_values=_;const M=this.config.audio_placeholder;if(!l.includes(M))throw new Error(`The input text does not contain the image token ${M}.`);l=l.replaceAll(M,M.repeat(I))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...u}}}},"./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(i,l){Array.isArray(i)||(i=[i]),Array.isArray(l)||(l=[l]);const c=await Promise.all(i.map(d=>this.preprocess(d))),p=await Promise.all(l.map(d=>this.preprocess(d,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,n.stack)(c.map((d,f)=>(0,n.cat)([d.pixel_values,p[f].pixel_values],0)),0),original_sizes:c.map(d=>d.original_size),reshaped_input_sizes:c.map(d=>d.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(a,i,{threshold:l=null}={}){const c=a.tolist(),[p,u,d,f]=a.dims,_=[];for(let P=0;P{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(i){const c=i.reduce((u,d)=>u+d,0)/i.length,p=i.reduce((u,d)=>u+(d-c)**2,0)/i.length;return i.map(u=>(u-c)/Math.sqrt(p+1e-7))}async _call(i){(0,s.validate_audio_inputs)(i,"Wav2Vec2FeatureExtractor"),i instanceof Float64Array&&(i=new Float32Array(i));let l=i;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:()=>a});var s=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/base/processing_utils.js");class a 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:()=>a});var s=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/base/processing_utils.js");class a 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(i){super(i);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(i){return i=i.map(l=>l*32768),(0,n.spectrogram)(i,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(i){(0,s.validate_audio_inputs)(i,"WeSpeakerFeatureExtractor");const l=(await this._extract_fbank_features(i)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const c=l.mean(1).data,p=l.data,[u,d,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:()=>a});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(([i,l])=>[l,i]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function a(i){i=i.toLowerCase();let l=o.get(i);if(l===void 0){const c=i.match(/^<\|([a-z]{2})\|>$/);if(c&&(i=c[1]),n.has(i))l=i;else{const u=i.length===2?n.keys():n.values();throw new Error(`Language "${i}" is not supported. Must be one of: ${JSON.stringify(Array.from(u))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>a});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 a 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,u=(0,o.max)(p)[0];for(let d=0;du?(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,u)):(p=new Float32Array(u),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:()=>a});var s=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/processing_utils.js");class a 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(...i){return(0,s.post_process_object_detection)(...i)}}class o extends n{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),n=t("./src/utils/tensor.js"),o=t("./src/env.js");const a=o.apis.IS_BROWSER_ENV||o.apis.IS_WEBWORKER_ENV,i=async(c,p,u)=>{const d=await(0,s.createInferenceSession)(new Uint8Array(c),p);let f=Promise.resolve();return async _=>{const P=(0,s.isONNXProxy)(),I=Object.fromEntries(Object.entries(_).map(([g,S])=>[g,(P?S.clone():S).ort_tensor])),M=await(f=a?f.then(()=>d.run(I)):d.run(I));return Array.isArray(u)?u.map(g=>new n.Tensor(M[g])):new n.Tensor(M[u])}};class l{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=i([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=i([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=i([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=i([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=i([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=i([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=i([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=i([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:()=>q,AutomaticSpeechRecognitionPipeline:()=>J,BackgroundRemovalPipeline:()=>re,DepthEstimationPipeline:()=>ne,DocumentQuestionAnsweringPipeline:()=>F,FeatureExtractionPipeline:()=>B,FillMaskPipeline:()=>S,ImageClassificationPipeline:()=>Q,ImageFeatureExtractionPipeline:()=>H,ImageSegmentationPipeline:()=>te,ImageToImagePipeline:()=>R,ImageToTextPipeline:()=>X,ObjectDetectionPipeline:()=>le,Pipeline:()=>P,QuestionAnsweringPipeline:()=>g,SummarizationPipeline:()=>x,Text2TextGenerationPipeline:()=>E,TextClassificationPipeline:()=>I,TextGenerationPipeline:()=>$,TextToAudioPipeline:()=>G,TokenClassificationPipeline:()=>M,TranslationPipeline:()=>w,ZeroShotAudioClassificationPipeline:()=>L,ZeroShotClassificationPipeline:()=>O,ZeroShotImageClassificationPipeline:()=>ce,ZeroShotObjectDetectionPipeline:()=>N,pipeline:()=>ve});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 a=t("./src/utils/generic.js"),i=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),c=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),u=t("./src/utils/image.js");async function d(fe){return Array.isArray(fe)||(fe=[fe]),await Promise.all(fe.map(K=>u.RawImage.read(K)))}async function f(fe,K){return Array.isArray(fe)||(fe=[fe]),await Promise.all(fe.map(U=>typeof U=="string"||U instanceof URL?(0,c.read_audio)(U,K):U instanceof Float64Array?new Float32Array(U):U))}function _(fe,K){K&&(fe=fe.map(Ce=>Ce|0));const[U,pe,ye,xe]=fe;return{xmin:U,ymin:pe,xmax:ye,ymax:xe}}class P extends a.Callable{constructor({task:K,model:U,tokenizer:pe=null,processor:ye=null}){super(),this.task=K,this.model=U,this.tokenizer=pe,this.processor=ye}async dispose(){await this.model.dispose()}}class I extends P{constructor(K){super(K)}async _call(K,{top_k:U=1}={}){const pe=this.tokenizer(K,{padding:!0,truncation:!0}),ye=await this.model(pe),xe=this.model.config.problem_type==="multi_label_classification"?Ae=>Ae.sigmoid():Ae=>new p.Tensor("float32",(0,l.softmax)(Ae.data),Ae.dims),Ce=this.model.config.id2label,$e=[];for(const Ae of ye.logits){const Re=xe(Ae),Ne=await(0,p.topk)(Re,U),A=Ne[0].tolist(),z=Ne[1].tolist().map((ee,oe)=>({label:Ce?Ce[ee]:`LABEL_${ee}`,score:A[oe]}));U===1?$e.push(...z):$e.push(z)}return Array.isArray(K)||U===1?$e:$e[0]}}class M extends P{constructor(K){super(K)}async _call(K,{ignore_labels:U=["O"]}={}){const pe=Array.isArray(K),ye=this.tokenizer(pe?K:[K],{padding:!0,truncation:!0}),Ce=(await this.model(ye)).logits,$e=this.model.config.id2label,Ae=[];for(let Re=0;ReMe==this.tokenizer.sep_token_id);Ae[A].map((Me,ke)=>Me==1&&(ke===0||ke>z&&Re.findIndex(st=>st==Y[ke])===-1));const ee=xe[A].tolist(),oe=Ce[A].tolist();for(let Me=1;Meke==Y[Me])!==-1)&&(ee[Me]=-1/0,oe[Me]=-1/0);const he=(0,l.softmax)(ee).map((Me,ke)=>[Me,ke]),Ee=(0,l.softmax)(oe).map((Me,ke)=>[Me,ke]);he[0][0]=0,Ee[0][0]=0;const Fe=(0,i.product)(he,Ee).filter(Me=>Me[0][1]<=Me[1][1]).map(Me=>[Me[0][1],Me[1][1],Me[0][0]*Me[1][0]]).sort((Me,ke)=>ke[2]-Me[2]);for(let Me=0;Meee==this.tokenizer.mask_token_id);if(Re===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ne=ye[$e][Re],A=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ne.data),Ne.dims),U),Y=A[0].tolist(),z=A[1].tolist();xe.push(z.map((ee,oe)=>{const he=Ae.slice();return he[Re]=ee,{score:Y[oe],token:Number(ee),token_str:this.tokenizer.decode([ee]),sequence:this.tokenizer.decode(he,{skip_special_tokens:!0})}}))}return Array.isArray(K)?xe:xe[0]}}class E extends P{_key="generated_text";constructor(K){super(K)}async _call(K,U={}){Array.isArray(K)||(K=[K]),this.model.config.prefix&&(K=K.map(Ae=>this.model.config.prefix+Ae));const pe=this.model.config.task_specific_params;pe&&pe[this.task]&&pe[this.task].prefix&&(K=K.map(Ae=>pe[this.task].prefix+Ae));const ye=this.tokenizer,xe={padding:!0,truncation:!0};let Ce;this instanceof w&&"_build_translation_inputs"in ye?Ce=ye._build_translation_inputs(K,xe,U):Ce=ye(K,xe);const $e=await this.model.generate({...Ce,...U});return ye.batch_decode($e,{skip_special_tokens:!0}).map(Ae=>({[this._key]:Ae}))}}class x extends E{_key="summary_text";constructor(K){super(K)}}class w extends E{_key="translation_text";constructor(K){super(K)}}function v(fe){return Array.isArray(fe)&&fe.every(K=>"role"in K&&"content"in K)}class $ extends P{constructor(K){super(K)}async _call(K,U={}){let pe=!1,ye=!1,xe;if(typeof K=="string")xe=K=[K];else if(Array.isArray(K)&&K.every(z=>typeof z=="string"))pe=!0,xe=K;else{if(v(K))K=[K];else if(Array.isArray(K)&&K.every(v))pe=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");ye=!0,xe=K.map(z=>this.tokenizer.apply_chat_template(z,{tokenize:!1,add_generation_prompt:!0}))}const Ce=U.add_special_tokens??!1,$e=ye?!1:U.return_full_text??!0;this.tokenizer.padding_side="left";const Ae=this.tokenizer(xe,{add_special_tokens:Ce,padding:!0,truncation:!0}),Re=await this.model.generate({...Ae,...U}),Ne=this.tokenizer.batch_decode(Re,{skip_special_tokens:!0});let A;!$e&&Ae.input_ids.dims.at(-1)>0&&(A=this.tokenizer.batch_decode(Ae.input_ids,{skip_special_tokens:!0}).map(z=>z.length));const Y=Array.from({length:K.length},z=>[]);for(let z=0;z[U.toLowerCase(),pe])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(K,U,{hypothesis_template:pe="This example is {}.",multi_label:ye=!1}={}){const xe=Array.isArray(K);xe||(K=[K]),Array.isArray(U)||(U=[U]);const Ce=U.map(Re=>pe.replace("{}",Re)),$e=ye||U.length===1,Ae=[];for(const Re of K){const Ne=[];for(const z of Ce){const ee=this.tokenizer(Re,{text_pair:z,padding:!0,truncation:!0}),oe=await this.model(ee);$e?Ne.push([oe.logits.data[this.contradiction_id],oe.logits.data[this.entailment_id]]):Ne.push(oe.logits.data[this.entailment_id])}const Y=($e?Ne.map(z=>(0,l.softmax)(z)[1]):(0,l.softmax)(Ne)).map((z,ee)=>[z,ee]).sort((z,ee)=>ee[0]-z[0]);Ae.push({sequence:Re,labels:Y.map(z=>U[z[1]]),scores:Y.map(z=>z[0])})}return xe?Ae:Ae[0]}}class B extends P{constructor(K){super(K)}async _call(K,{pooling:U="none",normalize:pe=!1,quantize:ye=!1,precision:xe="binary"}={}){const Ce=this.tokenizer(K,{padding:!0,truncation:!0}),$e=await this.model(Ce);let Ae=$e.last_hidden_state??$e.logits??$e.token_embeddings;if(U!=="none")if(U==="mean")Ae=(0,p.mean_pooling)(Ae,Ce.attention_mask);else if(U==="cls")Ae=Ae.slice(null,0);else throw Error(`Pooling method '${U}' not supported.`);return pe&&(Ae=Ae.normalize(2,-1)),ye&&(Ae=(0,p.quantize_embeddings)(Ae,xe)),Ae}}class H extends P{constructor(K){super(K)}async _call(K,{pool:U=null}={}){const pe=await d(K),{pixel_values:ye}=await this.processor(pe),xe=await this.model({pixel_values:ye});let Ce;if(U){if(!("pooler_output"in xe))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ce=xe.pooler_output}else Ce=xe.last_hidden_state??xe.logits??xe.image_embeds;return Ce}}class q extends P{constructor(K){super(K)}async _call(K,{top_k:U=5}={}){const pe=this.processor.feature_extractor.config.sampling_rate,ye=await f(K,pe),xe=this.model.config.id2label,Ce=[];for(const $e of ye){const Ae=await this.processor($e),Ne=(await this.model(Ae)).logits[0],A=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ne.data),Ne.dims),U),Y=A[0].tolist(),ee=A[1].tolist().map((oe,he)=>({label:xe?xe[oe]:`LABEL_${oe}`,score:Y[he]}));Ce.push(ee)}return Array.isArray(K)?Ce:Ce[0]}}class L extends P{constructor(K){super(K)}async _call(K,U,{hypothesis_template:pe="This is a sound of {}."}={}){const ye=!Array.isArray(K);ye&&(K=[K]);const xe=U.map(Ne=>pe.replace("{}",Ne)),Ce=this.tokenizer(xe,{padding:!0,truncation:!0}),$e=this.processor.feature_extractor.config.sampling_rate,Ae=await f(K,$e),Re=[];for(const Ne of Ae){const A=await this.processor(Ne),Y=await this.model({...Ce,...A}),z=(0,l.softmax)(Y.logits_per_audio.data);Re.push([...z].map((ee,oe)=>({score:ee,label:U[oe]})))}return ye?Re[0]:Re}}class J extends P{constructor(K){super(K)}async _call(K,U={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(K,U);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(K,U);case"moonshine":return this._call_moonshine(K,U);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(K,U){U.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),U.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const pe=!Array.isArray(K);pe&&(K=[K]);const ye=this.processor.feature_extractor.config.sampling_rate,xe=await f(K,ye),Ce=[];for(const $e of xe){const Ae=await this.processor($e),Ne=(await this.model(Ae)).logits[0],A=[];for(const z of Ne)A.push((0,l.max)(z.data)[1]);const Y=this.tokenizer.decode(A);Ce.push({text:Y})}return pe?Ce[0]:Ce}async _call_whisper(K,U){const pe=U.return_timestamps??!1,ye=U.chunk_length_s??0,xe=U.force_full_sequences??!1;let Ce=U.stride_length_s??null;const $e={...U};pe==="word"&&($e.return_token_timestamps=!0,$e.return_timestamps=!1);const Ae=!Array.isArray(K);Ae&&(K=[K]);const Re=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ne=this.processor.feature_extractor.config.hop_length,A=this.processor.feature_extractor.config.sampling_rate,Y=await f(K,A),z=[];for(const ee of Y){let oe=[];if(ye>0){if(Ce===null)Ce=ye/6;else if(ye<=Ce)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Fe=A*ye,Me=A*Ce,ke=Fe-2*Me;let st=0;for(;;){const ut=st+Fe,_t=ee.subarray(st,ut),gt=await this.processor(_t),er=st===0,It=ut>=ee.length;if(oe.push({stride:[_t.length,er?0:Me,It?0:Me],input_features:gt.input_features,is_last:It}),It)break;st+=ke}}else oe=[{stride:[ee.length,0,0],input_features:(await this.processor(ee)).input_features,is_last:!0}];for(const Fe of oe){$e.num_frames=Math.floor(Fe.stride[0]/Ne);const Me=await this.model.generate({inputs:Fe.input_features,...$e});pe==="word"?(Fe.tokens=Me.sequences.tolist()[0],Fe.token_timestamps=Me.token_timestamps.tolist()[0].map(ke=>(0,l.round)(ke,2))):Fe.tokens=Me[0].tolist(),Fe.stride=Fe.stride.map(ke=>ke/A)}const[he,Ee]=this.tokenizer._decode_asr(oe,{time_precision:Re,return_timestamps:pe,force_full_sequences:xe});z.push({text:he,...Ee})}return Ae?z[0]:z}async _call_moonshine(K,U){const pe=!Array.isArray(K);pe&&(K=[K]);const ye=this.processor.feature_extractor.config.sampling_rate,xe=await f(K,ye),Ce=[];for(const $e of xe){const Ae=await this.processor($e),Re=Math.floor($e.length/ye)*6,Ne=await this.model.generate({max_new_tokens:Re,...U,...Ae}),A=this.processor.batch_decode(Ne,{skip_special_tokens:!0})[0];Ce.push({text:A})}return pe?Ce[0]:Ce}}class X extends P{constructor(K){super(K)}async _call(K,U={}){const pe=Array.isArray(K),ye=await d(K),{pixel_values:xe}=await this.processor(ye),Ce=[];for(const $e of xe){$e.dims=[1,...$e.dims];const Ae=await this.model.generate({inputs:$e,...U}),Re=this.tokenizer.batch_decode(Ae,{skip_special_tokens:!0}).map(Ne=>({generated_text:Ne.trim()}));Ce.push(Re)}return pe?Ce:Ce[0]}}class Q extends P{constructor(K){super(K)}async _call(K,{top_k:U=5}={}){const pe=await d(K),{pixel_values:ye}=await this.processor(pe),xe=await this.model({pixel_values:ye}),Ce=this.model.config.id2label,$e=[];for(const Ae of xe.logits){const Re=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ae.data),Ae.dims),U),Ne=Re[0].tolist(),Y=Re[1].tolist().map((z,ee)=>({label:Ce?Ce[z]:`LABEL_${z}`,score:Ne[ee]}));$e.push(Y)}return Array.isArray(K)?$e:$e[0]}}class te extends P{constructor(K){super(K),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(K,{threshold:U=.5,mask_threshold:pe=.5,overlap_mask_area_threshold:ye=.8,label_ids_to_fuse:xe=null,target_sizes:Ce=null,subtask:$e=null}={}){if(Array.isArray(K)&&K.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const Re=await d(K),Ne=Re.map(Fe=>[Fe.height,Fe.width]),A=await this.processor(Re),{inputNames:Y,outputNames:z}=this.model.sessions.model;if(!Y.includes("pixel_values")){if(Y.length!==1)throw Error(`Expected a single input name, but got ${Y.length} inputs: ${Y}.`);const Fe=Y[0];if(Fe in A)throw Error(`Input name ${Fe} already exists in the inputs.`);A[Fe]=A.pixel_values}const ee=await this.model(A);let oe=null;if($e!==null)oe=this.subtasks_mapping[$e];else if(this.processor.image_processor){for(const[Fe,Me]of Object.entries(this.subtasks_mapping))if(Me in this.processor.image_processor){oe=this.processor.image_processor[Me].bind(this.processor.image_processor),$e=Fe;break}}const he=this.model.config.id2label,Ee=[];if($e)if($e==="panoptic"||$e==="instance"){const Fe=oe(ee,U,pe,ye,xe,Ce??Ne)[0],Me=Fe.segmentation;for(const ke of Fe.segments_info){const st=new Uint8ClampedArray(Me.data.length);for(let _t=0;_tgt<-1e-5||gt>1+1e-5)&&ut.sigmoid_();const _t=await u.RawImage.fromTensor(ut.mul_(255).to("uint8")).resize(st[1],st[0]);Ee.push({label:null,score:null,mask:_t})}}return Ee}}class re extends te{constructor(K){super(K)}async _call(K,U={}){if(Array.isArray(K)&&K.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const ye=await d(K),xe=await super._call(K,U);return ye.map(($e,Ae)=>{const Re=$e.clone();return Re.putAlpha(xe[Ae].mask),Re})}}class ce extends P{constructor(K){super(K)}async _call(K,U,{hypothesis_template:pe="This is a photo of {}"}={}){const ye=Array.isArray(K),xe=await d(K),Ce=U.map(Y=>pe.replace("{}",Y)),$e=this.tokenizer(Ce,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:Ae}=await this.processor(xe),Re=await this.model({...$e,pixel_values:Ae}),Ne=this.model.config.model_type==="siglip"?Y=>Y.sigmoid().data:Y=>(0,l.softmax)(Y.data),A=[];for(const Y of Re.logits_per_image){const ee=[...Ne(Y)].map((oe,he)=>({score:oe,label:U[he]}));ee.sort((oe,he)=>he.score-oe.score),A.push(ee)}return ye?A:A[0]}}class le extends P{constructor(K){super(K)}async _call(K,{threshold:U=.9,percentage:pe=!1}={}){const ye=Array.isArray(K);if(ye&&K.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const xe=await d(K),Ce=pe?null:xe.map(z=>[z.height,z.width]),{pixel_values:$e,pixel_mask:Ae}=await this.processor(xe),Re=await this.model({pixel_values:$e,pixel_mask:Ae}),Ne=this.processor.image_processor.post_process_object_detection(Re,U,Ce),A=this.model.config.id2label,Y=Ne.map(z=>z.boxes.map((ee,oe)=>({score:z.scores[oe],label:A[z.classes[oe]],box:_(ee,!pe)})));return ye?Y:Y[0]}}class N extends P{constructor(K){super(K)}async _call(K,U,{threshold:pe=.1,top_k:ye=null,percentage:xe=!1}={}){const Ce=Array.isArray(K),$e=await d(K),Ae=this.tokenizer(U,{padding:!0,truncation:!0}),Re=await this.processor($e),Ne=[];for(let A=0;A<$e.length;++A){const Y=$e[A],z=xe?null:[[Y.height,Y.width]],ee=Re.pixel_values[A].unsqueeze_(0),oe=await this.model({...Ae,pixel_values:ee});let he;if("post_process_grounded_object_detection"in this.processor){const Ee=this.processor.post_process_grounded_object_detection(oe,Ae.input_ids,{box_threshold:pe,text_threshold:pe,target_sizes:z})[0];he=Ee.boxes.map((Fe,Me)=>({score:Ee.scores[Me],label:Ee.labels[Me],box:_(Fe,!xe)}))}else{const Ee=this.processor.image_processor.post_process_object_detection(oe,pe,z,!0)[0];he=Ee.boxes.map((Fe,Me)=>({score:Ee.scores[Me],label:U[Ee.classes[Me]],box:_(Fe,!xe)}))}he.sort((Ee,Fe)=>Fe.score-Ee.score),ye!==null&&(he=he.slice(0,ye)),Ne.push(he)}return Ce?Ne:Ne[0]}}class F extends P{constructor(K){super(K)}async _call(K,U,pe={}){const ye=(await d(K))[0],{pixel_values:xe}=await this.processor(ye),Ce=`${U}`,$e=this.tokenizer(Ce,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,Ae=await this.model.generate({inputs:xe,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:$e,...pe}),Ne=this.tokenizer.batch_decode(Ae)[0].match(/(.*?)<\/s_answer>/);let A=null;return Ne&&Ne.length>=2&&(A=Ne[1].trim()),[{answer:A}]}}class G extends P{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(K){super(K),this.vocoder=K.vocoder??null}async _call(K,{speaker_embeddings:U=null}={}){return this.processor?this._call_text_to_spectrogram(K,{speaker_embeddings:U}):this._call_text_to_waveform(K)}async _call_text_to_waveform(K){const U=this.tokenizer(K,{padding:!0,truncation:!0}),{waveform:pe}=await this.model(U),ye=this.model.config.sampling_rate;return new c.RawAudio(pe.data,ye)}async _call_text_to_spectrogram(K,{speaker_embeddings:U}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await n.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof U=="string"||U instanceof URL)&&(U=new Float32Array(await(await fetch(U)).arrayBuffer())),U instanceof Float32Array)U=new p.Tensor("float32",U,[1,U.length]);else if(!(U instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:pe}=this.tokenizer(K,{padding:!0,truncation:!0}),{waveform:ye}=await this.model.generate_speech(pe,U,{vocoder:this.vocoder}),xe=this.processor.feature_extractor.config.sampling_rate;return new c.RawAudio(ye.data,xe)}}class R extends P{constructor(K){super(K)}async _call(K){const U=await d(K),pe=await this.processor(U),ye=await this.model(pe),xe=[];for(const Ce of ye.reconstruction){const $e=Ce.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");xe.push(u.RawImage.fromTensor($e))}return xe.length>1?xe:xe[0]}}class ne extends P{constructor(K){super(K)}async _call(K){const U=await d(K),pe=await this.processor(U),{predicted_depth:ye}=await this.model(pe),xe=[];for(let Ce=0;Ce1?xe:xe[0]}}const be=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:M,model:n.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:g,model:n.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:S,model:n.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:x,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:w,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:E,model:n.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:$,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:q,model:n.AutoModelForAudioClassification,processor:o.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:L,model:n.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:J,model:[n.AutoModelForSpeechSeq2Seq,n.AutoModelForCTC],processor:o.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:G,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:Q,model:n.AutoModelForImageClassification,processor:o.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:te,model:[n.AutoModelForImageSegmentation,n.AutoModelForSemanticSegmentation,n.AutoModelForUniversalSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:re,model:[n.AutoModelForImageSegmentation,n.AutoModelForSemanticSegmentation,n.AutoModelForUniversalSegmentation],processor:o.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:ce,model:n.AutoModel,processor:o.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:le,model:n.AutoModelForObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:N,model:n.AutoModelForZeroShotObjectDetection,processor:o.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:F,model:n.AutoModelForDocumentQuestionAnswering,processor:o.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:R,model:n.AutoModelForImageToImage,processor:o.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:ne,model:n.AutoModelForDepthEstimation,processor:o.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:B,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"}}),de=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ve(fe,K=null,{progress_callback:U=null,config:pe=null,cache_dir:ye=null,local_files_only:xe=!1,revision:Ce="main",device:$e=null,dtype:Ae=null,subfolder:Re="onnx",use_external_data_format:Ne=null,model_file_name:A=null,session_options:Y={}}={}){fe=de[fe]??fe;const z=be[fe.split("_",1)[0]];if(!z)throw Error(`Unsupported pipeline: ${fe}. Must be one of [${Object.keys(be)}]`);K||(K=z.default.model,console.log(`No model specified. Using default model: "${K}".`));const ee={progress_callback:U,config:pe,cache_dir:ye,local_files_only:xe,revision:Ce,device:$e,dtype:Ae,subfolder:Re,use_external_data_format:Ne,model_file_name:A,session_options:Y},oe=new Map([["tokenizer",z.tokenizer],["model",z.model],["processor",z.processor]]),he=await je(oe,K,ee);he.task=fe,(0,i.dispatchCallback)(U,{status:"ready",task:fe,model:K});const Ee=z.pipeline;return new Ee(he)}async function je(fe,K,U){const pe=Object.create(null),ye=[];for(const[xe,Ce]of fe.entries()){if(!Ce)continue;let $e;Array.isArray(Ce)?$e=new Promise(async(Ae,Re)=>{let Ne;for(const A of Ce){if(A===null){Ae(null);return}try{Ae(await A.from_pretrained(K,U));return}catch(Y){if(Y.message?.includes("Unsupported model type"))Ne=Y;else if(Y.message?.includes("Could not locate file"))Ne=Y;else{Re(Y);return}}}Re(Ne)}):$e=Ce.from_pretrained(K,U),pe[xe]=$e,ye.push($e)}await Promise.all(ye);for(const[xe,Ce]of Object.entries(pe))pe[xe]=await Ce;return pe}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Tt,AutoTokenizer:()=>En,BartTokenizer:()=>As,BertTokenizer:()=>Ur,BlenderbotSmallTokenizer:()=>qr,BlenderbotTokenizer:()=>Ys,BloomTokenizer:()=>Kr,CLIPTokenizer:()=>qs,CamembertTokenizer:()=>Ye,CodeGenTokenizer:()=>Hr,CodeLlamaTokenizer:()=>bs,CohereTokenizer:()=>rn,ConvBertTokenizer:()=>ur,DebertaTokenizer:()=>Gr,DebertaV2Tokenizer:()=>yr,DistilBertTokenizer:()=>He,ElectraTokenizer:()=>ks,EsmTokenizer:()=>Ks,FalconTokenizer:()=>ds,GPT2Tokenizer:()=>Is,GPTNeoXTokenizer:()=>$r,GemmaTokenizer:()=>xr,Grok1Tokenizer:()=>Dr,HerbertTokenizer:()=>cs,LlamaTokenizer:()=>Ms,M2M100Tokenizer:()=>vs,MBart50Tokenizer:()=>Fs,MBartTokenizer:()=>ws,MPNetTokenizer:()=>Os,MarianTokenizer:()=>Qs,MgpstrTokenizer:()=>ps,MobileBertTokenizer:()=>us,NllbTokenizer:()=>fr,NougatTokenizer:()=>en,PreTrainedTokenizer:()=>nt,Qwen2Tokenizer:()=>ys,RoFormerTokenizer:()=>De,RobertaTokenizer:()=>Sr,SiglipTokenizer:()=>Xs,SpeechT5Tokenizer:()=>Zs,SqueezeBertTokenizer:()=>Wr,T5Tokenizer:()=>Or,TokenizerModel:()=>H,VitsTokenizer:()=>tn,Wav2Vec2CTCTokenizer:()=>Js,WhisperTokenizer:()=>Hs,XLMRobertaTokenizer:()=>vr,XLMTokenizer:()=>cr,is_chinese_char:()=>S});var s=t("./src/utils/generic.js"),n=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),a=t("./src/utils/maths.js"),i=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 u(ue,C){const W=await Promise.all([(0,o.getModelJSON)(ue,"tokenizer.json",!0,C),(0,o.getModelJSON)(ue,"tokenizer_config.json",!0,C)]);return C.legacy!==null&&(W[1].legacy=C.legacy),W}function d(ue,C){const W=[];let Z=0;for(const se of ue.matchAll(C)){const _e=se[0];Z0&&W.push(_e),Z=se.index+_e.length}return Z=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 E(ue,C,W){const Z=[];let se=0;for(;sethis.tokens_to_ids.get(W)??this.unk_token_id)}convert_ids_to_tokens(C){return C.map(W=>this.vocab[W]??this.unk_token)}}class q extends H{constructor(C){super(C),this.tokens_to_ids=_(C.vocab),this.unk_token_id=this.tokens_to_ids.get(C.unk_token),this.unk_token=C.unk_token,this.max_input_chars_per_word=C.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[W,Z]of this.tokens_to_ids)this.vocab[Z]=W}encode(C){const W=[];for(const Z of C){const se=[...Z];if(se.length>this.max_input_chars_per_word){W.push(this.unk_token);continue}let _e=!1,Se=0;const Ue=[];for(;Se0&&(Ve=this.config.continuing_subword_prefix+Ve),this.tokens_to_ids.has(Ve)){Ke=Ve;break}--Ge}if(Ke===null){_e=!0;break}Ue.push(Ke),Se=Ge}_e?W.push(this.unk_token):W.push(...Ue)}return W}}class L extends H{constructor(C,W){super(C);const Z=C.vocab.length;this.vocab=new Array(Z),this.scores=new Array(Z);for(let se=0;se[se,_e])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=W.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,a.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(C){const W=C.chars,Z=1;let se=0;for(;se{const ue=[...Array.from({length:94},(se,_e)=>_e+33),...Array.from({length:12},(se,_e)=>_e+161),...Array.from({length:82},(se,_e)=>_e+174)],C=ue.slice();let W=0;for(let se=0;se<256;++se)ue.includes(se)||(ue.push(se),C.push(256+W),W+=1);const Z=C.map(se=>String.fromCharCode(se));return Object.fromEntries(ue.map((se,_e)=>[se,Z[_e]]))})(),X=(0,n.reverseDictionary)(J);class Q extends H{constructor(C){super(C),this.tokens_to_ids=_(C.vocab),this.unk_token_id=this.tokens_to_ids.get(C.unk_token),this.unk_token=C.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[Z,se]of this.tokens_to_ids)this.vocab[se]=Z;const W=Array.isArray(C.merges[0]);this.merges=W?C.merges:C.merges.map(Z=>Z.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((Z,se)=>[JSON.stringify(Z),se])),this.end_of_word_suffix=C.end_of_word_suffix,this.continuing_subword_suffix=C.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(C){if(C.length===0)return[];const W=this.cache.get(C);if(W!==void 0)return W;const Z=Array.from(C);this.end_of_word_suffix&&(Z[Z.length-1]+=this.end_of_word_suffix);let se=[];if(Z.length>1){const _e=new l.PriorityQueue((Ge,Ke)=>Ge.score`<0x${Ue.toString(16).toUpperCase().padStart(2,"0")}>`);Se.every(Ue=>this.tokens_to_ids.has(Ue))?W.push(...Se):W.push(this.unk_token)}else W.push(this.unk_token)}return W}}class te extends H{constructor(C,W){super(C),this.tokens_to_ids=_(W.target_lang?C.vocab[W.target_lang]:C.vocab),this.bos_token=W.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=W.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=W.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=W.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[Z,se]of this.tokens_to_ids)this.vocab[se]=Z}encode(C){return C}}class re extends s.Callable{constructor(C){super(),this.config=C}static fromConfig(C){if(C===null)return null;switch(C.type){case"BertNormalizer":return new fe(C);case"Precompiled":return new It(C);case"Sequence":return new je(C);case"Replace":return new ce(C);case"NFC":return new N(C);case"NFD":return new F(C);case"NFKC":return new G(C);case"NFKD":return new R(C);case"Strip":return new ne(C);case"StripAccents":return new be(C);case"Lowercase":return new de(C);case"Prepend":return new ve(C);default:throw new Error(`Unknown Normalizer type: ${C.type}`)}}normalize(C){throw Error("normalize should be implemented in subclass.")}_call(C){return this.normalize(C)}}class ce extends re{normalize(C){const W=f(this.config.pattern);return W===null?C:C.replaceAll(W,this.config.content)}}class le extends re{form=void 0;normalize(C){return C=C.normalize(this.form),C}}class N extends le{form="NFC"}class F extends le{form="NFD"}class G extends le{form="NFKC"}class R extends le{form="NFKD"}class ne extends re{normalize(C){return this.config.strip_left&&this.config.strip_right?C=C.trim():(this.config.strip_left&&(C=C.trimStart()),this.config.strip_right&&(C=C.trimEnd())),C}}class be extends re{normalize(C){return C=M(C),C}}class de extends re{normalize(C){return C=C.toLowerCase(),C}}class ve extends re{normalize(C){return C=this.config.prepend+C,C}}class je extends re{constructor(C){super(C),this.normalizers=C.normalizers.map(W=>re.fromConfig(W))}normalize(C){return this.normalizers.reduce((W,Z)=>Z.normalize(W),C)}}class fe extends re{_tokenize_chinese_chars(C){const W=[];for(let Z=0;Zthis.pre_tokenize_text(Z,W)):this.pre_tokenize_text(C,W)).flat()}_call(C,W){return this.pre_tokenize(C,W)}}class U extends K{constructor(C){super(),this.pattern=new RegExp(`[^\\s${w}]+|[${w}]`,"gu")}pre_tokenize_text(C,W){return C.trim().match(this.pattern)||[]}}class pe extends K{constructor(C){super(),this.config=C,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=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=J,this.text_encoder=new TextEncoder}pre_tokenize_text(C,W){return this.add_prefix_space&&!C.startsWith(" ")&&(C=" "+C),(this.use_regex?C.match(this.pattern)||[]:[C]).map(se=>Array.from(this.text_encoder.encode(se),_e=>this.byte_encoder[_e]).join(""))}}class ye extends K{constructor(C){super(),this.config=C,this.pattern=f(this.config.pattern,this.config.invert)}pre_tokenize_text(C,W){return this.pattern===null?[]:this.config.invert?C.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?C.split(this.pattern).filter(Z=>Z):d(C,this.pattern)}}class xe extends K{constructor(C){super(),this.config=C,this.pattern=new RegExp(`[^${w}]+|[${w}]+`,"gu")}pre_tokenize_text(C,W){return C.match(this.pattern)||[]}}class Ce extends K{constructor(C){super(),this.config=C;const W=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(W,"gu")}pre_tokenize_text(C,W){return C.match(this.pattern)||[]}}class $e extends s.Callable{constructor(C){super(),this.config=C}static fromConfig(C){if(C===null)return null;switch(C.type){case"TemplateProcessing":return new Ne(C);case"ByteLevel":return new A(C);case"RobertaProcessing":return new Re(C);case"BertProcessing":return new Ae(C);case"Sequence":return new Y(C);default:throw new Error(`Unknown PostProcessor type: ${C.type}`)}}post_process(C,...W){throw Error("post_process should be implemented in subclass.")}_call(C,...W){return this.post_process(C,...W)}}class Ae extends $e{constructor(C){super(C),this.cls=C.cls[0],this.sep=C.sep[0]}post_process(C,W=null,{add_special_tokens:Z=!0}={}){Z&&(C=(0,n.mergeArrays)([this.cls],C,[this.sep]));let se=new Array(C.length).fill(0);if(W!==null){const _e=Z&&this instanceof Re?[this.sep]:[],Se=Z?[this.sep]:[];C=(0,n.mergeArrays)(C,_e,W,Se),se=(0,n.mergeArrays)(se,new Array(W.length+_e.length+Se.length).fill(1))}return{tokens:C,token_type_ids:se}}}class Re extends Ae{}class Ne extends $e{constructor(C){super(C),this.single=C.single,this.pair=C.pair}post_process(C,W=null,{add_special_tokens:Z=!0}={}){const se=W===null?this.single:this.pair;let _e=[],Se=[];for(const Ue of se)"SpecialToken"in Ue?Z&&(_e.push(Ue.SpecialToken.id),Se.push(Ue.SpecialToken.type_id)):"Sequence"in Ue&&(Ue.Sequence.id==="A"?(_e=(0,n.mergeArrays)(_e,C),Se=(0,n.mergeArrays)(Se,new Array(C.length).fill(Ue.Sequence.type_id))):Ue.Sequence.id==="B"&&(_e=(0,n.mergeArrays)(_e,W),Se=(0,n.mergeArrays)(Se,new Array(W.length).fill(Ue.Sequence.type_id))));return{tokens:_e,token_type_ids:Se}}}class A extends $e{post_process(C,W=null){return W&&(C=(0,n.mergeArrays)(C,W)),{tokens:C}}}class Y extends $e{constructor(C){super(C),this.processors=C.processors.map(W=>$e.fromConfig(W))}post_process(C,W=null,Z={}){let se;for(const _e of this.processors)if(_e instanceof A)C=_e.post_process(C).tokens,W&&(W=_e.post_process(W).tokens);else{const Se=_e.post_process(C,W,Z);C=Se.tokens,se=Se.token_type_ids}return{tokens:C,token_type_ids:se}}}class z extends s.Callable{constructor(C){super(),this.config=C,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=C.trim_offsets}static fromConfig(C){if(C===null)return null;switch(C.type){case"WordPiece":return new Fe(C);case"Metaspace":return new er(C);case"ByteLevel":return new Me(C);case"Replace":return new ee(C);case"ByteFallback":return new oe(C);case"Fuse":return new he(C);case"Strip":return new Ee(C);case"Sequence":return new st(C);case"CTC":return new ke(C);case"BPEDecoder":return new ut(C);default:throw new Error(`Unknown Decoder type: ${C.type}`)}}_call(C){return this.decode(C)}decode(C){return this.decode_chain(C).join("")}decode_chain(C){throw Error("`decode_chain` should be implemented in subclass.")}}class ee extends z{decode_chain(C){const W=f(this.config.pattern);return W===null?C:C.map(Z=>Z.replaceAll(W,this.config.content))}}class oe extends z{constructor(C){super(C),this.text_decoder=new TextDecoder}decode_chain(C){const W=[];let Z=[];for(const se of C){let _e=null;if(se.length===6&&se.startsWith("<0x")&&se.endsWith(">")){const Se=parseInt(se.slice(3,5),16);isNaN(Se)||(_e=Se)}if(_e!==null)Z.push(_e);else{if(Z.length>0){const Se=this.text_decoder.decode(Uint8Array.from(Z));W.push(Se),Z=[]}W.push(se)}}if(Z.length>0){const se=this.text_decoder.decode(Uint8Array.from(Z));W.push(se),Z=[]}return W}}class he extends z{decode_chain(C){return[C.join("")]}}class Ee extends z{constructor(C){super(C),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(C){return C.map(W=>{let Z=0;for(let _e=0;_e(Z!==0&&(W.startsWith(this.config.prefix)?W=W.replace(this.config.prefix,""):W=" "+W),this.cleanup&&(W=I(W)),W))}}class Me extends z{constructor(C){super(C),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(C){const W=C.join(""),Z=new Uint8Array([...W].map(_e=>this.byte_decoder[_e]));return this.text_decoder.decode(Z)}decode_chain(C){const W=[];let Z=[];for(const se of C)this.added_tokens.find(_e=>_e.content===se)!==void 0?(Z.length>0&&(W.push(this.convert_tokens_to_string(Z)),Z=[]),W.push(se)):Z.push(se);return Z.length>0&&W.push(this.convert_tokens_to_string(Z)),W}}class ke extends z{constructor(C){super(C),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(C){if(C.length===0)return"";const W=[C[0]];for(let _e=1;_e_e!==this.pad_token).join("");return this.cleanup&&(se=I(se).replaceAll(this.word_delimiter_token," ").trim()),se}decode_chain(C){return[this.convert_tokens_to_string(C)]}}class st extends z{constructor(C){super(C),this.decoders=C.decoders.map(W=>z.fromConfig(W))}decode_chain(C){return this.decoders.reduce((W,Z)=>Z.decode_chain(W),C)}}class ut extends z{constructor(C){super(C),this.suffix=this.config.suffix}decode_chain(C){return C.map((W,Z)=>W.replaceAll(this.suffix,Z===C.length-1?"":" "))}}class _t extends z{decode_chain(C){let W="";for(let Z=1;ZZ.normalize("NFKC")).join("~"):C=C.normalize("NFKC"),C}}class lr extends K{constructor(C){super(),this.tokenizers=C.pretokenizers.map(W=>K.fromConfig(W))}pre_tokenize_text(C,W){return this.tokenizers.reduce((Z,se)=>se.pre_tokenize(Z,W),[C])}}class as extends K{constructor(C){super()}pre_tokenize_text(C,W){return C.match(/\w+|[^\w\s]+/g)||[]}}class fs extends K{constructor(C){super()}pre_tokenize_text(C,W){return x(C)}}class Cr extends K{constructor(C){super(),this.config=C,this.pattern=f(this.config.pattern),this.content=this.config.content}pre_tokenize_text(C,W){return this.pattern===null?[C]:[C.replaceAll(this.pattern,this.config.content)]}}const $s=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function ls(ue,C,W,Z){for(const se of Object.keys(ue)){const _e=C-ue[se].length,Se=W(se),Ue=new Array(_e).fill(Se);ue[se]=Z==="right"?(0,n.mergeArrays)(ue[se],Ue):(0,n.mergeArrays)(Ue,ue[se])}}function gs(ue,C){for(const W of Object.keys(ue))ue[W].length=C}class nt extends s.Callable{return_token_type_ids=!1;padding_side="right";constructor(C,W){super(),this._tokenizer_config=W,this.normalizer=re.fromConfig(C.normalizer),this.pre_tokenizer=K.fromConfig(C.pre_tokenizer),this.model=H.fromConfig(C.model,W),this.post_processor=$e.fromConfig(C.post_processor),this.decoder=z.fromConfig(C.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const Z of C.added_tokens){const se=new B(Z);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=W.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(Z=>Z.content)),this.added_tokens_map=new Map(this.added_tokens.map(Z=>[Z.content,Z])),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=W.model_max_length,this.remove_space=W.remove_space,this.clean_up_tokenization_spaces=W.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=W.do_lowercase_and_remove_accent??!1,W.padding_side&&(this.padding_side=W.padding_side),this.legacy=!1,this.chat_template=W.chat_template??null,Array.isArray(this.chat_template)){const Z=Object.create(null);for(const{name:se,template:_e}of this.chat_template){if(typeof se!="string"||typeof _e!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');Z[se]=_e}this.chat_template=Z}this._compiled_template_cache=new Map}getToken(...C){for(const W of C){const Z=this._tokenizer_config[W];if(Z)if(typeof Z=="object"){if(Z.__type==="AddedToken")return Z.content;throw Error(`Unknown token: ${Z}`)}else return Z}return null}static async from_pretrained(C,{progress_callback:W=null,config:Z=null,cache_dir:se=null,local_files_only:_e=!1,revision:Se="main",legacy:Ue=null}={}){const Ge=await u(C,{progress_callback:W,config:Z,cache_dir:se,local_files_only:_e,revision:Se,legacy:Ue});return new this(...Ge)}_call(C,{text_pair:W=null,add_special_tokens:Z=!0,padding:se=!1,truncation:_e=null,max_length:Se=null,return_tensor:Ue=!0,return_token_type_ids:Ge=null}={}){const Ke=Array.isArray(C);let Ve;if(Ke){if(C.length===0)throw Error("text array must be non-empty");if(W!==null){if(Array.isArray(W)){if(C.length!==W.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Ve=C.map((lt,zt)=>this._encode_plus(lt,{text_pair:W[zt],add_special_tokens:Z,return_token_type_ids:Ge}))}else Ve=C.map(lt=>this._encode_plus(lt,{add_special_tokens:Z,return_token_type_ids:Ge}))}else{if(C==null)throw Error("text may not be null or undefined");if(Array.isArray(W))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Ve=[this._encode_plus(C,{text_pair:W,add_special_tokens:Z,return_token_type_ids:Ge})]}if(Se===null?se==="max_length"?Se=this.model_max_length:Se=(0,a.max)(Ve.map(lt=>lt.input_ids.length))[0]:_e||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."),Se=Math.min(Se,this.model_max_length??1/0),se||_e)for(let lt=0;ltSe?_e&&gs(Ve[lt],Se):se&&ls(Ve[lt],Se,zt=>zt==="input_ids"?this.pad_token_id:0,this.padding_side));const Mt={};if(Ue){if(!(se&&_e)&&Ve.some(zt=>{for(const rr of Object.keys(zt))if(zt[rr].length!==Ve[0][rr]?.length)return!0;return!1}))throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.");const lt=[Ve.length,Ve[0].input_ids.length];for(const zt of Object.keys(Ve[0]))Mt[zt]=new i.Tensor("int64",BigInt64Array.from(Ve.flatMap(rr=>rr[zt]).map(BigInt)),lt)}else{for(const lt of Object.keys(Ve[0]))Mt[lt]=Ve.map(zt=>zt[lt]);if(!Ke)for(const lt of Object.keys(Mt))Mt[lt]=Mt[lt][0]}return Mt}_encode_text(C){if(C===null)return null;const W=this.added_tokens_splitter.split(C);for(let se=0;se0&&(W[se-1]=W[se-1].trimEnd()),_e.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=g(se)),this.normalizer!==null&&(se=this.normalizer(se)),se.length===0)return[];const Se=this.pre_tokenizer!==null?this.pre_tokenizer(se,{section_index:_e}):[se];return this.model(Se)})}_encode_plus(C,{text_pair:W=null,add_special_tokens:Z=!0,return_token_type_ids:se=null}={}){const{tokens:_e,token_type_ids:Se}=this._tokenize_helper(C,{pair:W,add_special_tokens:Z}),Ue=this.model.convert_tokens_to_ids(_e),Ge={input_ids:Ue,attention_mask:new Array(Ue.length).fill(1)};return(se??this.return_token_type_ids)&&Se&&(Ge.token_type_ids=Se),Ge}_tokenize_helper(C,{pair:W=null,add_special_tokens:Z=!1}={}){const se=this._encode_text(C),_e=this._encode_text(W);return this.post_processor?this.post_processor(se,_e,{add_special_tokens:Z}):{tokens:(0,n.mergeArrays)(se??[],_e??[])}}tokenize(C,{pair:W=null,add_special_tokens:Z=!1}={}){return this._tokenize_helper(C,{pair:W,add_special_tokens:Z}).tokens}encode(C,{text_pair:W=null,add_special_tokens:Z=!0,return_token_type_ids:se=null}={}){return this._encode_plus(C,{text_pair:W,add_special_tokens:Z,return_token_type_ids:se}).input_ids}batch_decode(C,W={}){return C instanceof i.Tensor&&(C=C.tolist()),C.map(Z=>this.decode(Z,W))}decode(C,W={}){if(C instanceof i.Tensor&&(C=P(C)),!Array.isArray(C)||C.length===0||!(0,n.isIntegralNumber)(C[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(C,W)}decode_single(C,{skip_special_tokens:W=!1,clean_up_tokenization_spaces:Z=null}){let se=this.model.convert_ids_to_tokens(C);W&&(se=se.filter(Se=>!this.special_tokens.includes(Se)));let _e=this.decoder?this.decoder(se):se.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(_e=_e.replaceAll(this.decoder.end_of_word_suffix," "),W&&(_e=_e.trim())),(Z??this.clean_up_tokenization_spaces)&&(_e=I(_e)),_e}get_chat_template({chat_template:C=null,tools:W=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const Z=this.chat_template;if(C!==null&&Object.hasOwn(Z,C))C=Z[C];else if(C===null)if(W!==null&&"tool_use"in Z)C=Z.tool_use;else if("default"in Z)C=Z.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(Z).sort()}.`)}else if(C===null)if(this.chat_template)C=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 C}apply_chat_template(C,{tools:W=null,documents:Z=null,chat_template:se=null,add_generation_prompt:_e=!1,tokenize:Se=!0,padding:Ue=!1,truncation:Ge=!1,max_length:Ke=null,return_tensor:Ve=!0,return_dict:Mt=!1,tokenizer_kwargs:lt={},...zt}={}){if(se=this.get_chat_template({chat_template:se,tools:W}),typeof se!="string")throw Error(`chat_template must be a string, but got ${typeof se}`);let rr=this._compiled_template_cache.get(se);rr===void 0&&(rr=new c.Template(se),this._compiled_template_cache.set(se,rr));const Nt=Object.create(null);for(const Ot of $s){const Ht=this.getToken(Ot);Ht&&(Nt[Ot]=Ht)}const jt=rr.render({messages:C,add_generation_prompt:_e,tools:W,documents:Z,...Nt,...zt});if(Se){const Ot=this._call(jt,{add_special_tokens:!1,padding:Ue,truncation:Ge,max_length:Ke,return_tensor:Ve,...lt});return Mt?Ot:Ot.input_ids}return jt}}class Ur extends nt{return_token_type_ids=!0}class Tt extends nt{return_token_type_ids=!0}class us extends nt{return_token_type_ids=!0}class Wr extends nt{return_token_type_ids=!0}class Gr extends nt{return_token_type_ids=!0}class yr extends nt{return_token_type_ids=!0}class cs extends nt{return_token_type_ids=!0}class ur extends nt{return_token_type_ids=!0}class De extends nt{return_token_type_ids=!0}class He extends nt{}class Ye extends nt{}class cr extends nt{return_token_type_ids=!0;constructor(C,W){super(C,W),console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class ks extends nt{return_token_type_ids=!0}class Or extends nt{}class Is extends nt{}class As extends nt{}class ws extends nt{constructor(C,W){super(C,W),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(Z=>this.languageRegex.test(Z)),this.lang_to_token=Z=>Z}_build_translation_inputs(C,W,Z){return tr(this,C,W,Z)}}class Fs extends ws{}class Sr extends nt{}class Kr extends nt{}const _r="▁";class Ms extends nt{padding_side="left";constructor(C,W){super(C,W),this.legacy=W.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new gt({replacement:_r,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(C){if(C===null)return null;if(this.legacy||C.length===0)return super._encode_text(C);let W=super._encode_text(_r+C.replaceAll(_r," "));return W.length>1&&W[0]===_r&&this.special_tokens.includes(W[1])&&(W=W.slice(1)),W}}class bs extends nt{}class vr extends nt{}class Os extends nt{}class ds extends nt{}class $r extends nt{}class Ks extends nt{}class ys extends nt{}class xr extends nt{}class Dr extends nt{}function tr(ue,C,W,Z){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=Z.src_lang,_e=Z.tgt_lang;if(!ue.language_codes.includes(_e))throw new Error(`Target language code "${_e}" 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 Se of ue.post_processor.config.single)if("SpecialToken"in Se&&ue.languageRegex.test(Se.SpecialToken.id)){Se.SpecialToken.id=ue.lang_to_token(se);break}}return Z.forced_bos_token_id=ue.model.convert_tokens_to_ids([ue.lang_to_token(_e)])[0],ue._call(C,W)}class fr extends nt{constructor(C,W){super(C,W),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(Z=>this.languageRegex.test(Z)),this.lang_to_token=Z=>Z}_build_translation_inputs(C,W,Z){return tr(this,C,W,Z)}}class vs extends nt{constructor(C,W){super(C,W),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(Z=>this.languageRegex.test(Z)).map(Z=>Z.slice(2,-2)),this.lang_to_token=Z=>`__${Z}__`}_build_translation_inputs(C,W,Z){return tr(this,C,W,Z)}}class Hs extends nt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(C,{return_timestamps:W=!1,return_language:Z=!1,time_precision:se=null,force_full_sequences:_e=!0}={}){if(se===null)throw Error("Must specify time_precision");let Se=null;const Ue=W==="word";function Ge(){return{language:Se,timestamp:[null,null],text:""}}const Ke=[];let Ve=Ge(),Mt=0;const lt=this.timestamp_begin,rr=lt+1500;let Nt=[],jt=[],Ot=!1,Ht=null;const ms=new Set(this.all_special_ids);for(const Dt of C){const nr=Dt.tokens,dr=Ue?Dt.token_timestamps:null;let zr=null,Br=lt;if("stride"in Dt){const[or,Gt,Rt]=Dt.stride;if(Mt-=Gt,Ht=or-Rt,Gt&&(Br=Gt/se+lt),Rt)for(let Xt=nr.length-1;Xt>=0;--Xt){const ir=Number(nr[Xt]);if(ir>=lt){if(zr!==null&&(ir-lt)*se=lt&&Gt<=rr){const Rt=(Gt-lt)*se+Mt,Xt=(0,a.round)(Rt,2);if(zr!==null&&Gt>=zr)Ot=!0;else if(Ot||Nt.length>0&&Gt0?(Nt.push(qt),Ue&&jt.push(Tr)):Nt.every(or=>or.length===0)&&(Ve=Ge(),Nt=[],qt=[],jt=[],Tr=[])}if(Nt.length>0){if(_e&&W)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Dt,nr]=this.findLongestCommonSequence(Nt,jt),dr=this.decode(Dt);Ve.text=dr,Ue&&(Ve.words=this.collateWordTimestamps(Dt,nr,Se)),Ke.push(Ve)}let sr=Object.create(null);const Lr=Ke.map(Dt=>Dt.text).join("");if(W||Z){for(let Dt=0;Dt0;let Ue=Se?[]:null,Ge=Se?W[0]:null;for(let Ke=1;KeGt===Br[Rt]&&Ge[Lr+Rt]<=W[Ke][dr+Rt]).length:qt=nr.filter((Gt,Rt)=>Gt===Br[Rt]).length;const Tr=sr/1e4,or=qt/sr+Tr;qt>1&&or>Mt&&(Mt=or,lt=[Lr,Dt,dr,zr])}const[rr,Nt,jt,Ot]=lt,Ht=Math.floor((Nt+rr)/2),ms=Math.floor((Ot+jt)/2);_e.push(...Z.slice(0,Ht)),Z=Ve.slice(ms),se=Z.length,Se&&(Ue.push(...Ge.slice(0,Ht)),Ge=W[Ke].slice(ms))}return _e.push(...Z),Se?(Ue.push(...Ge),[_e,Ue]):[_e,[]]}collateWordTimestamps(C,W,Z){const[se,_e,Se]=this.combineTokensIntoWords(C,Z),Ue=[];for(let Ge=0;Ge=se){const Ue=((Se-se)*Z).toFixed(2);_e.push(`<|${Ue}|>`),_e.push([])}else _e[_e.length-1].push(Se);return _e=_e.map(Se=>typeof Se=="string"?Se:super.decode(Se,W)),_e.join("")}splitTokensOnUnicode(C){const W=this.decode(C,{decode_with_timestamps:!0}),Z="�",se=[],_e=[],Se=[];let Ue=[],Ge=[],Ke=0;for(let Ve=0;Ve=this.model.tokens_to_ids.get("<|endoftext|>"),rr=Ve.startsWith(" "),Nt=Ve.trim(),jt=Ge.test(Nt);if(zt||rr||jt||_e.length===0)_e.push(Ve),Se.push(Mt),Ue.push(lt);else{const Ot=_e.length-1;_e[Ot]+=Ve,Se[Ot].push(...Mt),Ue[Ot].push(...lt)}}return[_e,Se,Ue]}mergePunctuations(C,W,Z,se,_e){const Se=structuredClone(C),Ue=structuredClone(W),Ge=structuredClone(Z);let Ke=Se.length-2,Ve=Se.length-1;for(;Ke>=0;)Se[Ke].startsWith(" ")&&se.includes(Se[Ke].trim())?(Se[Ve]=Se[Ke]+Se[Ve],Ue[Ve]=(0,n.mergeArrays)(Ue[Ke],Ue[Ve]),Ge[Ve]=(0,n.mergeArrays)(Ge[Ke],Ge[Ve]),Se[Ke]="",Ue[Ke]=[],Ge[Ke]=[]):Ve=Ke,--Ke;for(Ke=0,Ve=1;VeMt),Ue.filter(Mt=>Mt.length>0),Ge.filter(Mt=>Mt.length>0)]}}class Hr extends nt{}class qs extends nt{}class Xs extends nt{}class Qs extends nt{constructor(C,W){super(C,W),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(Z=>this.languageRegex.test(Z)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(C){if(C===null)return null;const[W,...Z]=C.trim().split(this.languageRegex);if(Z.length===0)return super._encode_text(W);if(Z.length===2){const[se,_e]=Z;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(_e))}}}class Js extends nt{}class Ys extends nt{}class qr extends nt{}class Zs extends nt{}class en extends nt{}class tn extends nt{constructor(C,W){super(C,W),this.decoder=new _t({})}}class rn extends nt{}class ps extends nt{}class En{static TOKENIZER_CLASS_MAPPING={T5Tokenizer:Or,DistilBertTokenizer:He,CamembertTokenizer:Ye,DebertaTokenizer:Gr,DebertaV2Tokenizer:yr,BertTokenizer:Ur,HerbertTokenizer:cs,ConvBertTokenizer:ur,RoFormerTokenizer:De,XLMTokenizer:cr,ElectraTokenizer:ks,MobileBertTokenizer:us,SqueezeBertTokenizer:Wr,AlbertTokenizer:Tt,GPT2Tokenizer:Is,BartTokenizer:As,MBartTokenizer:ws,MBart50Tokenizer:Fs,RobertaTokenizer:Sr,WhisperTokenizer:Hs,CodeGenTokenizer:Hr,CLIPTokenizer:qs,SiglipTokenizer:Xs,MarianTokenizer:Qs,BloomTokenizer:Kr,NllbTokenizer:fr,M2M100Tokenizer:vs,LlamaTokenizer:Ms,CodeLlamaTokenizer:bs,XLMRobertaTokenizer:vr,MPNetTokenizer:Os,FalconTokenizer:ds,GPTNeoXTokenizer:$r,EsmTokenizer:Ks,Wav2Vec2CTCTokenizer:Js,BlenderbotTokenizer:Ys,BlenderbotSmallTokenizer:qr,SpeechT5Tokenizer:Zs,NougatTokenizer:en,VitsTokenizer:tn,Qwen2Tokenizer:ys,GemmaTokenizer:xr,Grok1Tokenizer:Dr,CohereTokenizer:rn,MgpstrTokenizer:ps,PreTrainedTokenizer:nt};static async from_pretrained(C,{progress_callback:W=null,config:Z=null,cache_dir:se=null,local_files_only:_e=!1,revision:Se="main",legacy:Ue=null}={}){const[Ge,Ke]=await u(C,{progress_callback:W,config:Z,cache_dir:se,local_files_only:_e,revision:Se,legacy:Ue}),Ve=Ke.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer";let Mt=this.TOKENIZER_CLASS_MAPPING[Ve];return Mt||(console.warn(`Unknown tokenizer class "${Ve}", attempting to construct from base class.`),Mt=nt),new Mt(Ge,Ke)}}},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>q,hamming:()=>d,hanning:()=>u,mel_filter_bank:()=>S,read_audio:()=>c,spectrogram:()=>$,window_function:()=>O});var s=t("./src/utils/hub.js"),n=t("./src/utils/maths.js"),o=t("./src/utils/core.js"),a=t("./src/env.js"),i=t("?7a2c"),l=t("./src/utils/tensor.js");async function c(L,J){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)(L)).arrayBuffer(),Q=new AudioContext({sampleRate:J});typeof J>"u"&&console.warn(`No sampling rate provided, using default of ${Q.sampleRate}Hz.`);const te=await Q.decodeAudioData(X);let re;if(te.numberOfChannels===2){const ce=Math.sqrt(2),le=te.getChannelData(0),N=te.getChannelData(1);re=new Float32Array(le.length);for(let F=0;F2595*Math.log10(1+L/700),kaldi:L=>1127*Math.log(1+L/700),slaney:(L,J=1e3,X=15,Q=27/Math.log(6.4))=>L>=J?X+Math.log(L/J)*Q:3*L/200};function _(L,J="htk"){const X=f[J];if(!X)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof L=="number"?X(L):L.map(Q=>X(Q))}const P={htk:L=>700*(10**(L/2595)-1),kaldi:L=>700*(Math.exp(L/1127)-1),slaney:(L,J=1e3,X=15,Q=Math.log(6.4)/27)=>L>=X?J*Math.exp(Q*(L-X)):200*L/3};function I(L,J="htk"){const X=P[J];if(!X)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof L=="number"?X(L):L.map(Q=>X(Q))}function M(L,J){const X=Float64Array.from({length:J.length-1},(ce,le)=>J[le+1]-J[le]),Q=Array.from({length:L.length},()=>new Array(J.length));for(let ce=0;cenew Array(L.length));for(let ce=0;ceL+Q*re)}function S(L,J,X,Q,te,re=null,ce="htk",le=!1){if(re!==null&&re!=="slaney")throw new Error('norm must be one of null or "slaney"');if(L<2)throw new Error(`Require num_frequency_bins: ${L} >= 2`);if(X>Q)throw new Error(`Require min_frequency: ${X} <= max_frequency: ${Q}`);const N=_(X,ce),F=_(Q,ce),G=g(N,F,J+2);let R=I(G,ce),ne;if(le){const de=te/((L-1)*2);ne=_(Float64Array.from({length:L},(ve,je)=>je*de),ce),R=G}else ne=g(0,Math.floor(te/2),L);const be=M(ne,R);if(re!==null&&re==="slaney")for(let de=0;dete)throw Error(`frame_length (${X}) may not be larger than fft_length (${te})`);if(ye!==X)throw new Error(`Length of the window (${ye}) must equal frame_length (${X})`);if(Q<=0)throw new Error("hop_length must be greater than zero");if(re===null&&G!==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(ce){if(le!=="reflect")throw new Error(`pad_mode="${le}" not implemented yet.`);const he=Math.floor((te-1)/2)+1;L=E(L,he,he)}let xe=Math.floor(1+Math.floor((L.length-X)/Q));fe!==null&&xexe?U&&(Ae=K):Ae=$e=K);const Re=new n.FFT(te),Ne=new Float64Array(te),A=new Float64Array(Re.outputBufferSize),Y=new Float32Array(Ce*Ae);for(let he=0;he<$e;++he){const Ee=he*Q,Fe=Math.min(L.length-Ee,X);Fe!==X&&Ne.fill(0,0,X);for(let Me=0;Me=1;--Me)Ne[Me]-=F*Ne[Me-1];Ne[0]*=1-F}for(let Me=0;MeMath.pow(le,.85));break;default:throw new Error(`Unknown window type ${J}.`)}if(X&&(ce=ce.subarray(0,L)),Q===null)return ce;if(L>Q)throw new Error(`Length of the window (${L}) may not be larger than frame_length (${Q})`);return ce}function B(L,J){let X=44;const Q=new ArrayBuffer(X+L.length*4),te=new DataView(Q);H(te,0,"RIFF"),te.setUint32(4,36+L.length*4,!0),H(te,8,"WAVE"),H(te,12,"fmt "),te.setUint32(16,16,!0),te.setUint16(20,3,!0),te.setUint16(22,1,!0),te.setUint32(24,J,!0),te.setUint32(28,J*4,!0),te.setUint16(32,4,!0),te.setUint16(34,32,!0),H(te,36,"data"),te.setUint32(40,L.length*4,!0);for(let re=0;re{let re=await te.arrayBuffer();i.writeFileSync(Q,Buffer.from(re))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await X(J,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:()=>a,PROCESSOR_NAME:()=>i});const s="https://github.com/huggingface/transformers.js/issues/new/choose",n="config.json",o="preprocessor_config.json",a=o,i="processor_config.json",l="chat_template.json",c="generation_config.json"},"./src/utils/core.js":(e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>c,calculateReflectOffset:()=>f,count:()=>M,dispatchCallback:()=>s,escapeRegExp:()=>o,isIntegralNumber:()=>i,isNullishDimension:()=>l,isTypedArray:()=>a,len:()=>I,mergeArrays:()=>u,pick:()=>P,pop:()=>p,product:()=>d,reverseDictionary:()=>n,saveBlob:()=>_});function s(g,S){g&&g(S)}function n(g){return Object.fromEntries(Object.entries(g).map(([S,E])=>[E,S]))}function o(g){return g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function a(g){return g?.prototype?.__proto__?.constructor?.name==="TypedArray"}function i(g){return Number.isInteger(g)||typeof g=="bigint"}function l(g){return g==null||g===-1}function c(g){const S=[];let E=g;for(;Array.isArray(E);)S.push(E.length),E=E[0];return S}function p(g,S,E=void 0){const x=g[S];if(x!==void 0)return delete g[S],x;if(E===void 0)throw Error(`Key ${S} does not exist in object.`);return E}function u(...g){return Array.prototype.concat.apply([],g)}function d(...g){return g.reduce((S,E)=>S.flatMap(x=>E.map(w=>[x,w])))}function f(g,S){return Math.abs((g+S)%(2*S)-S)}function _(g,S){const E=URL.createObjectURL(S),x=document.createElement("a");x.href=E,x.download=g,x.click(),x.remove(),URL.revokeObjectURL(E)}function P(g,S){return Object.assign({},...S.map(E=>{if(g[E]!==void 0)return{[E]:g[E]}}))}function I(g){let S=0;for(const E of g)++S;return S}function M(g,S){let E=0;for(const x of g)x===S&&++E;return E}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>n,DictionarySplitter:()=>l,LRUCache:()=>c,PriorityQueue:()=>s,TokenLattice:()=>a});class s{constructor(u=(f,_)=>f>_,d=1/0){this._heap=[],this._comparator=u,this._maxSize=d}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...u){return this.extend(u)}extend(u){for(const d of u)if(this.size0&&this._swap(0,d),this._heap.pop(),this._siftDown(),u}replace(u){const d=this.peek();return this._heap[0]=u,this._siftDown(),d}_parent(u){return(u+1>>>1)-1}_left(u){return(u<<1)+1}_right(u){return u+1<<1}_greater(u,d){return this._comparator(this._heap[u],this._heap[d])}_swap(u,d){const f=this._heap[u];this._heap[u]=this._heap[d],this._heap[d]=f}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(u){for(;u>0&&this._greater(u,this._parent(u));)this._swap(u,this._parent(u)),u=this._parent(u)}_siftDown(){let u=0;for(;this._left(u)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const _=new i(this.bosTokenId,0,0,0,0),P=new i(this.eosTokenId,1,this.len,0,0);this.nodes.push(_.clone()),this.nodes.push(P.clone()),this.beginNodes[this.len].push(P),this.endNodes[0].push(_)}insert(u,d,f,_){const P=this.nodes.length,I=new i(_,P,u,d,f);this.beginNodes[u].push(I),this.endNodes[u+d].push(I),this.nodes.push(I)}viterbi(){const u=this.len;let d=0;for(;d<=u;){if(this.beginNodes[d].length==0)return[];for(let M of this.beginNodes[d]){M.prev=null;let g=0,S=null;for(let E of this.endNodes[d]){const x=E.backtraceScore+M.score;(S===null||x>g)&&(S=E.clone(),g=x)}if(S!==null)M.prev=S,M.backtraceScore=g;else return[]}++d}const f=[],P=this.beginNodes[u][0].prev;if(P===null)return[];let I=P.clone();for(;I.prev!==null;)f.push(I.clone()),I=I.clone().prev.clone();return f.reverse(),f}piece(u){return this.chars.slice(u.pos,u.pos+u.length).join("")}tokens(){return this.viterbi().map(d=>this.piece(d))}tokenIds(){return this.viterbi().map(d=>d.tokenId)}}class i{constructor(u,d,f,_,P){this.tokenId=u,this.nodeId=d,this.pos=f,this.length=_,this.score=P,this.prev=null,this.backtraceScore=0}clone(){const u=new i(this.tokenId,this.nodeId,this.pos,this.length,this.score);return u.prev=this.prev,u.backtraceScore=this.backtraceScore,u}}class l{constructor(u){this.trie=this._buildTrie(u)}_buildTrie(u){const d=Object.create(null);for(const f of u){let _=d;for(let P=0;P_&&d.push(u.slice(_,P)),d.push(M),P+=M.length,_=P):++P}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:()=>a,DEFAULT_DEVICE_DTYPE_MAPPING:()=>i,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}}(),a=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),i=Object.freeze({[n.DEVICE_TYPES.wasm]:a.q8}),l=Object.freeze({[a.fp32]:"",[a.fp16]:"_fp16",[a.int8]:"_int8",[a.uint8]:"_uint8",[a.q8]:"_quantized",[a.q4]:"_q4",[a.q4f16]:"_q4f16",[a.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:()=>i,getFile:()=>f,getModelFile:()=>g,getModelJSON:()=>S});var s=t("?7a2c"),n=t("?a42a"),o=t("./src/env.js"),a=t("./src/utils/core.js");const i=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(v){if(this.filePath=v,this.headers=new Headers,this.exists=s.existsSync(v),this.exists){this.status=200,this.statusText="OK";let $=s.statSync(v);this.headers.set("content-length",$.size.toString()),this.updateContentType();const O=s.createReadStream(v);this.body=new ReadableStream({start(B){O.on("data",H=>B.enqueue(H)),O.on("end",()=>B.close()),O.on("error",H=>B.error(H))},cancel(){O.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const v=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[v]??"application/octet-stream")}clone(){let v=new c(this.filePath);return v.exists=this.exists,v.status=this.status,v.statusText=this.statusText,v.headers=new Headers(this.headers),v}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const v=await s.promises.readFile(this.filePath);return new Blob([v],{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(w,v=null,$=null){let O;try{O=new URL(w)}catch{return!1}return!(v&&!v.includes(O.protocol)||$&&!$.includes(O.hostname))}const u=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function d(w){return!(!u.test(w)||w.includes("..")||w.includes("--")||w.endsWith(".git")||w.endsWith(".ipynb"))}async function f(w){if(o.env.useFS&&!p(w,["http:","https:","blob:"]))return new c(w.toString());if(typeof process<"u"&&process?.release?.name==="node"){const v=!!xu?.TESTING_REMOTELY,$=o.env.version,O=new Headers;if(O.set("User-Agent",`transformers.js/${$}; is_ci/${v};`),p(w,["http:","https:"],["huggingface.co","hf.co"])){const H=xu?.HF_TOKEN??xu?.HF_ACCESS_TOKEN;H&&O.set("Authorization",`Bearer ${H}`)}return fetch(w,{headers:O})}else return fetch(w)}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 P(w,v,$){if(!$)return null;const O=_[w]??`Error (${w}) occurred while trying to load file`;throw Error(`${O}: "${v}".`)}class I{constructor(v){this.path=v}async match(v){let $=n.join(this.path,v),O=new c($);if(O.exists)return O}async put(v,$,O=void 0){let B=n.join(this.path,v);try{const H=$.headers.get("Content-Length"),q=parseInt(H??"0");let L=0;await s.promises.mkdir(n.dirname(B),{recursive:!0});const J=s.createWriteStream(B),X=$.body.getReader();for(;;){const{done:Q,value:te}=await X.read();if(Q)break;await new Promise((ce,le)=>{J.write(te,N=>{if(N){le(N);return}ce()})}),L+=te.length;const re=q?L/q*100:0;O?.({progress:re,loaded:L,total:q})}J.close()}catch(H){try{await s.promises.unlink(B)}catch{}throw H}}}async function M(w,...v){for(let $ of v)try{let O=await w.match($);if(O)return O}catch{continue}}async function g(w,v,$=!0,O={},B=!1){if(!o.env.allowLocalModels){if(O.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,a.dispatchCallback)(O.progress_callback,{status:"initiate",name:w,file:v});let H;if(!H&&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");H=o.env.customCache}if(!H&&o.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{H=await caches.open("transformers-cache")}catch(R){console.warn("An error occurred while opening the browser cache:",R)}}if(!H&&o.env.useFSCache){if(!o.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");H=new I(O.cache_dir??o.env.cacheDir)}const q=O.revision??"main",L=x(w,v),J=d(w),X=J?x(o.env.localModelPath,L):L,Q=x(o.env.remoteHost,o.env.remotePathTemplate.replaceAll("{model}",w).replaceAll("{revision}",encodeURIComponent(q)),v);let te;const re=H instanceof I?q==="main"?L:x(w,q,v):Q;let ce=!1,le;H&&(le=await M(H,X,re));const N=le!==void 0;if(le===void 0){if(o.env.allowLocalModels)if(p(L,["http:","https:"])){if(O.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${L}.`);if(!o.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${L}.`)}else try{le=await f(X),te=X}catch(ne){console.warn(`Unable to load from local path "${X}": "${ne}"`)}if(le===void 0||le.status===404){if(O.local_files_only||!o.env.allowRemoteModels){if($)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${X}".`);return null}if(!J)throw Error(`Local file missing at "${X}" and download aborted due to invalid model ID "${w}".`);if(le=await f(Q),le.status!==200)return P(le.status,Q,$);te=re}ce=H&&typeof Response<"u"&&le instanceof Response&&le.status===200}(0,a.dispatchCallback)(O.progress_callback,{status:"download",name:w,file:v});let F;if(!(o.apis.IS_NODE_ENV&&B)){let R;O.progress_callback?N&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(R=new Uint8Array(await le.arrayBuffer()),(0,a.dispatchCallback)(O.progress_callback,{status:"progress",name:w,file:v,progress:100,loaded:R.length,total:R.length})):R=await E(le,ne=>{(0,a.dispatchCallback)(O.progress_callback,{status:"progress",name:w,file:v,...ne})}):R=new Uint8Array(await le.arrayBuffer()),F=R}if(ce&&te&&await H.match(te)===void 0&&(F?await H.put(te,new Response(F,{headers:le.headers})).catch(R=>{console.warn(`Unable to add response to browser cache: ${R}.`)}):await H.put(te,le,O.progress_callback)),(0,a.dispatchCallback)(O.progress_callback,{status:"done",name:w,file:v}),F){if(!o.apis.IS_NODE_ENV&&B)throw new Error("Cannot return path in a browser environment.");return F}if(le instanceof c)return le.filePath;const G=await H?.match(te);if(G instanceof c)return G.filePath;if(G instanceof Response)return new Uint8Array(await G.arrayBuffer());if(typeof G=="string")return G;throw new Error("Unable to get model file path or buffer.")}async function S(w,v,$=!0,O={}){const B=await g(w,v,$,O,!1);if(B===null)return{};const q=new TextDecoder("utf-8").decode(B);return JSON.parse(q)}async function E(w,v){const $=w.headers.get("Content-Length");$===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let O=parseInt($??"0"),B=new Uint8Array(O),H=0;const q=w.body.getReader();async function L(){const{done:J,value:X}=await q.read();if(J)return;const Q=H+X.length;if(Q>O){O=Q;const re=new Uint8Array(O);re.set(B),B=re}B.set(X,H),H=Q;const te=H/O*100;return v({progress:te,loaded:H,total:O}),L()}return await L(),B}function x(...w){return w=w.map((v,$)=>($&&(v=v.replace(new RegExp("^/"),"")),$!==w.length-1&&(v=v.replace(new RegExp("/$"),"")),v)),w.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>_,load_image:()=>P});var s=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),o=t("./src/env.js"),a=t("./src/utils/tensor.js"),i=t("?2b25");let l,c,p;const u=o.apis.IS_BROWSER_ENV||o.apis.IS_WEBWORKER_ENV;if(u)l=(I,M)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(I,M)},p=self.createImageBitmap,c=self.ImageData;else if(i)p=async I=>{const g=(await I.metadata()).channels,{data:S,info:E}=await I.rotate().raw().toBuffer({resolveWithObject:!0}),x=new _(new Uint8ClampedArray(S),E.width,E.height,E.channels);return g!==void 0&&g!==E.channels&&x.convert(g),x};else throw new Error("Unable to load image processing library.");const d={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(M,g,S,E){this.data=M,this.width=g,this.height=S,this.channels=E}get size(){return[this.width,this.height]}static async read(M){if(M instanceof _)return M;if(typeof M=="string"||M instanceof URL)return await this.fromURL(M);if(M instanceof Blob)return await this.fromBlob(M);if(typeof HTMLCanvasElement<"u"&&M instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&M instanceof OffscreenCanvas)return this.fromCanvas(M);throw new Error(`Unsupported input type: ${typeof M}`)}static fromCanvas(M){if(!u)throw new Error("fromCanvas() is only supported in browser environments.");const S=M.getContext("2d").getImageData(0,0,M.width,M.height).data;return new _(S,M.width,M.height,4)}static async fromURL(M){const g=await(0,n.getFile)(M);if(g.status!==200)throw new Error(`Unable to read image from "${M}" (${g.status} ${g.statusText})`);const S=await g.blob();return this.fromBlob(S)}static async fromBlob(M){if(u){const g=await p(M),S=l(g.width,g.height).getContext("2d");return S.drawImage(g,0,0),new this(S.getImageData(0,0,g.width,g.height).data,g.width,g.height,4)}else{const g=i(await M.arrayBuffer());return await p(g)}}static fromTensor(M,g="CHW"){if(M.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${M.dims.length} dimensions.`);if(g==="CHW")M=M.transpose(1,2,0);else if(g!=="HWC")throw new Error(`Unsupported channel format: ${g}`);if(!(M.data instanceof Uint8ClampedArray||M.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${M.type}`);switch(M.dims[2]){case 1:case 2:case 3:case 4:return new _(M.data,M.dims[1],M.dims[0],M.dims[2]);default:throw new Error(`Unsupported number of channels: ${M.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const M=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let g=0,S=0;g=0?$=S:B=-S,E>=0?O=E:H=-E,v.drawImage(w,$,O,M,g,B,H,M,g),new _(v.getImageData(0,0,M,g).data,M,g,4).convert(x)}else{let x=this.toSharp();if(S>=0&&E>=0)x=x.extract({left:Math.floor(S),top:Math.floor(E),width:M,height:g});else if(S<=0&&E<=0){const w=Math.floor(-E),v=Math.floor(-S);x=x.extend({top:w,left:v,right:M-this.width-v,bottom:g-this.height-w})}else{let w=[0,0],v=0;E<0?(w[0]=Math.floor(-E),w[1]=g-this.height-w[0]):v=Math.floor(E);let $=[0,0],O=0;S<0?($[0]=Math.floor(-S),$[1]=M-this.width-$[0]):O=Math.floor(S),x=x.extend({top:w[0],bottom:w[1],left:$[0],right:$[1]}).extract({left:O,top:v,width:M,height:g})}return await p(x)}}async toBlob(M="image/png",g=1){if(!u)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:M,quality:g})}toTensor(M="CHW"){let g=new a.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(M!=="HWC")if(M==="CHW")g=g.permute(2,0,1);else throw new Error(`Unsupported channel format: ${M}`);return g}toCanvas(){if(!u)throw new Error("toCanvas() is only supported in browser environments.");const M=this.clone().rgba(),g=l(M.width,M.height),S=new c(M.data,M.width,M.height);return g.getContext("2d").putImageData(S,0,0),g}split(){const{data:M,width:g,height:S,channels:E}=this,x=M.constructor,w=M.length/E,v=Array.from({length:E},()=>new x(w));for(let $=0;$new _($,g,S,1))}_update(M,g,S,E=null){return this.data=M,this.width=g,this.height=S,E!==null&&(this.channels=E),this}clone(){return new _(this.data.slice(),this.width,this.height,this.channels)}convert(M){if(this.channels===M)return this;switch(M){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(M){if(u){if(o.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const g=M.split(".").pop().toLowerCase(),S=f.get(g)??"image/png",E=await this.toBlob(S);(0,s.saveBlob)(M,E)}else{if(o.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(M);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(u)throw new Error("toSharp() is only supported in server-side environments.");return i(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const P=_.read.bind(_)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>P,bankers_round:()=>g,cos_sim:()=>l,dot:()=>i,dynamic_time_warping:()=>S,interpolate_data:()=>s,log_softmax:()=>a,magnitude:()=>c,max:()=>u,medianFilter:()=>I,min:()=>p,permute_data:()=>n,round:()=>M,softmax:()=>o});function s(E,[x,w,v],[$,O],B="bilinear",H=!1){const q=O/v,L=$/w,J=new E.constructor($*O*x),X=w*v,Q=$*O;for(let te=0;te<$;++te)for(let re=0;re=0;--H)$[H]=q,v[H]=x[w[H]],q*=v[H];const O=w.map((H,q)=>$[w.indexOf(q)]),B=new E.constructor(E.length);for(let H=0;H=0;--L)q+=J%x[L]*O[L],J=Math.floor(J/x[L]);B[q]=E[H]}return[B,v]}function o(E){const x=u(E)[0],w=E.map(O=>Math.exp(O-x)),v=w.reduce((O,B)=>O+B,0);return w.map(O=>O/v)}function a(E){const x=u(E)[0];let w=0;for(let O=0;OO-x-v)}function i(E,x){let w=0;for(let v=0;vx+w*w,0))}function p(E){if(E.length===0)throw Error("Array must not be empty");let x=E[0],w=0;for(let v=1;vx&&(x=E[v],w=v);return[x,w]}function d(E){return E>0&&(E&E-1)===0}class f{constructor(x){if(this.size=x|0,this.size<=1||!d(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=x<<1,this.table=new Float64Array(this.size*2);for(let v=0;vv;v<<=1)++w;this._width=w%2===0?w-1:w,this._bitrev=new Int32Array(1<>>$&3)<>>1);for(let $=0;$>>1]=x[$];return v}toComplexArray(x,w){const v=w||this.createComplexArray();for(let $=0;$>>1],v[$+1]=0;return v}transform(x,w){if(x===w)throw new Error("Input and output buffers must be different");this._transform4(x,w,1)}realTransform(x,w){if(x===w)throw new Error("Input and output buffers must be different");this._realTransform4(x,w,1)}inverseTransform(x,w){if(x===w)throw new Error("Input and output buffers must be different");this._transform4(x,w,-1);for(let v=0;v>=2;B>=2;B>>=2){H=$/B<<1;const Q=H>>>2;for(q=0;q<$;q+=H){const te=q+Q-1;for(let re=q,ce=0;re>>1,B>>>1)}else for(q=0,L=0;q<$;q+=H,++L){const te=J[L];this._singleRealTransform4(w,x,q,te>>>1,B>>>1,v)}const X=this.table;for(B>>=2;B>=2;B>>=2){H=$/B<<1;const te=H>>>1,re=te>>>1,ce=re>>>1;for(q=0;q<$;q+=H)for(let le=0,N=0;le<=ce;le+=2,N+=B){const F=q+le,G=F+re,R=G+re,ne=R+re,be=x[F],de=x[F+1],ve=x[G],je=x[G+1],fe=x[R],K=x[R+1],U=x[ne],pe=x[ne+1],ye=be,xe=de,Ce=X[N],$e=v*X[N+1],Ae=ve*Ce-je*$e,Re=ve*$e+je*Ce,Ne=X[2*N],A=v*X[2*N+1],Y=fe*Ne-K*A,z=fe*A+K*Ne,ee=X[3*N],oe=v*X[3*N+1],he=U*ee-pe*oe,Ee=U*oe+pe*ee,Fe=ye+Y,Me=xe+z,ke=ye-Y,st=xe-z,ut=Ae+he,_t=Re+Ee,gt=v*(Ae-he),er=v*(Re-Ee);if(x[F]=Fe+ut,x[F+1]=Me+_t,x[G]=ke+er,x[G+1]=st-gt,le===0){x[R]=Fe-ut,x[R+1]=Me-_t;continue}if(le===ce)continue;const It=q+re-le,lr=q+te-le;x[It]=ke-v*er,x[It+1]=-st-v*gt,x[lr]=Fe-v*ut,x[lr+1]=-Me+v*_t}}const Q=$>>>1;for(let te=2;te>1;++J){const X=(J+1-x)**2/2,Q=Math.sqrt(q**2+L**2)**X,te=X*Math.atan2(L,q),re=2*J;O[re]=Q*Math.cos(te),O[re+1]=Q*Math.sin(te),B[re]=O[re],B[re+1]=-O[re+1]}this._slicedChirpBuffer=O.subarray(w,v),this._f=new f($>>1),this._f.transform(this._chirpBuffer,B)}_transform(x,w,v){const $=this._buffer1,O=this._buffer2,B=this._outBuffer1,H=this._outBuffer2,q=this._chirpBuffer,L=this._slicedChirpBuffer,J=this._a;if(v)for(let X=0;X>1,re=w[te];$[X]=re*L[X],$[Q]=re*L[Q]}else for(let X=0;X=E.length&&(q=2*(E.length-1)-q),v[B++]=E[q]}v.sort(),w[O]=v[$]}return w}function M(E,x){const w=Math.pow(10,x);return Math.round(E*w)/w}function g(E){const x=Math.round(E);return Math.abs(E)%1===.5?x%2===0?x:x-1:x}function S(E){const x=E.length,w=E[0].length,v=[x+1,w+1],$=Array.from({length:v[0]},()=>Array(v[1]).fill(1/0));$[0][0]=0;const O=Array.from({length:v[0]},()=>Array(v[1]).fill(-1));for(let J=1;J0||H>0;)switch(q.push(B-1),L.push(H-1),O[B][H]){case 0:--B,--H;break;case 1:--B;break;case 2:--H;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${B}, ${H}]. Please file a bug report.`)}return q.reverse(),L.reverse(),[q,L]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>a,Tensor:()=>i,cat:()=>w,full:()=>L,full_like:()=>J,interpolate:()=>p,interpolate_4d:()=>u,layer_norm:()=>g,matmul:()=>d,mean:()=>B,mean_pooling:()=>M,ones:()=>X,ones_like:()=>Q,permute:()=>c,quantize_embeddings:()=>le,rand:()=>ce,rfft:()=>f,slice:()=>I,stack:()=>v,std_mean:()=>O,topk:()=>_,zeros:()=>te,zeros_like:()=>re});var s=t("./src/utils/maths.js"),n=t("./src/backends/onnx.js"),o=t("./src/ops/registry.js");const a=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 i{get dims(){return this.ort_tensor.dims}set dims(F){this.ort_tensor.dims=F}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...F){return(0,n.isONNXTensor)(F[0])?this.ort_tensor=F[0]:this.ort_tensor=new n.Tensor(F[0],F[1],F[2]),new Proxy(this,{get:(G,R)=>{if(typeof R=="string"){let ne=Number(R);if(Number.isInteger(ne))return G._getitem(ne)}return G[R]},set:(G,R,ne)=>G[R]=ne})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[F,...G]=this.dims;if(G.length>0){const R=G.reduce((ne,be)=>ne*be);for(let ne=0;ne0){const ne=R.reduce((be,de)=>be*de);return this._subarray(F,ne,R)}else return new i(this.type,[this.data[F]],R)}indexOf(F){const G=this.data;for(let R=0;Rpe)throw new Error(`Invalid slice: ${K}`);const ye=[Math.max(U,0),Math.min(pe,this.dims[fe])];R.push(ye),G.push(ye[1]-ye[0])}else throw new Error(`Invalid slice: ${K}`)}const ne=R.map(([fe,K])=>K-fe),be=ne.reduce((fe,K)=>fe*K),de=this.data,ve=new de.constructor(be),je=this.stride();for(let fe=0;fe=0;--U){const ye=ne[U];K+=(pe%ye+R[U][0])*je[U],pe=Math.floor(pe/ye)}ve[fe]=de[K]}return new i(this.type,ve,G)}permute(...F){return c(this,F)}transpose(...F){return this.permute(...F)}sum(F=null,G=!1){return this.norm(1,F,G)}norm(F="fro",G=null,R=!1){if(F==="fro")F=2;else if(typeof F=="string")throw Error(`Unsupported norm: ${F}`);const ne=this.data,be=(fe,K)=>fe+K**F;if(G===null){const fe=ne.reduce(be,0)**(1/F);return new i(this.type,[fe],[])}const[de,ve,je]=$(be,this,G,R);if(F!==1)for(let fe=0;fe=0;--je){const U=this.dims[je];if(je!==G){const pe=fe%U;ve+=pe*K,K*=this.dims[je]}fe=Math.floor(fe/U)}ne[de]/=be[ve]}return this}normalize(F=2,G=1){return this.clone().normalize_(F,G)}stride(){return H(this.dims)}squeeze(F=null){return new i(this.type,this.data,S(this.dims,F))}squeeze_(F=null){return this.dims=S(this.dims,F),this}unsqueeze(F=null){return new i(this.type,this.data,E(this.dims,F))}unsqueeze_(F=null){return this.dims=E(this.dims,F),this}flatten_(F=0,G=-1){G=(G+this.dims.length)%this.dims.length;let R=this.dims.slice(0,F),ne=this.dims.slice(F,G+1),be=this.dims.slice(G+1);return this.dims=[...R,ne.reduce((de,ve)=>de*ve,1),...be],this}flatten(F=0,G=-1){return this.clone().flatten_(F,G)}view(...F){let G=-1;for(let ne=0;neve!==G?be*de:be,1);F[G]=R.length/ne}return new i(this.type,R,F)}neg_(){const F=this.data;for(let G=0;GF?1:0;return new i("bool",G,this.dims)}lt(F){const G=new Uint8Array(this.data.length),R=this.data;for(let ne=0;neMath.min(de,ve),this,F,G,1/0);return new i(R,ne,be)}max(F=null,G=!1){if(F===null){const de=(0,s.max)(this.data)[0];return new i(this.type,[de],[])}const[R,ne,be]=$((de,ve)=>Math.max(de,ve),this,F,G,-1/0);return new i(R,ne,be)}argmin(F=null,G=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const R=(0,s.min)(this.data)[1];return new i("int64",[BigInt(R)],[])}argmax(F=null,G=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const R=(0,s.max)(this.data)[1];return new i("int64",[BigInt(R)],[])}to(F){if(this.type===F)return this;if(!a.hasOwnProperty(F))throw new Error(`Unsupported type: ${F}`);let G;const R=["int64","uint64"].includes(this.type),ne=["int64","uint64"].includes(F);return R&&!ne?G=Number:!R&&ne&&(G=BigInt),new i(F,a[F].from(this.data,G),this.dims)}}function l(N,F){const G=N.length,R=F.reduce((be,de)=>be*de);if(G!==R)throw Error(`cannot reshape array of size ${G} into shape (${F})`);let ne=N;for(let be=F.length-1;be>=0;be--)ne=ne.reduce((de,ve)=>{let je=de[de.length-1];return je.lengthnew i("int64",N,[N.length]);async function I(N,F,G,R,ne){return await(await o.TensorOpRegistry.slice)({x:N,s:P(F),e:P(G),a:P(R),t:P(ne??new Array(R.length).fill(1))})}function M(N,F){const G=N.data,R=F.data,ne=[N.dims[0],N.dims[2]],be=new G.constructor(ne[0]*ne[1]),[de,ve,je]=N.dims;let fe=0;for(let K=0;KG!==1):typeof F=="number"?N[F]===1&&N.splice(F,1):Array.isArray(F)&&(N=N.filter((G,R)=>G!==1||!F.includes(R))),N}function E(N,F){return F=x(F,N.length+1),N=N.slice(),N.splice(F,0,1),N}function x(N,F,G=null,R=!0){if(N<-F||N>=F){if(R)throw new Error(`IndexError: index ${N} is out of bounds for dimension${G===null?"":" "+G} with size ${F}`);return N<-F?0:F}return N<0&&(N=(N%F+F)%F),N}function w(N,F=0){F=x(F,N[0].dims.length);const G=N[0].dims.slice();G[F]=N.reduce((de,ve)=>de+ve.dims[F],0);const R=G.reduce((de,ve)=>de*ve,1),ne=new N[0].data.constructor(R),be=N[0].type;if(F===0){let de=0;for(const ve of N){const je=ve.data;ne.set(je,de),de+=je.length}}else{let de=0;for(let ve=0;ve=0;--pe){const Ce=fe[pe];let $e=ye%Ce;pe===F&&($e+=de),U+=$e*xe,xe*=G[pe],ye=Math.floor(ye/Ce)}ne[U]=je[K]}de+=fe[F]}}return new i(be,ne,G)}function v(N,F=0){return w(N.map(G=>G.unsqueeze(F)),F)}function $(N,F,G=null,R=!1,ne=null){const be=F.data,de=F.dims;G=x(G,de.length);const ve=de.slice();ve[G]=1;const je=new be.constructor(be.length/de[G]);ne!==null&&je.fill(ne);for(let fe=0;fe=0;--U){const xe=de[U];if(U!==G){const Ce=pe%xe;K+=Ce*ye,ye*=ve[U]}pe=Math.floor(pe/xe)}je[K]=N(je[K],be[fe],fe,K)}return R||ve.splice(G,1),[F.type,je,ve]}function O(N,F=null,G=1,R=!1){const ne=N.data,be=N.dims;if(F===null){const ye=ne.reduce((Ae,Re)=>Ae+Re,0)/ne.length,xe=Math.sqrt(ne.reduce((Ae,Re)=>Ae+(Re-ye)**2,0)/(ne.length-G)),Ce=new i(N.type,[ye],[]);return[new i(N.type,[xe],[]),Ce]}F=x(F,be.length);const de=B(N,F,R),ve=de.data,[je,fe,K]=$((pe,ye,xe,Ce)=>pe+(ye-ve[Ce])**2,N,F,R);for(let pe=0;pefe+K,0);return new i(N.type,[je/ne.length],[])}F=x(F,R.length);const[be,de,ve]=$((je,fe)=>je+fe,N,F,G);if(R[F]!==1)for(let je=0;je=0;--G)F[G]=R,R*=N[G];return F}function q(N,F,G,R){const ne=N.reduce((be,de)=>be*de,1);return new i(G,new R(ne).fill(F),N)}function L(N,F){let G,R;if(typeof F=="number")G="float32",R=Float32Array;else if(typeof F=="bigint")G="int64",R=BigInt64Array;else if(typeof F=="boolean")G="bool",R=Uint8Array;else throw new Error(`Unsupported data type: ${typeof F}`);return q(N,F,G,R)}function J(N,F){return L(N.dims,F)}function X(N){return q(N,1n,"int64",BigInt64Array)}function Q(N){return X(N.dims)}function te(N){return q(N,0n,"int64",BigInt64Array)}function re(N){return te(N.dims)}function ce(N){const F=N.reduce((G,R)=>G*R,1);return new i("float32",Float32Array.from({length:F},()=>Math.random()),N)}function le(N,F){if(N.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(N.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(F))throw new Error("The precision must be either 'binary' or 'ubinary'");const G=F==="binary",R=G?"int8":"uint8",ne=G?Int8Array:Uint8Array,be=N.data,de=new ne(be.length/8);for(let ve=0;ve0?1:0,fe=Math.floor(ve/8),K=ve%8;de[fe]|=je<<7-K,G&&K===0&&(de[fe]-=128)}return new i(R,de,[N.dims[0],N.dims[1]/8])}},"./src/utils/video.js":(e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>a,RawVideoFrame:()=>o,load_video:()=>i});var s=t("./src/utils/image.js"),n=t("./src/env.js");class o{constructor(c,p){this.image=c,this.timestamp=p}}class a{constructor(c,p){c.length>0&&c[0]instanceof s.RawImage&&(c=c.map((u,d)=>new o(u,(d+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 i(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 u=[],d=document.createElement("video");if(d.crossOrigin="anonymous",d.muted=!0,typeof l=="string")d.src=l;else if(l instanceof Blob)d.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)d.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(S=>d.onloadedmetadata=S),d.seekable.start(0)===d.seekable.end(0)){const E=await(await fetch(d.src)).blob();d.src=URL.createObjectURL(E),await new Promise(x=>d.onloadedmetadata=x)}const f=d.duration;let _,P;c!=null?(_=c,P=c===1?0:f/(c-1)):(P=1/p,_=Math.floor(f/P));let I=[];for(let S=0;S<_;++S)I.push(c===1?f/2:S*P);const M=document.createElement("canvas");M.width=d.videoWidth,M.height=d.videoHeight;const g=M.getContext("2d",{willReadFrequently:!0});for(const S of I){d.currentTime=S,await new Promise(v=>{d.onseeked=v}),g.drawImage(d,0,0,M.width,M.height);const E=g.getImageData(0,0,M.width,M.height),x=new s.RawImage(E.data,M.width,M.height,4),w=new o(x,S);u.push(w)}return d.remove(),new a(u,f)}}},Mw={};function Et(e){var r=Mw[e];if(r!==void 0)return r.exports;var t=Mw[e]={exports:{}};return Wx[e](t,t.exports,Et),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;Et.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);Et.r(n);var o={};r=r||[null,e({}),e([]),e(e)];for(var a=s&2&&t;typeof a=="object"&&!~r.indexOf(a);a=e(a))Object.getOwnPropertyNames(a).forEach(i=>o[i]=()=>t[i]);return o.default=()=>t,Et.d(n,o),n}})();Et.d=(e,r)=>{for(var t in r)Et.o(r,t)&&!Et.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})};Et.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);Et.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var h={};(()=>{/*!*****************************!*\ !*** ./src/transformers.js ***! \*****************************/Et.r(h),Et.d(h,{ASTFeatureExtractor:()=>u.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,AudioClassificationPipeline:()=>r.AudioClassificationPipeline,AutoConfig:()=>n.AutoConfig,AutoFeatureExtractor:()=>d.AutoFeatureExtractor,AutoImageProcessor:()=>P.AutoImageProcessor,AutoModel:()=>t.AutoModel,AutoModelForAudioClassification:()=>t.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>t.AutoModelForAudioFrameClassification,AutoModelForAudioTextToText:()=>t.AutoModelForAudioTextToText,AutoModelForCTC:()=>t.AutoModelForCTC,AutoModelForCausalLM:()=>t.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>t.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>t.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>t.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>t.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>t.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>t.AutoModelForImageSegmentation,AutoModelForImageTextToText:()=>t.AutoModelForImageTextToText,AutoModelForImageToImage:()=>t.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>t.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>t.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>t.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>t.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>t.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>t.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>t.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>t.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>t.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>t.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>t.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>t.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>t.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>t.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>t.AutoModelForVision2Seq,AutoModelForXVector:()=>t.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>t.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>g.AutoProcessor,AutoTokenizer:()=>s.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>r.AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline:()=>r.BackgroundRemovalPipeline,BartForConditionalGeneration:()=>t.BartForConditionalGeneration,BartForSequenceClassification:()=>t.BartForSequenceClassification,BartModel:()=>t.BartModel,BartPretrainedModel:()=>t.BartPretrainedModel,BartTokenizer:()=>s.BartTokenizer,BaseModelOutput:()=>t.BaseModelOutput,BaseStreamer:()=>S.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:()=>u.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>x.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,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:()=>u.DacFeatureExtractor,DacModel:()=>t.DacModel,DacPreTrainedModel:()=>t.DacPreTrainedModel,DataTypeMap:()=>l.DataTypeMap,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>s.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>s.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>_.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>_.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>r.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>_.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>_.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>s.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>r.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>_.DonutFeatureExtractor,DonutImageProcessor:()=>_.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>_.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>s.ElectraTokenizer,EncodecFeatureExtractor:()=>u.EncodecFeatureExtractor,EosTokenCriteria:()=>E.EosTokenCriteria,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>s.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>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:()=>M.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>x.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>x.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,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>s.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>M.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:()=>M.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>u.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>f.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>E.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>_.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>M.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>_.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LogitsProcessor:()=>x.LogitsProcessor,LogitsProcessorList:()=>x.LogitsProcessorList,LogitsWarper:()=>x.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,Mask2FormerImageProcessor:()=>_.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>_.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>_.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>E.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>M.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>x.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>x.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>_.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>_.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>_.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>_.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>_.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>_.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>_.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>_.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>_.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>_.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>u.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>M.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NllbTokenizer:()=>s.NllbTokenizer,NoBadWordsLogitsProcessor:()=>x.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>x.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:()=>M.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>_.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>M.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>_.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>M.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,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:()=>u.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>M.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:()=>M.Qwen2VLProcessor,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:()=>a.RawImage,RawVideo:()=>i.RawVideo,RawVideoFrame:()=>i.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>x.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>s.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>s.RobertaTokenizer,SamImageProcessor:()=>_.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>M.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>u.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,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>_.SmolVLMImageProcessor,SmolVLMProcessor:()=>M.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>u.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>u.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>M.SpeechT5Processor,SpeechT5Tokenizer:()=>s.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>s.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>E.StoppingCriteria,StoppingCriteriaList:()=>E.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>x.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:()=>x.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>S.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>x.TopKLogitsWarper,TopPLogitsWarper:()=>x.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>M.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:()=>M.VLChatProcessor,VLMImageProcessor:()=>_.VLMImageProcessor,ViTFeatureExtractor:()=>_.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>_.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>_.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>_.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>s.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>u.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>M.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>M.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>u.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>u.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>M.WhisperProcessor,WhisperTextStreamer:()=>S.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>x.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,getKeyValueShapes:()=>n.getKeyValueShapes,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:()=>a.load_image,load_video:()=>i.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,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=Et("./src/env.js"),r=Et("./src/pipelines.js"),t=Et("./src/models.js"),s=Et("./src/tokenizers.js"),n=Et("./src/configs.js"),o=Et("./src/utils/audio.js"),a=Et("./src/utils/image.js"),i=Et("./src/utils/video.js"),l=Et("./src/utils/tensor.js"),c=Et("./src/utils/maths.js"),p=Et("./src/base/feature_extraction_utils.js"),u=Et("./src/models/feature_extractors.js"),d=Et("./src/models/auto/feature_extraction_auto.js"),f=Et("./src/base/image_processors_utils.js"),_=Et("./src/models/image_processors.js"),P=Et("./src/models/auto/image_processing_auto.js"),I=Et("./src/base/processing_utils.js"),M=Et("./src/models/processors.js"),g=Et("./src/models/auto/processing_auto.js"),S=Et("./src/generation/streamers.js"),E=Et("./src/generation/stopping_criteria.js"),x=Et("./src/generation/logits_process.js")})();h.ASTFeatureExtractor;h.ASTForAudioClassification;h.ASTModel;h.ASTPreTrainedModel;h.AlbertForMaskedLM;h.AlbertForQuestionAnswering;h.AlbertForSequenceClassification;h.AlbertModel;h.AlbertPreTrainedModel;h.AlbertTokenizer;h.AudioClassificationPipeline;h.AutoConfig;h.AutoFeatureExtractor;h.AutoImageProcessor;h.AutoModel;h.AutoModelForAudioClassification;h.AutoModelForAudioFrameClassification;h.AutoModelForAudioTextToText;h.AutoModelForCTC;h.AutoModelForCausalLM;h.AutoModelForDepthEstimation;h.AutoModelForDocumentQuestionAnswering;h.AutoModelForImageClassification;h.AutoModelForImageFeatureExtraction;h.AutoModelForImageMatting;h.AutoModelForImageSegmentation;h.AutoModelForImageTextToText;h.AutoModelForImageToImage;h.AutoModelForMaskGeneration;h.AutoModelForMaskedLM;h.AutoModelForNormalEstimation;h.AutoModelForObjectDetection;h.AutoModelForPoseEstimation;h.AutoModelForQuestionAnswering;h.AutoModelForSemanticSegmentation;h.AutoModelForSeq2SeqLM;h.AutoModelForSequenceClassification;h.AutoModelForSpeechSeq2Seq;h.AutoModelForTextToSpectrogram;h.AutoModelForTextToWaveform;h.AutoModelForTokenClassification;h.AutoModelForUniversalSegmentation;h.AutoModelForVision2Seq;h.AutoModelForXVector;h.AutoModelForZeroShotObjectDetection;h.AutoProcessor;h.AutoTokenizer;h.AutomaticSpeechRecognitionPipeline;h.BackgroundRemovalPipeline;h.BartForConditionalGeneration;h.BartForSequenceClassification;h.BartModel;h.BartPretrainedModel;h.BartTokenizer;h.BaseModelOutput;h.BaseStreamer;h.BeitFeatureExtractor;h.BeitForImageClassification;h.BeitModel;h.BeitPreTrainedModel;h.BertForMaskedLM;h.BertForQuestionAnswering;h.BertForSequenceClassification;h.BertForTokenClassification;h.BertModel;h.BertPreTrainedModel;h.BertTokenizer;h.BitImageProcessor;h.BlenderbotForConditionalGeneration;h.BlenderbotModel;h.BlenderbotPreTrainedModel;h.BlenderbotSmallForConditionalGeneration;h.BlenderbotSmallModel;h.BlenderbotSmallPreTrainedModel;h.BlenderbotSmallTokenizer;h.BlenderbotTokenizer;h.BloomForCausalLM;h.BloomModel;h.BloomPreTrainedModel;h.BloomTokenizer;h.CLIPFeatureExtractor;h.CLIPImageProcessor;h.CLIPModel;h.CLIPPreTrainedModel;h.CLIPSegForImageSegmentation;h.CLIPSegModel;h.CLIPSegPreTrainedModel;h.CLIPTextModel;h.CLIPTextModelWithProjection;h.CLIPTokenizer;h.CLIPVisionModel;h.CLIPVisionModelWithProjection;h.CamembertForMaskedLM;h.CamembertForQuestionAnswering;h.CamembertForSequenceClassification;h.CamembertForTokenClassification;h.CamembertModel;h.CamembertPreTrainedModel;h.CamembertTokenizer;h.CausalLMOutput;h.CausalLMOutputWithPast;h.ChineseCLIPFeatureExtractor;h.ChineseCLIPModel;h.ChineseCLIPPreTrainedModel;h.ClapAudioModelWithProjection;h.ClapFeatureExtractor;h.ClapModel;h.ClapPreTrainedModel;h.ClapTextModelWithProjection;h.ClassifierFreeGuidanceLogitsProcessor;h.CodeGenForCausalLM;h.CodeGenModel;h.CodeGenPreTrainedModel;h.CodeGenTokenizer;h.CodeLlamaTokenizer;h.CohereForCausalLM;h.CohereModel;h.CoherePreTrainedModel;h.CohereTokenizer;h.ConvBertForMaskedLM;h.ConvBertForQuestionAnswering;h.ConvBertForSequenceClassification;h.ConvBertForTokenClassification;h.ConvBertModel;h.ConvBertPreTrainedModel;h.ConvBertTokenizer;h.ConvNextFeatureExtractor;h.ConvNextForImageClassification;h.ConvNextImageProcessor;h.ConvNextModel;h.ConvNextPreTrainedModel;h.ConvNextV2ForImageClassification;h.ConvNextV2Model;h.ConvNextV2PreTrainedModel;h.DPTFeatureExtractor;h.DPTForDepthEstimation;h.DPTImageProcessor;h.DPTModel;h.DPTPreTrainedModel;h.DacDecoderModel;h.DacDecoderOutput;h.DacEncoderModel;h.DacEncoderOutput;h.DacFeatureExtractor;h.DacModel;h.DacPreTrainedModel;h.DataTypeMap;h.DebertaForMaskedLM;h.DebertaForQuestionAnswering;h.DebertaForSequenceClassification;h.DebertaForTokenClassification;h.DebertaModel;h.DebertaPreTrainedModel;h.DebertaTokenizer;h.DebertaV2ForMaskedLM;h.DebertaV2ForQuestionAnswering;h.DebertaV2ForSequenceClassification;h.DebertaV2ForTokenClassification;h.DebertaV2Model;h.DebertaV2PreTrainedModel;h.DebertaV2Tokenizer;h.DecisionTransformerModel;h.DecisionTransformerPreTrainedModel;h.DeiTFeatureExtractor;h.DeiTForImageClassification;h.DeiTImageProcessor;h.DeiTModel;h.DeiTPreTrainedModel;h.DepthAnythingForDepthEstimation;h.DepthAnythingPreTrainedModel;h.DepthEstimationPipeline;h.DepthProForDepthEstimation;h.DepthProPreTrainedModel;h.DetrFeatureExtractor;h.DetrForObjectDetection;h.DetrForSegmentation;h.DetrImageProcessor;h.DetrModel;h.DetrObjectDetectionOutput;h.DetrPreTrainedModel;h.DetrSegmentationOutput;h.Dinov2ForImageClassification;h.Dinov2Model;h.Dinov2PreTrainedModel;h.Dinov2WithRegistersForImageClassification;h.Dinov2WithRegistersModel;h.Dinov2WithRegistersPreTrainedModel;h.DistilBertForMaskedLM;h.DistilBertForQuestionAnswering;h.DistilBertForSequenceClassification;h.DistilBertForTokenClassification;h.DistilBertModel;h.DistilBertPreTrainedModel;h.DistilBertTokenizer;h.DocumentQuestionAnsweringPipeline;h.DonutFeatureExtractor;h.DonutImageProcessor;h.DonutSwinModel;h.DonutSwinPreTrainedModel;h.EfficientNetForImageClassification;h.EfficientNetImageProcessor;h.EfficientNetModel;h.EfficientNetPreTrainedModel;h.ElectraForMaskedLM;h.ElectraForQuestionAnswering;h.ElectraForSequenceClassification;h.ElectraForTokenClassification;h.ElectraModel;h.ElectraPreTrainedModel;h.ElectraTokenizer;h.EncodecFeatureExtractor;h.EosTokenCriteria;h.EsmForMaskedLM;h.EsmForSequenceClassification;h.EsmForTokenClassification;h.EsmModel;h.EsmPreTrainedModel;h.EsmTokenizer;h.ExaoneForCausalLM;h.ExaoneModel;h.ExaonePreTrainedModel;h.FFT;h.FalconForCausalLM;h.FalconModel;h.FalconPreTrainedModel;h.FalconTokenizer;h.FastViTForImageClassification;h.FastViTModel;h.FastViTPreTrainedModel;h.FeatureExtractionPipeline;h.FeatureExtractor;h.FillMaskPipeline;h.Florence2ForConditionalGeneration;h.Florence2PreTrainedModel;h.Florence2Processor;h.ForcedBOSTokenLogitsProcessor;h.ForcedEOSTokenLogitsProcessor;h.GLPNFeatureExtractor;h.GLPNForDepthEstimation;h.GLPNModel;h.GLPNPreTrainedModel;h.GPT2LMHeadModel;h.GPT2Model;h.GPT2PreTrainedModel;h.GPT2Tokenizer;h.GPTBigCodeForCausalLM;h.GPTBigCodeModel;h.GPTBigCodePreTrainedModel;h.GPTJForCausalLM;h.GPTJModel;h.GPTJPreTrainedModel;h.GPTNeoForCausalLM;h.GPTNeoModel;h.GPTNeoPreTrainedModel;h.GPTNeoXForCausalLM;h.GPTNeoXModel;h.GPTNeoXPreTrainedModel;h.GPTNeoXTokenizer;h.Gemma2ForCausalLM;h.Gemma2Model;h.Gemma2PreTrainedModel;h.Gemma3ForCausalLM;h.Gemma3Model;h.Gemma3PreTrainedModel;h.GemmaForCausalLM;h.GemmaModel;h.GemmaPreTrainedModel;h.GemmaTokenizer;h.GlmForCausalLM;h.GlmModel;h.GlmPreTrainedModel;h.GraniteForCausalLM;h.GraniteModel;h.GranitePreTrainedModel;h.Grok1Tokenizer;h.GroundingDinoForObjectDetection;h.GroundingDinoImageProcessor;h.GroundingDinoPreTrainedModel;h.GroundingDinoProcessor;h.GroupViTModel;h.GroupViTPreTrainedModel;h.HeliumForCausalLM;h.HeliumModel;h.HeliumPreTrainedModel;h.HerbertTokenizer;h.HieraForImageClassification;h.HieraModel;h.HieraPreTrainedModel;h.HubertForCTC;h.HubertForSequenceClassification;h.HubertModel;h.HubertPreTrainedModel;h.IJepaForImageClassification;h.IJepaModel;h.IJepaPreTrainedModel;h.Idefics3ForConditionalGeneration;h.Idefics3ImageProcessor;h.Idefics3PreTrainedModel;h.Idefics3Processor;h.ImageClassificationPipeline;h.ImageFeatureExtractionPipeline;h.ImageFeatureExtractor;h.ImageMattingOutput;h.ImageProcessor;h.ImageSegmentationPipeline;h.ImageToImagePipeline;h.ImageToTextPipeline;var Gx=h.InterruptableStoppingCriteria;h.JAISLMHeadModel;h.JAISModel;h.JAISPreTrainedModel;h.JinaCLIPImageProcessor;h.JinaCLIPModel;h.JinaCLIPPreTrainedModel;h.JinaCLIPProcessor;h.JinaCLIPTextModel;h.JinaCLIPVisionModel;h.LiteWhisperForConditionalGeneration;h.LlamaForCausalLM;h.LlamaModel;h.LlamaPreTrainedModel;h.LlamaTokenizer;h.LlavaForConditionalGeneration;h.LlavaOnevisionForConditionalGeneration;h.LlavaOnevisionImageProcessor;h.LlavaPreTrainedModel;h.LogitsProcessor;h.LogitsProcessorList;h.LogitsWarper;h.LongT5ForConditionalGeneration;h.LongT5Model;h.LongT5PreTrainedModel;h.M2M100ForConditionalGeneration;h.M2M100Model;h.M2M100PreTrainedModel;h.M2M100Tokenizer;h.MBart50Tokenizer;h.MBartForCausalLM;h.MBartForConditionalGeneration;h.MBartForSequenceClassification;h.MBartModel;h.MBartPreTrainedModel;h.MBartTokenizer;h.MPNetForMaskedLM;h.MPNetForQuestionAnswering;h.MPNetForSequenceClassification;h.MPNetForTokenClassification;h.MPNetModel;h.MPNetPreTrainedModel;h.MPNetTokenizer;h.MT5ForConditionalGeneration;h.MT5Model;h.MT5PreTrainedModel;h.MarianMTModel;h.MarianModel;h.MarianPreTrainedModel;h.MarianTokenizer;h.Mask2FormerImageProcessor;h.MaskFormerFeatureExtractor;h.MaskFormerForInstanceSegmentation;h.MaskFormerImageProcessor;h.MaskFormerModel;h.MaskFormerPreTrainedModel;h.MaskedLMOutput;h.MaxLengthCriteria;h.Metric3DForDepthEstimation;h.Metric3DPreTrainedModel;h.Metric3Dv2ForDepthEstimation;h.Metric3Dv2PreTrainedModel;h.MgpstrForSceneTextRecognition;h.MgpstrModelOutput;h.MgpstrPreTrainedModel;h.MgpstrProcessor;h.MgpstrTokenizer;h.MimiDecoderModel;h.MimiDecoderOutput;h.MimiEncoderModel;h.MimiEncoderOutput;h.MimiModel;h.MimiPreTrainedModel;h.MinLengthLogitsProcessor;h.MinNewTokensLengthLogitsProcessor;h.MistralForCausalLM;h.MistralModel;h.MistralPreTrainedModel;h.MobileBertForMaskedLM;h.MobileBertForQuestionAnswering;h.MobileBertForSequenceClassification;h.MobileBertModel;h.MobileBertPreTrainedModel;h.MobileBertTokenizer;h.MobileLLMForCausalLM;h.MobileLLMModel;h.MobileLLMPreTrainedModel;h.MobileNetV1FeatureExtractor;h.MobileNetV1ForImageClassification;h.MobileNetV1ForSemanticSegmentation;h.MobileNetV1ImageProcessor;h.MobileNetV1Model;h.MobileNetV1PreTrainedModel;h.MobileNetV2FeatureExtractor;h.MobileNetV2ForImageClassification;h.MobileNetV2ForSemanticSegmentation;h.MobileNetV2ImageProcessor;h.MobileNetV2Model;h.MobileNetV2PreTrainedModel;h.MobileNetV3FeatureExtractor;h.MobileNetV3ForImageClassification;h.MobileNetV3ForSemanticSegmentation;h.MobileNetV3ImageProcessor;h.MobileNetV3Model;h.MobileNetV3PreTrainedModel;h.MobileNetV4FeatureExtractor;h.MobileNetV4ForImageClassification;h.MobileNetV4ForSemanticSegmentation;h.MobileNetV4ImageProcessor;h.MobileNetV4Model;h.MobileNetV4PreTrainedModel;h.MobileViTFeatureExtractor;h.MobileViTForImageClassification;h.MobileViTImageProcessor;h.MobileViTModel;h.MobileViTPreTrainedModel;h.MobileViTV2ForImageClassification;h.MobileViTV2Model;h.MobileViTV2PreTrainedModel;h.ModelOutput;h.ModernBertForMaskedLM;h.ModernBertForSequenceClassification;h.ModernBertForTokenClassification;h.ModernBertModel;h.ModernBertPreTrainedModel;h.Moondream1ForConditionalGeneration;h.MoonshineFeatureExtractor;h.MoonshineForConditionalGeneration;h.MoonshineModel;h.MoonshinePreTrainedModel;h.MoonshineProcessor;h.MptForCausalLM;h.MptModel;h.MptPreTrainedModel;h.MultiModalityCausalLM;h.MultiModalityPreTrainedModel;h.MusicgenForCausalLM;h.MusicgenForConditionalGeneration;h.MusicgenModel;h.MusicgenPreTrainedModel;h.NllbTokenizer;h.NoBadWordsLogitsProcessor;h.NoRepeatNGramLogitsProcessor;h.NomicBertModel;h.NomicBertPreTrainedModel;h.NougatImageProcessor;h.NougatTokenizer;h.OPTForCausalLM;h.OPTModel;h.OPTPreTrainedModel;h.ObjectDetectionPipeline;h.Olmo2ForCausalLM;h.Olmo2Model;h.Olmo2PreTrainedModel;h.OlmoForCausalLM;h.OlmoModel;h.OlmoPreTrainedModel;h.OpenELMForCausalLM;h.OpenELMModel;h.OpenELMPreTrainedModel;h.OwlViTFeatureExtractor;h.OwlViTForObjectDetection;h.OwlViTImageProcessor;h.OwlViTModel;h.OwlViTPreTrainedModel;h.OwlViTProcessor;h.Owlv2ForObjectDetection;h.Owlv2ImageProcessor;h.Owlv2Model;h.Owlv2PreTrainedModel;h.PaliGemmaForConditionalGeneration;h.PaliGemmaPreTrainedModel;h.PaliGemmaProcessor;h.PatchTSMixerForPrediction;h.PatchTSMixerModel;h.PatchTSMixerPreTrainedModel;h.PatchTSTForPrediction;h.PatchTSTModel;h.PatchTSTPreTrainedModel;h.Phi3ForCausalLM;h.Phi3Model;h.Phi3PreTrainedModel;h.Phi3VForCausalLM;h.Phi3VImageProcessor;h.Phi3VPreTrainedModel;h.Phi3VProcessor;h.PhiForCausalLM;h.PhiModel;h.PhiPreTrainedModel;h.Pipeline;h.PreTrainedModel;h.PreTrainedTokenizer;h.PretrainedConfig;h.PretrainedMixin;h.Processor;h.PvtForImageClassification;h.PvtImageProcessor;h.PvtModel;h.PvtPreTrainedModel;h.PyAnnoteFeatureExtractor;h.PyAnnoteForAudioFrameClassification;h.PyAnnoteModel;h.PyAnnotePreTrainedModel;h.PyAnnoteProcessor;h.QuestionAnsweringModelOutput;h.QuestionAnsweringPipeline;h.Qwen2ForCausalLM;h.Qwen2Model;h.Qwen2PreTrainedModel;h.Qwen2Tokenizer;h.Qwen2VLForConditionalGeneration;h.Qwen2VLImageProcessor;h.Qwen2VLPreTrainedModel;h.Qwen2VLProcessor;h.RFDetrForObjectDetection;h.RFDetrModel;h.RFDetrObjectDetectionOutput;h.RFDetrPreTrainedModel;h.RTDetrForObjectDetection;h.RTDetrImageProcessor;h.RTDetrModel;h.RTDetrObjectDetectionOutput;h.RTDetrPreTrainedModel;h.RTDetrV2ForObjectDetection;h.RTDetrV2Model;h.RTDetrV2ObjectDetectionOutput;h.RTDetrV2PreTrainedModel;h.RawAudio;h.RawImage;h.RawVideo;h.RawVideoFrame;h.RepetitionPenaltyLogitsProcessor;h.ResNetForImageClassification;h.ResNetModel;h.ResNetPreTrainedModel;h.RoFormerForMaskedLM;h.RoFormerForQuestionAnswering;h.RoFormerForSequenceClassification;h.RoFormerForTokenClassification;h.RoFormerModel;h.RoFormerPreTrainedModel;h.RoFormerTokenizer;h.RobertaForMaskedLM;h.RobertaForQuestionAnswering;h.RobertaForSequenceClassification;h.RobertaForTokenClassification;h.RobertaModel;h.RobertaPreTrainedModel;h.RobertaTokenizer;h.SamImageProcessor;h.SamImageSegmentationOutput;h.SamModel;h.SamPreTrainedModel;h.SamProcessor;h.SapiensForDepthEstimation;h.SapiensForNormalEstimation;h.SapiensForSemanticSegmentation;h.SapiensPreTrainedModel;h.SeamlessM4TFeatureExtractor;h.SegformerFeatureExtractor;h.SegformerForImageClassification;h.SegformerForSemanticSegmentation;h.SegformerImageProcessor;h.SegformerModel;h.SegformerPreTrainedModel;h.Seq2SeqLMOutput;h.SequenceClassifierOutput;h.SiglipImageProcessor;h.SiglipModel;h.SiglipPreTrainedModel;h.SiglipTextModel;h.SiglipTokenizer;h.SiglipVisionModel;h.SmolVLMForConditionalGeneration;h.SmolVLMImageProcessor;h.SmolVLMProcessor;h.SnacDecoderModel;h.SnacEncoderModel;h.SnacFeatureExtractor;h.SnacModel;h.SnacPreTrainedModel;h.SpeechT5FeatureExtractor;h.SpeechT5ForSpeechToText;h.SpeechT5ForTextToSpeech;h.SpeechT5HifiGan;h.SpeechT5Model;h.SpeechT5PreTrainedModel;h.SpeechT5Processor;h.SpeechT5Tokenizer;h.SqueezeBertForMaskedLM;h.SqueezeBertForQuestionAnswering;h.SqueezeBertForSequenceClassification;h.SqueezeBertModel;h.SqueezeBertPreTrainedModel;h.SqueezeBertTokenizer;h.StableLmForCausalLM;h.StableLmModel;h.StableLmPreTrainedModel;h.Starcoder2ForCausalLM;h.Starcoder2Model;h.Starcoder2PreTrainedModel;h.StoppingCriteria;h.StoppingCriteriaList;h.StyleTextToSpeech2Model;h.StyleTextToSpeech2PreTrainedModel;h.SummarizationPipeline;h.SuppressTokensAtBeginLogitsProcessor;h.Swin2SRForImageSuperResolution;h.Swin2SRImageProcessor;h.Swin2SRModel;h.Swin2SRPreTrainedModel;h.SwinForImageClassification;h.SwinForSemanticSegmentation;h.SwinModel;h.SwinPreTrainedModel;h.T5ForConditionalGeneration;h.T5Model;h.T5PreTrainedModel;h.T5Tokenizer;h.TableTransformerForObjectDetection;h.TableTransformerModel;h.TableTransformerObjectDetectionOutput;h.TableTransformerPreTrainedModel;h.TemperatureLogitsWarper;h.Tensor;h.Text2TextGenerationPipeline;h.TextClassificationPipeline;h.TextGenerationPipeline;var Kx=h.TextStreamer;h.TextToAudioPipeline;h.TokenClassificationPipeline;h.TokenClassifierOutput;h.TokenizerModel;h.TopKLogitsWarper;h.TopPLogitsWarper;h.TrOCRForCausalLM;h.TrOCRPreTrainedModel;h.TranslationPipeline;var Hx=h.UltravoxModel;h.UltravoxPreTrainedModel;var qx=h.UltravoxProcessor;h.UniSpeechForCTC;h.UniSpeechForSequenceClassification;h.UniSpeechModel;h.UniSpeechPreTrainedModel;h.UniSpeechSatForAudioFrameClassification;h.UniSpeechSatForCTC;h.UniSpeechSatForSequenceClassification;h.UniSpeechSatModel;h.UniSpeechSatPreTrainedModel;h.VLChatProcessor;h.VLMImageProcessor;h.ViTFeatureExtractor;h.ViTForImageClassification;h.ViTImageProcessor;h.ViTMAEModel;h.ViTMAEPreTrainedModel;h.ViTMSNForImageClassification;h.ViTMSNModel;h.ViTMSNPreTrainedModel;h.ViTModel;h.ViTPreTrainedModel;h.VisionEncoderDecoderModel;h.VitMatteForImageMatting;h.VitMatteImageProcessor;h.VitMattePreTrainedModel;h.VitPoseForPoseEstimation;h.VitPoseImageProcessor;h.VitPosePreTrainedModel;h.VitsModel;h.VitsModelOutput;h.VitsPreTrainedModel;h.VitsTokenizer;h.Wav2Vec2BertForCTC;h.Wav2Vec2BertForSequenceClassification;h.Wav2Vec2BertModel;h.Wav2Vec2BertPreTrainedModel;h.Wav2Vec2CTCTokenizer;h.Wav2Vec2FeatureExtractor;h.Wav2Vec2ForAudioFrameClassification;h.Wav2Vec2ForCTC;h.Wav2Vec2ForSequenceClassification;h.Wav2Vec2Model;h.Wav2Vec2PreTrainedModel;h.Wav2Vec2Processor;h.Wav2Vec2ProcessorWithLM;h.WavLMForAudioFrameClassification;h.WavLMForCTC;h.WavLMForSequenceClassification;h.WavLMForXVector;h.WavLMModel;h.WavLMPreTrainedModel;h.WeSpeakerFeatureExtractor;h.WeSpeakerResNetModel;h.WeSpeakerResNetPreTrainedModel;h.WhisperFeatureExtractor;h.WhisperForConditionalGeneration;h.WhisperModel;h.WhisperPreTrainedModel;h.WhisperProcessor;h.WhisperTextStreamer;h.WhisperTimeStampLogitsProcessor;h.WhisperTokenizer;h.XLMForQuestionAnswering;h.XLMForSequenceClassification;h.XLMForTokenClassification;h.XLMModel;h.XLMPreTrainedModel;h.XLMRobertaForMaskedLM;h.XLMRobertaForQuestionAnswering;h.XLMRobertaForSequenceClassification;h.XLMRobertaForTokenClassification;h.XLMRobertaModel;h.XLMRobertaPreTrainedModel;h.XLMRobertaTokenizer;h.XLMTokenizer;h.XLMWithLMHeadModel;h.XVectorOutput;h.YolosFeatureExtractor;h.YolosForObjectDetection;h.YolosImageProcessor;h.YolosModel;h.YolosObjectDetectionOutput;h.YolosPreTrainedModel;h.ZeroShotAudioClassificationPipeline;h.ZeroShotClassificationPipeline;h.ZeroShotImageClassificationPipeline;h.ZeroShotObjectDetectionPipeline;h.bankers_round;h.cat;h.cos_sim;h.dot;h.dynamic_time_warping;h.env;h.full;h.full_like;h.getKeyValueShapes;h.hamming;h.hanning;h.interpolate;h.interpolate_4d;h.interpolate_data;h.is_chinese_char;h.layer_norm;h.load_image;h.load_video;h.log_softmax;h.magnitude;h.matmul;h.max;h.mean;h.mean_pooling;h.medianFilter;h.mel_filter_bank;h.min;h.ones;h.ones_like;h.permute;h.permute_data;h.pipeline;h.quantize_embeddings;h.rand;h.read_audio;h.rfft;h.round;h.slice;h.softmax;h.spectrogram;h.stack;h.std_mean;h.topk;h.window_function;h.zeros;h.zeros_like;class wc{static model_id="onnx-community/ultravox-v0_5-llama-3_2-1b-ONNX";static processor=null;static model=null;static async getInstance(r=null){return this.processor??=qx.from_pretrained(this.model_id,{progress_callback:r}),this.model??=Hx.from_pretrained(this.model_id,{dtype:{embed_tokens:"fp32",audio_encoder:"q4",decoder_model_merged:"q4"},device:"webgpu",progress_callback:r}),Promise.all([this.processor,this.model])}}const ca=new Gx;function Xx(e){const r=e.lastIndexOf("assistant");if(r!==-1){const n=e.substring(r+9).trim();if(n)return n}const t=/(?:helloassistant|hello assistant)([\s\S]*?)$/i,s=e.match(t);return s&&s[1].trim()?s[1].trim():e.replace(/system[\s\S]*?user/i,"").replace(/Cutting Knowledge Date:[\s\S]*?Today Date:[\s\S]*?\d{4}/i,"").replace(/\b(user|assistant|system)\b/gi,"").trim()}let to=[],ra=!1;async function a0(){if(!(ra||to.length===0)){ra=!0;try{const e=to.shift();e.type==="generate"||e.type==="generate_with_audio"?await Qx(e.data):e.type==="summarize"&&await Jx(e.data)}catch(e){console.error("Error processing request:",e),self.postMessage({status:"error",data:e.toString()})}finally{ra=!1,to.length>0&&setTimeout(a0,0)}}}function bw(e,r){to.push({type:e,data:r}),a0()}async function Qx(e){const{messages:r,audio:t}=e;ca.reset();try{const[s,n]=await wc.getInstance(),o=s.tokenizer.apply_chat_template(r,{add_generation_prompt:!0,tokenize:!1}),a=await s(o,t);let i="";const l=P=>{self.postMessage({status:"update",output:P})},c=new Kx(s.tokenizer,{skip_prompt:!0,skip_special_tokens:!0,callback_function:l});self.postMessage({status:"start"});const{sequences:p}=await n.generate({...a,do_sample:!1,max_new_tokens:1024,streamer:c,stopping_criteria:ca,return_dict_in_generate:!0}),u=a.input_ids.dims.at(-1),d=p.slice(null,[u,null]),f=s.batch_decode(d,{skip_special_tokens:!0}),_=Xx(f[0]);self.postMessage({status:"complete",output:_,raw:f[0]})}catch(s){console.error("Generation error:",s),self.postMessage({status:"error",data:s.toString()})}}async function Jx(e){const{textToSummarize:r}=e;try{const[t,s]=await wc.getInstance(),n=`Rewrite the following User Statement from the user's perspective into a single sentence starting with "The user". Focus ONLY on the information stated by the user. Do not add external knowledge, notes,commentary, or formatting. User Statement: ${r} Rewritten Sentence:`,o=t.tokenizer(n,{return_tensors:"pt"});self.postMessage({status:"summarization_start"});const{sequences:a}=await s.generate({...o,max_new_tokens:72,do_sample:!1,num_beams:1,return_dict_in_generate:!0}),i=o.input_ids.dims.at(-1);if(!a||!a.slice)throw console.error("Summarization error: 'sequences' is not in the expected format.",a),new Error("Summarization failed: Invalid output structure from model.generate.");const l=a.slice(null,[i,null]),p=t.batch_decode(l,{skip_special_tokens:!0})[0]?.trim()||"";if(!p){console.warn("Summarization resulted in an empty string after decoding."),self.postMessage({status:"summary_error",error:"Failed to extract summary content."});return}self.postMessage({status:"summary_complete",summary:p})}catch(t){console.error("Summarization error:",t),self.postMessage({status:"summary_error",data:t.toString()})}}async function Yx(){try{if(!await navigator.gpu.requestAdapter())throw new Error("WebGPU is not supported (no adapter found)")}catch(e){self.postMessage({status:"error",data:e.toString()})}}async function Zx(){self.postMessage({status:"loading",data:"Loading model..."});try{const[e,r]=await wc.getInstance(o=>{self.postMessage(o)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const t=e.tokenizer.apply_chat_template([{role:"user",content:"warmup <|audio|>"}],{add_generation_prompt:!0,tokenize:!1}),s=new Float32Array(160),n=await e(t,s);await r.generate({...n,max_new_tokens:1}),self.postMessage({status:"ready"})}catch(e){self.postMessage({status:"error",data:e.toString()})}}self.addEventListener("message",async e=>{const{type:r,data:t}=e.data;switch(r){case"check":Yx();break;case"load":Zx();break;case"generate":case"generate_with_audio":bw(r,t);break;case"summarize":bw(r,t);break;case"interrupt":ca.interrupt(),to=[];break;case"reset":ca.reset(),to=[],ra=!1;break}});