diff --git "a/assets/worker-CGHCbKK3.js" "b/assets/worker-CGHCbKK3.js" new file mode 100644--- /dev/null +++ "b/assets/worker-CGHCbKK3.js" @@ -0,0 +1,2888 @@ +var Jx=Object.defineProperty;var Yx=(xs,zr,Ln)=>zr in xs?Jx(xs,zr,{enumerable:!0,configurable:!0,writable:!0,value:Ln}):xs[zr]=Ln;var Z=(xs,zr,Ln)=>Yx(xs,typeof zr!="symbol"?zr+"":zr,Ln);(function(){"use strict";const xs=new Map,zr=[],Ln=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=xs.get(e);if(s===void 0)xs.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){const o=zr.indexOf(e);o!==-1&&zr.splice(o,1);for(let n=0;n{const r=xs.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}}},U0=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?zr:t;let o;const n=[],i=new Set;for(const l of s){const u=await V0(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);const a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]},W0="1.21.0";let Ec="warning";const ls={wasm:{},webgl:{},webgpu:{},versions:{common:W0},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}`);Ec=e}},get logLevel(){return Ec}};Object.defineProperty(ls,"logLevel",{enumerable:!0});const G0=ls,K0=(e,r)=>{const t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];const s=t.getContext("2d");if(s!=null){let o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);const i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm;let l,u;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));const p=n*o;let c=0,d=p,_=p*2,f=-1;i==="RGBA"?(c=0,d=p,_=p*2,f=p*3):i==="RGB"?(c=0,d=p,_=p*2):i==="RBG"&&(c=0,_=p,d=p*2);for(let T=0;T{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm;let u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));const c=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const d=4;let _=0,f=1,T=2,k=3,w=0,g=c,S=c*2,E=-1;a==="RGBA"?(w=0,g=c,S=c*2,E=c*3):a==="RGB"?(w=0,g=c,S=c*2):a==="RBG"&&(w=0,S=c,g=c*2),s=t.createImageData(o,n);for(let y=0;y{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:t,width:s}=r,o=r.norm??{mean:255,bias:0};let n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3);let c=4,d=0,_=1,f=2,T=3,k=0,w=u,g=u*2,S=-1;a==="RGB"&&(c=3,d=0,_=1,f=2,T=-1),l==="RGBA"?S=u*3:l==="RBG"?(k=0,g=u,w=u*2):l==="BGR"&&(g=0,w=u,k=u*2);for(let y=0;y{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string";let i,a=r??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){const p=l();p.width=e.width,p.height=e.height;const c=u(p);if(c!=null){let d=e.height,_=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(d=r.resizedHeight,_=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=d,a.width=_}else a.tensorFormat="RGBA",a.height=d,a.width=_;c.drawImage(e,0,0),i=c.getImageData(0,0,_,d).data}else throw new Error("Can not access image data")}else if(s){let p,c;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,c=r.resizedWidth):(p=e.height,c=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=c,r!==void 0){const d=l();d.width=c,d.height=p;const _=u(d);if(_!=null)_.putImageData(e,0,0),i=_.getImageData(0,0,c,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");const p=l();p.width=e.width,p.height=e.height;const c=u(p);if(c!=null){const d=e.height,_=e.width;return c.drawImage(e,0,0,_,d),i=c.getImageData(0,0,_,d).data,a.height=d,a.width=_,ga(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,c)=>{const d=l(),_=u(d);if(!e||!_)return c();const f=new Image;f.crossOrigin="Anonymous",f.src=e,f.onload=()=>{d.width=f.width,d.height=f.height,_.drawImage(f,0,0,d.width,d.height);const T=_.getImageData(0,0,d.width,d.height);a.height=d.height,a.width=d.width,p(ga(T.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return ga(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Q0=(e,r)=>{const{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Yr({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},X0=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new Yr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},J0=(e,r)=>{const{dataType:t,dims:s,download:o,dispose:n}=r;return new Yr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},Y0=(e,r,t)=>new Yr({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]]),Yo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Pc=!1;const Z0=()=>{if(!Pc){Pc=!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),Yo.set(BigInt64Array,"int64")),r&&(zn.set("uint64",BigUint64Array),Yo.set(BigUint64Array,"uint64")),s?(zn.set("float16",t),Yo.set(t,"float16")):zn.set("float16",Uint16Array)}},ev=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Yr(e.type,e.data,r);case"cpu-pinned":return new Yr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Yr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Yr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Yr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Yr=class{constructor(r,t,s){Z0();let o,n;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,o=r.type,n=r.dims,r.location){case"cpu-pinned":{const a=zn.get(o);if(!a)throw new TypeError(`unsupported type "${o}" to create tensor from pinned buffer`);if(!(r.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=r.data;break}case"texture":{if(o!=="float32")throw new TypeError(`unsupported type "${o}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(o!=="float32"&&o!=="float16"&&o!=="int32"&&o!=="int64"&&o!=="uint32"&&o!=="uint64"&&o!=="int8"&&o!=="uint8"&&o!=="bool"&&o!=="uint4"&&o!=="int4")throw new TypeError(`unsupported type "${o}" to create tensor from MLTensor`);this.mlTensorData=r.mlTensor,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,l;if(typeof r=="string")if(o=r,l=s,r==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{const u=zn.get(r);if(u===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&u===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${u.name} as data.`);r==="uint64"||r==="int64"?a=u.from(t,BigInt):a=u.from(t)}else if(t instanceof u)a=t;else if(t instanceof Uint8ClampedArray)if(r==="uint8")a=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(r==="float16"&&t instanceof Uint16Array&&u!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${o} tensor's data must be type of ${u}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const u=typeof r[0];if(u==="string")o="string",a=r;else if(u==="boolean")o="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${u}.`)}else if(r instanceof Uint8ClampedArray)o="uint8",a=Uint8Array.from(r);else{const u=Yo.get(r.constructor);if(u===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);o=u,a=r}if(l===void 0)l=[a.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");n=l,this.cpuData=a,this.dataLocation="cpu"}const i=ev(n);if(this.cpuData&&i!==this.cpuData.length&&!((o==="uint4"||o==="int4")&&Math.ceil(i/2)===this.cpuData.length))throw new Error(`Tensor's size(${i}) does not match data length(${this.cpuData.length}).`);this.type=o,this.dims=n,this.size=i}static async fromImage(r,t){return q0(r,t)}static fromTexture(r,t){return Q0(r,t)}static fromGpuBuffer(r,t){return X0(r,t)}static fromMLTensor(r,t){return J0(r,t)}static fromPinnedBuffer(r,t,s){return Y0(r,t,s)}toDataURL(r){return K0(this,r)}toImageData(r){return H0(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 tv(this,r)}};const Bn=Yr,Cc=(e,r)=>{(typeof ls.trace>"u"?!ls.wasm.trace:!ls.trace)||console.timeStamp(`${e}::ORT::${r}`)},Sc=(e,r)=>{var o;const t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[];let s=!1;for(let n=0;n{(typeof ls.trace>"u"?!ls.wasm.trace:!ls.trace)||Sc("BEGIN",e)},Ma=e=>{(typeof ls.trace>"u"?!ls.wasm.trace:!ls.trace)||Sc("END",e)};var rv=Object.freeze({__proto__:null,InferenceSession:class R0{constructor(r){this.handler=r}async run(r,t,s){wa();const o={};let n={};if(typeof r!="object"||r===null||r instanceof Bn||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof Bn)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(const u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1;const p=Object.getOwnPropertyNames(t);for(const c of this.outputNames)if(p.indexOf(c)!==-1){const d=t[c];(d===null||d instanceof Bn)&&(u=!0,i=!1,o[c]=d)}if(u){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(const u of this.outputNames)o[u]=null;const a=await this.handler.run(r,o,n),l={};for(const u in a)if(Object.hasOwnProperty.call(a,u)){const p=a[u];p instanceof Bn?l[u]=p:l[u]=new Bn(p.type,p.data,p.dims)}return Ma(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){wa();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){const p=r;let c=0,d=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(c=t,!Number.isSafeInteger(c))throw new RangeError("'byteOffset' must be an integer.");if(c<0||c>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(d=r.byteLength-c,typeof s=="number"){if(d=s,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||c+d>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-c}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,c,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await U0(i),u=await a.createInferenceSessionHandler(n,l);return Ma(),new R0(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}},TRACE:Cc,TRACE_FUNC_BEGIN:wa,TRACE_FUNC_END:Ma,Tensor:Bn,env:G0,registerBackend:Ln});/*! + * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var ba=Object.defineProperty,sv=Object.getOwnPropertyDescriptor,nv=Object.getOwnPropertyNames,ov=Object.prototype.hasOwnProperty,iv=(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),Rn=(e,r)=>{for(var t in r)ba(e,t,{get:r[t],enumerable:!0})},av=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of nv(r))!ov.call(e,o)&&o!==t&&ba(e,o,{get:()=>r[o],enumerable:!(s=sv(r,o))||s.enumerable});return e},io=e=>av(ba({},"__esModule",{value:!0}),e),ao,Ns,tn,$c,kc,Ic=ze(()=>{ao=new Map,Ns=[],tn=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=ao.get(e);if(s===void 0)ao.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){let o=Ns.indexOf(e);o!==-1&&Ns.splice(o,1);for(let n=0;n{let r=ao.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}}},kc=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Ns:t,o,n=[],i=new Set;for(let l of s){let u=await $c(l);typeof u=="string"?n.push({name:l,err:u}):(o||(o=u),o===u&&i.add(l))}if(!o)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:u}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${u}`);let a=r.filter(l=>i.has(typeof l=="string"?l:l.name));return[o,new Proxy(e,{get:(l,u)=>u==="executionProviders"?a:Reflect.get(l,u)})]}}),lv=ze(()=>{Ic()}),Ac,uv=ze(()=>{Ac="1.22.0-dev.20250409-89f8206ba4"}),ya,Zr,Fc=ze(()=>{uv(),ya="warning",Zr={wasm:{},webgl:{},webgpu:{},versions:{common:Ac},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}`);ya=e}},get logLevel(){return ya}},Object.defineProperty(Zr,"logLevel",{enumerable:!0})}),Xt,cv=ze(()=>{Fc(),Xt=Zr}),Oc,Dc,dv=ze(()=>{Oc=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];let s=t.getContext("2d");if(s!=null){let o,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[3]):(o=e.dims[3],n=e.dims[2]);let i=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm,l,u;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?u=[0,0,0,0]:typeof a.bias=="number"?u=[a.bias,a.bias,a.bias,a.bias]:(u=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(u[3]=a.bias[3]));let p=n*o,c=0,d=p,_=p*2,f=-1;i==="RGBA"?(c=0,d=p,_=p*2,f=p*3):i==="RGB"?(c=0,d=p,_=p*2):i==="RBG"&&(c=0,_=p,d=p*2);for(let T=0;T{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let o,n,i;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(o=e.dims[2],n=e.dims[1],i=e.dims[3]):(o=e.dims[3],n=e.dims[2],i=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm,u,p;l===void 0||l.mean===void 0?u=[255,255,255,255]:typeof l.mean=="number"?u=[l.mean,l.mean,l.mean,l.mean]:(u=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(u[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let c=n*o;if(r!==void 0&&(r.format!==void 0&&i===4&&r.format!=="RGBA"||i===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let d=4,_=0,f=1,T=2,k=3,w=0,g=c,S=c*2,E=-1;a==="RGBA"?(w=0,g=c,S=c*2,E=c*3):a==="RGB"?(w=0,g=c,S=c*2):a==="RBG"&&(w=0,S=c,g=c*2),s=t.createImageData(o,n);for(let y=0;y{xa(),Zo=(e,r)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:s}=r,o=r.norm??{mean:255,bias:0},n,i;typeof o.mean=="number"?n=[o.mean,o.mean,o.mean,o.mean]:n=[o.mean[0],o.mean[1],o.mean[2],o.mean[3]??255],typeof o.bias=="number"?i=[o.bias,o.bias,o.bias,o.bias]:i=[o.bias[0],o.bias[1],o.bias[2],o.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",u=t*s,p=l==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),c=4,d=0,_=1,f=2,T=3,k=0,w=u,g=u*2,S=-1;a==="RGB"&&(c=3,d=0,_=1,f=2,T=-1),l==="RGBA"?S=u*3:l==="RBG"?(k=0,g=u,w=u*2):l==="BGR"&&(g=0,w=u,k=u*2);for(let E=0;E{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,o=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string",i,a=r??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},u=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){let p=l();p.width=e.width,p.height=e.height;let c=u(p);if(c!=null){let d=e.height,_=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(d=r.resizedHeight,_=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=d,a.width=_}else a.tensorFormat="RGBA",a.height=d,a.width=_;c.drawImage(e,0,0),i=c.getImageData(0,0,_,d).data}else throw new Error("Can not access image data")}else if(s){let p,c;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,c=r.resizedWidth):(p=e.height,c=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=c,r!==void 0){let d=l();d.width=c,d.height=p;let _=u(d);if(_!=null)_.putImageData(e,0,0),i=_.getImageData(0,0,c,p).data;else throw new Error("Can not access image data")}else i=e.data}else if(o){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=e.width,p.height=e.height;let c=u(p);if(c!=null){let d=e.height,_=e.width;return c.drawImage(e,0,0,_,d),i=c.getImageData(0,0,_,d).data,a.height=d,a.width=_,Zo(i,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,c)=>{let d=l(),_=u(d);if(!e||!_)return c();let f=new Image;f.crossOrigin="Anonymous",f.src=e,f.onload=()=>{d.width=f.width,d.height=f.height,_.drawImage(f,0,0,d.width,d.height);let T=_.getImageData(0,0,d.width,d.height);a.height=d.height,a.width=d.width,p(Zo(T.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(i!==void 0)return Zo(i,a);throw new Error("Input data provided is not supported - aborted tensor creation")},zc=(e,r)=>{let{width:t,height:s,download:o,dispose:n}=r,i=[1,s,t,4];return new Wr({location:"texture",type:"float32",texture:e,dims:i,download:o,dispose:n})},Bc=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Wr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:o,dispose:n})},Rc=(e,r)=>{let{dataType:t,dims:s,download:o,dispose:n}=r;return new Wr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:o,dispose:n})},jc=(e,r,t)=>new Wr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),rn,lo,va,Nc,hv=ze(()=>{rn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),lo=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),va=!1,Nc=()=>{if(!va){va=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&(rn.set("int64",BigInt64Array),lo.set(BigInt64Array,"int64")),r&&(rn.set("uint64",BigUint64Array),lo.set(BigUint64Array,"uint64")),s?(rn.set("float16",t),lo.set(t,"float16")):rn.set("float16",Uint16Array)}}}),Vc,Uc,mv=ze(()=>{xa(),Vc=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Wr(e.type,e.data,r);case"cpu-pinned":return new Wr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Wr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Wr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Wr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Wr,xa=ze(()=>{dv(),pv(),hv(),mv(),Wr=class{constructor(e,r,t){Nc();let s,o;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,o=e.dims,e.location){case"cpu-pinned":{let i=rn.get(s);if(!i)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof i))throw new TypeError(`buffer should be of type ${i.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let i,a;if(typeof e=="string")if(s=e,a=t,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");i=r}else{let l=rn.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?i=l.from(r,BigInt):i=l.from(r)}else if(r instanceof l)i=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")i=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&l!==Uint16Array)i=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(a=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",i=e;else if(l==="boolean")s="bool",i=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",i=Uint8Array.from(e);else{let l=lo.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,i=e}if(a===void 0)a=[i.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");o=a,this.cpuData=i,this.dataLocation="cpu"}let n=Vc(o);if(this.cpuData&&n!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(n/2)===this.cpuData.length))throw new Error(`Tensor's size(${n}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=o,this.size=n}static async fromImage(e,r){return Lc(e,r)}static fromTexture(e,r){return zc(e,r)}static fromGpuBuffer(e,r){return Bc(e,r)}static fromMLTensor(e,r){return Rc(e,r)}static fromPinnedBuffer(e,r,t){return jc(e,r,t)}toDataURL(e){return Oc(this,e)}toImageData(e){return Dc(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 Uc(this,e)}}}),us,Wc=ze(()=>{xa(),us=Wr}),uo,Ta,cs,es,Gc=ze(()=>{Fc(),uo=(e,r)=>{(typeof Zr.trace>"u"?!Zr.wasm.trace:!Zr.trace)||console.timeStamp(`${e}::ORT::${r}`)},Ta=(e,r)=>{var o;let t=((o=new Error().stack)==null?void 0:o.split(/\r\n|\r|\n/g))||[],s=!1;for(let n=0;n{(typeof Zr.trace>"u"?!Zr.wasm.trace:!Zr.trace)||Ta("BEGIN",e)},es=e=>{(typeof Zr.trace>"u"?!Zr.wasm.trace:!Zr.trace)||Ta("END",e)}}),Kc,fv=ze(()=>{Ic(),Wc(),Gc(),Kc=class j0{constructor(r){this.handler=r}async run(r,t,s){cs();let o={},n={};if(typeof r!="object"||r===null||r instanceof us||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let i=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof us)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");i=!1;for(let u of t){if(typeof u!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(u)===-1)throw new RangeError(`'fetches' contains invalid output name: ${u}.`);o[u]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,p=Object.getOwnPropertyNames(t);for(let c of this.outputNames)if(p.indexOf(c)!==-1){let d=t[c];(d===null||d instanceof us)&&(u=!0,i=!1,o[c]=d)}if(u){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let u of this.inputNames)if(typeof r[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(i)for(let u of this.outputNames)o[u]=null;let a=await this.handler.run(r,o,n),l={};for(let u in a)if(Object.hasOwnProperty.call(a,u)){let p=a[u];p instanceof us?l[u]=p:l[u]=new us(p.type,p.data,p.dims)}return es(),l}async release(){return this.handler.dispose()}static async create(r,t,s,o){cs();let n,i={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)i=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){let p=r,c=0,d=r.byteLength;if(typeof t=="object"&&t!==null)i=t;else if(typeof t=="number"){if(c=t,!Number.isSafeInteger(c))throw new RangeError("'byteOffset' must be an integer.");if(c<0||c>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(d=r.byteLength-c,typeof s=="number"){if(d=s,!Number.isSafeInteger(d))throw new RangeError("'byteLength' must be an integer.");if(d<=0||c+d>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-c}].`);if(typeof o=="object"&&o!==null)i=o;else if(typeof o<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,c,d)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await kc(i),u=await a.createInferenceSessionHandler(n,l);return es(),new j0(u)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ea,_v=ze(()=>{fv(),Ea=Kc}),gv=ze(()=>{}),wv=ze(()=>{}),Mv=ze(()=>{}),bv=ze(()=>{}),Hc={};Rn(Hc,{InferenceSession:()=>Ea,TRACE:()=>uo,TRACE_FUNC_BEGIN:()=>cs,TRACE_FUNC_END:()=>es,Tensor:()=>us,env:()=>Xt,registerBackend:()=>tn});var ds=ze(()=>{lv(),cv(),_v(),Wc(),gv(),wv(),Gc(),Mv(),bv()}),Pa=ze(()=>{}),qc={};Rn(qc,{default:()=>Qc});var Ca,Sa,Qc,yv=ze(()=>{var e;$g(),sn(),La(),Ca="ort-wasm-proxy-worker",Sa=((e=globalThis.self)==null?void 0:e.name)===Ca,Sa&&(self.onmessage=r=>{let{type:t,in:s}=r.data;try{switch(t){case"init-wasm":Ra(s.wasm).then(()=>{Yl(s).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})})},o=>{postMessage({type:t,err:o})});break;case"init-ep":{let{epName:o,env:n}=s;Zl(n,o).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})});break}case"copy-from":{let{buffer:o}=s,n=wi(o);postMessage({type:t,out:n});break}case"create":{let{model:o,options:n}=s;tu(o,n).then(i=>{postMessage({type:t,out:i})},i=>{postMessage({type:t,err:i})});break}case"release":ru(s),postMessage({type:t});break;case"run":{let{sessionId:o,inputIndices:n,inputs:i,outputIndices:a,options:l}=s;nu(o,n,i,a,new Array(a.length).fill(null),l).then(u=>{u.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:u},iu([...i,...u]))},u=>{postMessage({type:t,err:u})});break}case"end-profiling":ou(s),postMessage({type:t});break;default:}}catch(o){postMessage({type:t,err:o})}}),Qc=Sa?null:r=>new Worker(r??Gr,{type:"module",name:Ca})}),Xc={};Rn(Xc,{default:()=>Jc});var $a,ka,Jc,Yc,vv=ze(()=>{var e,r;ka=($a=self.location.href,async function(t={}){var Qo;var s,o,n=t,i=new Promise((h,x)=>{s=h,o=x}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",u=l&&((Qo=self.name)==null?void 0:Qo.startsWith("em-pthread"));n.mountExternalData=(h,x)=>{h.startsWith("./")&&(h=h.substring(2)),(n.Eb||(n.Eb=new Map)).set(h,x)},n.unmountExternalData=()=>{delete n.Eb};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,pc:!0}).buffer.constructor;let c=h=>async(...x)=>{var I;try{if(n.Fb)throw Error("Session already started");let L=n.Fb={dc:x[0],errors:[]},U=await h(...x);if(n.Fb!==L)throw Error("Session mismatch");(I=n.Jb)==null||I.flush();let le=L.errors;if(0Fe),0{if(h==="webgpu"){[n.Jb,n.Ub,n.Yb,n.Kb,n.Xb,n.jb,n.Zb,n.ac,n.Vb,n.Wb,n.$b]=x;let I=n.Jb;n.jsepRegisterBuffer=(L,U,le,xe)=>I.registerBuffer(L,U,le,xe),n.jsepGetBuffer=L=>I.getBuffer(L),n.jsepCreateDownloader=(L,U,le)=>I.createDownloader(L,U,le),n.jsepOnCreateSession=L=>{I.onCreateSession(L)},n.jsepOnReleaseSession=L=>{I.onReleaseSession(L)},n.jsepOnRunStart=L=>I.onRunStart(L),n.bc=(L,U)=>{I.upload(L,U)}}else if(h==="webnn"){let I=x[0];[n.nc,n.Nb,n.webnnEnsureTensor,n.Ob,n.webnnDownloadTensor]=x.slice(1),n.webnnReleaseTensorId=n.Nb,n.webnnUploadTensor=n.Ob,n.webnnOnRunStart=L=>I.onRunStart(L),n.webnnOnRunEnd=I.onRunEnd.bind(I),n.webnnRegisterMLContext=(L,U)=>{I.registerMLContext(L,U)},n.webnnOnReleaseSession=L=>{I.onReleaseSession(L)},n.webnnCreateMLTensorDownloader=(L,U)=>I.createMLTensorDownloader(L,U),n.webnnRegisterMLTensor=(L,U,le,xe)=>I.registerMLTensor(L,U,le,xe),n.webnnCreateMLContext=L=>I.createMLContext(L),n.webnnRegisterMLConstant=(L,U,le,xe,Fe,He)=>I.registerMLConstant(L,U,le,xe,Fe,n.Eb,He),n.webnnRegisterGraphInput=I.registerGraphInput.bind(I),n.webnnIsGraphInput=I.isGraphInput.bind(I),n.webnnCreateTemporaryTensor=I.createTemporaryTensor.bind(I),n.webnnIsInt64Supported=I.isInt64Supported.bind(I)}};let d=()=>{let h=(x,I,L)=>(...U)=>{let le=Yt,xe=I==null?void 0:I();U=x(...U);let Fe=I==null?void 0:I();return xe!==Fe&&(x=Fe,L(xe),I=L=null),Yt!=le?new Promise((He,st)=>{qr={resolve:He,reject:st}}):U};(()=>{for(let x of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])n[x]=h(n[x],()=>n[x],I=>n[x]=I)})(),c!==void 0&&(n._OrtRun=c(n._OrtRun),n._OrtRunWithBinding=c(n._OrtRunWithBinding)),d=void 0};n.asyncInit=()=>{d==null||d()};var _,f,T=Object.assign({},n),k=(h,x)=>{throw x},w="";(a||l)&&(l?w=self.location.href:typeof document<"u"&&document.currentScript&&(w=document.currentScript.src),$a&&(w=$a),w=w.startsWith("blob:")?"":w.slice(0,w.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(f=h=>{var x=new XMLHttpRequest;return x.open("GET",h,!1),x.responseType="arraybuffer",x.send(null),new Uint8Array(x.response)}),_=async h=>{if(V(h))return new Promise((I,L)=>{var U=new XMLHttpRequest;U.open("GET",h,!0),U.responseType="arraybuffer",U.onload=()=>{U.status==200||U.status==0&&U.response?I(U.response):L(U.status)},U.onerror=L,U.send(null)});var x=await fetch(h,{credentials:"same-origin"});if(x.ok)return x.arrayBuffer();throw Error(x.status+" : "+x.url)});var g=console.log.bind(console),S=console.error.bind(console),E=g,y=S;Object.assign(n,T),T=null;var M,v,C,A,z,K,G,j,Y,H,J,Q,oe,he=n.wasmBinary,ae=!1,V=h=>h.startsWith("file://");function F(){return M.buffer!=A.buffer&&R(),A}function W(){return M.buffer!=A.buffer&&R(),z}function ee(){return M.buffer!=A.buffer&&R(),K}function me(){return M.buffer!=A.buffer&&R(),G}function te(){return M.buffer!=A.buffer&&R(),j}function ue(){return M.buffer!=A.buffer&&R(),Y}function Pe(){return M.buffer!=A.buffer&&R(),H}function Ne(){return M.buffer!=A.buffer&&R(),oe}if(u){let h=function(x){try{var I=x.data,L=I.Bb;if(L==="load"){let U=[];self.onmessage=le=>U.push(le),self.startWorker=()=>{postMessage({Bb:"loaded"});for(let le of U)h(le);self.onmessage=h};for(let le of I.Rb)n[le]&&!n[le].proxy||(n[le]=(...xe)=>{postMessage({Bb:"callHandler",Qb:le,args:xe})},le=="print"&&(E=n[le]),le=="printErr"&&(y=n[le]));M=I.kc,R(),we(I.lc)}else if(L==="run"){Ve(I.Ab),Sn(I.Ab,0,0,1,0,0),re(),ye(I.Ab),q||(No(),q=!0);try{Tt(I.fc,I.Hb)}catch(U){if(U!="unwind")throw U}}else I.target!=="setimmediate"&&(L==="checkMailbox"?q&&Be():L&&(y(`worker: received unknown command ${L}`),y(I)))}catch(U){throw Vo(),U}};var we,q=!1;y=function(...x){x=x.join(" "),console.error(x)},self.alert=function(...x){postMessage({Bb:"alert",text:x.join(" "),ic:Ys()})},self.onunhandledrejection=x=>{throw x.reason||x},self.onmessage=h}function R(){var h=M.buffer;n.HEAP8=A=new Int8Array(h),n.HEAP16=K=new Int16Array(h),n.HEAPU8=z=new Uint8Array(h),n.HEAPU16=G=new Uint16Array(h),n.HEAP32=j=new Int32Array(h),n.HEAPU32=Y=new Uint32Array(h),n.HEAPF32=H=new Float32Array(h),n.HEAPF64=oe=new Float64Array(h),n.HEAP64=J=new BigInt64Array(h),n.HEAPU64=Q=new BigUint64Array(h)}function de(){u?startWorker(n):dt.Ca()}u||(M=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),R());var ve,be=0,Ce=null;function Se(){if(--be==0&&Ce){var h=Ce;Ce=null,h()}}function $e(h){throw y(h="Aborted("+h+")"),ae=!0,h=new WebAssembly.RuntimeError(h+". Build with -sASSERTIONS for more info."),o(h),h}function Le(){return{a:{L:Ye,Aa:Ke,b:mt,$:ct,A:ir,pa:Ar,X:rs,Z:Es,qa:ws,na:Ps,ga:ss,ma:Rr,J:Cs,Y:Ss,V:ns,oa:Ms,W:bs,va:De,E:$s,Q:ks,O:fn,D:gn,u:wn,r:Is,P:Mn,z:N,R:X,ja:ie,T:Qe,aa:et,M:gt,F:At,ia:ye,sa:Lt,t:sr,Ba:Or,w:gr,o:dr,l:Hs,c:zs,n:vi,j:Ei,v:Pi,p:Ci,f:Si,s:$i,m:To,e:ki,k:Ii,i:Eo,g:Ai,d:Po,da:Fi,ea:So,fa:Di,ba:Tn,ca:$o,N:ko,xa:zi,ua:Ri,h:ji,C:Io,G:Rs,ta:Bi,x:Ni,ra:hu,U:Vi,q:Li,y:mu,K:Ui,S:Ao,za:Wi,ya:Gi,ka:Do,la:qn,_:St,B:Lo,I:zo,ha:Qn,H:Bo,a:M,wa:Re}}}var Ie={829644:(h,x,I,L,U)=>{if(n===void 0||!n.Eb)return 1;if((h=Ot(Number(h>>>0))).startsWith("./")&&(h=h.substring(2)),!(h=n.Eb.get(h)))return 2;if(x=Number(x>>>0),I=Number(I>>>0),L=Number(L>>>0),x+I>h.byteLength)return 3;try{let le=h.subarray(x,x+I);switch(U){case 0:W().set(le,L>>>0);break;case 1:n.mc?n.mc(L,le):n.bc(L,le);break;default:return 4}return 0}catch{return 4}},830468:(h,x,I)=>{n.Ob(h,W().subarray(x>>>0,x+I>>>0))},830532:()=>n.nc(),830574:h=>{n.Nb(h)},830611:()=>{n.Vb()},830642:()=>{n.Wb()},830671:()=>{n.$b()},830696:h=>n.Ub(h),830729:h=>n.Yb(h),830761:(h,x,I)=>{n.Kb(Number(h),Number(x),Number(I),!0)},830824:(h,x,I)=>{n.Kb(Number(h),Number(x),Number(I))},830881:()=>typeof wasmOffsetConverter<"u",830938:h=>{n.jb("Abs",h,void 0)},830989:h=>{n.jb("Neg",h,void 0)},831040:h=>{n.jb("Floor",h,void 0)},831093:h=>{n.jb("Ceil",h,void 0)},831145:h=>{n.jb("Reciprocal",h,void 0)},831203:h=>{n.jb("Sqrt",h,void 0)},831255:h=>{n.jb("Exp",h,void 0)},831306:h=>{n.jb("Erf",h,void 0)},831357:h=>{n.jb("Sigmoid",h,void 0)},831412:(h,x,I)=>{n.jb("HardSigmoid",h,{alpha:x,beta:I})},831491:h=>{n.jb("Log",h,void 0)},831542:h=>{n.jb("Sin",h,void 0)},831593:h=>{n.jb("Cos",h,void 0)},831644:h=>{n.jb("Tan",h,void 0)},831695:h=>{n.jb("Asin",h,void 0)},831747:h=>{n.jb("Acos",h,void 0)},831799:h=>{n.jb("Atan",h,void 0)},831851:h=>{n.jb("Sinh",h,void 0)},831903:h=>{n.jb("Cosh",h,void 0)},831955:h=>{n.jb("Asinh",h,void 0)},832008:h=>{n.jb("Acosh",h,void 0)},832061:h=>{n.jb("Atanh",h,void 0)},832114:h=>{n.jb("Tanh",h,void 0)},832166:h=>{n.jb("Not",h,void 0)},832217:(h,x,I)=>{n.jb("Clip",h,{min:x,max:I})},832286:h=>{n.jb("Clip",h,void 0)},832338:(h,x)=>{n.jb("Elu",h,{alpha:x})},832396:h=>{n.jb("Gelu",h,void 0)},832448:h=>{n.jb("Relu",h,void 0)},832500:(h,x)=>{n.jb("LeakyRelu",h,{alpha:x})},832564:(h,x)=>{n.jb("ThresholdedRelu",h,{alpha:x})},832634:(h,x)=>{n.jb("Cast",h,{to:x})},832692:h=>{n.jb("Add",h,void 0)},832743:h=>{n.jb("Sub",h,void 0)},832794:h=>{n.jb("Mul",h,void 0)},832845:h=>{n.jb("Div",h,void 0)},832896:h=>{n.jb("Pow",h,void 0)},832947:h=>{n.jb("Equal",h,void 0)},833e3:h=>{n.jb("Greater",h,void 0)},833055:h=>{n.jb("GreaterOrEqual",h,void 0)},833117:h=>{n.jb("Less",h,void 0)},833169:h=>{n.jb("LessOrEqual",h,void 0)},833228:(h,x,I,L,U)=>{n.jb("ReduceMean",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(te().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833403:(h,x,I,L,U)=>{n.jb("ReduceMax",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(te().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833577:(h,x,I,L,U)=>{n.jb("ReduceMin",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(te().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833751:(h,x,I,L,U)=>{n.jb("ReduceProd",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(te().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},833926:(h,x,I,L,U)=>{n.jb("ReduceSum",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(te().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834100:(h,x,I,L,U)=>{n.jb("ReduceL1",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(te().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834273:(h,x,I,L,U)=>{n.jb("ReduceL2",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(te().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834446:(h,x,I,L,U)=>{n.jb("ReduceLogSum",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(te().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834623:(h,x,I,L,U)=>{n.jb("ReduceSumSquare",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(te().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834803:(h,x,I,L,U)=>{n.jb("ReduceLogSumExp",h,{keepDims:!!x,noopWithEmptyAxes:!!I,axes:L?Array.from(te().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},834983:h=>{n.jb("Where",h,void 0)},835036:(h,x,I)=>{n.jb("Transpose",h,{perm:x?Array.from(te().subarray(Number(x)>>>0,Number(I)>>>0)):[]})},835160:(h,x,I,L)=>{n.jb("DepthToSpace",h,{blocksize:x,mode:Ot(I),format:L?"NHWC":"NCHW"})},835293:(h,x,I,L)=>{n.jb("DepthToSpace",h,{blocksize:x,mode:Ot(I),format:L?"NHWC":"NCHW"})},835426:(h,x,I,L,U,le,xe,Fe,He,st,bt,Ft,Ut,fr,js)=>{n.jb("ConvTranspose",h,{format:He?"NHWC":"NCHW",autoPad:x,dilations:[I],group:L,kernelShape:[U],pads:[le,xe],strides:[Fe],wIsConst:()=>!!F()[st>>>0],outputPadding:bt?Array.from(te().subarray(Number(bt)>>>0,Number(Ft)>>>0)):[],outputShape:Ut?Array.from(te().subarray(Number(Ut)>>>0,Number(fr)>>>0)):[],activation:Ot(js)})},835859:(h,x,I,L,U,le,xe,Fe,He,st,bt,Ft,Ut,fr)=>{n.jb("ConvTranspose",h,{format:Fe?"NHWC":"NCHW",autoPad:x,dilations:Array.from(te().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(te().subarray(Number(U)>>>0,2+(Number(U)>>>0)>>>0)),pads:Array.from(te().subarray(Number(le)>>>0,4+(Number(le)>>>0)>>>0)),strides:Array.from(te().subarray(Number(xe)>>>0,2+(Number(xe)>>>0)>>>0)),wIsConst:()=>!!F()[He>>>0],outputPadding:st?Array.from(te().subarray(Number(st)>>>0,Number(bt)>>>0)):[],outputShape:Ft?Array.from(te().subarray(Number(Ft)>>>0,Number(Ut)>>>0)):[],activation:Ot(fr)})},836520:(h,x,I,L,U,le,xe,Fe,He,st,bt,Ft,Ut,fr,js)=>{n.jb("ConvTranspose",h,{format:He?"NHWC":"NCHW",autoPad:x,dilations:[I],group:L,kernelShape:[U],pads:[le,xe],strides:[Fe],wIsConst:()=>!!F()[st>>>0],outputPadding:bt?Array.from(te().subarray(Number(bt)>>>0,Number(Ft)>>>0)):[],outputShape:Ut?Array.from(te().subarray(Number(Ut)>>>0,Number(fr)>>>0)):[],activation:Ot(js)})},836953:(h,x,I,L,U,le,xe,Fe,He,st,bt,Ft,Ut,fr)=>{n.jb("ConvTranspose",h,{format:Fe?"NHWC":"NCHW",autoPad:x,dilations:Array.from(te().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),group:L,kernelShape:Array.from(te().subarray(Number(U)>>>0,2+(Number(U)>>>0)>>>0)),pads:Array.from(te().subarray(Number(le)>>>0,4+(Number(le)>>>0)>>>0)),strides:Array.from(te().subarray(Number(xe)>>>0,2+(Number(xe)>>>0)>>>0)),wIsConst:()=>!!F()[He>>>0],outputPadding:st?Array.from(te().subarray(Number(st)>>>0,Number(bt)>>>0)):[],outputShape:Ft?Array.from(te().subarray(Number(Ft)>>>0,Number(Ut)>>>0)):[],activation:Ot(fr)})},837614:(h,x)=>{n.jb("GlobalAveragePool",h,{format:x?"NHWC":"NCHW"})},837705:(h,x,I,L,U,le,xe,Fe,He,st,bt,Ft,Ut,fr)=>{n.jb("AveragePool",h,{format:fr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:le?Array.from(te().subarray(Number(le)>>>0,Number(xe)>>>0)):[],kernel_shape:Fe?Array.from(te().subarray(Number(Fe)>>>0,Number(He)>>>0)):[],pads:st?Array.from(te().subarray(Number(st)>>>0,Number(bt)>>>0)):[],strides:Ft?Array.from(te().subarray(Number(Ft)>>>0,Number(Ut)>>>0)):[]})},838184:(h,x)=>{n.jb("GlobalAveragePool",h,{format:x?"NHWC":"NCHW"})},838275:(h,x,I,L,U,le,xe,Fe,He,st,bt,Ft,Ut,fr)=>{n.jb("AveragePool",h,{format:fr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:le?Array.from(te().subarray(Number(le)>>>0,Number(xe)>>>0)):[],kernel_shape:Fe?Array.from(te().subarray(Number(Fe)>>>0,Number(He)>>>0)):[],pads:st?Array.from(te().subarray(Number(st)>>>0,Number(bt)>>>0)):[],strides:Ft?Array.from(te().subarray(Number(Ft)>>>0,Number(Ut)>>>0)):[]})},838754:(h,x)=>{n.jb("GlobalMaxPool",h,{format:x?"NHWC":"NCHW"})},838841:(h,x,I,L,U,le,xe,Fe,He,st,bt,Ft,Ut,fr)=>{n.jb("MaxPool",h,{format:fr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:le?Array.from(te().subarray(Number(le)>>>0,Number(xe)>>>0)):[],kernel_shape:Fe?Array.from(te().subarray(Number(Fe)>>>0,Number(He)>>>0)):[],pads:st?Array.from(te().subarray(Number(st)>>>0,Number(bt)>>>0)):[],strides:Ft?Array.from(te().subarray(Number(Ft)>>>0,Number(Ut)>>>0)):[]})},839316:(h,x)=>{n.jb("GlobalMaxPool",h,{format:x?"NHWC":"NCHW"})},839403:(h,x,I,L,U,le,xe,Fe,He,st,bt,Ft,Ut,fr)=>{n.jb("MaxPool",h,{format:fr?"NHWC":"NCHW",auto_pad:x,ceil_mode:I,count_include_pad:L,storage_order:U,dilations:le?Array.from(te().subarray(Number(le)>>>0,Number(xe)>>>0)):[],kernel_shape:Fe?Array.from(te().subarray(Number(Fe)>>>0,Number(He)>>>0)):[],pads:st?Array.from(te().subarray(Number(st)>>>0,Number(bt)>>>0)):[],strides:Ft?Array.from(te().subarray(Number(Ft)>>>0,Number(Ut)>>>0)):[]})},839878:(h,x,I,L,U)=>{n.jb("Gemm",h,{alpha:x,beta:I,transA:L,transB:U})},839982:h=>{n.jb("MatMul",h,void 0)},840036:(h,x,I,L)=>{n.jb("ArgMax",h,{keepDims:!!x,selectLastIndex:!!I,axis:L})},840144:(h,x,I,L)=>{n.jb("ArgMin",h,{keepDims:!!x,selectLastIndex:!!I,axis:L})},840252:(h,x)=>{n.jb("Softmax",h,{axis:x})},840315:(h,x)=>{n.jb("Concat",h,{axis:x})},840375:(h,x,I,L,U)=>{n.jb("Split",h,{axis:x,numOutputs:I,splitSizes:L?Array.from(te().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},840531:h=>{n.jb("Expand",h,void 0)},840585:(h,x)=>{n.jb("Gather",h,{axis:Number(x)})},840656:(h,x)=>{n.jb("GatherElements",h,{axis:Number(x)})},840735:(h,x)=>{n.jb("GatherND",h,{batch_dims:Number(x)})},840814:(h,x,I,L,U,le,xe,Fe,He,st,bt)=>{n.jb("Resize",h,{antialias:x,axes:I?Array.from(te().subarray(Number(I)>>>0,Number(L)>>>0)):[],coordinateTransformMode:Ot(U),cubicCoeffA:le,excludeOutside:xe,extrapolationValue:Fe,keepAspectRatioPolicy:Ot(He),mode:Ot(st),nearestMode:Ot(bt)})},841176:(h,x,I,L,U,le,xe)=>{n.jb("Slice",h,{starts:x?Array.from(te().subarray(Number(x)>>>0,Number(I)>>>0)):[],ends:L?Array.from(te().subarray(Number(L)>>>0,Number(U)>>>0)):[],axes:le?Array.from(te().subarray(Number(le)>>>0,Number(xe)>>>0)):[]})},841440:h=>{n.jb("Tile",h,void 0)},841492:(h,x,I)=>{n.jb("InstanceNormalization",h,{epsilon:x,format:I?"NHWC":"NCHW"})},841606:(h,x,I)=>{n.jb("InstanceNormalization",h,{epsilon:x,format:I?"NHWC":"NCHW"})},841720:h=>{n.jb("Range",h,void 0)},841773:(h,x)=>{n.jb("Einsum",h,{equation:Ot(x)})},841854:(h,x,I,L,U)=>{n.jb("Pad",h,{mode:x,value:I,pads:L?Array.from(te().subarray(Number(L)>>>0,Number(U)>>>0)):[]})},841997:(h,x,I,L,U,le)=>{n.jb("BatchNormalization",h,{epsilon:x,momentum:I,spatial:!!U,trainingMode:!!L,format:le?"NHWC":"NCHW"})},842166:(h,x,I,L,U,le)=>{n.jb("BatchNormalization",h,{epsilon:x,momentum:I,spatial:!!U,trainingMode:!!L,format:le?"NHWC":"NCHW"})},842335:(h,x,I)=>{n.jb("CumSum",h,{exclusive:Number(x),reverse:Number(I)})},842432:(h,x,I)=>{n.jb("DequantizeLinear",h,{axis:x,blockSize:I})},842522:(h,x,I,L,U)=>{n.jb("GridSample",h,{align_corners:x,mode:Ot(I),padding_mode:Ot(L),format:U?"NHWC":"NCHW"})},842692:(h,x,I,L,U)=>{n.jb("GridSample",h,{align_corners:x,mode:Ot(I),padding_mode:Ot(L),format:U?"NHWC":"NCHW"})},842862:(h,x)=>{n.jb("ScatterND",h,{reduction:Ot(x)})},842947:(h,x,I,L,U,le,xe,Fe,He)=>{n.jb("Attention",h,{numHeads:x,isUnidirectional:I,maskFilterValue:L,scale:U,doRotary:le,qkvHiddenSizes:xe?Array.from(te().subarray(Number(Fe)>>>0,Number(Fe)+xe>>>0)):[],pastPresentShareBuffer:!!He})},843219:h=>{n.jb("BiasAdd",h,void 0)},843274:h=>{n.jb("BiasSplitGelu",h,void 0)},843335:h=>{n.jb("FastGelu",h,void 0)},843391:(h,x,I,L,U,le,xe,Fe,He,st,bt,Ft,Ut,fr,js,Hi)=>{n.jb("Conv",h,{format:Ft?"NHWC":"NCHW",auto_pad:x,dilations:I?Array.from(te().subarray(Number(I)>>>0,Number(L)>>>0)):[],group:U,kernel_shape:le?Array.from(te().subarray(Number(le)>>>0,Number(xe)>>>0)):[],pads:Fe?Array.from(te().subarray(Number(Fe)>>>0,Number(He)>>>0)):[],strides:st?Array.from(te().subarray(Number(st)>>>0,Number(bt)>>>0)):[],w_is_const:()=>!!F()[Number(Ut)>>>0],activation:Ot(fr),activation_params:js?Array.from(Pe().subarray(Number(js)>>>0,Number(Hi)>>>0)):[]})},843975:h=>{n.jb("Gelu",h,void 0)},844027:(h,x,I,L,U,le,xe,Fe,He)=>{n.jb("GroupQueryAttention",h,{numHeads:x,kvNumHeads:I,scale:L,softcap:U,doRotary:le,rotaryInterleaved:xe,smoothSoftmax:Fe,localWindowSize:He})},844244:(h,x,I,L)=>{n.jb("LayerNormalization",h,{axis:x,epsilon:I,simplified:!!L})},844355:(h,x,I,L)=>{n.jb("LayerNormalization",h,{axis:x,epsilon:I,simplified:!!L})},844466:(h,x,I,L,U,le)=>{n.jb("MatMulNBits",h,{k:x,n:I,accuracyLevel:L,bits:U,blockSize:le})},844593:(h,x,I,L,U,le)=>{n.jb("MultiHeadAttention",h,{numHeads:x,isUnidirectional:I,maskFilterValue:L,scale:U,doRotary:le})},844752:(h,x)=>{n.jb("QuickGelu",h,{alpha:x})},844816:(h,x,I,L,U)=>{n.jb("RotaryEmbedding",h,{interleaved:!!x,numHeads:I,rotaryEmbeddingDim:L,scale:U})},844955:(h,x,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:x,simplified:!!I})},845057:(h,x,I)=>{n.jb("SkipLayerNormalization",h,{epsilon:x,simplified:!!I})},845159:(h,x,I,L)=>{n.jb("GatherBlockQuantized",h,{gatherAxis:x,quantizeAxis:I,blockSize:L})},845280:h=>{n.Zb(h)},845314:(h,x)=>n.ac(Number(h),Number(x),n.Fb.dc,n.Fb.errors)};function Ke(h,x,I){return Qr(async()=>{await n.Xb(Number(h),Number(x),Number(I))})}function Ye(){return typeof wasmOffsetConverter<"u"}class ke{constructor(x){Z(this,"name","ExitStatus");this.message=`Program terminated with exit(${x})`,this.status=x}}var Ze=h=>{h.terminate(),h.onmessage=()=>{}},Xe=[],tt=h=>{at.length==0&&(Ae(),fe(at[0]));var x=at.pop();if(!x)return 6;jt.push(x),se[h.Ab]=x,x.Ab=h.Ab;var I={Bb:"run",fc:h.ec,Hb:h.Hb,Ab:h.Ab};return x.postMessage(I,h.Mb),0},ut=0,Ue=(h,x,...I)=>{for(var L=2*I.length,U=eo(),le=kn(8*L),xe=le>>>3,Fe=0;Fe>>0]=He)}return h=Uo(h,0,L,le,x),$n(U),h};function Re(h){if(u)return Ue(0,1,h);if(C=h,!(0{if(C=h,u)throw _t(h),"unwind";Re(h)},at=[],jt=[],O=[],se={},B=h=>{var x=h.Ab;delete se[x],at.push(h),jt.splice(jt.indexOf(h),1),h.Ab=0,Jn(x)};function re(){O.forEach(h=>h())}var fe=h=>new Promise(x=>{h.onmessage=U=>{var le=(U=U.data).Bb;if(U.Gb&&U.Gb!=Ys()){var xe=se[U.Gb];xe?xe.postMessage(U,U.Mb):y(`Internal error! Worker sent a message "${le}" to target pthread ${U.Gb}, but that thread no longer exists!`)}else le==="checkMailbox"?Be():le==="spawnThread"?tt(U):le==="cleanupThread"?B(se[U.hc]):le==="loaded"?(h.loaded=!0,x(h)):le==="alert"?alert(`Thread ${U.ic}: ${U.text}`):U.target==="setimmediate"?h.postMessage(U):le==="callHandler"?n[U.Qb](...U.args):le&&y(`worker sent an unknown command ${le}`)},h.onerror=U=>{throw y(`worker sent an error! ${U.filename}:${U.lineno}: ${U.message}`),U};var I,L=[];for(I of[])n.propertyIsEnumerable(I)&&L.push(I);h.postMessage({Bb:"load",Rb:L,kc:M,lc:v})});function Ae(){var h=new Worker((()=>{let x=URL;return self.location.href>"file:"&&self.location.href<"file;"?new x("ort.bundle.min.mjs",self.location.href):new URL(self.location.href)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});at.push(h)}var Ve=h=>{R();var x=ue()[h+52>>>2>>>0];h=ue()[h+56>>>2>>>0],Go(x,x-h),$n(x)},Tt=(h,x)=>{ut=0,h=Ko(h,x),0>>=0);throw x>>>=0,I>>>=0,ue()[L.Ib+16>>>2>>>0]=0,ue()[L.Ib+4>>>2>>>0]=x,ue()[L.Ib+8>>>2>>>0]=I,h}function Ge(h,x,I,L){return u?Ue(2,1,h,x,I,L):ct(h,x,I,L)}function ct(h,x,I,L){if(h>>>=0,I>>>=0,L>>>=0,p===void 0)return 6;var U=[];return u&&U.length===0?Ge(h,x>>>=0,I,L):(h={ec:I,Ab:h,Hb:L,Mb:U},u?(h.Bb="spawnThread",postMessage(h,U),0):tt(h))}var It=typeof TextDecoder<"u"?new TextDecoder:void 0,Gt=(h,x=0,I=NaN)=>{var L=(x>>>=0)+I;for(I=x;h[I]&&!(I>=L);)++I;if(16(U=(240&U)==224?(15&U)<<12|le<<6|xe:(7&U)<<18|le<<12|xe<<6|63&h[x++])?L+=String.fromCharCode(U):(U-=65536,L+=String.fromCharCode(55296|U>>10,56320|1023&U))}}else L+=String.fromCharCode(U)}return L},Ot=(h,x)=>(h>>>=0)?Gt(W(),h,x):"";function ir(h,x,I){return u?Ue(3,1,h,x,I):0}function Ar(h,x){if(u)return Ue(4,1,h,x)}var ts=h=>{for(var x=0,I=0;I=L?x++:2047>=L?x+=2:55296<=L&&57343>=L?(x+=4,++I):x+=3}return x},yr=(h,x,I)=>{var L=W();if(x>>>=0,0=xe&&(xe=65536+((1023&xe)<<10)|1023&h.charCodeAt(++le)),127>=xe){if(x>=I)break;L[x++>>>0]=xe}else{if(2047>=xe){if(x+1>=I)break;L[x++>>>0]=192|xe>>6}else{if(65535>=xe){if(x+2>=I)break;L[x++>>>0]=224|xe>>12}else{if(x+3>=I)break;L[x++>>>0]=240|xe>>18,L[x++>>>0]=128|xe>>12&63}L[x++>>>0]=128|xe>>6&63}L[x++>>>0]=128|63&xe}}L[x>>>0]=0,h=x-U}else h=0;return h};function rs(h,x){if(u)return Ue(5,1,h,x)}function Es(h,x,I){if(u)return Ue(6,1,h,x,I)}function ws(h,x,I){return u?Ue(7,1,h,x,I):0}function Ps(h,x){if(u)return Ue(8,1,h,x)}function ss(h,x,I){if(u)return Ue(9,1,h,x,I)}function Rr(h,x,I,L){if(u)return Ue(10,1,h,x,I,L)}function Cs(h,x,I,L){if(u)return Ue(11,1,h,x,I,L)}function Ss(h,x,I,L){if(u)return Ue(12,1,h,x,I,L)}function ns(h){if(u)return Ue(13,1,h)}function Ms(h,x){if(u)return Ue(14,1,h,x)}function bs(h,x,I){if(u)return Ue(15,1,h,x,I)}var Ur,ar,De=()=>$e(""),qe=h=>{for(var x="";W()[h>>>0];)x+=Ur[W()[h++>>>0]];return x},nt={},Qt={};function lr(h,x,I={}){return function(L,U,le={}){var xe=U.name;if(!L)throw new ar(`type "${xe}" must have a positive integer typeid pointer`);if(Qt.hasOwnProperty(L)){if(le.Sb)return;throw new ar(`Cannot register type '${xe}' twice`)}Qt[L]=U,nt.hasOwnProperty(L)&&(U=nt[L],delete nt[L],U.forEach(Fe=>Fe()))}(h,x,I)}var ys=(h,x,I)=>{switch(x){case 1:return I?L=>F()[L>>>0]:L=>W()[L>>>0];case 2:return I?L=>ee()[L>>>1>>>0]:L=>me()[L>>>1>>>0];case 4:return I?L=>te()[L>>>2>>>0]:L=>ue()[L>>>2>>>0];case 8:return I?L=>J[L>>>3]:L=>Q[L>>>3];default:throw new TypeError(`invalid integer width (${x}): ${h}`)}};function $s(h,x,I){I>>>=0,lr(h>>>=0,{name:x=qe(x>>>0),fromWireType:L=>L,toWireType:function(L,U){if(typeof U!="bigint"&&typeof U!="number")throw U=U===null?"null":(L=typeof U)=="object"||L==="array"||L==="function"?U.toString():""+U,new TypeError(`Cannot convert "${U}" to ${this.name}`);return typeof U=="number"&&(U=BigInt(U)),U},Cb:Fr,readValueFromPointer:ys(x,I,x.indexOf("u")==-1),Db:null})}var Fr=8;function ks(h,x,I,L){lr(h>>>=0,{name:x=qe(x>>>0),fromWireType:function(U){return!!U},toWireType:function(U,le){return le?I:L},Cb:Fr,readValueFromPointer:function(U){return this.fromWireType(W()[U>>>0])},Db:null})}var jr=[],vr=[];function zs(h){9<(h>>>=0)&&--vr[h+1]==0&&(vr[h]=void 0,jr.push(h))}var xr=h=>{if(!h)throw new ar("Cannot use deleted val. handle = "+h);return vr[h]},$r=h=>{switch(h){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let x=jr.pop()||vr.length;return vr[x]=h,vr[x+1]=1,x}};function Hr(h){return this.fromWireType(ue()[h>>>2>>>0])}var mn={name:"emscripten::val",fromWireType:h=>{var x=xr(h);return zs(h),x},toWireType:(h,x)=>$r(x),Cb:Fr,readValueFromPointer:Hr,Db:null};function fn(h){return lr(h>>>0,mn)}var _n=(h,x)=>{switch(x){case 4:return function(I){return this.fromWireType(Pe()[I>>>2>>>0])};case 8:return function(I){return this.fromWireType(Ne()[I>>>3>>>0])};default:throw new TypeError(`invalid float width (${x}): ${h}`)}};function gn(h,x,I){I>>>=0,lr(h>>>=0,{name:x=qe(x>>>0),fromWireType:L=>L,toWireType:(L,U)=>U,Cb:Fr,readValueFromPointer:_n(x,I),Db:null})}function wn(h,x,I,L,U){if(h>>>=0,I>>>=0,x=qe(x>>>0),U===-1&&(U=4294967295),U=Fe=>Fe,L===0){var le=32-8*I;U=Fe=>Fe<>>le}var xe=x.includes("unsigned")?function(Fe,He){return He>>>0}:function(Fe,He){return He};lr(h,{name:x,fromWireType:U,toWireType:xe,Cb:Fr,readValueFromPointer:ys(x,I,L!==0),Db:null})}function Is(h,x,I){function L(le){var xe=ue()[le>>>2>>>0];return le=ue()[le+4>>>2>>>0],new U(F().buffer,le,xe)}var U=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][x];lr(h>>>=0,{name:I=qe(I>>>0),fromWireType:L,Cb:Fr,readValueFromPointer:L},{Sb:!0})}function Mn(h,x){lr(h>>>=0,{name:x=qe(x>>>0),fromWireType:function(I){for(var L,U=ue()[I>>>2>>>0],le=I+4,xe=le,Fe=0;Fe<=U;++Fe){var He=le+Fe;Fe!=U&&W()[He>>>0]!=0||(xe=Ot(xe,He-xe),L===void 0?L=xe:(L+="\0",L+=xe),xe=He+1)}return Xr(I),L},toWireType:function(I,L){L instanceof ArrayBuffer&&(L=new Uint8Array(L));var U=typeof L=="string";if(!(U||L instanceof Uint8Array||L instanceof Uint8ClampedArray||L instanceof Int8Array))throw new ar("Cannot pass non-string to std::string");var le=U?ts(L):L.length,xe=Cn(4+le+1),Fe=xe+4;if(ue()[xe>>>2>>>0]=le,U)yr(L,Fe,le+1);else if(U)for(U=0;U>>0]=He}else for(U=0;U>>0]=L[U];return I!==null&&I.push(Xr,xe),xe},Cb:Fr,readValueFromPointer:Hr,Db(I){Xr(I)}})}var Ks=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,bn=(h,x)=>{for(var I=h>>1,L=I+x/2;!(I>=L)&&me()[I>>>0];)++I;if(32<(I<<=1)-h&&Ks)return Ks.decode(W().slice(h,I));for(I="",L=0;!(L>=x/2);++L){var U=ee()[h+2*L>>>1>>>0];if(U==0)break;I+=String.fromCharCode(U)}return I},yn=(h,x,I)=>{if(I??(I=2147483647),2>I)return 0;var L=x;I=(I-=2)<2*h.length?I/2:h.length;for(var U=0;U>>1>>>0]=le,x+=2}return ee()[x>>>1>>>0]=0,x-L},As=h=>2*h.length,vn=(h,x)=>{for(var I=0,L="";!(I>=x/4);){var U=te()[h+4*I>>>2>>>0];if(U==0)break;++I,65536<=U?(U-=65536,L+=String.fromCharCode(55296|U>>10,56320|1023&U)):L+=String.fromCharCode(U)}return L},pe=(h,x,I)=>{if(x>>>=0,I??(I=2147483647),4>I)return 0;var L=x;I=L+I-4;for(var U=0;U=le&&(le=65536+((1023&le)<<10)|1023&h.charCodeAt(++U)),te()[x>>>2>>>0]=le,(x+=4)+4>I)break}return te()[x>>>2>>>0]=0,x-L},$=h=>{for(var x=0,I=0;I=L&&++I,x+=4}return x};function N(h,x,I){if(h>>>=0,x>>>=0,I=qe(I>>>=0),x===2)var L=bn,U=yn,le=As,xe=Fe=>me()[Fe>>>1>>>0];else x===4&&(L=vn,U=pe,le=$,xe=Fe=>ue()[Fe>>>2>>>0]);lr(h,{name:I,fromWireType:Fe=>{for(var He,st=ue()[Fe>>>2>>>0],bt=Fe+4,Ft=0;Ft<=st;++Ft){var Ut=Fe+4+Ft*x;Ft!=st&&xe(Ut)!=0||(bt=L(bt,Ut-bt),He===void 0?He=bt:(He+="\0",He+=bt),bt=Ut+x)}return Xr(Fe),He},toWireType:(Fe,He)=>{if(typeof He!="string")throw new ar(`Cannot pass non-string to C++ string type ${I}`);var st=le(He),bt=Cn(4+st+x);return ue()[bt>>>2>>>0]=st/x,U(He,bt+4,st+x),Fe!==null&&Fe.push(Xr,bt),bt},Cb:Fr,readValueFromPointer:Hr,Db(Fe){Xr(Fe)}})}function X(h,x){lr(h>>>=0,{Tb:!0,name:x=qe(x>>>0),Cb:0,fromWireType:()=>{},toWireType:()=>{}})}function ie(h){Sn(h>>>0,!l,1,!a,131072,!1),re()}var ce=h=>{if(!ae)try{if(h(),!(0>>=0,typeof Atomics.jc=="function"&&(Atomics.jc(te(),h>>>2,h).value.then(Be),h+=128,Atomics.store(te(),h>>>2,1))}var Be=()=>{var h=Ys();h&&(ye(h),ce(Zn))};function Qe(h,x){(h>>>=0)==x>>>0?setTimeout(Be):u?postMessage({Gb:h,Bb:"checkMailbox"}):(h=se[h])&&h.postMessage({Bb:"checkMailbox"})}var We=[];function et(h,x,I,L,U){for(x>>>=0,L/=2,We.length=L,I=U>>>0>>>3,U=0;U>>0];return(x?Ie[x]:Ro[h])(...We)}var gt=()=>{ut=0};function At(h){h>>>=0,u?postMessage({Bb:"cleanupThread",hc:h}):B(se[h])}function Lt(h){}var Jt=(h,x)=>{var I=Qt[h];if(I===void 0)throw h=jo(h),I=qe(h),Xr(h),new ar(`${x} has unknown type ${I}`);return I},Vt=(h,x,I)=>{var L=[];return h=h.toWireType(L,I),L.length&&(ue()[x>>>2>>>0]=$r(L)),h};function sr(h,x,I){return x>>>=0,I>>>=0,h=xr(h>>>0),x=Jt(x,"emval::as"),Vt(x,I,h)}function Or(h,x){return x>>>=0,h=xr(h>>>0),(x=Jt(x,"emval::as")).toWireType(null,h)}var Tr=h=>{try{h()}catch(x){$e(x)}},Er=0,Yt=null,os=0,Kt=[],mr={},kr={},is=0,qr=null,cr=[];function Qr(h){return function(x){if(!ae){if(Er===0){var I=!1,L=!1;x((U=0)=>{if(!ae&&(os=U,I=!0,L)){Er=2,Tr(()=>qo(Yt)),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.resume(),U=!1;try{var le=function(){var He=te()[Yt+8>>>2>>>0];return He=dt[kr[He]],--ut,He()}()}catch(He){le=He,U=!0}var xe=!1;if(!Yt){var Fe=qr;Fe&&(qr=null,(U?Fe.reject:Fe.resolve)(le),xe=!0)}if(U&&!xe)throw le}}),L=!0,I||(Er=1,Yt=function(){var U=Cn(65548),le=U+12;ue()[U>>>2>>>0]=le,ue()[U+4>>>2>>>0]=le+65536,le=Kt[0];var xe=mr[le];return xe===void 0&&(xe=is++,mr[le]=xe,kr[xe]=le),le=xe,te()[U+8>>>2>>>0]=le,U}(),typeof MainLoop<"u"&&MainLoop.Pb&&MainLoop.pause(),Tr(()=>to(Yt)))}else Er===2?(Er=0,Tr(ro),Xr(Yt),Yt=null,cr.forEach(ce)):$e(`invalid state: ${Er}`);return os}}(x=>{h().then(x)})}function gr(h){return h>>>=0,Qr(async()=>{var x=await xr(h);return $r(x)})}var Zt=[];function dr(h,x,I,L){return I>>>=0,L>>>=0,(h=Zt[h>>>0])(null,x=xr(x>>>0),I,L)}var pr={},hr=h=>{var x=pr[h];return x===void 0?qe(h):x};function Hs(h,x,I,L,U){return I>>>=0,L>>>=0,U>>>=0,(h=Zt[h>>>0])(x=xr(x>>>0),x[I=hr(I)],L,U)}var xn=()=>typeof globalThis=="object"?globalThis:Function("return this")();function vi(h){return(h>>>=0)==0?$r(xn()):(h=hr(h),$r(xn()[h]))}var xi=h=>{var x=Zt.length;return Zt.push(h),x},Ti=(h,x)=>{for(var I=Array(h),L=0;L>>2>>>0],"parameter "+L);return I},Bs=(h,x)=>Object.defineProperty(x,"name",{value:h});function Ei(h,x,I){var L=(x=Ti(h,x>>>0)).shift();h--;var U=`return function (obj, func, destructorsRef, args) { +`,le=0,xe=[];I===0&&xe.push("obj");for(var Fe=["retType"],He=[L],st=0;stbt.name).join(", ")}) => ${L.name}>`,xi(Bs(I,h))}function Pi(h){return h=hr(h>>>0),$r(n[h])}function Ci(h,x){return x>>>=0,h=xr(h>>>0),x=xr(x),$r(h[x])}function Si(h){9<(h>>>=0)&&(vr[h+1]+=1)}function $i(){return $r([])}function To(h){h=xr(h>>>0);for(var x=Array(h.length),I=0;I>>0))}function Ii(){return $r({})}function Eo(h){for(var x=xr(h>>>=0);x.length;){var I=x.pop();x.pop()(I)}zs(h)}function Ai(h,x,I){x>>>=0,I>>>=0,h=xr(h>>>0),x=xr(x),I=xr(I),h[x]=I}function Po(h,x){return x>>>=0,h=(h=Jt(h>>>0,"_emval_take_value")).readValueFromPointer(x),$r(h)}function Fi(h,x){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),te()[x>>>2>>>0]=h.getUTCSeconds(),te()[x+4>>>2>>>0]=h.getUTCMinutes(),te()[x+8>>>2>>>0]=h.getUTCHours(),te()[x+12>>>2>>>0]=h.getUTCDate(),te()[x+16>>>2>>>0]=h.getUTCMonth(),te()[x+20>>>2>>>0]=h.getUTCFullYear()-1900,te()[x+24>>>2>>>0]=h.getUTCDay(),h=(h.getTime()-Date.UTC(h.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,te()[x+28>>>2>>>0]=h}var Gn=h=>h%4==0&&(h%100!=0||h%400==0),Oi=[0,31,60,91,121,152,182,213,244,274,305,335],Co=[0,31,59,90,120,151,181,212,243,273,304,334];function So(h,x){h=-9007199254740992>h||9007199254740992>>=0,h=new Date(1e3*h),te()[x>>>2>>>0]=h.getSeconds(),te()[x+4>>>2>>>0]=h.getMinutes(),te()[x+8>>>2>>>0]=h.getHours(),te()[x+12>>>2>>>0]=h.getDate(),te()[x+16>>>2>>>0]=h.getMonth(),te()[x+20>>>2>>>0]=h.getFullYear()-1900,te()[x+24>>>2>>>0]=h.getDay();var I=(Gn(h.getFullYear())?Oi:Co)[h.getMonth()]+h.getDate()-1|0;te()[x+28>>>2>>>0]=I,te()[x+36>>>2>>>0]=-60*h.getTimezoneOffset(),I=new Date(h.getFullYear(),6,1).getTimezoneOffset();var L=new Date(h.getFullYear(),0,1).getTimezoneOffset();h=0|(I!=L&&h.getTimezoneOffset()==Math.min(L,I)),te()[x+32>>>2>>>0]=h}function Di(h){h>>>=0;var x=new Date(te()[h+20>>>2>>>0]+1900,te()[h+16>>>2>>>0],te()[h+12>>>2>>>0],te()[h+8>>>2>>>0],te()[h+4>>>2>>>0],te()[h>>>2>>>0],0),I=te()[h+32>>>2>>>0],L=x.getTimezoneOffset(),U=new Date(x.getFullYear(),6,1).getTimezoneOffset(),le=new Date(x.getFullYear(),0,1).getTimezoneOffset(),xe=Math.min(le,U);return 0>I?te()[h+32>>>2>>>0]=+(U!=le&&xe==L):0>>2>>>0]=x.getDay(),I=(Gn(x.getFullYear())?Oi:Co)[x.getMonth()]+x.getDate()-1|0,te()[h+28>>>2>>>0]=I,te()[h>>>2>>>0]=x.getSeconds(),te()[h+4>>>2>>>0]=x.getMinutes(),te()[h+8>>>2>>>0]=x.getHours(),te()[h+12>>>2>>>0]=x.getDate(),te()[h+16>>>2>>>0]=x.getMonth(),te()[h+20>>>2>>>0]=x.getYear(),h=x.getTime(),BigInt(isNaN(h)?-1:h/1e3)}function Tn(h,x,I,L,U,le,xe){return u?Ue(16,1,h,x,I,L,U,le,xe):-52}function $o(h,x,I,L,U,le){if(u)return Ue(17,1,h,x,I,L,U,le)}var qs={},Li=()=>performance.timeOrigin+performance.now();function ko(h,x){if(u)return Ue(18,1,h,x);if(qs[h]&&(clearTimeout(qs[h].id),delete qs[h]),!x)return 0;var I=setTimeout(()=>{delete qs[h],ce(()=>Wo(h,performance.timeOrigin+performance.now()))},x);return qs[h]={id:I,qc:x},0}function zi(h,x,I,L){h>>>=0,x>>>=0,I>>>=0,L>>>=0;var U=new Date().getFullYear(),le=new Date(U,0,1).getTimezoneOffset();U=new Date(U,6,1).getTimezoneOffset();var xe=Math.max(le,U);ue()[h>>>2>>>0]=60*xe,te()[x>>>2>>>0]=+(le!=U),h=(x=Fe=>{var He=Math.abs(Fe);return`UTC${0<=Fe?"-":"+"}${String(Math.floor(He/60)).padStart(2,"0")}${String(He%60).padStart(2,"0")}`})(le),x=x(U),UDate.now();function Ri(h,x,I){return 0<=h&&3>=h?(h===0?h=Date.now():h=performance.timeOrigin+performance.now(),J[I>>>0>>>3]=BigInt(Math.round(1e6*h)),0):28}var Qs=[],Kn=(h,x)=>{Qs.length=0;for(var I;I=W()[h++>>>0];){var L=I!=105;x+=(L&=I!=112)&&x%8?4:0,Qs.push(I==112?ue()[x>>>2>>>0]:I==106?J[x>>>3]:I==105?te()[x>>>2>>>0]:Ne()[x>>>3>>>0]),x+=L?8:4}return Qs};function ji(h,x,I){return h>>>=0,x=Kn(x>>>0,I>>>0),Ie[h](...x)}function Io(h,x,I){return h>>>=0,x=Kn(x>>>0,I>>>0),Ie[h](...x)}var Rs=()=>{};function Ni(h,x){return y(Ot(h>>>0,x>>>0))}var hu=()=>{throw ut+=1,"unwind"};function Vi(){return 4294901760}var mu=()=>navigator.hardwareConcurrency;function Ui(){return $e("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Ao(h){h>>>=0;var x=W().length;if(h<=x||4294901760=I;I*=2){var L=x*(1+.2/I);L=Math.min(L,h+100663296);e:{L=(Math.min(4294901760,65536*Math.ceil(Math.max(h,L)/65536))-M.buffer.byteLength+65535)/65536|0;try{M.grow(L),R();var U=1;break e}catch{}U=void 0}if(U)return!0}return!1}var En=()=>($e("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),Xs={},Fo=h=>{h.forEach(x=>{En()})};function Wi(){var h=Error().stack.toString().split(` +`);return h[0]=="Error"&&h.shift(),Fo(h),Xs.Lb=En(),Xs.cc=h,Xs.Lb}function Gi(h,x,I){if(h>>>=0,x>>>=0,Xs.Lb==h)var L=Xs.cc;else(L=Error().stack.toString().split(` +`))[0]=="Error"&&L.shift(),Fo(L);for(var U=3;L[U]&&En()!=h;)++U;for(h=0;h>>2>>>0]=En();return h}var Js,Hn={},Oo=()=>{if(!Js){var h,x={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(h in Hn)Hn[h]===void 0?delete x[h]:x[h]=Hn[h];var I=[];for(h in x)I.push(`${h}=${x[h]}`);Js=I}return Js};function Do(h,x){if(u)return Ue(19,1,h,x);h>>>=0,x>>>=0;var I=0;return Oo().forEach((L,U)=>{var le=x+I;for(U=ue()[h+4*U>>>2>>>0]=le,le=0;le>>0]=L.charCodeAt(le);F()[U>>>0]=0,I+=L.length+1}),0}function qn(h,x){if(u)return Ue(20,1,h,x);h>>>=0,x>>>=0;var I=Oo();ue()[h>>>2>>>0]=I.length;var L=0;return I.forEach(U=>L+=U.length+1),ue()[x>>>2>>>0]=L,0}function Lo(h){return u?Ue(21,1,h):52}function zo(h,x,I,L){return u?Ue(22,1,h,x,I,L):52}function Qn(h,x,I,L){return u?Ue(23,1,h,x,I,L):70}var Ki=[null,[],[]];function Bo(h,x,I,L){if(u)return Ue(24,1,h,x,I,L);x>>>=0,I>>>=0,L>>>=0;for(var U=0,le=0;le>>2>>>0],Fe=ue()[x+4>>>2>>>0];x+=8;for(var He=0;He>>0],bt=Ki[h];st===0||st===10?((h===1?E:y)(Gt(bt)),bt.length=0):bt.push(st)}U+=Fe}return ue()[L>>>2>>>0]=U,0}u||function(){for(var h=n.numThreads-1;h--;)Ae();Xe.unshift(()=>{be++,function(x){u?x():Promise.all(at.map(fe)).then(x)}(()=>Se())})}();for(var Xn=Array(256),Pn=0;256>Pn;++Pn)Xn[Pn]=String.fromCharCode(Pn);Ur=Xn,ar=n.BindingError=class extends Error{constructor(h){super(h),this.name="BindingError"}},n.InternalError=class extends Error{constructor(h){super(h),this.name="InternalError"}},vr.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>vr.length/2-5-jr.length;var dt,Ro=[Re,_t,Ge,ir,Ar,rs,Es,ws,Ps,ss,Rr,Cs,Ss,ns,Ms,bs,Tn,$o,ko,Do,qn,Lo,zo,Qn,Bo];(async function(){function h(L,U){return dt=L.exports,dt=function(){var le=dt,xe={};for(let[Fe,He]of Object.entries(le))xe[Fe]=typeof He=="function"?(...st)=>{Kt.push(Fe);try{return He(...st)}finally{ae||(Kt.pop(),Yt&&Er===1&&Kt.length===0&&(Er=0,ut+=1,Tr(Ho),typeof Fibers<"u"&&Fibers.rc()))}}:He;return xe}(),dt=function(){var le=dt,xe=He=>st=>He(st)>>>0,Fe=He=>()=>He()>>>0;return(le=Object.assign({},le)).Da=xe(le.Da),le.fb=Fe(le.fb),le.hb=xe(le.hb),le.tb=xe(le.tb),le.ub=Fe(le.ub),le.__cxa_get_exception_ptr=xe(le.__cxa_get_exception_ptr),le}(),O.push(dt.ib),v=U,Se(),dt}be++;var x=Le();if(n.instantiateWasm)return new Promise(L=>{n.instantiateWasm(x,(U,le)=>{h(U,le),L(U.exports)})});if(u)return new Promise(L=>{we=U=>{var le=new WebAssembly.Instance(U,Le());L(h(le,U))}});ve??(ve=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",w):w+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href);try{var I=await async function(L){var U=ve;if(!he&&typeof WebAssembly.instantiateStreaming=="function"&&!V(U))try{var le=fetch(U,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(le,L)}catch(xe){y(`wasm streaming compile failed: ${xe}`),y("falling back to ArrayBuffer instantiation")}return async function(xe,Fe){try{var He=await async function(st){if(!he)try{var bt=await _(st);return new Uint8Array(bt)}catch{}if(st==ve&&he)st=new Uint8Array(he);else{if(!f)throw"both async and sync fetching of the wasm failed";st=f(st)}return st}(xe);return await WebAssembly.instantiate(He,Fe)}catch(st){y(`failed to asynchronously prepare wasm: ${st}`),$e(st)}}(U,L)}(x);return h(I.instance,I.module)}catch(L){return o(L),Promise.reject(L)}})();var jo=h=>(jo=dt.Da)(h),No=()=>(No=dt.Ea)();n._OrtInit=(h,x)=>(n._OrtInit=dt.Fa)(h,x),n._OrtGetLastError=(h,x)=>(n._OrtGetLastError=dt.Ga)(h,x),n._OrtCreateSessionOptions=(h,x,I,L,U,le,xe,Fe,He,st)=>(n._OrtCreateSessionOptions=dt.Ha)(h,x,I,L,U,le,xe,Fe,He,st),n._OrtAppendExecutionProvider=(h,x,I,L,U)=>(n._OrtAppendExecutionProvider=dt.Ia)(h,x,I,L,U),n._OrtAddFreeDimensionOverride=(h,x,I)=>(n._OrtAddFreeDimensionOverride=dt.Ja)(h,x,I),n._OrtAddSessionConfigEntry=(h,x,I)=>(n._OrtAddSessionConfigEntry=dt.Ka)(h,x,I),n._OrtReleaseSessionOptions=h=>(n._OrtReleaseSessionOptions=dt.La)(h),n._OrtCreateSession=(h,x,I)=>(n._OrtCreateSession=dt.Ma)(h,x,I),n._OrtReleaseSession=h=>(n._OrtReleaseSession=dt.Na)(h),n._OrtGetInputOutputCount=(h,x,I)=>(n._OrtGetInputOutputCount=dt.Oa)(h,x,I),n._OrtGetInputOutputMetadata=(h,x,I,L)=>(n._OrtGetInputOutputMetadata=dt.Pa)(h,x,I,L),n._OrtFree=h=>(n._OrtFree=dt.Qa)(h),n._OrtCreateTensor=(h,x,I,L,U,le)=>(n._OrtCreateTensor=dt.Ra)(h,x,I,L,U,le),n._OrtGetTensorData=(h,x,I,L,U)=>(n._OrtGetTensorData=dt.Sa)(h,x,I,L,U),n._OrtReleaseTensor=h=>(n._OrtReleaseTensor=dt.Ta)(h),n._OrtCreateRunOptions=(h,x,I,L)=>(n._OrtCreateRunOptions=dt.Ua)(h,x,I,L),n._OrtAddRunConfigEntry=(h,x,I)=>(n._OrtAddRunConfigEntry=dt.Va)(h,x,I),n._OrtReleaseRunOptions=h=>(n._OrtReleaseRunOptions=dt.Wa)(h),n._OrtCreateBinding=h=>(n._OrtCreateBinding=dt.Xa)(h),n._OrtBindInput=(h,x,I)=>(n._OrtBindInput=dt.Ya)(h,x,I),n._OrtBindOutput=(h,x,I,L)=>(n._OrtBindOutput=dt.Za)(h,x,I,L),n._OrtClearBoundOutputs=h=>(n._OrtClearBoundOutputs=dt._a)(h),n._OrtReleaseBinding=h=>(n._OrtReleaseBinding=dt.$a)(h),n._OrtRunWithBinding=(h,x,I,L,U)=>(n._OrtRunWithBinding=dt.ab)(h,x,I,L,U),n._OrtRun=(h,x,I,L,U,le,xe,Fe)=>(n._OrtRun=dt.bb)(h,x,I,L,U,le,xe,Fe),n._OrtEndProfiling=h=>(n._OrtEndProfiling=dt.cb)(h),n._JsepOutput=(h,x,I)=>(n._JsepOutput=dt.db)(h,x,I),n._JsepGetNodeName=h=>(n._JsepGetNodeName=dt.eb)(h);var Ys=()=>(Ys=dt.fb)(),Xr=n._free=h=>(Xr=n._free=dt.gb)(h),Cn=n._malloc=h=>(Cn=n._malloc=dt.hb)(h),Sn=(h,x,I,L,U,le)=>(Sn=dt.kb)(h,x,I,L,U,le),Vo=()=>(Vo=dt.lb)(),Uo=(h,x,I,L,U)=>(Uo=dt.mb)(h,x,I,L,U),Jn=h=>(Jn=dt.nb)(h),Yn=h=>(Yn=dt.ob)(h),Wo=(h,x)=>(Wo=dt.pb)(h,x),Zn=()=>(Zn=dt.qb)(),Go=(h,x)=>(Go=dt.rb)(h,x),$n=h=>($n=dt.sb)(h),kn=h=>(kn=dt.tb)(h),eo=()=>(eo=dt.ub)(),Ko=n.dynCall_ii=(h,x)=>(Ko=n.dynCall_ii=dt.vb)(h,x),to=h=>(to=dt.wb)(h),Ho=()=>(Ho=dt.xb)(),qo=h=>(qo=dt.yb)(h),ro=()=>(ro=dt.zb)();return n.stackSave=()=>eo(),n.stackRestore=h=>$n(h),n.stackAlloc=h=>kn(h),n.setValue=function(h,x,I="i8"){switch(I.endsWith("*")&&(I="*"),I){case"i1":case"i8":F()[h>>>0]=x;break;case"i16":ee()[h>>>1>>>0]=x;break;case"i32":te()[h>>>2>>>0]=x;break;case"i64":J[h>>>3]=BigInt(x);break;case"float":Pe()[h>>>2>>>0]=x;break;case"double":Ne()[h>>>3>>>0]=x;break;case"*":ue()[h>>>2>>>0]=x;break;default:$e(`invalid type for setValue: ${I}`)}},n.getValue=function(h,x="i8"){switch(x.endsWith("*")&&(x="*"),x){case"i1":case"i8":return F()[h>>>0];case"i16":return ee()[h>>>1>>>0];case"i32":return te()[h>>>2>>>0];case"i64":return J[h>>>3];case"float":return Pe()[h>>>2>>>0];case"double":return Ne()[h>>>3>>>0];case"*":return ue()[h>>>2>>>0];default:$e(`invalid type for getValue: ${x}`)}},n.UTF8ToString=Ot,n.stringToUTF8=yr,n.lengthBytesUTF8=ts,function h(){if(0{Pa(),Ia=typeof location>"u"?void 0:location.origin,Aa=self.location.href>"file:"&&self.location.href<"file;",Zc=()=>{{if(Aa){let e=URL;return new URL(new e("ort.bundle.min.mjs",self.location.href).href,Ia).href}return self.location.href}},Gr=Zc(),ed=()=>{if(Gr&&!Gr.startsWith("blob:"))return Gr.substring(0,Gr.lastIndexOf("/")+1)},ei=(e,r)=>{try{let t=r??Gr;return(t?new URL(e,t):new URL(e)).origin===Ia}catch{return!1}},td=(e,r)=>{let t=r??Gr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},rd=(e,r)=>`${r??"./"}${e}`,Fa=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},sd=async e=>(await import(e)).default,Oa=(yv(),io(qc)).default,nd=async()=>{if(!Gr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ei(Gr))return[void 0,Oa()];let e=await Fa(Gr);return[e,Oa(e)]},Da=(vv(),io(Xc)).default,od=async(e,r,t)=>{if(!e&&!r&&Da&&Gr&&ei(Gr))return[void 0,Da];{let s="ort-wasm-simd-threaded.jsep.mjs",o=e??td(s,r),n=t&&o&&!ei(o,r),i=n?await Fa(o):o??rd(s,r);return[n?i:void 0,await sd(i)]}}}),za,ti,co,Ba,id,ad,ld,Ra,qt,sn=ze(()=>{La(),ti=!1,co=!1,Ba=!1,id=()=>{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}},ad=()=>{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}},ld=()=>{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}},Ra=async e=>{if(ti)return Promise.resolve();if(co)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ba)throw new Error("previous call to 'initializeWebAssembly()' failed.");co=!0;let r=e.initTimeout,t=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!ld())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ad())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let s=id();t>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=t=1);let o=e.wasmPaths,n=typeof o=="string"?o:void 0,i=o==null?void 0:o.mjs,a=(i==null?void 0:i.href)??i,l=o==null?void 0:o.wasm,u=(l==null?void 0:l.href)??l,p=e.wasmBinary,[c,d]=await od(a,n,t>1),_=!1,f=[];if(r>0&&f.push(new Promise(T=>{setTimeout(()=>{_=!0,T()},r)})),f.push(new Promise((T,k)=>{let w={numThreads:t};if(p)w.wasmBinary=p;else if(u||n)w.locateFile=g=>u??n+g;else if(a&&a.indexOf("blob:")!==0)w.locateFile=g=>new URL(g,a).href;else if(c){let g=ed();g&&(w.locateFile=S=>g+S)}d(w).then(g=>{co=!1,ti=!0,za=g,T(),c&&URL.revokeObjectURL(c)},g=>{co=!1,Ba=!0,k(g)})})),await Promise.race(f),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},qt=()=>{if(ti&&za)return za;throw new Error("WebAssembly is not initialized yet.")}}),ps,ri,Wt,ja=ze(()=>{sn(),ps=(e,r)=>{let t=qt(),s=t.lengthBytesUTF8(e)+1,o=t._malloc(s);return t.stringToUTF8(e,o,s),r.push(o),o},ri=(e,r,t,s)=>{if(typeof e=="object"&&e!==null){if(t.has(e))throw new Error("Circular reference in options");t.add(e)}Object.entries(e).forEach(([o,n])=>{let i=r?r+o:o;if(typeof n=="object")ri(n,i+".",t,s);else if(typeof n=="string"||typeof n=="number")s(i,n.toString());else if(typeof n=="boolean")s(i,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},Wt=e=>{let r=qt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetLastError(o,o+s);let n=Number(r.getValue(o,s===4?"i32":"i64")),i=r.getValue(o+s,"*"),a=i?r.UTF8ToString(i):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),ud,xv=ze(()=>{sn(),ja(),ud=e=>{let r=qt(),t=0,s=[],o=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)o.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${e.logSeverityLevel}`);if((e==null?void 0:e.logVerbosityLevel)===void 0)o.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);(e==null?void 0:e.terminate)===void 0&&(o.terminate=!1);let n=0;return(e==null?void 0:e.tag)!==void 0&&(n=ps(e.tag,s)),t=r._OrtCreateRunOptions(o.logSeverityLevel,o.logVerbosityLevel,!!o.terminate,n),t===0&&Wt("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&ri(e.extra,"",new WeakSet,(i,a)=>{let l=ps(i,s),u=ps(a,s);r._OrtAddRunConfigEntry(t,l,u)!==0&&Wt(`Can't set a run config entry: ${i} - ${a}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(i=>r._free(i)),n}}}),cd,dd,pd,po,hd,md,Tv=ze(()=>{sn(),ja(),cd=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}`)}},dd=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},pd=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)},po=(e,r,t,s)=>{let o=ps(r,s),n=ps(t,s);qt()._OrtAddSessionConfigEntry(e,o,n)!==0&&Wt(`Can't set a session config entry: ${r} - ${t}.`)},hd=async(e,r,t)=>{for(let s of r){let o=typeof s=="string"?s:s.name,n=[];switch(o){case"webnn":if(o="WEBNN",typeof s!="string"){let p=s==null?void 0:s.deviceType;p&&po(e,"deviceType",p,t)}break;case"webgpu":if(o="JS",typeof s!="string"){let p=s;if(p!=null&&p.preferredLayout){if(p.preferredLayout!=="NCHW"&&p.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${p.preferredLayout}`);po(e,"preferredLayout",p.preferredLayout,t)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${o}`)}let i=ps(o,t),a=n.length,l=0,u=0;if(a>0){l=qt()._malloc(a*qt().PTR_SIZE),t.push(l),u=qt()._malloc(a*qt().PTR_SIZE),t.push(u);for(let p=0;p{let r=qt(),t=0,s=[],o=e||{};pd(o);try{let n=cd(o.graphOptimizationLevel??"all"),i=dd(o.executionMode??"sequential"),a=typeof o.logId=="string"?ps(o.logId,s):0,l=o.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let u=o.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let p=typeof o.optimizedModelFilePath=="string"?ps(o.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!o.enableCpuMemArena,!!o.enableMemPattern,i,!!o.enableProfiling,0,a,l,u,p),t===0&&Wt("Can't create session options."),o.executionProviders&&await hd(t,o.executionProviders,s),o.enableGraphCapture!==void 0){if(typeof o.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${o.enableGraphCapture}`);po(t,"enableGraphCapture",o.enableGraphCapture.toString(),s)}if(o.freeDimensionOverrides)for(let[c,d]of Object.entries(o.freeDimensionOverrides)){if(typeof c!="string")throw new Error(`free dimension override name must be a string: ${c}`);if(typeof d!="number"||!Number.isInteger(d)||d<0)throw new Error(`free dimension override value must be a non-negative integer: ${d}`);let _=ps(c,s);r._OrtAddFreeDimensionOverride(t,_,d)!==0&&Wt(`Can't set a free dimension override: ${c} - ${d}.`)}return o.extra!==void 0&&ri(o.extra,"",new WeakSet,(c,d)=>{po(t,c,d,s)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&Wt("Can't release session options."),s.forEach(i=>r._free(i)),n}}}),jn,Fs,nn,Na,si,Va,Ua,Wa,ft=ze(()=>{jn=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},Fs=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},nn=(e,r)=>{let t=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof r=="number"?r:r.reduce((o,n)=>o*n,1);return t>0?Math.ceil(s*t):void 0},Na=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}`)}},si=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}`)}},Va=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Ua=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Wa=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}`)}}}),Ga,fd=ze(()=>{Pa(),Ga=async e=>{if(typeof e=="string"){let r=await fetch(e);if(!r.ok)throw new Error(`failed to load external data file: ${e}`);let t=r.headers.get("Content-Length"),s=t?parseInt(t,10):0;if(s<1073741824)return new Uint8Array(await r.arrayBuffer());{if(!r.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let o=r.body.getReader(),n;try{n=new ArrayBuffer(s)}catch(a){if(a instanceof RangeError){let l=Math.ceil(s/65536);n=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw a}let i=0;for(;;){let{done:a,value:l}=await o.read();if(a)break;let u=l.byteLength;new Uint8Array(n,i,u).set(l),i+=u}return new Uint8Array(n,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),_d,gd,wd,Md,Ka,bd,kt,Os=ze(()=>{ft(),_d=["V","I","W","E","F"],gd=(e,r)=>{console.log(`[${_d[e]},${new Date().toISOString()}]${r}`)},Ka=(e,r)=>{wd=e,Md=r},bd=(e,r)=>{let t=si(e),s=si(wd);t>=s&&gd(t,typeof r=="function"?r():r)},kt=(...e)=>{Md&&bd(...e)}}),yd,Nn,Me,ni,vd,xd,Td,yt=ze(()=>{yd=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},Nn=class{static calcShape(e,r,t=!1){let s=e.length,o=r.length;if(s===0)return r;if(o===0)return e;let n=Math.max(e.length,r.length),i=new Array(n);if(t){if(s<2||o<2)return;let a=yd.calcMatMulShape([e[s-2],e[s-1]],[r[o-2],r[o-1]]);if(a===void 0)return;[i[n-2],i[n-1]]=a}for(let a=t?3:1;a<=n;a++){let l=s-a<0?1:e[s-a],u=o-a<0?1:r[o-a];if(l!==u&&l>1&&u>1)return;let p=Math.max(l,u);if(l&&u)i[n-a]=Math.max(l,u);else{if(p>1)return;i[n-a]=0}}return i}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let o=1;o<=t;o++)if(e[t-o]!==1&&e[t-o]!==r[s-o])return!1;return!0}},Me=class _a{static size(r){return _a.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let o=new Array(s),n=s-1;for(;n>=0;){if(r[n]%t===0){o[n]=r[n]/t;break}if(t%r[n]!==0)throw new Error("cannot convert shape");o[n]=1,t/=r[n],n--}for(n--;n>=0;n--)o[n]=r[n];return o}static sizeFromDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${r.length} dimensions.`);return _a.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 _a.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let o=1;for(let n=t;n=0;--o)s[o]=s[o+1]*r[o+1];return s}static normalizeAxis(r,t){if(r<-t&&r>=t)throw new Error("unsupported axis for this operation.");return r<0?r+t:r}static normalizeAxes(r,t){return r.map(s=>this.normalizeAxis(s,t??r.length))}static sortBasedOnPerm(r,t){return t?t.map(s=>r[s]):r.slice().reverse()}static padShape(r,t){let s=r.length;return r.map((o,n)=>o+t[n]+t[n+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,o)=>s===t[o])}},ni=class Jo{static adjustPoolAttributes(r,t,s,o,n,i){if(!r&&s.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(r)for(let a=0;a=s.length?s.push(t[a+2]):s[a]=t[a+2];for(let a=0;a=s[a]||i[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,o,n,i,a){if(a){if(n.length!==2*(r.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==r.length-2)throw new Error("length of strides should be the length of data dimensions");if(o.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{ft(),Ha=(e,r)=>new(Na(r))(e)}),qa,Qa,Pd,Xa,Cd,Ja,Ya,Za,Sd,$d,Ev=ze(()=>{Os(),qa=(e,r=!0)=>{if(e.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let t=e.byteLength/8,s=new BigInt64Array(e.buffer,e.byteOffset,t),o=new Int32Array(t);for(let n=0;n2147483647n||i<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${n}: ${i}`);o[n]=Number(i)}return r?new Uint8Array(o.buffer):o},Qa=(e,r=!0)=>{if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let t=e.byteLength/4,s=new Int32Array(e.buffer,e.byteOffset,t),o=BigInt64Array.from(s,BigInt);return r?new Uint8Array(o.buffer):o},Pd=1,Xa=()=>Pd++,Cd=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Ja=(e,r)=>{let t=Cd.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,o)=>s*o)*t/8):0},Ya=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:r,context:t,tensor:s,dataType:o,shape:n,shouldConvertInt64toInt32:i=!1}=e;this.sessionId=r,this.mlContext=t,this.mlTensor=s,this.dataType=o,this.tensorShape=n,this.shouldConvertInt64toInt32=i}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Ja(this.dataType,this.tensorShape)}destroy(){kt("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=Qa(new Uint8Array(t));if(r){(r instanceof ArrayBuffer?new Uint8Array(r):new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).set(s);return}else return s.buffer}else return r?this.mlContext.readTensor(this.mlTensor,r):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,r,t){return this.mlContext===e&&this.dataType===r&&this.tensorShape.length===t.length&&this.tensorShape.every((s,o)=>s===t[o])}setIsInt64ToInt32Converted(e){this.isInt64ToInt32Converted=e}},Za=class{constructor(e,r){this.tensorManager=e,this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,r,t,s){let o=r,n=this.tensorManager.getMLContext(e),i=o==="int64"&&!n.opSupportLimits().input.dataTypes.includes("int64");if(i&&(o="int32",kt("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(n,o,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Ja(o,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let a=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,o,t,a,!0,!0,i),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let r=e;if(this.wrapper)if(this.wrapper.shouldConvertInt64toInt32&&(r=qa(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),r.byteLength===this.wrapper.byteLength){this.wrapper.write(r);return}else kt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(r):this.activeUpload=new Uint8Array(r)}async download(e){var r,t,s;if(this.activeUpload){let o=(r=this.wrapper)!=null&&r.isInt64ToInt32Converted?Qa(this.activeUpload):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(o):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o);return}else return o.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read((t=this.wrapper)==null?void 0:t.shouldConvertInt64toInt32,e):this.wrapper.read((s=this.wrapper)==null?void 0:s.shouldConvertInt64toInt32)}},Sd=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=Xa();return this.tensorTrackersById.set(e,new Za(this)),e}releaseTensorId(e){let r=this.tensorTrackersById.get(e);r&&(this.tensorTrackersById.delete(e),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(e,r,t,s,o){kt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${o}}`);let n=this.tensorTrackersById.get(r);if(!n)throw new Error("Tensor not found.");return n.ensureTensor(e,t,s,o)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){kt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${r==null?void 0:r.byteLength}}`);let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");return t.download(r)}releaseTensorsForSession(e){for(let r of this.freeTensors)r.sessionId===e&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==e)}registerTensor(e,r,t,s){let o=this.getMLContext(e),n=Xa(),i=new Ya({sessionId:e,context:o,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(n,new Za(this,i)),this.externalTensors.add(i),n}async getCachedTensor(e,r,t,s,o,n,i=!1){let a=this.getMLContext(e);for(let[u,p]of this.freeTensors.entries())if(p.canReuseTensor(a,r,t)){kt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let c=this.freeTensors.splice(u,1)[0];return c.sessionId=e,c}kt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let l=await a.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:o,readable:n});return new Ya({sessionId:e,context:a,tensor:l,dataType:r,shape:t,shouldConvertInt64toInt32:i})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},$d=(...e)=>new Sd(...e)}),oi,kd,Id,Pv=ze(()=>{ft(),sn(),Ed(),Ev(),Os(),oi=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),kd=(e,r)=>{if(e===r)return!0;if(e===void 0||r===void 0)return!1;let t=Object.keys(e).sort(),s=Object.keys(r).sort();return t.length===s.length&&t.every((o,n)=>o===s[n]&&e[o]===r[o])},Id=class{constructor(e){this.tensorManager=$d(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,Ka(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){kt("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){kt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)kt("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=>kd(t.options,e));if(r!==-1)return this.mlContextCache[r].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,r){this.mlContextBySessionId.set(e,r);let t=this.sessionIdsByMLContext.get(r);t||(t=new Set,this.sessionIdsByMLContext.set(r,t)),t.add(e),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e);let r=this.mlContextBySessionId.get(e);if(!r)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let t=this.sessionIdsByMLContext.get(r);if(t.delete(e),t.size===0){this.sessionIdsByMLContext.delete(r);let s=this.mlContextCache.findIndex(o=>o.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){kt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,o){let n=oi.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,n,s,o)}async createTemporaryTensor(e,r,t){kt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=oi.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let o=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,o,s,t,!1);let n=this.temporarySessionTensorIds.get(e);return n?n.push(o):this.temporarySessionTensorIds.set(e,[o]),o}uploadTensor(e,r){if(!qt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");kt("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 Ha(t,r)}}registerMLTensor(e,r,t,s){let o=oi.get(t);if(!o)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(e,r,o,s);return kt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${o}, dimensions: ${s}} -> {tensorId: ${n}}`),n}registerMLConstant(e,r,t,s,o,n,i=!1){if(!n)throw new Error("External mounted files are not available.");let a=e;e.startsWith("./")&&(a=e.substring(2));let l=n.get(a);if(!l)throw new Error(`File with name ${a} not found in preloaded files.`);if(r+t>l.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=l.slice(r,r+t).buffer,p;switch(o.dataType){case"float32":p=new Float32Array(u);break;case"float16":p=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":p=new Int32Array(u);break;case"uint32":p=new Uint32Array(u);break;case"int64":i?(p=qa(new Uint8Array(u),!1),o.dataType="int32"):p=new BigInt64Array(u);break;case"uint64":p=new BigUint64Array(u);break;case"int8":p=new Int8Array(u);break;case"int4":case"uint4":case"uint8":p=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${o.dataType} in creating WebNN Constant from external data.`)}return kt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${o.dataType}, shape: ${o.shape}}} ${i?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),s.constant(o,p)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}isInt64Supported(e){var r;return!!((r=this.mlContextBySessionId.get(e))!=null&&r.opSupportLimits().input.dataTypes.includes("int64"))}flush(){}}}),el=ze(()=>{}),tl,ii,ai,Ad,Fd,rl,sl,Od,Dd,Cv=ze(()=>{Os(),el(),tl=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]]),ii=[],ai=e=>Math.ceil(Number(e)/16)*16,Ad=e=>{for(let r=0;rFd++,sl=async(e,r,t,s)=>{let o=ai(t),n=e.device.createBuffer({size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let i=e.getCommandEncoder();e.endComputePass(),i.copyBufferToBuffer(r,0,n,0,o),e.flush(),await n.mapAsync(GPUMapMode.READ);let a=n.getMappedRange();if(s){let l=s();return l.set(new Uint8Array(a,0,t)),l}else return new Uint8Array(a.slice(0,t))}finally{n.destroy()}},Od=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 tl)ii.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,o=r.byteLength,n=ai(o),i=this.storageCache.get(e);if(!i)throw new Error("gpu data for uploading does not exist");if(Number(i.originalSize)!==o)throw new Error(`inconsistent data size. gpu data size=${i.originalSize}, data size=${o}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:n,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=a.getMappedRange();new Uint8Array(l).set(new Uint8Array(t,s,o)),a.unmap();let u=this.backend.device.createCommandEncoder();u.copyBufferToBuffer(a,0,i.gpuData.buffer,0,n),this.backend.device.queue.submit([u.finish()]),a.destroy(),kt("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,r){let t=this.storageCache.get(e);if(!t)throw new Error("source gpu data for memcpy does not exist");let s=this.storageCache.get(r);if(!s)throw new Error("destination gpu data for memcpy does not exist");if(t.originalSize!==s.originalSize)throw new Error("inconsistent source and destination gpu data size");let o=ai(t.originalSize),n=this.backend.getCommandEncoder();this.backend.endComputePass(),n.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,o)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return kt("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=rl();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),kt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),kt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=Ad(e),s,o=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,n=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(o||n){let a=(o?this.freeBuffers:this.freeUniformBuffers).get(t);a?a.length>0?s=a.pop():s=this.backend.device.createBuffer({size:t,usage:r}):s=this.backend.device.createBuffer({size:t,usage:r})}else s=this.backend.device.createBuffer({size:t,usage:r});let i={id:rl(),type:0,buffer:s};return this.storageCache.set(i.id,{gpuData:i,originalSize:Number(e)}),kt("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${i.id}`),i}get(e){var r;return(r=this.storageCache.get(e))==null?void 0:r.gpuData}release(e){let r=typeof e=="bigint"?Number(e):e,t=this.storageCache.get(r);if(!t){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return kt("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 sl(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=tl.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&&(kt("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Dd=(...e)=>new Od(...e)}),Ld,Bt,or=ze(()=>{Ld=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}},Bt=e=>new Ld(e)}),Vn,li,br,Dr,lt,rr,nl,Un,Vs,ot,ho,Te,rt,zd,ol,Bd,Rd,xt=ze(()=>{ft(),yt(),Vn=64,li=(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}`)}},br=(e,r=1)=>{let t=li(e,r);return typeof t=="string"?t:t[0]},Dr=(e,r=1)=>{let t=li(e,r);return typeof t=="string"?t:t[1]},lt=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:Me.computeStrides(t)})}),r},rr=e=>e%4===0?4:e%2===0?2:1,nl=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,Un=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,Vs=(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,ot=(e,r,t,s)=>e.startsWith("uniforms.")&&t>4?typeof r=="string"?s==="f16"?`${e}[(${r}) / 8][(${r}) % 8 / 4][(${r}) % 8 % 4]`:`${e}[(${r}) / 4][(${r}) % 4]`:s==="f16"?`${e}[${Math.floor(r/8)}][${Math.floor(r%8/4)}][${r%8%4}]`:`${e}[${Math.floor(r/4)}][${r%4}]`:t>1?`${e}[${r}]`:e,ho=(e,r,t,s,o)=>{let n=typeof t=="number",i=n?t:t.length,a=[...new Array(i).keys()],l=i<2?"u32":i<=4?`vec${i}`:`array`,u=li(r,o),p=typeof u=="string"?u:u[1],c=typeof u=="string"?u:u[0],d={indices:l,value:p,storage:c,tensor:r},_=V=>typeof V=="string"?V:`${V}u`,f={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},T=n?"uniforms.":"",k=`${T}${e}_shape`,w=`${T}${e}_strides`,g="";for(let V=0;V ${d.indices} { + var indices: ${d.indices}; + var current = offset; + ${g} + return indices; + }`,E=V=>(f.offsetToIndices=!0,i<2?V:`o2i_${e}(${V})`),y=[];if(i>=2)for(let V=i-1;V>=0;V--)y.push(`${ot(w,V,i)} * (indices[${V}])`);let M=i<2?"":` + fn i2o_${e}(indices: ${d.indices}) -> u32 { + return ${y.join("+")}; + }`,v=V=>(f.indicesToOffset=!0,i<2?V:`i2o_${e}(${V})`),C=(...V)=>i===0?"0u":`${d.indices}(${V.map(_).join(",")})`,A=(V,F)=>i<2?`${V}`:`${ot(V,F,i)}`,z=(V,F,W)=>i<2?`${V}=${W};`:`${ot(V,F,i)}=${W};`,K={},G=(V,F)=>{f.broadcastedIndicesToOffset=!0;let W=`${F.name}broadcastedIndicesTo${e}Offset`;if(W in K)return`${W}(${V})`;let ee=[];for(let me=i-1;me>=0;me--){let te=F.indicesGet("outputIndices",me+F.rank-i);ee.push(`${A(w,me)} * (${te} % ${A(k,me)})`)}return K[W]=`fn ${W}(outputIndices: ${F.type.indices}) -> u32 { + return ${ee.length>0?ee.join("+"):"0u"}; + }`,`${W}(${V})`},j=(V,F)=>(()=>{if(d.storage===d.value)return`${e}[${V}]=${F};`;if(d.storage==="vec2"&&d.value==="i32")return`${e}[${V}]=vec2(u32(${F}), select(0u, 0xFFFFFFFFu, ${F} < 0));`;if(d.storage==="vec2"&&d.value==="u32")return`${e}[${V}]=vec2(u32(${F}), 0u);`;if(d.storage==="u32"&&d.value==="vec4")return`${e}[${V}]=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`)})(),Y=V=>(()=>{if(d.storage===d.value)return`${e}[${V}]`;if(d.storage==="vec2"&&d.value==="i32")return`i32(${e}[${V}].x)`;if(d.storage==="vec2"&&d.value==="u32")return`u32(${e}[${V}].x)`;if(d.storage==="u32"&&d.value==="vec4")return`vec4(bool(${e}[${V}] & 0xFFu), bool(${e}[${V}] & 0xFF00u), bool(${e}[${V}] & 0xFF0000u), bool(${e}[${V}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${d.storage} and value type ${d.value} yet`)})(),H=i<2?"":` + fn get_${e}ByIndices(indices: ${d.indices}) -> ${p} { + return ${Y(`i2o_${e}(indices)`)}; + }`,J=i<2?"":(()=>{let V=a.map(W=>`d${W}: u32`).join(", "),F=a.map(W=>`d${W}`).join(", ");return` + fn get_${e}(${V}) -> ${p} { + return get_${e}ByIndices(${C(F)}); + }`})(),Q=(...V)=>{if(V.length!==i)throw new Error(`indices length must be ${i}`);let F=V.map(_).join(",");return i===0?Y("0u"):i===1?Y(F[0]):(f.get=!0,f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}(${F})`)},oe=V=>i<2?Y(V):(f.getByIndices=!0,f.indicesToOffset=!0,`get_${e}ByIndices(${V})`),he=i<2?"":` + fn set_${e}ByIndices(indices: ${d.indices}, value: ${p}) { + ${j(`i2o_${e}(indices)`,"value")} + }`,ae=i<2?"":(()=>{let V=a.map(W=>`d${W}: u32`).join(", "),F=a.map(W=>`d${W}`).join(", ");return` + fn set_${e}(${V}, value: ${p}) { + set_${e}ByIndices(${C(F)}, value); + }`})();return{impl:()=>{let V=[],F=!1;return f.offsetToIndices&&(V.push(S),F=!0),f.indicesToOffset&&(V.push(M),F=!0),f.broadcastedIndicesToOffset&&(Object.values(K).forEach(W=>V.push(W)),F=!0),f.set&&(V.push(ae),F=!0),f.setByIndices&&(V.push(he),F=!0),f.get&&(V.push(J),F=!0),f.getByIndices&&(V.push(H),F=!0),!n&&F&&V.unshift(`const ${k} = ${d.indices}(${t.join(",")});`,`const ${w} = ${d.indices}(${Me.computeStrides(t).join(",")});`),V.join(` +`)},type:d,offsetToIndices:E,indicesToOffset:v,broadcastedIndicesToOffset:G,indices:C,indicesGet:A,indicesSet:z,set:(...V)=>{if(V.length!==i+1)throw new Error(`indices length must be ${i}`);let F=V[i];if(typeof F!="string")throw new Error("value must be string");let W=V.slice(0,i).map(_).join(",");return i===0?j("0u",F):i===1?j(W[0],F):(f.set=!0,f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}(${W}, ${F})`)},setByOffset:j,setByIndices:(V,F)=>i<2?j(V,F):(f.setByIndices=!0,f.indicesToOffset=!0,`set_${e}ByIndices(${V}, ${F});`),get:Q,getByOffset:Y,getByIndices:oe,usage:s,name:e,strides:w,shape:k,rank:i}},Te=(e,r,t,s=1)=>ho(e,r,t,"input",s),rt=(e,r,t,s=1)=>ho(e,r,t,"output",s),zd=(e,r,t)=>ho(e,r,t,"atomicOutput",1),ol=(e,r,t,s=1)=>ho(e,r,t,"internal",s),Bd=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=Vn){let r=typeof e=="number"?e:e[0],t=typeof e=="number"?1:e[1],s=typeof e=="number"?1:e[2];if(r>this.limits.maxComputeWorkgroupSizeX||t>this.limits.maxComputeWorkgroupSizeY||s>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*t*s>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let o=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,n=o?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,i=o?`let global_idx = global_id.x; + let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] + + workgroup_id.y * num_workgroups[0] + workgroup_id.x; + let global_idx = workgroup_index * ${r*t*s}u + local_idx;`;return`@compute @workgroup_size(${r}, ${t}, ${s}) + fn main(${n}) { + ${i} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,r){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let t=e.usage==="input"?"read":"read_write",s=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${r}) var ${e.name}: array<${s}>;`}declareVariables(...e){return e.map(r=>this.declareVariable(r,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(e,r,t=1){return this.uniforms.push({name:e,type:r,length:t}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:r,type:t,length:s}of this.uniforms)if(s&&s>4)t==="f16"?e.push(`@align(16) ${r}:array, ${Math.ceil(s/8)}>`):e.push(`${r}:array, ${Math.ceil(s/4)}>`);else{let o=s==null||s===1?t:`vec${s}<${t}>`;e.push(`${r}:${o}`)}return` + struct Uniforms { ${e.join(", ")} }; + @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` +`)+this.internalVariables.map(e=>e.impl()).join(` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[e(r.type),r.length??1])}},Rd=(e,r)=>new Bd(e,r)}),jd,il,Nd,Vd,Ud,Wd,Kr,Gd,Kd,Us=ze(()=>{ft(),yt(),or(),xt(),jd=(e,r)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(r.length!==0&&r.length!==e[0].dims.length)throw new Error(`perm size ${r.length} does not match input rank ${e[0].dims.length}`)},il=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),Nd=(e,r)=>Me.sortBasedOnPerm(e,il(e.length,r)),Vd=(e,r,t,s)=>{let o=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`;for(let n=0;n{let t=[],s=[];for(let o=0;o{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,o=il(s,r),n=Nd(e.dims,o),i=e.dims,a=n,l=s<2||Wd(o,e.dims),u;if(l)return u=f=>{let T=Te("input",t,i,4),k=rt("output",t,a,4);return` + ${f.registerUniform("output_size","u32").declareVariables(T,k)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let f=Me.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64/4)},programUniforms:[{type:12,data:Math.ceil(f/4)}]}},getShaderSource:u};let{newShape:p,newPerm:c}=Ud(e.dims,o),d=Me.areEqual(c,[2,3,1]),_=Me.areEqual(c,[3,1,2]);if(p.length===2||d||_){i=d?[p[0],p[1]*p[2]]:_?[p[0]*p[1],p[2]]:p,a=[i[1],i[0]];let f=16;return u=T=>{let k=Te("a",t,i.length),w=rt("output",t,a.length);return` + ${T.registerUniform("output_size","u32").declareVariables(k,w)} + var tile : array, ${f}>; + ${T.mainStart([f,f,1])} + let stride = (uniforms.output_shape[1] - 1) / ${f} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${f}u + local_id.x; + let input_row = workgroup_id_x * ${f}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${k.getByIndices(`${k.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${f}u + local_id.x; + let output_row = workgroup_id_y * ${f}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${w.setByIndices(`${w.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let T=Me.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/f),y:Math.ceil(a[0]/f)},programUniforms:[{type:12,data:T},...lt(i,a)]}},getShaderSource:u}}return u=f=>{let T=Te("a",t,i.length),k=rt("output",t,a.length);return` + ${f.registerUniform("output_size","u32").declareVariables(T,k)} + + ${Vd(o,s,T,k)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${k.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${k.setByOffset("global_idx",T.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let f=Me.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...lt(i,a)]}},getShaderSource:u}},Gd=(e,r)=>{jd(e.inputs,r.perm),e.compute(Kr(e.inputs[0],r.perm))},Kd=e=>Bt({perm:e.perm})}),Hd,qd,Qd,Xd,Jd,Yd,Zd,ep,tp,rp,hs,sp,np,op,ip,ap,lp,up,cp,dp,pp,Sv=ze(()=>{ft(),yt(),xt(),ll(),Us(),Hd={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"},qd={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"},Qd={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Xd={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Jd=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,o]},Zd=(e,r)=>{let t=e.length+r.length,s=[],o=0;for(let n=0;n{for(let t=0;t{let t=[];if(!ep(e,r)){for(let s=0;st.push(s))}return t},rp=(e,r,t,s,o,n,i)=>{let a=t[0].dims,l=Me.size(n),u=Me.size(i),p=Te("_A",t[0].dataType,a),c=rt("output",o,n),d=64;l===1&&(d=256);let _=` + var aBestValues : array; + `,f=T=>` + ${T.registerUniform("reduceSize","u32").declareVariables(p,c)} + ${_} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${T.mainStart(d)} + + let outputIndex = global_idx / ${d}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${Qd[s]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${d}) { + let candidate = f32(${p.getByOffset("offset + k")}); + bestValue = ${Hd[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 = ${qd[s]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${c.setByOffset("outputIndex",`${s==="mean"?`${c.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${c.type.storage}(${Xd[s]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${r};${d}`,inputDependencies:["type"]},getShaderSource:f,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:l},programUniforms:[{type:12,data:u}]})}},hs=(e,r,t,s)=>{let o=e.inputs.length===1?t:al(e.inputs,t),n=o.axes;n.length===0&&!o.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((_,f)=>f));let i=Me.normalizeAxes(n,e.inputs[0].dims.length),a=i,l=e.inputs[0],u=tp(a,e.inputs[0].dims.length);u.length>0&&(l=e.compute(Kr(e.inputs[0],u),{inputs:[0],outputs:[-1]})[0],a=Jd(a.length,l.dims.length));let[p,c]=Yd(l.dims,a),d=p;o.keepDims&&(d=Zd(p,i)),e.compute(rp(r,o.cacheKey,[l],s,e.inputs[0].dataType,d,c),{inputs:[l]})},sp=(e,r)=>{hs(e,"ReduceMeanShared",r,"mean")},np=(e,r)=>{hs(e,"ReduceL1Shared",r,"l1")},op=(e,r)=>{hs(e,"ReduceL2Shared",r,"l2")},ip=(e,r)=>{hs(e,"ReduceLogSumExpShared",r,"logSumExp")},ap=(e,r)=>{hs(e,"ReduceMaxShared",r,"max")},lp=(e,r)=>{hs(e,"ReduceMinShared",r,"min")},up=(e,r)=>{hs(e,"ReduceProdShared",r,"prod")},cp=(e,r)=>{hs(e,"ReduceSumShared",r,"sum")},dp=(e,r)=>{hs(e,"ReduceSumSquareShared",r,"sumSquare")},pp=(e,r)=>{hs(e,"ReduceLogSumShared",r,"logSum")}}),ms,hp,ui,al,fs,mp,fp,_p,gp,wp,Mp,bp,yp,vp,xp,_s,Tp,Ep,Pp,Cp,Sp,$p,kp,Ip,Ap,Fp,ll=ze(()=>{ft(),yt(),or(),xt(),Sv(),ms=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.")},hp=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],ui=(e,r,t,s,o,n,i=!1,a=!1)=>{let l=[],u=t[0].dims,p=u.length,c=Me.normalizeAxes(o,p),d=!a&&c.length===0;u.forEach((T,k)=>{d||c.indexOf(k)>=0?i&&l.push(1):l.push(T)});let _=l.length,f=Me.size(l);return{name:e,shaderCache:r,getShaderSource:T=>{let k=[],w=Te("_A",t[0].dataType,p),g=rt("output",n,_),S=s(w,g,c),E=S[2];for(let y=0,M=0;y=0?(i&&M++,E=`for(var j${y}: u32 = 0; j${y} < ${u[y]}; j${y}++) { + ${S[2].includes("last_index")?`let last_index = j${y};`:""} + ${w.indicesSet("input_indices",y,`j${y}`)} + ${E} + }`):(k.push(`${w.indicesSet("input_indices",y,g.indicesGet("output_indices",M))};`),M++);return` + + ${T.registerUniform("output_size","u32").declareVariables(w,g)} + + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${w.type.indices}; + let output_indices = ${g.offsetToIndices("global_idx")}; + + ${k.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:n}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...lt(u,l)]})}},al=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),Bt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},fs=(e,r,t,s)=>{let o=e.inputs,n=o.length===1?t:al(o,t);e.compute(ui(r,{hint:n.cacheKey,inputDependencies:["rank"]},[o[0]],n.noopWithEmptyAxes&&n.axes.length===0?hp:s,n.axes,o[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},mp=(e,r)=>{ms(e.inputs),fs(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},fp=(e,r)=>{ms(e.inputs),fs(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},_p=(e,r)=>{ms(e.inputs),fs(e,"ReduceL2",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},gp=(e,r)=>{ms(e.inputs),fs(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},wp=(e,r)=>{ms(e.inputs),fs(e,"ReduceMax",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(t.indicesSet("input_indices",i,0));return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},Mp=(e,r)=>{ms(e.inputs),fs(e,"ReduceMean",r,(t,s,o)=>{let n=1;for(let i=0;i=0||o.length===0)&&(n*=e.inputs[0].dims[i]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${n});`]})},bp=(e,r)=>{ms(e.inputs),fs(e,"ReduceMin",r,(t,s,o)=>{let n=[];for(let i=0;i=0||o.length===0)&&n.push(`input_indices[${i}] = 0;`);return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},yp=(e,r)=>{ms(e.inputs),fs(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},vp=(e,r)=>{ms(e.inputs),fs(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},xp=(e,r)=>{ms(e.inputs),fs(e,"ReduceSumSquare",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},_s=(e,r,t)=>{if(r.length===0)return t;let s=1,o=1;for(let n=0;n1024},Tp=(e,r)=>{_s(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Mp(e,r):sp(e,r)},Ep=(e,r)=>{_s(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?fp(e,r):np(e,r)},Pp=(e,r)=>{_s(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?_p(e,r):op(e,r)},Cp=(e,r)=>{_s(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?gp(e,r):ip(e,r)},Sp=(e,r)=>{_s(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?wp(e,r):ap(e,r)},$p=(e,r)=>{_s(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?bp(e,r):lp(e,r)},kp=(e,r)=>{_s(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?yp(e,r):up(e,r)},Ip=(e,r)=>{_s(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?vp(e,r):cp(e,r)},Ap=(e,r)=>{_s(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?xp(e,r):dp(e,r)},Fp=(e,r)=>{_s(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?mp(e,r):pp(e,r)}}),ul,Op,Dp,cl,$v=ze(()=>{ft(),or(),ll(),ul=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Op=(e,r)=>{ul(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` +`)}`,`var value = ${s.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?"<=":"<"} value) { + value = ${s.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(ui("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Dp=(e,r)=>{ul(e.inputs);let t=(s,o,n)=>{let i=[];for(let a=0;a=0||n.length===0)&&i.push(`input_indices[${a}] = 0;`);return[`${i.join(` +`)}`,`var value = ${s.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?">=":">"} value) { + value = ${s.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",o.setByOffset("global_idx","best_index")]};e.compute(ui("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},cl=e=>Bt(e)}),Lp,ci,zp,Bp,Rp,mo,jp,Np,dl=ze(()=>{ft(),yt(),el(),xt(),Lp=(e,r)=>{let t=e[0],s=e[1],o=e[2],n=e[3],i=e[4],a=e[5];if(i&&a)throw new Error("Attention cannot have both past and attention_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=t.dims[0],u=t.dims[1],p=t.dims[2];if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(s.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(s.dims[0]!==p)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(o.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let c=o.dims[0]/3,d=c,_=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");c=r.qkvHiddenSizes[0],d=r.qkvHiddenSizes[1],_=r.qkvHiddenSizes[2]}let f=u;if(c!==d)throw new Error("qkv_hidden_sizes first element should be same as the second");if(o.dims[0]!==c+d+_)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let T=0;if(i){if(d!==_)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(i.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(i.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(i.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(i.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(i.dims[4]!==d/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(T=i.dims[3])}let k=f+T,w=-1,g=0;if(n)throw new Error("Mask not supported");if(i)throw new Error("past is not supported");if(a){if(a.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(a.dims[0]!==l||a.dims[1]!==r.numHeads||a.dims[2]!==u||a.dims[3]!==k)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:u,pastSequenceLength:T,kvSequenceLength:f,totalSequenceLength:k,maxSequenceLength:w,inputHiddenSize:p,hiddenSize:c,vHiddenSize:_,headSize:Math.floor(c/r.numHeads),vHeadSize:Math.floor(_/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ci=(e,r,t)=>r&&e?` + let total_sequence_length_input = u32(${r.getByOffset("0")}); + let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); + let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + `:` + ${t?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,zp=(e,r,t,s,o,n,i,a)=>{let l=rr(i?1:n),u=64,p=n/l;p{let g=rt("x",e.dataType,e.dims,l),S=[g],E=i?Te("seq_lens",i.dataType,i.dims):void 0;E&&S.push(E);let y=a?Te("total_sequence_length_input",a.dataType,a.dims):void 0;y&&S.push(y);let M=Dr(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; + ${w.registerUniforms(v).declareVariables(...S)} + ${w.mainStart([u,1,1])} + let batchIdx = workgroup_id.z / uniforms.num_heads; + let headIdx = workgroup_id.z % uniforms.num_heads; + let sequence_length = uniforms.sequence_length; + var total_sequence_length = uniforms.total_sequence_length; + ${ci(E,y,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${u}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${i?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + var thread_max_vector = ${f}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${f}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(l){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${l}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${u}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${f}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${f}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(l){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${l}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${u}; i++) { + sum += thread_sum[i]; + } + + if (sum == 0) { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + x[offset + i] = ${g.type.value}(${M}(1.0) / ${M}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${f}(x[offset + i]); + x[offset + i] = ${g.type.value}(exp(f32input - max_value) / sum); + } + } + ${i?` + for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { + x[offset + total_seq_id] = ${g.type.value}(${M}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${u};${_};${l}`,inputDependencies:T},getShaderSource:k,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:o,z:r*t},programUniforms:d})}},Bp=(e,r,t,s,o,n,i,a,l)=>{let u=i+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,u],c=e>1&&s,d=n.kvNumHeads?n.kvNumHeads:n.numHeads,_=c?[n.batchSize,d,u,n.headSize]:void 0,f=n.nReps?n.nReps:1,T=n.scale===0?1/Math.sqrt(n.headSize):n.scale,k=rr(n.headSize),w=n.headSize/k,g=12,S={x:Math.ceil(u/g),y:Math.ceil(n.sequenceLength/g),z:n.batchSize*n.numHeads},E=[{type:12,data:n.sequenceLength},{type:12,data:w},{type:12,data:u},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:T},{type:12,data:i},{type:12,data:n.kvSequenceLength},{type:12,data:f}],y=c&&s&&Me.size(s.dims)>0,M=["type","type"];y&&M.push("type"),o&&M.push("type"),a&&M.push("type"),l&&M.push("type");let v=[{dims:p,dataType:r.dataType,gpuDataType:0}];c&&v.push({dims:_,dataType:r.dataType,gpuDataType:0});let C=A=>{let z=Te("q",r.dataType,r.dims,k),K=Te("key",t.dataType,t.dims,k),G=[z,K];if(y){let he=Te("past_key",s.dataType,s.dims,k);G.push(he)}o&&G.push(Te("attention_bias",o.dataType,o.dims));let j=a?Te("seq_lens",a.dataType,a.dims):void 0;j&&G.push(j);let Y=l?Te("total_sequence_length_input",l.dataType,l.dims):void 0;Y&&G.push(Y);let H=rt("output",r.dataType,p),J=[H];c&&J.push(rt("present_key",r.dataType,_,k));let Q=Dr(1,k),oe=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${g}u; + + var tileQ: array<${z.type.storage}, ${g*g}>; + var tileK: array<${z.type.storage}, ${g*g}>; + ${A.registerUniforms(oe).declareVariables(...G,...J)} + ${A.mainStart([g,g,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${f===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${f===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${ci(j,Y,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${y&&c?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${c?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${Q}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (global_id.y < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = q[qOffset + local_id.y * uniforms.K + w + local_id.x]; + } + if (n + local_id.y < uniforms.N && w + local_id.x < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${y&&c?` + 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]; + }`} + ${c?`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 += ${Q}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]); + } + + workgroupBarrier(); + } + + if (global_id.y < uniforms.M && global_id.x < total_sequence_length) { + let headOffset = workgroup_id.z * uniforms.M * uniforms.N; + let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x; + var sum: f32 = ${(()=>{switch(k){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw new Error(`Unsupported components: ${k}`)}})()}; + output[outputIdx] = ${H.type.value} (sum * uniforms.alpha) + ${o?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${k};${o!==void 0};${s!==void 0};${e}`,inputDependencies:M},getRunData:()=>({outputs:v,dispatchGroup:S,programUniforms:E}),getShaderSource:C}},Rp=(e,r,t,s,o,n,i=void 0,a=void 0)=>{let l=n+o.kvSequenceLength,u=o.nReps?o.nReps:1,p=o.vHiddenSize*u,c=e>1&&s,d=o.kvNumHeads?o.kvNumHeads:o.numHeads,_=c?[o.batchSize,d,l,o.headSize]:void 0,f=[o.batchSize,o.sequenceLength,p],T=12,k={x:Math.ceil(o.vHeadSize/T),y:Math.ceil(o.sequenceLength/T),z:o.batchSize*o.numHeads},w=[{type:12,data:o.sequenceLength},{type:12,data:l},{type:12,data:o.vHeadSize},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:12,data:p},{type:12,data:n},{type:12,data:o.kvSequenceLength},{type:12,data:u}],g=c&&s&&Me.size(s.dims)>0,S=["type","type"];g&&S.push("type"),i&&S.push("type"),a&&S.push("type");let E=[{dims:f,dataType:r.dataType,gpuDataType:0}];c&&E.push({dims:_,dataType:r.dataType,gpuDataType:0});let y=M=>{let v=Te("probs",r.dataType,r.dims),C=Te("v",t.dataType,t.dims),A=[v,C];g&&A.push(Te("past_value",s.dataType,s.dims));let z=i?Te("seq_lens",i.dataType,i.dims):void 0;i&&A.push(z);let K=a?Te("total_sequence_length_input",a.dataType,a.dims):void 0;a&&A.push(K);let G=[rt("output",r.dataType,f)];c&&G.push(rt("present_value",r.dataType,_));let j=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${T}u; + var tileQ: array<${v.type.value}, ${T*T}>; + var tileV: array<${v.type.value}, ${T*T}>; + ${M.registerUniforms(j).declareVariables(...A,...G)} + ${M.mainStart([T,T,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${u===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${u===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let m = global_id.y; + let n = global_id.x; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.K; + ${ci(z,K,!0)} + let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch + ${g&&c?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${c?"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&&c?` + 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]; + }`} + ${c?` + 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:k,programUniforms:w}),getShaderSource:y}},mo=(e,r,t,s,o,n,i,a,l,u,p=void 0,c=void 0)=>{let d=Math.min(e.outputCount,1+(i?1:0)+(a?1:0)),_=d>1?u.pastSequenceLength:0,f=_+u.kvSequenceLength,T=l&&Me.size(l.dims)>0?l:void 0,k=[r,t];d>1&&i&&Me.size(i.dims)>0&&k.push(i),T&&k.push(T),p&&k.push(p),c&&k.push(c);let w=e.compute(Bp(d,r,t,i,T,u,_,p,c),{inputs:k,outputs:d>1?[-1,1]:[-1]})[0];e.compute(zp(w,u.batchSize,u.numHeads,_,u.sequenceLength,f,p,c),{inputs:p&&c?[w,p,c]:[w],outputs:[]});let g=[w,s];d>1&&a&&Me.size(a.dims)>0&&g.push(a),p&&g.push(p),c&&g.push(c),e.compute(Rp(d,w,s,a,u,_,p,c),{inputs:g,outputs:d>1?[0,2]:[0]})},jp=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,o=r.inputHiddenSize,n=r.headSize,i=12,a={x:Math.ceil(r.headSize/i),y:Math.ceil(r.sequenceLength/i),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],u=[{type:12,data:s},{type:12,data:o},{type:12,data:n},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:r.hiddenSize},{type:12,data:r.hiddenSize+r.hiddenSize+r.vHiddenSize}],p=c=>{let d=rt("output_q",l[0].dataType,t),_=rt("output_k",l[0].dataType,t),f=rt("output_v",l[0].dataType,t),T=Te("input",l[0].dataType,l[0].dims),k=Te("weight",l[1].dataType,l[1].dims),w=Te("bias",l[2].dataType,l[2].dims),g=T.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 = ${i}u; + var tileInput: array<${g}, ${i*i}>; + var tileWeightQ: array<${g}, ${i*i}>; + var tileWeightK: array<${g}, ${i*i}>; + var tileWeightV: array<${g}, ${i*i}>; + ${c.registerUniforms(S).declareVariables(T,k,w,d,_,f)} + ${c.mainStart([i,i,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${g}(0); + var valueK = ${g}(0); + var valueV = ${g}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:a,programUniforms:u}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},Np=(e,r)=>{let t=Lp(e.inputs,r),[s,o,n]=jp(e,t);return mo(e,s,o,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),Vp,Up,Wp,Gp,kv=ze(()=>{ds(),ft(),yt(),or(),xt(),Vp=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,o,n)=>{let i=o.length;if(i!==s.length)throw new Error(`${n}: num dimensions != ${i}`);o.forEach((a,l)=>{if(a!==s[l])throw new Error(`${n}: dim[${l}] do not match`)})};if(e[0].dims.length>1){let s=r.format==="NHWC"?r.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,r.spatial?2:void 0);t(e[1].dims,s,"Invalid input scale"),t(e[2].dims,s,"Invalid input B"),t(e[3].dims,s,"Invalid input mean"),t(e[4].dims,s,"Invalid input var")}else t(e[1].dims,[1],"Invalid input scale"),t(e[2].dims,[1],"Invalid input B"),t(e[3].dims,[1],"Invalid input mean"),t(e[4].dims,[1],"Invalid input var")},Up=(e,r)=>{let{epsilon:t,spatial:s,format:o}=r,n=e[0].dims,i=s?rr(n[n.length-1]):1,a=o==="NHWC"&&n.length>1?i:1,l=Me.size(n)/i,u=s,p=u?n.length:n,c=Te("x",e[0].dataType,e[0].dims,i),d=Te("scale",e[1].dataType,e[1].dims,a),_=Te("bias",e[2].dataType,e[2].dims,a),f=Te("inputMean",e[3].dataType,e[3].dims,a),T=Te("inputVar",e[4].dataType,e[4].dims,a),k=rt("y",e[0].dataType,p,i),w=()=>{let S="";if(s)S=`let cOffset = ${n.length===1?"0u":o==="NHWC"?`outputIndices[${n.length-1}] / ${i}`:"outputIndices[1]"};`;else if(o==="NCHW")S=` + ${k.indicesSet("outputIndices","0","0")} + let cOffset = ${k.indicesToOffset("outputIndices")};`;else{S=`var cIndices = ${d.type.indices}(0); + cIndices[0] = outputIndices[${n.length-1}];`;for(let E=1;E` + const epsilon = ${t}; + ${S.registerUniform("outputSize","u32").declareVariables(c,d,_,f,T,k)} + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${k.offsetToIndices(`global_idx * ${i}`)}; + ${w()} + let scale = ${d.getByOffset("cOffset")}; + let bias = ${_.getByOffset("cOffset")}; + let inputMean = ${f.getByOffset("cOffset")}; + let inputVar = ${T.getByOffset("cOffset")}; + let x = ${c.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${k.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${i}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u?[{type:12,data:l},...lt(n)]:[{type:12,data:l}]})}},Wp=e=>Bt(e),Gp=(e,r)=>{let{inputs:t,outputCount:s}=e,o=Wp({...r,outputCount:s});if(Xt.webgpu.validateInputContent&&Vp(t,o),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Up(t,o))}}),Kp,Hp,qp,Iv=ze(()=>{yt(),xt(),Kp=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")},Hp=e=>{let r=e[0].dims,t=e[0].dims[2],s=Me.size(r)/4,o=e[0].dataType,n=Te("input",o,r,4),i=Te("bias",o,[t],4),a=Te("residual",o,r,4),l=rt("output",o,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:u=>` + const channels = ${t}u / 4; + ${u.declareVariables(n,i,a,l)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(s)} + let value = ${n.getByOffset("global_idx")} + + ${i.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; + ${l.setByOffset("global_idx","value")} + }`}},qp=e=>{Kp(e.inputs),e.compute(Hp(e.inputs))}}),Qp,Dt,Xp,Jp,Yp,Zp,eh,th,rh,sh,nh,oh,ih,ah,lh,uh,fo,ch,di,dh,ph,hh,mh,fh,_h,gh,wh,Mh,bh,yh,vh,xh,Th,Eh,Ph,pl,Ch,hl,ml,Sh,$h,kh,Ih,Ah,Fh,fl=ze(()=>{ft(),yt(),or(),xt(),Qp=(e,r,t,s,o,n,i)=>{let a=Math.ceil(r/4),l="";typeof o=="string"?l=`${o}(a)`:l=o("a");let u=Te("inputData",t,[a],4),p=rt("outputData",s,[a],4),c=[{name:"vec_size",type:"u32"}];return i&&c.push(...i),` + ${e.registerUniforms(c).declareVariables(u,p)} + + ${n??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${u.getByOffset("global_idx")}; + ${p.setByOffset("global_idx",l)} + }`},Dt=(e,r,t,s,o,n=e.dataType,i,a)=>{let l=[{type:12,data:Math.ceil(Me.size(e.dims)/4)}];return i&&l.push(...i),{name:r,shaderCache:{hint:o,inputDependencies:["type"]},getShaderSource:u=>Qp(u,Me.size(e.dims),e.dataType,n,t,s,a),getRunData:u=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(Me.size(u[0].dims)/64/4)},programUniforms:l})}},Xp=e=>{e.compute(Dt(e.inputs[0],"Abs","abs"))},Jp=e=>{e.compute(Dt(e.inputs[0],"Acos","acos"))},Yp=e=>{e.compute(Dt(e.inputs[0],"Acosh","acosh"))},Zp=e=>{e.compute(Dt(e.inputs[0],"Asin","asin"))},eh=e=>{e.compute(Dt(e.inputs[0],"Asinh","asinh"))},th=e=>{e.compute(Dt(e.inputs[0],"Atan","atan"))},rh=e=>{e.compute(Dt(e.inputs[0],"Atanh","atanh"))},sh=e=>Bt(e),nh=(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(Dt(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},oh=e=>{let r,t,s=e.length>=2&&e[1].data!==0,o=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=o?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=o?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Bt({min:r,max:t})},ih=(e,r)=>{let t=r||oh(e.inputs),s=Dr(e.inputs[0].dataType);e.compute(Dt(e.inputs[0],"Clip",o=>`clamp(${o}, vec4<${s}>(uniforms.min), vec4<${s}>(uniforms.max))`,void 0,t.cacheKey,void 0,[{type:e.inputs[0].dataType,data:t.min},{type:e.inputs[0].dataType,data:t.max}],[{name:"min",type:s},{name:"max",type:s}]),{inputs:[0]})},ah=e=>{e.compute(Dt(e.inputs[0],"Ceil","ceil"))},lh=e=>{e.compute(Dt(e.inputs[0],"Cos","cos"))},uh=e=>{e.compute(Dt(e.inputs[0],"Cosh","cosh"))},fo=e=>Bt(e),ch=(e,r)=>{let t=Dr(e.inputs[0].dataType);e.compute(Dt(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))},di=(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)); +}`,dh=e=>{let r=Dr(e.inputs[0].dataType);e.compute(Dt(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,di(r)))},ph=e=>{e.compute(Dt(e.inputs[0],"Exp","exp"))},hh=e=>{e.compute(Dt(e.inputs[0],"Floor","floor"))},mh=e=>{let r=Dr(e.inputs[0].dataType);e.compute(Dt(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,di(r)))},fh=(e,r)=>{let t=Dr(e.inputs[0].dataType);e.compute(Dt(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))},_h=e=>{e.compute(Dt(e.inputs[0],"Not",r=>`!${r}`))},gh=e=>{e.compute(Dt(e.inputs[0],"Neg",r=>`-${r}`))},wh=e=>{e.compute(Dt(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},Mh=e=>{let r=Dr(e.inputs[0].dataType);e.compute(Dt(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},bh=e=>{e.compute(Dt(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},yh=e=>Bt(e),vh=(e,r)=>{let t=Dr(e.inputs[0].dataType);e.compute(Dt(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))},xh=e=>{e.compute(Dt(e.inputs[0],"Sin","sin"))},Th=e=>{e.compute(Dt(e.inputs[0],"Sinh","sinh"))},Eh=e=>{e.compute(Dt(e.inputs[0],"Sqrt","sqrt"))},Ph=e=>{e.compute(Dt(e.inputs[0],"Tan","tan"))},pl=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Ch=e=>{e.compute(Dt(e.inputs[0],"Tanh",pl))},hl=(e="f32")=>` +const fast_gelu_a: ${e} = 0.5; +const fast_gelu_b: ${e} = 0.7978845608028654; +const fast_gelu_c: ${e} = 0.035677408136300125; + +fn tanh_v(v: vec4<${e}>) -> vec4<${e}> { + return ${pl("v")}; +} +`,ml=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,Sh=e=>{let r=Dr(e.inputs[0].dataType);e.compute(Dt(e.inputs[0],"FastGelu",ml,hl(r),void 0,e.inputs[0].dataType))},$h=(e,r)=>{let t=Dr(e.inputs[0].dataType);return e.compute(Dt(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},kh=e=>{e.compute(Dt(e.inputs[0],"Log","log"))},Ih=(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; +} +`,Ah=e=>`quick_gelu_impl(${e})`,Fh=(e,r)=>{let t=Dr(e.inputs[0].dataType);e.compute(Dt(e.inputs[0],"QuickGelu",Ah,Ih(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),Oh,Dh,Lh,Av=ze(()=>{yt(),xt(),fl(),Oh=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")},Dh=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=Te("input",e[0].dataType,e[0].dims,4),s=Te("bias",e[0].dataType,[e[0].dims[2]],4),o=rt("output",e[0].dataType,r,4),n=Me.size(r)/4,i=br(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:a=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${a.declareVariables(t,s,o)} + + ${di(i)} + + ${a.mainStart()} + ${a.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${o.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Lh=e=>{Oh(e.inputs),e.compute(Dh(e.inputs))}}),zh,Bh,gs,Rh,jh,Nh,Vh,Uh,Wh,Gh,Kh,Hh,qh,Fv=ze(()=>{ft(),yt(),xt(),zh=(e,r,t,s,o,n,i,a,l,u,p,c)=>{let d,_;typeof a=="string"?d=_=(g,S)=>`${a}((${g}),(${S}))`:typeof a=="function"?d=_=a:(d=a.scalar,_=a.vector);let f=rt("outputData",p,s.length,4),T=Te("aData",l,r.length,4),k=Te("bData",u,t.length,4),w;if(o)if(n){let g=Me.size(r)===1,S=Me.size(t)===1,E=r.length>0&&r[r.length-1]%4===0,y=t.length>0&&t[t.length-1]%4===0;g||S?w=f.setByOffset("global_idx",_(g?`${T.type.value}(${T.getByOffset("0")}.x)`:T.getByOffset("global_idx"),S?`${k.type.value}(${k.getByOffset("0")}.x)`:k.getByOffset("global_idx"))):w=` + let outputIndices = ${f.offsetToIndices("global_idx * 4u")}; + let offsetA = ${T.broadcastedIndicesToOffset("outputIndices",f)}; + let offsetB = ${k.broadcastedIndicesToOffset("outputIndices",f)}; + ${f.setByOffset("global_idx",_(i||E?T.getByOffset("offsetA / 4u"):`${T.type.value}(${T.getByOffset("offsetA / 4u")}[offsetA % 4u])`,i||y?k.getByOffset("offsetB / 4u"):`${k.type.value}(${k.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else w=f.setByOffset("global_idx",_(T.getByOffset("global_idx"),k.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let g=(S,E,y="")=>{let M=`aData[indexA${E}][componentA${E}]`,v=`bData[indexB${E}][componentB${E}]`;return` + let outputIndices${E} = ${f.offsetToIndices(`global_idx * 4u + ${E}u`)}; + let offsetA${E} = ${T.broadcastedIndicesToOffset(`outputIndices${E}`,f)}; + let offsetB${E} = ${k.broadcastedIndicesToOffset(`outputIndices${E}`,f)}; + let indexA${E} = offsetA${E} / 4u; + let indexB${E} = offsetB${E} / 4u; + let componentA${E} = offsetA${E} % 4u; + let componentB${E} = offsetB${E} % 4u; + ${S}[${E}] = ${y}(${d(M,v)}); + `};p===9?w=` + var data = vec4(0); + ${g("data",0,"u32")} + ${g("data",1,"u32")} + ${g("data",2,"u32")} + ${g("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:w=` + ${g("outputData[global_idx]",0)} + ${g("outputData[global_idx]",1)} + ${g("outputData[global_idx]",2)} + ${g("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(T,k,f)} + + ${c??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${w} + }`},Bh=(e,r,t,s,o,n,i=t.dataType)=>{let a=t.dims.map(T=>Number(T)??1),l=s.dims.map(T=>Number(T)??1),u=!Me.areEqual(a,l),p=a,c=Me.size(a),d=!1,_=!1,f=[u];if(u){let T=Nn.calcShape(a,l,!1);if(!T)throw new Error("Can't perform binary op on the given tensors");p=T.slice(),c=Me.size(p);let k=Me.size(a)===1,w=Me.size(l)===1,g=a.length>0&&a[a.length-1]%4===0,S=l.length>0&&l[l.length-1]%4===0;f.push(k),f.push(w),f.push(g),f.push(S);let E=1;for(let y=1;yT.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:T=>zh(T,a,l,p,d,u,_,o,t.dataType,s.dataType,i,n),getRunData:()=>({outputs:[{dims:p,dataType:i}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:Math.ceil(Me.size(p)/4)},...lt(a,l,p)]})}},gs=(e,r,t,s,o,n)=>{e.compute(Bh(r,o??"",e.inputs[0],e.inputs[1],t,s,n))},Rh=e=>{gs(e,"Add",(r,t)=>`${r}+${t}`)},jh=e=>{gs(e,"Div",(r,t)=>`${r}/${t}`)},Nh=e=>{gs(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},Vh=e=>{gs(e,"Mul",(r,t)=>`${r}*${t}`)},Uh=e=>{let r=Te("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;gs(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)); + } + `)},Wh=e=>{gs(e,"Sub",(r,t)=>`${r}-${t}`)},Gh=e=>{gs(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},Kh=e=>{gs(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},Hh=e=>{gs(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},qh=e=>{gs(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),Qh,Xh,Jh,Yh,Zh,em,Ov=ze(()=>{ft(),yt(),or(),xt(),Qh=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],o=s.dataType,n=s.dims.length;e.forEach((i,a)=>{if(a!==t){if(i.dataType!==o)throw new Error("input tensors should be one type");if(i.dims.length!==n)throw new Error("input tensors should have the same shape");i.dims.forEach((l,u)=>{if(u!==r&&l!==s.dims[u])throw new Error("non concat dimensions must match")})}})},Xh=(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; + }`,Jh=(e,r)=>{let t=e.length,s=[];for(let o=0;o{let o=Me.size(t),n=new Array(e.length),i=new Array(e.length),a=0,l=[],u=[],p=[{type:12,data:o}];for(let T=0;T`uniforms.sizeInConcatAxis${T}`).join(","),f=T=>` + + ${(()=>{T.registerUniform("outputSize","u32");for(let k=0;k(${_}); + ${d} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${Jh(i,c)} + }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:p}),getShaderSource:f}},Zh=(e,r)=>{let t=e.inputs,s=t[0].dims,o=Me.normalizeAxis(r.axis,s.length);Qh(t,o);let n=s.slice();n[o]=t.reduce((a,l)=>a+(l.dims.length>o?l.dims[o]:0),0);let i=t.filter(a=>Me.size(a.dims)>0);e.compute(Yh(i,o,n,t[0].dataType),{inputs:i})},em=e=>Bt({axis:e.axis})}),on,an,ln,_l,un=ze(()=>{ft(),yt(),on=(e,r,t="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${r}(0.0));`;case"Sigmoid":return`value = (${r}(1.0) / (${r}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${r}(${t}(uniforms.clip_min)), ${r}(${t}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${r}(0.0), min(${r}(1.0), ${t}(uniforms.alpha) * value + ${t}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${t}(uniforms.alpha) * value, value, value >= ${r}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},an=(e,r)=>{e.activation==="Clip"?r.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?r.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&r.push({type:1,data:e.alpha})},ln=(e,r)=>{e.activation==="Clip"?r.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?r.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&r.push({name:"alpha",type:"f32"})},_l=e=>{let r=(e==null?void 0:e.activation)||"";if(r==="HardSigmoid"){let[t,s]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:r,alpha:t,beta:s}}else if(r==="Clip"){let[t,s]=(e==null?void 0:e.activation_params)||[xd,Td];return{activation:r,clipMax:s,clipMin:t}}else if(r==="LeakyRelu"){let[t]=(e==null?void 0:e.activation_params)||[.01];return{activation:r,alpha:t}}return{activation:r}}}),Sr,tm,gl=ze(()=>{Sr=(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.`)}},tm=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),rm,Dv=ze(()=>{rm=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)); +} +`}),_o,wl,Ml=ze(()=>{ft(),yt(),xt(),un(),_o=(e,r,t,s,o)=>{let n=s-t;return` + ${Array.from({length:t}).map((i,a)=>` + if (${ot(r.shape,a,r.rank)} != 1) { + ${r.indicesSet(e,a,ot(o,a+n,s))} + } else { + ${r.indicesSet(e,a,0)} + }`).join("")} +`},wl=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i[i.length-2],u=a[a.length-1],p=i[i.length-1],c=rr(u),d=rr(p),_=rr(l),f=Me.size(t)/c/_,T=e.length>2,k=s?s.slice(0,-2):t.slice(0,-2),w=[Me.size(k),l,u],g=[{type:12,data:f},{type:12,data:l},{type:12,data:u},{type:12,data:p}];an(r,g),g.push(...lt(k,i,a)),T&&g.push(...lt(e[2].dims)),g.push(...lt(w));let S=E=>{let y=ol("batch_dims",e[0].dataType,k.length),M=Te("a",e[0].dataType,i.length,d),v=Te("b",e[1].dataType,a.length,c),C=rt("output",e[0].dataType,w.length,c),A=br(C.type.tensor),z=on(r,C.type.value,A),K=[M,v],G="";if(T){let H=o?c:1;K.push(Te("bias",e[2].dataType,e[2].dims.length,H)),G=`${o?`value += bias[col / ${H}];`:`value += ${C.type.value}(bias[row + i]);`}`}let j=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];ln(r,j);let Y=()=>{let H=`var a_data: ${M.type.value};`;for(let J=0;J; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${d}) { + ${Y()} + } + for (var i = 0u; i < ${_}u; i++) { + var value = values[i]; + ${G} + ${z} + let cur_indices = ${C.type.indices}(batch, row + i, col); + let offset = ${C.indicesToOffset("cur_indices")}; + ${C.setByOffset(`offset / ${c}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${c};${d};${_};${o}`,inputDependencies:T?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:g}),getShaderSource:S}}}),sm,nm,bl,yl,om,vl,im,pi,xl=ze(()=>{ft(),yt(),xt(),un(),Ml(),gl(),sm=(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":""}); + `,nm=(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];"} + }`,bl=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32)=>{let l=r[1]*e[1],u=r[0]*e[0],p=o?l:n,c=o?n:l,d=p/r[0],_=n/r[1];if(!((o&&d===4&&e[1]===4||!o&&(d===3||d===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${o} 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 ${n} must be divisible by workgroupSize[1] ${r[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${p/d}>, ${c}>; +var mm_Bsub: array, ${u/e[0]}>, ${n}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${d}; +const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${l}; + + let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${_}; + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let inputRow = tileRow + innerRow; + let inputCol = tileCol; + ${sm(o,s)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${d===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${nm(o,d)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},yl=(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":""}); + `,om=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",vl=(e,r,t="f32",s,o=!1,n=32,i=!1,a=32,l=!1)=>{let u=e[1]*r[1],p=e[0]*r[0],c=o?u:n,d=o?n:u;if(!(d%r[1]===0&&c%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${d} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${c} must be divisible by workgroupSize[0]${r[0]}, tileInner ${n} must be divisible by workgroupSize[1]${r[1]}`);let _=d/r[1],f=c/r[0],T=n/r[1],k=l?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${u}; + let globalColStart = i32(workgroupId.x) * ${p}; + + // Loop over shared dimension. + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${d}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${c}; inputCol = inputCol + ${r[0]}) { + ${yl(o,s)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${n}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${r[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${s?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${t}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${r[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${o?`mm_Asub[k][localRow + innerRow * ${r[1]}];`:`mm_Asub[localRow + innerRow * ${r[1]}][k];`} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + + ACached * BCached[innerCol]; + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let gRow = globalRowStart + localRow + innerRow * ${r[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${r[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${u}; + +let tileRowA = i32(localId.y) * ${_}; +let tileColA = i32(localId.x) * ${f}; +let tileRowB = i32(localId.y) * ${T}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${_}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${f}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${yl(o,s)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${T}; 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) { + ${om(o)} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; + } + } + } + + workgroupBarrier(); +} + +for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + mm_write(batch, globalRow + innerRow, globalCol + innerCol, + acc[innerRow][innerCol]); + } +} +`;return` + var mm_Asub : array, ${d}>; + var mm_Bsub : array, ${n}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${i?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${i?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${i?`i32(globalId.z) * ${a}`:"0"}; + + var acc : array, rowPerThread>; + ${k} + } +`},im=(e,r,t,s,o=!1)=>{let[n,i,a,l]=s,u=br(s[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${Sr(e,u)} { + var value = ${Sr(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${i.type.indices}; + ${_o("aIndices",i,i.rank-2,n.rank,"batchIndices")} + ${i.indicesSet("aIndices",i.rank-2,"u32(row)")} + ${i.indicesSet("aIndices",i.rank-1,"u32(colIn)")} + value = ${i.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${Sr(e,u)} { + var value = ${Sr(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${a.type.indices}; + ${_o("bIndices",a,a.rank-2,n.rank,"batchIndices")} + ${a.indicesSet("bIndices",a.rank-2,"u32(row)")} + ${a.indicesSet("bIndices",a.rank-1,"u32(colIn)")} + value = ${a.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Sr(e,u)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${r?`value = value + ${o?"bias[colIn]":`${Sr(e,u)}(bias[row])`};`:""} + ${t} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},pi=(e,r,t,s,o=!1,n)=>{let i=e[0].dims,a=e[1].dims,l=i.slice(0,-2),u=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),c=Me.size(p),d=i[i.length-2],_=i[i.length-1],f=a[a.length-1],T=_%4===0&&f%4===0,k=d<=8?[4,1,1]:[4,4,1],w=[8,8,1],g=[Math.ceil(f/w[0]/k[0]),Math.ceil(d/w[1]/k[1]),Math.ceil(c/w[2]/k[2])],S=T?4:1,E=[...l,d,_/S],y=E.length,M=[...u,_,f/S],v=M.length,C=[c,d,f/S],A=[{type:6,data:d},{type:6,data:f},{type:6,data:_}];an(r,A),A.push(...lt(p,E,M));let z=["rank","rank"],K=e.length>2;K&&(A.push(...lt(e[2].dims)),z.push("rank")),A.push(...lt(C));let G=j=>{let Y=p.length,H=ol("batchDims",e[0].dataType,Y,1),J=br(e[0].dataType),Q=Te("a",e[0].dataType,y,S),oe=Te("b",e[1].dataType,v,S),he=rt("result",e[0].dataType,C.length,S),ae=[Q,oe];if(K){let me=o?S:1;ae.push(Te("bias",e[2].dataType,e[2].dims.length,me))}let V=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];ln(r,V);let F=br(he.type.tensor),W=on(r,he.type.value,F),ee=im(S,K,W,[H,Q,oe,he],o);return` + ${j.registerUniforms(V).registerInternalVariables(H).declareVariables(...ae,he)} + ${ee} + ${T?bl(k,w,J,H):vl(k,w,J,H)} + `};return{name:"MatMul",shaderCache:{hint:`${k};${r.activation};${T};${o}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:g[0],y:g[1],z:g[2]},programUniforms:A}),getShaderSource:G}}}),am,lm,Lv=ze(()=>{ft(),Os(),xt(),un(),gl(),Dv(),xl(),am=(e,r,t,s,o=!1,n,i=4,a=4,l=4,u="f32")=>{let p=A=>{switch(A){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${u}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${A} is not supported.`)}},c=A=>{switch(A){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${A} is not supported.`)}},d=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,_=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,f=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",T=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",k=e?"row":"col",w=e?"col":"row",g=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${k} / outWidth; + let outCol = ${k} % outWidth; + + let WRow = ${w} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${w} / inChannels % i32(uniforms.w_shape[1]); + let xRow = outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0]; + let xCol = outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1]; + let xCh = ${w} % inChannels; + var resData = ${Sr(i,u)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${f} && xCol >= 0 && xCol < ${T}) { + ${d} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${p(i)} + } + return resData;`,S=e?r&&s?` + let col = colIn * ${i}; + ${g}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${g} + } + return ${Sr(i,u)}(0.0);`:s&&t?` + let col = colIn * ${i}; + ${g}`:` + let col = colIn * ${i}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${g} + } + return ${Sr(i,u)}(0.0);`,E=e?s&&t?c(a):` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${c(a)} + } + return ${Sr(a,u)}(0.0);`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${c(a)} + } + return ${Sr(a,u)}(0.0);`,y=Sr(l,u),M=Sr(e?i:a,u),v=Sr(e?a:i,u),C=on(n,y,u);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${M} { + ${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 : ${y}) { + let col = colIn * ${l}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${_} + ${tm(o)} + ${C} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},lm=(e,r,t,s,o,n,i,a,l)=>{let u=r.format==="NHWC",p=u?e[0].dims[3]:e[0].dims[1],c=t[0],d=u?t[2]:t[3],_=u?t[1]:t[2],f=u?t[3]:t[1],T=u&&(p%4===0||p%3===0)&&f%4===0,k=u?f:d*_,w=u?d*_:f,g=[8,8,1],S=s<=8?[4,1,1]:[4,4,1],E=[Math.ceil(k/g[0]/S[0]),Math.ceil(w/g[1]/S[1]),Math.ceil(c/g[2]/S[2])];kt("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${E}`);let y=T?u&&p%4!==0?3:4:1,M=g[1]*S[1],v=g[0]*S[0],C=Math.max(g[0]*y,g[1]),A=s%M===0,z=o%v===0,K=n%C===0,G=T?[y,4,4]:[1,1,1],j=[{type:6,data:s},{type:6,data:o},{type:6,data:n},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];an(r,j),j.push(...lt(e[0].dims,e[1].dims));let Y=["rank","rank"];i&&(j.push(...lt(e[2].dims)),Y.push("rank")),j.push(...lt(t));let H=J=>{let Q=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];ln(r,Q);let oe=T?4:1,he=br(e[0].dataType),ae=` + fn setOutputAtIndex(flatIndex : i32, value : ${T?`vec4<${he}>`:he}) { + result[flatIndex] = ${T?`vec4<${he}>`:he}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${T?`vec4<${he}>`:he}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${T?"/ 4":""}, value); + }`,V=Te("x",e[0].dataType,e[0].dims.length,y===3?1:y),F=Te("w",e[1].dataType,e[1].dims.length,oe),W=[V,F],ee=rt("result",e[0].dataType,t.length,oe);if(i){let me=Te("bias",e[2].dataType,e[2].dims.length,oe);W.push(me),ae+=` + fn getBiasByOutputCoords(coords : vec4) -> ${T?`vec4<${he}>`:he} { + return bias[coords.${u?"w":"y"}${T?"/ 4":""}]; + }`}return` + ${rm("uniforms.result_strides")} + //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, + // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, + // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; + ${J.registerUniforms(Q).declareVariables(...W,ee)} + ${ae} + ${am(u,A,z,K,i,r,G[0],G[1],G[2],he)} + ${T?bl(S,g,he,void 0,!u,C):vl(S,g,he,void 0,!u,C,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${y};${T};${A};${z};${K};${M};${v};${C}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:E[0],y:E[1],z:E[2]},programUniforms:j}),getShaderSource:H}}}),um,Tl,go,cm,El,dm,pm,hm,zv=ze(()=>{ft(),Os(),yt(),xt(),un(),gl(),um=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,go=(e,r)=>r<=1?e:e+(e-1)*(r-1),cm=(e,r,t,s=1)=>{let o=go(r,s);return Math.floor((e[0]*(t-1)-t+o)/2)},El=(e,r,t,s,o)=>{o==null&&(o=cm(e,r[0],s[0]));let n=[0,0,0,t];for(let i=0;i<3;i++)e[i]+2*o>=r[i]&&(n[i]=Math.trunc((e[i]-r[i]+2*o)/s[i]+1));return n},dm=(e,r,t,s,o,n,i,a,l,u)=>{let p,c,d,_;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let f=El([r,t,s,1],[a,l,u],1,[o,n,i],e);c=f[0],d=f[1],_=f[2]}else if(Array.isArray(e)){if(!e.every((T,k,w)=>T===w[0]))throw Error(`Unsupported padding parameter: ${e}`);p={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let f=El([r,t,s,1],[a,l,u],1,[o,n,i],e[0]);c=f[0],d=f[1],_=f[2]}else if(e==="SAME_UPPER"){c=Math.ceil(r/o),d=Math.ceil(t/n),_=Math.ceil(s/i);let f=(c-1)*o+a-r,T=(d-1)*n+l-t,k=(_-1)*i+u-s,w=Math.floor(f/2),g=f-w,S=Math.floor(T/2),E=T-S,y=Math.floor(k/2),M=k-y;p={top:S,bottom:E,left:y,right:M,front:w,back:g}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:c,outHeight:d,outWidth:_}},pm=(e,r,t,s,o,n=!1,i="channelsLast")=>{let a,l,u,p,c;if(i==="channelsLast")[a,l,u,p,c]=e;else if(i==="channelsFirst")[a,c,l,u,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[d,,_,f,T]=r,[k,w,g]=Tl(t),[S,E,y]=Tl(s),M=go(_,S),v=go(f,E),C=go(T,y),{padInfo:A,outDepth:z,outHeight:K,outWidth:G}=dm(o,l,u,p,k,w,g,M,v,C),j=n?d*c:d,Y=[0,0,0,0,0];return i==="channelsFirst"?Y=[a,j,z,K,G]:i==="channelsLast"&&(Y=[a,z,K,G,j]),{batchSize:a,dataFormat:i,inDepth:l,inHeight:u,inWidth:p,inChannels:c,outDepth:z,outHeight:K,outWidth:G,outChannels:j,padInfo:A,strideDepth:k,strideHeight:w,strideWidth:g,filterDepth:_,filterHeight:f,filterWidth:T,effectiveFilterDepth:M,effectiveFilterHeight:v,effectiveFilterWidth:C,dilationDepth:S,dilationHeight:E,dilationWidth:y,inShape:e,outShape:Y,filterShape:r}},hm=(e,r,t,s,o,n)=>{let i=n==="channelsLast";i?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((k,w)=>w)},u=[Math.ceil(um(l.x.map(k=>t[k]))/a[0]),1,1];kt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let p=1,c=Me.size(t),d=[{type:12,data:c},{type:12,data:s},{type:12,data:o},{type:12,data:r.strides},{type:12,data:r.dilations}];an(r,d),d.push(...lt(e[0].dims,e[1].dims));let _=["rank","rank"],f=e.length===3;f&&(d.push(...lt(e[2].dims)),_.push("rank")),d.push(...lt(t));let T=k=>{let w=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:o.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];ln(r,w);let g=1,S=br(e[0].dataType),E=Te("x",e[0].dataType,e[0].dims.length,p),y=Te("W",e[1].dataType,e[1].dims.length,g),M=[E,y],v=rt("result",e[0].dataType,t.length,g),C="";if(f){let K=Te("bias",e[2].dataType,e[2].dims.length,g);M.push(K),C+=` + fn getBiasByOutputCoords(coords : array) -> ${S} { + return bias[${i?ot("coords",4,5):ot("coords",1,5)}]; + }`}let A=Sr(p,S),z=on(r,A,S);return` + ${C} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${E.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${y.getByIndices("aIndices")}; + } + ${k.registerUniforms(w).declareVariables(...M,v)} + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${v.offsetToIndices("global_idx")}; + let batch = ${ot("coords",0,E.rank)}; + let d2 = ${i?ot("coords",E.rank-1,E.rank):ot("coords",1,E.rank)}; + let xFRCCorner = vec3(${i?ot("coords",1,E.rank):ot("coords",2,E.rank)}, + ${i?ot("coords",2,E.rank):ot("coords",3,E.rank)}, + ${i?ot("coords",3,E.rank):ot("coords",4,E.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${i?ot("uniforms.x_shape",1,E.rank):ot("uniforms.x_shape",2,E.rank)}; + let xShapeZ = ${i?ot("uniforms.x_shape",2,E.rank):ot("uniforms.x_shape",3,E.rank)}; + let xShapeW = ${i?ot("uniforms.x_shape",3,E.rank):ot("uniforms.x_shape",4,E.rank)}; + let xShapeU = ${i?ot("uniforms.x_shape",4,E.rank):ot("uniforms.x_shape",1,E.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${i?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${i?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${i?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${i?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${f?"value = value + getBiasByOutputCoords(coords)":""}; + ${z} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${i};${p};${f}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:d}),getShaderSource:T}}}),mm,fm,Bv=ze(()=>{ft(),yt(),xt(),un(),mm=(e,r,t,s)=>{let o=e.length>2,n=o?"value += b[output_channel];":"",i=e[0].dims,a=e[1].dims,l=r.format==="NHWC",u=l?t[3]:t[1],p=u/r.group,c=l&&p>=4?rr(u):1,d=Me.size(t)/c,_=[{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}];an(r,_),_.push(...lt(i,[a[0],a[1],a[2],a[3]/c]));let f=o?["rank","rank","rank"]:["rank","rank"];_.push(...lt([t[0],t[1],t[2],t[3]/c]));let T=k=>{let w=rt("output",e[0].dataType,t.length,c),g=br(w.type.tensor),S=on(r,w.type.value,g),E=Te("x",e[0].dataType,i.length),y=Te("w",e[1].dataType,a.length,c),M=[E,y];o&&M.push(Te("b",e[2].dataType,e[2].dims,c));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"}];ln(r,v);let C=l?` + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { + continue; + } + + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + let xVal = ${E.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${y.get("wHeight","wWidth","wInChannel","output_channel")}; + value += xVal * wVal; + } + } + } + `:` + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[2]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[2]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[3]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[3]) { + continue; + } + + let xVal = ${E.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${y.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${k.registerUniforms(v).declareVariables(...M,w)} + + ${k.mainStart()} + ${k.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${w.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${l?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${c} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}]; + + var value: ${w.type.value} = ${w.type.value}(0); + ${C} + ${n} + ${S} + ${w.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${c}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:_}),getShaderSource:T}},fm=(e,r,t,s)=>{let o=e.length>2,n=rr(t[3]),i=rr(t[2]),a=Me.size(t)/n/i,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],u=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/n],p=[t[0],t[1],t[2],t[3]/n],c=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];an(r,c),c.push(...lt(l,u,p));let d=(i-1)*r.strides[1]+u[1],_=f=>{let T=rt("output",e[0].dataType,p.length,n),k=br(T.type.tensor),w=on(r,T.type.value,k),g=Te("x",e[0].dataType,l.length,n),S=Te("w",e[1].dataType,u.length,n),E=[g,S];o&&E.push(Te("b",e[2].dataType,e[2].dims,n));let y=o?"value += b[output_channel];":"",M=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return ln(r,M),` + ${f.registerUniforms(M).declareVariables(...E,T)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${i}u; + let col = (index1 % width1) * ${i}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${g.type.value}, ${d}>; + var values: array<${T.type.value}, ${i}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${u[0]}; w_height++) { + let x_height = x_corner.x + i32(w_height); + if (x_height >= 0 && u32(x_height) < uniforms.x_shape[1]) { + for (var i = 0; i < ${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 < ${u[1]}; w_width++) { + let w_val = ${S.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${i}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${i}u; i++) { + var value = values[i]; + ${y} + ${w} + ${T.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${i};${d};${u[0]};${u[1]}`,inputDependencies:o?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c}),getShaderSource:_}}}),_m,hi,gm,mi,Pl,Cl,wm,Mm,Sl,Rv=ze(()=>{yt(),Lv(),zv(),xl(),Bv(),un(),Ml(),Us(),_m=(e,r,t,s,o,n)=>{let i=e[0],a=e.slice(n?1:2,n?3:4),l=a.length,u=r[0],p=r.slice(2).map((d,_)=>d+(d-1)*(t[_]-1)),c=a.map((d,_)=>d+s[_]+s[_+l]).map((d,_)=>Math.floor((d-p[_]+o[_])/o[_]));return c.splice(0,0,i),c.splice(n?3:1,0,u),c},hi=[2,3,1,0],gm=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[1]*r.group;if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let o=e[0].dims.length-2;if(r.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(r.strides.length!==o)throw new Error(`strides should be ${o}D`);if(r.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},mi=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=_l(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],o=e.dilations,n=e.group,i=e.kernel_shape,a=e.pads,l=e.strides,u=e.w_is_const();return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},Cl=(e,r,t,s)=>{let o=t.format==="NHWC",n=_m(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,o);if(t.group!==1){let M=[r[0]];if(o){let v=e.kernelCustomData.wT??e.compute(Kr(r[1],hi),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=v),M.push(v)}else M.push(r[1]);r.length===3&&M.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&o&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(fm(M,t,n,s),{inputs:M}):e.compute(mm(M,t,n,s),{inputs:M});return}let i=r.length===3,a=r[0].dims[o?1:2],l=r[0].dims[o?2:3],u=r[0].dims[o?3:1],p=r[1].dims[2],c=r[1].dims[3],d=n[o?1:2],_=n[o?2:3],f=n[o?3:1],T=o&&p===a&&c===l&&t.pads[0]===0&&t.pads[1]===0;if(T||p===1&&c===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 M=n[0],v,C,A,z=[];if(o){let j=e.kernelCustomData.wT??e.compute(Kr(r[1],hi),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=j),T){let Y=a*l*u;v=r[0].reshape([1,M,Y]),C=j.reshape([1,Y,f]),A=[1,M,f]}else v=r[0].reshape([M,a*l,u]),C=j.reshape([1,u,f]),A=[M,d*_,f];z.push(v),z.push(C)}else v=r[0].reshape([M,u,a*l]),C=r[1].reshape([1,f,u]),A=[M,f,d*_],z.push(C),z.push(v);i&&z.push(r[2]);let K=A[2],G=z[0].dims[z[0].dims.length-1];K<8&&G<8?e.compute(wl(z,t,n,A,o,s),{inputs:z}):e.compute(pi(z,t,n,A,o,s),{inputs:z});return}let k=!0,w=e.kernelCustomData.wT??e.compute(Kr(r[1],hi),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=w);let g=[r[0],w];i&&g.push(r[2]);let S=o?d*_:f,E=o?f:d*_,y=p*c*u;e.compute(lm(g,t,n,S,E,y,i,k,s),{inputs:g})},wm=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let o=[0,r.pads[0],0,r.pads[1]],n=[1].concat(r.strides),i=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=mi({...r,pads:o,strides:n,dilations:i,kernelShape:a},s);Cl(e,s,l,u=>t?[u[0],u[2],u[3]]:[u[0],u[1],u[3]])},Mm=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",o=mi(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,i=pm(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(hm(r,o,i.outShape,[i.filterDepth,i.filterHeight,i.filterWidth],[i.padInfo.front,i.padInfo.top,i.padInfo.left],s))},Sl=(e,r)=>{if(gm(e.inputs,r),e.inputs[0].dims.length===3)wm(e,r);else if(e.inputs[0].dims.length===5)Mm(e,e.inputs,r);else{let t=mi(r,e.inputs);Cl(e,e.inputs,t)}}}),bm,jv=ze(()=>{ft(),Os(),yt(),xt(),bm=(e,r,t)=>{let s=e.length>2,o=r.outputShape,n=r.format==="NHWC",i=r.group,a=e[1].dims,l=a[2]/i,u=a[3],p=n?rr(l):1,c=n&&u===1&&l>=4,d=c?Math.floor(l/4)*4:Math.floor(l/p)*p,_=l-d,f=n?rr(u):1,T=n?u===1?p:f:1,k=Me.size(o)/f,w=[Math.ceil(k/64),1,1];kt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${w}`);let g=["rank","rank"],S=[r.strides[0],r.strides[1]],E=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],y=[r.dilations[0],r.dilations[1]],M=[E[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),E[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],v=[M[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),M[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],C=[{type:12,data:k},{type:12,data:S},{type:12,data:E},{type:12,data:y},{type:12,data:M},{type:6,data:v},{type:12,data:d},{type:12,data:l},{type:12,data:u},...lt(e[0].dims,e[1].dims)];s&&(C.push(...lt(e[2].dims)),g.push("rank")),C.push(...lt(o));let A=z=>{let K=[{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:M.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"}],G=br(e[0].dataType),j=n?1:2,Y=n?2:3,H=n?3:1,J=Te("W",e[1].dataType,e[1].dims.length,T),Q=Te("Dy",e[0].dataType,e[0].dims.length,p),oe=[Q,J];s&&oe.push(Te("bias",e[2].dataType,[o[H]].length,f));let he=rt("result",e[0].dataType,o.length,f),ae=()=>{let W="";if(c)p===4?W+=` + let xValue = ${Q.getByOffset("x_offset")}; + let wValue = ${J.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue); + x_offset += 1u; + w_offset += 1u;`:p===2?W+=` + dotProd = dotProd + dot(vec4<${G}>(${Q.getByOffset("x_offset")}, ${Q.getByOffset("x_offset + 1u")}), vec4<${G}>(${J.getByOffset("w_offset")}, ${J.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;`:p===1&&(W+=` + dotProd = dotProd + dot(vec4<${G}>(${Q.getByOffset("x_offset")}, ${Q.getByOffset("x_offset + 1u")}, ${Q.getByOffset("x_offset + 2u")}, ${Q.getByOffset("x_offset + 3u")}), vec4<${G}>(${J.getByOffset("w_offset")}, ${J.getByOffset("w_offset + 1u")}, ${J.getByOffset("w_offset + 2u")}, ${J.getByOffset("w_offset + 3u")})); + x_offset += 4u; + w_offset += 4u;`);else if(W+=` + let xValue = ${n?Q.getByOffset(`${Q.indicesToOffset(`${Q.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):Q.get("batch","inputChannel","idyR","idyC")}; + `,p===1)W+=` + let w_offset = ${J.indicesToOffset(`${J.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${J.getByOffset(`w_offset / ${T}`)}; + dotProd = dotProd + xValue * wValue;`;else for(let ee=0;ee{if(_===0)return"";if(!c)throw new Error(`packInputAs4 ${c} is not true.`);let W="";if(p===1){W+="dotProd = dotProd";for(let ee=0;ee<_;ee++)W+=` + + ${Q.getByOffset(`x_offset + ${ee}`)} * ${J.getByOffset(`w_offset + ${ee}`)}`;W+=";"}else if(p===2){if(_!==2)throw new Error(`Invalid inputChannelsRemainder ${_}.`);W+=` + let xValue = ${Q.getByOffset("x_offset")}; + let wValue = ${J.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue);`}return W},F=` + let outputIndices = ${he.offsetToIndices(`global_idx * ${f}`)}; + let batch = ${he.indicesGet("outputIndices",0)}; + let d1 = ${he.indicesGet("outputIndices",H)}; + let r = ${he.indicesGet("outputIndices",j)}; + let c = ${he.indicesGet("outputIndices",Y)}; + let dyCorner = vec2(i32(r), i32(c)) - uniforms.pads; + let dyRCorner = dyCorner.x; + let dyCCorner = dyCorner.y; + let groupId = d1 / uniforms.output_channels_per_group; + let wOutChannel = d1 - groupId * uniforms.output_channels_per_group; + // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). + // ? = to be determined. : = across all values in that axis. + var dotProd = ${he.type.value}(0.0); + var wR: u32 = 0; + if (uniforms.dilations.x == 1) { + // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 + wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); + } + for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${G}(dyRCorner) + ${G}(wR)) / ${G}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${G}(uniforms.Dy_shape[${j}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + var wC: u32 = 0; + if (uniforms.dilations.y == 1) { + // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 + wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); + } + for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${G}(dyCCorner) + ${G}(wC)) / ${G}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${G}(uniforms.Dy_shape[${Y}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + ${c?` + var x_offset = ${Q.indicesToOffset(`${Q.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; + var w_offset = ${J.indicesToOffset(`${J.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${T}; + `:""} + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${c?4:p}) { + ${ae()} + inputChannel = inputChannel + ${c?4:p}; + } + ${V()} + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${s?` + bias[d1 / ${f}]`:""}; + ${he.setByOffset("global_idx","value")}; + `;return` + ${z.registerUniforms(K).declareVariables(...oe,he)} + ${z.mainStart()} + ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${F}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${T}${f}${c}${_}`,inputDependencies:g},getRunData:()=>({dispatchGroup:{x:w[0],y:w[1],z:w[2]},outputs:[{dims:t?t(o):o,dataType:e[0].dataType}],programUniforms:C}),getShaderSource:A}}}),ym,vm,xm,$l,Tm,Em,kl,Pm,Cm,Nv=ze(()=>{jv(),un(),Us(),ym=(e,r,t,s,o,n)=>(e-1)*r+t+(s-1)*o+1-n,vm=(e,r,t,s,o)=>{let n=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=n,t[o]=e-n):r==="SAME_LOWER"&&(t[s]=e-n,t[o]=n)},xm=(e,r,t,s,o,n,i,a,l,u)=>{let p=e.length-2,c=u.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((c,d)=>c*d,1)===0){t.length=0;for(let c=2;cc+d,0)===0){let c=r[0].dims.length-2;l=new Array(c).fill(1)}let u=e.strides.slice();if(u.reduce((c,d)=>c+d,0)===0){let c=r[0].dims.length-2;u=new Array(c).fill(1)}xm(a,t,l,e.autoPad,e.group,o,u,s,i,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:o,outputPadding:i,outputShape:n,dilations:l,strides:u}),p},Tm=e=>{let r=_l(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],o=e.dilations,n=e.group,i=e.kernelShape,a=e.pads,l=e.strides,u=e.wIsConst(),p=e.outputPadding,c=e.outputShape;return{autoPad:s,format:t,dilations:o,group:n,kernelShape:i,outputPadding:p,outputShape:c,pads:a,strides:l,wIsConst:u,...r,cacheKey:`${e.format};${r.activation};`}},Em=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[0];if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let o=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==o))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.reduce((i,a)=>i+a,0)>0&&r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.reduce((i,a)=>i+a,0)>0&&r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.reduce((i,a)=>i+a,0)>0&&r.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(r.outputPadding.length!==n&&r.outputPadding.length!==0)throw new Error(`output_padding should be ${n}D`);if(r.kernelShape.reduce((i,a)=>i+a,0)>0&&r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(r.outputShape.length!==0&&r.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},kl=(e,r,t,s)=>{let o=e.kernelCustomData.wT??e.compute(Kr(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=o);let n=[r[0],o];r.length===3&&n.push(r[2]),e.compute(bm(n,t,s),{inputs:n})},Pm=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let o=r.kernelShape;(o.length===0||o[0]===0)&&(o=[e.inputs[1].dims[2]]);let n=r.dilations;(n.length===0||n[0]===0)&&(n=[1]);let i=r.strides;(i.length===0||i[0]===0)&&(i=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],i=[1].concat(i),n=[1].concat(n),o=[1].concat(o);let l=r.outputPadding;l=[0].concat(l);let u=$l({...r,pads:a,strides:i,dilations:n,kernelShape:o,outputPadding:l},s);kl(e,s,u,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},Cm=(e,r)=>{if(Em(e.inputs,r),e.inputs[0].dims.length===3)Pm(e,r);else{let t=$l(r,e.inputs);kl(e,e.inputs,t)}}}),Sm,$m,km,Vv=ze(()=>{ft(),yt(),or(),xt(),Sm=(e,r,t,s)=>{let o=Me.size(r),n=r.length,i=Te("input",e,n),a=rt("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),u=Me.normalizeAxis(l,n),p=c=>{let d=` i32(${i.indicesGet("inputIndices","uniforms.axis")}) `,_=ot("uniforms.input_shape","uniforms.axis",n),f=s.reverse?d+(s.exclusive?" + 1":""):"0",T=s.reverse?_:d+(s.exclusive?"":" + 1");return` + ${c.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(i,a)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${a.offsetToIndices("global_idx")}; + var sum = ${a.type.value}(0); + let first : i32 = ${f}; + let last : i32 = ${T}; + for (var i : i32 = first; i < last; i++) { + ${i.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${i.getByIndices("inputIndices")}; + } + ${a.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},{type:12,data:u},...lt(r,r)]}),getShaderSource:p}},$m=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,o=e.inputs[1];e.compute(Sm(s,t,o,r),{inputs:[0]})},km=e=>{let r=e.exclusive===1,t=e.reverse===1;return Bt({exclusive:r,reverse:t})}}),Im,Am,Fm,Om,Dm,Uv=ze(()=>{ft(),yt(),or(),xt(),Im=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.")},Am=(e,r,t,s)=>{let o=[];o.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`);for(let n=0;n{let t,s,o,n,i,a,l=r.format==="NHWC",u=r.blocksize,p=r.mode==="DCR";l?([t,s,o,n]=e.dims,i=p?[t,s,o,u,u,n/u**2]:[t,s,o,n/u**2,u,u],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,o,n]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],i=p?[t,u,u,n/u**2,s,o]:[t,n/u**2,u,u,s,o],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let c=e.reshape(i),d=c.dims.length,_=e.dataType,f=Te("a",_,d),T=rt("output",_,d),k=w=>` + ${w.registerUniform("output_size","u32").declareVariables(f,T)} + + ${Am(a,d,f,T)} + + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${T.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${T.setByOffset("global_idx",f.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:w=>{let g=l?[t,s*u,o*u,n/u**2]:[t,n/u**2,s*u,o*u],S=Me.size(g),E=c.dims,y=Me.sortBasedOnPerm(E,a);return{outputs:[{dims:g,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...lt(E,y)]}},getShaderSource:k}},Om=(e,r)=>{Im(e.inputs),e.compute(Fm(e.inputs[0],r))},Dm=e=>Bt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),fi,wo,Il,Lm,zm,Bm,Rm,Al,jm,Nm,Vm,Wv=ze(()=>{ft(),yt(),or(),xt(),fi="[a-zA-Z]|\\.\\.\\.",wo="("+fi+")+",Il="^"+wo+"$",Lm="("+wo+",)*"+wo,zm="^"+Lm+"$",Bm=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)}},Rm=class{constructor(e,r){var o;this.equation=r,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,s]=r.includes("->")?r.split("->",2):[r,""];if(!t.match(RegExp(zm)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,i)=>{let a=e[i].dims.slice();if(!n.match(RegExp(Il)))throw new Error("Invalid LHS term");let l=this.processTerm(n,!0,a,i);this.lhs.push(l)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,i])=>i.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(wo)))throw new Error("Invalid RHS");(o=s.match(RegExp(fi,"g")))==null||o.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let i=this.symbolToInfo.get(n);if(i===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(i.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(e,r,t){let s=this.symbolToInfo.get(e);if(s!==void 0){if(s.dimValue!==r&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(t)}else s={count:1,dimValue:r,inputIndices:[t]};this.symbolToInfo.set(e,s)}processTerm(e,r,t,s=-1){let o=t.length,n=!1,i=[],a=0;if(!e.match(RegExp(Il))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(fi,"g")),u=new Bm(s);return l==null||l.forEach((p,c)=>{if(p==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let d=o-l.length+1;if(d<0)throw new Error("Ellipsis out of bounds");if(i=t.slice(a,a+d),this.hasEllipsis){if(this.ellipsisDims.length!==i.length||this.ellipsisDims.toString()!==i.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=i;else throw new Error("Ellipsis must be specified in the LHS");for(let _=0;_e+"_max",jm=(e,r,t,s)=>{let o=e.map(u=>u.length).map((u,p)=>Te(`input${p}`,r,u)),n=Me.size(s),i=rt("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(u=>!t.rhs.symbolToIndices.has(u)),l=u=>{let p=[],c="var prod = 1.0;",d="var sum = 0.0;",_="sum += prod;",f=[],T=[],k=[],w=[],g=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((E,y)=>{var M;if(t.rhs.symbolToIndices.has(y)){let v=(M=t.rhs.symbolToIndices.get(y))==null?void 0:M[0];v!==void 0&&t.lhs.forEach((C,A)=>{if(E.inputIndices.includes(A)){let z=C.symbolToIndices.get(y);if(z===void 0)throw new Error("Invalid symbol error");z.forEach(K=>{p.push(`${o[A].indicesSet(`input${A}Indices`,K,i.indicesGet("outputIndices",v))}`)})}})}else t.lhs.forEach((v,C)=>{if(E.inputIndices.includes(C)){let A=v.symbolToIndices.get(y);if(A===void 0)throw new Error("Invalid symbol error");A.forEach(z=>{f.push(`${o[C].indicesSet(`input${C}Indices`,z,`${y}`)}`)}),w.push(`prod *= ${o[C].getByIndices(`input${C}Indices`)};`)}}),T.push(`for(var ${y}: u32 = 0; ${y} < uniforms.${Al(y)}; ${y}++) {`),k.push("}")});let S=g?[...p,`let sum = ${o.map((E,y)=>E.getByIndices(`input${y}Indices`)).join(" * ")};`]:[...p,d,...T,...f,c,...w,_,...k];return` + ${u.registerUniforms(a.map(E=>({name:`${Al(E)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...o,i)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${i.offsetToIndices("global_idx")}; + ${o.map((E,y)=>`var input${y}Indices: ${o[y].type.indices};`).join(` +`)} + ${S.join(` +`)}; + ${i.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let u=a.filter(c=>t.symbolToInfo.has(c)).map(c=>{var d;return{type:12,data:((d=t.symbolToInfo.get(c))==null?void 0:d.dimValue)||0}});u.push({type:12,data:n});let p=e.map((c,d)=>[...lt(c)]).reduce((c,d)=>c.concat(d),u);return p.push(...lt(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},Nm=(e,r)=>{let t=new Rm(e.inputs,r.equation),s=t.outputDims,o=e.inputs.map((n,i)=>n.dims);e.compute(jm(o,e.inputs[0].dataType,t,s))},Vm=e=>{let r=e.equation.replace(/\s+/g,"");return Bt({equation:r})}}),Um,Fl,Wm,Gm,Km,Gv=ze(()=>{ft(),yt(),xt(),Um=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=t.length{let t=e.length-r.length,s=[];for(let o=0;oe.length>r.length?Fl(e,r):Fl(r,e),Gm=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=Wm(r,t),o=e[0].dataType,n=o===9||Me.size(r)===1,i=o===9||r.length>0&&r[r.length-1]%4===0?4:1,a=n||s.length>0&&s[s.length-1]%4===0?4:1,l=Math.ceil(Me.size(s)/a),u=c=>{let d=Te("input",o,r.length,i),_=rt("output",o,s.length,a),f;if(o===9){let T=(k,w,g="")=>` + let outputIndices${w} = ${_.offsetToIndices(`outputOffset + ${w}u`)}; + let offset${w} = ${d.broadcastedIndicesToOffset(`outputIndices${w}`,_)}; + let index${w} = offset${w} / 4u; + let component${w} = offset${w} % 4u; + ${k}[${w}] = ${g}(${d.getByOffset(`index${w}`)}[component${w}]); + `;f=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${T("data",0,"u32")} + ${T("data",1,"u32")} + ${T("data",2,"u32")} + ${T("data",3,"u32")} + ${_.setByOffset("global_idx","data")} + }`}else f=` + let outputIndices = ${_.offsetToIndices(`global_idx * ${a}`)}; + let inputOffset = ${d.broadcastedIndicesToOffset("outputIndices",_)}; + let data = ${_.type.value}(${d.getByOffset(`inputOffset / ${i}`)}); + ${_.setByOffset("global_idx","data")} + }`;return` + ${c.registerUniform("vec_size","u32").declareVariables(d,_)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${f}`},p=[{type:12,data:l},...lt(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${i}${a}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},Km=e=>{Um(e.inputs),e.compute(Gm(e.inputs),{inputs:[0]})}}),Hm,qm,Kv=ze(()=>{ft(),yt(),xt(),fl(),Hm=e=>{let r=e[0].dataType,t=Me.size(e[0].dims),s=Me.size(e[1].dims),o=s%4===0,n=i=>{let a=Te("x",r,[1],4),l=Te("bias",r,[1],4),u=rt("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],c=_=>` + let bias${_}_offset: u32 = (global_idx * 4 + ${_}) % uniforms.bias_size; + let bias${_} = ${l.getByOffset(`bias${_}_offset / 4`)}[bias${_}_offset % 4];`,d=o?` + let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${c(0)}${c(1)}${c(2)}${c(3)} + let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${i.registerUniforms(p).declareVariables(a,l,u)} + + ${hl(Dr(r))} + + ${i.mainStart(Vn)} + ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${a.getByOffset("global_idx")}; + ${d} + let x_in = x + bias; + ${u.setByOffset("global_idx",ml("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${o}`,inputDependencies:["type","type"]},getShaderSource:n,getRunData:i=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/Vn/4)}})}},qm=e=>{e.inputs.length<2||Me.size(e.inputs[1].dims)===0?Sh(e):e.compute(Hm(e.inputs))}}),Qm,Xm,Jm,Ym,Hv=ze(()=>{ft(),yt(),or(),xt(),Qm=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Xm=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=Me.normalizeAxis(r.axis,o),i=t.slice(0);i.splice(n,1,...s);let a=t[n],l=e[0].dataType===9?4:1,u=Math.ceil(Me.size(i)/l),p=[{type:12,data:u},{type:6,data:a},{type:12,data:n},...lt(e[0].dims,e[1].dims,i)],c=d=>{let _=Te("data",e[0].dataType,e[0].dims.length,l),f=Te("inputIndices",e[1].dataType,e[1].dims.length),T=rt("output",e[0].dataType,i.length,l),k=g=>{let S=s.length,E=`var indicesIndices${g} = ${f.type.indices}(0);`;for(let y=0;y1?`indicesIndices${g}[${y}]`:`indicesIndices${g}`} = ${i.length>1?`outputIndices${g}[uniforms.axis + ${y}]`:`outputIndices${g}`};`;E+=` + var idx${g} = ${f.getByIndices(`indicesIndices${g}`)}; + if (idx${g} < 0) { + idx${g} = idx${g} + uniforms.axisDimLimit; + } + var dataIndices${g} : ${_.type.indices}; + `;for(let y=0,M=0;y1?`dataIndices${g}[${y}]`:`dataIndices${g}`} = u32(idx${g});`,M+=S):(E+=`${o>1?`dataIndices${g}[${y}]`:`dataIndices${g}`} = ${i.length>1?`outputIndices${g}[${M}]`:`outputIndices${g}`};`,M++);return E},w;if(e[0].dataType===9){let g=(S,E,y="")=>` + let outputIndices${E} = ${T.offsetToIndices(`outputOffset + ${E}u`)}; + ${k(E)}; + let offset${E} = ${_.indicesToOffset(`dataIndices${E}`)}; + let index${E} = offset${E} / 4u; + let component${E} = offset${E} % 4u; + ${S}[${E}] = ${y}(${_.getByOffset(`index${E}`)}[component${E}]); + `;w=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${g("value",0,"u32")} + ${g("value",1,"u32")} + ${g("value",2,"u32")} + ${g("value",3,"u32")} + ${T.setByOffset("global_idx","value")} + `}else w=` + let outputIndices = ${T.offsetToIndices("global_idx")}; + ${k("")}; + let value = ${_.getByIndices("dataIndices")}; + ${T.setByOffset("global_idx","value")}; + `;return` + ${d.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(_,f,T)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${w} + }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:c}},Jm=e=>Bt({axis:e.axis}),Ym=(e,r)=>{let t=e.inputs;Qm(t),e.compute(Xm(e.inputs,r))}}),Zm,ef,tf,qv=ze(()=>{ft(),yt(),xt(),Zm=(e,r,t,s,o,n,i,a,l)=>{let u=[{type:12,data:n},{type:12,data:s},{type:12,data:o},{type:12,data:t},{type:12,data:i},{type:12,data:a},{type:12,data:l}],p=[n];u.push(...lt(r.dims,p));let c=d=>{let _=Te("indices_data",r.dataType,r.dims.length),f=rt("input_slice_offsets_data",12,1,1),T=[_,f],k=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:o.length},{name:"sizes_from_slice_dims_data",type:"u32",length:t.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${d.registerUniforms(k).declareVariables(...T)} + ${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) { + ${o.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${t.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${o.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:u}),getShaderSource:c},{inputs:[r],outputs:[-1]})[0]},ef=(e,r)=>{let t=e.inputs,s=t[0].dims,o=t[0].dataType,n=t[1].dims,i=n[n.length-1],a=Me.sizeToDimension(n,n.length-1),l=Me.sizeFromDimension(s,r.batchDims+i),u=Me.sizeToDimension(s,r.batchDims),p=Me.sizeFromDimension(s,r.batchDims),c=a/u,d=new Array(i),_=l;for(let E=0;Es.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let k=n.slice(0,-1).concat(s.slice(T)),w=Me.size(k),g=[{type:12,data:w},{type:12,data:l},...lt(t[0].dims,f.dims,k)],S=E=>{let y=Te("data",t[0].dataType,t[0].dims.length),M=Te("slice_offsets",12,f.dims.length),v=rt("output",t[0].dataType,k.length);return` + ${E.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(y,M,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:k,dataType:o}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:g}),getShaderSource:S},{inputs:[t[0],f]})},tf=e=>({batchDims:e.batch_dims,cacheKey:""})}),rf,sf,nf,of,Qv=ze(()=>{ft(),yt(),or(),xt(),rf=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=Me.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,o=e[0],n=e[2],i=e.length===4?e[3]:void 0;if(n.dims.length!==o.dims.length||!o.dims.map((a,l)=>l===t?Math.ceil(a/s)===n.dims[l]:a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(i){if(i.dataType!==o.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(i.dims.length!==n.dims.length||!i.dims.map((a,l)=>a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},sf=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t.length,n=Me.normalizeAxis(r.gatherAxis,o),i=Me.normalizeAxis(r.quantizeAxis,o),a=t.slice(0);a.splice(n,1,...s);let l=Me.size(a),u=e[2].dataType,p=e[0].dataType===22,c=[{type:12,data:l},{type:12,data:i},{type:12,data:n},{type:12,data:r.blockSize},...lt(...e.map((_,f)=>_.dims),a)],d=_=>{let f=Te("data",e[0].dataType,e[0].dims.length),T=Te("inputIndices",e[1].dataType,e[1].dims.length),k=Te("scales",e[2].dataType,e[2].dims.length),w=e.length>3?Te("zeroPoint",e[3].dataType,e[3].dims.length):void 0,g=rt("output",u,a.length),S=[f,T,k];w&&S.push(w);let E=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${_.registerUniforms(E).declareVariables(...S,g)} + ${_.mainStart()} + let output_indices = ${g.offsetToIndices("global_idx")}; + var indices_indices = ${T.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")}; + ${T.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${g.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${f.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${g.indicesGet("output_indices","i")}; + ${f.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${T.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${t[n]}; + } + ${f.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${a.length}; i++) { + let index = ${g.indicesGet("output_indices",`i + ${s.length} - 1`)}; + ${f.indicesSet("data_indices","i","index")}; + } + let data_offset = ${f.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${f.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); + let quantized_data = quantized_data_vec[data_index / 2]; + var scale_indices = data_indices; + let quantize_axis_index = ${k.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${k.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${k.getByIndices("scale_indices")}; + ${w?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${w.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${w.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${Dr(u)}(quantized_data - zero_point) * scale; + ${g.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((_,f)=>f!==1).map(_=>_.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(_,f)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:u}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:c}),getShaderSource:d}},nf=(e,r)=>{let t=e.inputs;rf(t,r),e.compute(sf(e.inputs,r))},of=e=>Bt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),af,lf,uf,cf,Xv=ze(()=>{ft(),yt(),or(),xt(),af=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.`)},lf=(e,r)=>{let t=e[0].dims,s=e[0].dataType,o=t.length,n=e[1].dims,i=e[1].dataType,a=Me.normalizeAxis(r.axis,o),l=t[a],u=n.slice(0),p=Me.size(u),c=Te("input",s,o),d=Te("indicesInput",i,n.length),_=rt("output",s,u.length),f=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return f.push(...lt(t,n,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:f}),getShaderSource:T=>` + ${T.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(c,d,_)} + ${T.mainStart()} + ${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${_.offsetToIndices("global_idx")}; + + var idx = ${d.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${c.type.indices}(outputIndices); + ${c.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${c.getByIndices("inputIndices")}; + + ${_.setByOffset("global_idx","value")}; + }`}},uf=e=>Bt({axis:e.axis}),cf=(e,r)=>{let t=e.inputs;af(t),e.compute(lf(e.inputs,r))}}),df,pf,hf,mf,Jv=ze(()=>{ft(),yt(),xt(),df=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")},pf=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[o,n,i]=vd.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[o,n];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,u=Math.ceil(n/l),p=Math.ceil(o/l),c=!0,d=Me.size(a),_=[{type:12,data:c?u:d},{type:12,data:o},{type:12,data:n},{type:12,data:i},{type:1,data:r.alpha},{type:1,data:r.beta}],f=["type","type"];e.length===3&&(_.push(...lt(e[2].dims)),f.push("rank")),_.push(...lt(a));let T=w=>{let g="";r.transA&&r.transB?g="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?g="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?g="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(g="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let S=r.alpha===1?"":"value *= uniforms.alpha;",E=Te("a",e[0].dataType,e[0].dims),y=Te("b",e[1].dataType,e[1].dims),M=E.type.value,v=null,C=[E,y];e.length===3&&(v=Te("c",e[2].dataType,e[2].dims.length),C.push(v));let A=rt("output",e[0].dataType,a.length);C.push(A);let z=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}];return` + ${w.registerUniforms(z).declareVariables(...C)} + + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${M}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${g} + } + + ${S} + ${v!=null?`let cOffset = ${v.broadcastedIndicesToOffset("vec2(m, n)",A)}; value += ${M}(uniforms.beta) * ${v.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},k=w=>{let g=Te("a",e[0].dataType,e[0].dims),S=Te("b",e[1].dataType,e[1].dims),E=null,y=[g,S];e.length===3&&(E=Te("c",e[2].dataType,e[2].dims.length),y.push(E));let M=rt("output",e[0].dataType,a.length);y.push(M);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"}],C="",A="";r.transA&&r.transB?(A=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${g.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + } + `,C="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(A=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${g.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + } + `,C="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(A=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${g.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + } + `,C="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(A=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${g.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + } + `,C="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let z=r.alpha===1?"":"value *= uniforms.alpha;";return` + ${w.registerUniforms(v).declareVariables(...y)} + var tile_a: array, ${l}>; + var tile_b: array, ${l}>; + ${w.mainStart([l,l,1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${l}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${l}; + let num_tiles = (uniforms.K - 1) / ${l} + 1; + var k_start = 0u; + var value = ${M.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${A} + k_start = k_start + ${l}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${l}; k++) { + ${C} + } + workgroupBarrier(); + } + + ${z} + 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)",M)}; value += ${M.type.value}(uniforms.beta) * ${E.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return c?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:u*p},programUniforms:_}),getShaderSource:k}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:_}),getShaderSource:T}},hf=e=>{let r=e.transA,t=e.transB,s=e.alpha,o=e.beta;return{transA:r,transB:t,alpha:s,beta:o,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},mf=(e,r)=>{df(e.inputs),e.compute(pf(e.inputs,r))}}),Ts,Ds,cn,dn,ff,_f,gf,wf,Mf,bf,yf,vf,xf,Tf,Yv=ze(()=>{ft(),yt(),or(),xt(),[Ts,Ds,cn,dn]=[0,1,2,3],ff=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")},_f=` + 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; + } +`,gf=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; + } +`,wf=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)); + `} + } +`,Mf=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); + }`:""} +`,bf=(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[${Ts}] = batch; + indices[${Ds}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${cn}] = u32(r); + indices[${dn}] = u32(c); + } else { + return ${r}(0); + } + `;case"border":return` + indices[${cn}] = u32(clamp(r, 0, H - 1)); + indices[${dn}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${cn}] = gs_reflect(r, border[1], border[3]); + indices[${dn}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,yf=(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[${Ts}], indices[${Ds}], 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[${Ts}], indices[${Ds}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Ts}], indices[${Ds}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Ts}], indices[${Ds}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Ts}], indices[${Ds}], 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[${Ts}], indices[${Ds}], 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")}`,vf=(e,r)=>{let t=Te("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],o=Te("grid",e[1].dataType,s.length,2),n=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];r.format==="NHWC"&&(n=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[Ts,Ds,cn,dn]=[0,3,1,2]);let i=rt("output",e[0].dataType,n.length),a=t.type.value,l=Me.size(n),u=[{type:12,data:l},...lt(e[0].dims,s,n)],p=c=>` + ${c.registerUniform("output_size","u32").declareVariables(t,o,i)} + ${_f} + ${gf(a)} + ${wf(r)} + ${Mf(r)} + ${bf(t,a,r)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${cn}]); + let W_in = i32(uniforms.x_shape[${dn}]); + + ${r.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${i.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${Ts}], indices[${cn}], indices[${dn}]); + let nxy = ${o.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${yf(i,a,r)} + }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:c=>{let d=Me.size(n);return{outputs:[{dims:n,dataType:c[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:u}},getShaderSource:p}},xf=(e,r)=>{ff(e.inputs),e.compute(vf(e.inputs,r))},Tf=e=>Bt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Br,Ef,Pf,Ol,Cf,Mo,Sf,$f=ze(()=>{ft(),yt(),or(),el(),dl(),xt(),Us(),Br=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,Ef=(e,r)=>{let t=e[0],s=Br(e,1),o=Br(e,2),n=Br(e,3),i=Br(e,4),a=Br(e,5),l=Br(e,6),u=Br(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],c=t.dims[1],d=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],_=c,f=0,T=0,k=Math.floor(d/r.numHeads);if(l&&u&&Me.size(l.dims)&&Me.size(u.dims)){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==p||l.dims[1]!==r.numHeads||l.dims[3]!==k)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[0]!==p||u.dims[1]!==r.numHeads||u.dims[3]!==k)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(u.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');f=l.dims[2],T=l.dims[2]}else if(l&&Me.size(l.dims)||u&&Me.size(u.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(s&&Me.size(s.dims)>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(s.dims[2]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');w=2,_=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==k)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');w=5,_=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==k)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');w=0,_=s.dims[2]}}else{if(t.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(t.dims[2]!==r.numHeads||t.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}if(n&&Me.size(n.dims)>0){if(n.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let g=f+_,S=0;if(i&&Me.size(i.dims)>0){S=8;let v=i.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,y=d;if(o&&Me.size(o.dims)>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(_!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');y=o.dims[2]}else{if(_!==o.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');y=o.dims[1]*o.dims[3],E=!0}}let M=!1;if(i&&Me.size(i.dims)>0)throw new Error("Key padding mask is not supported");if(a&&Me.size(a.dims)>0){if(a.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(a.dims[0]!==p||a.dims[1]!==r.numHeads||a.dims[2]!==c||a.dims[3]!==g)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:c,pastSequenceLength:f,kvSequenceLength:_,totalSequenceLength:g,maxSequenceLength:T,inputHiddenSize:0,hiddenSize:d,vHiddenSize:y,headSize:k,vHeadSize:Math.floor(y/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:S,scale:r.scale,broadcastResPosBias:M,passPastInKv:E,qkvFormat:w}},Pf=e=>Bt({...e}),Ol=Bt({perm:[0,2,1,3]}),Cf=(e,r,t,s,o,n,i)=>{let a=[s,o,n],l=Me.size(a),u=[{type:12,data:l},{type:12,data:i},{type:12,data:n}],p=c=>{let d=rt("qkv_with_bias",r.dataType,a),_=Te("qkv",r.dataType,a),f=Te("bias",t.dataType,a),T=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${c.registerUniforms(T).declareVariables(_,f,d)} + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; + + qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; + }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},Mo=(e,r,t,s,o,n,i,a)=>{let l=n;if(i&&Me.size(i.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=Cf(e,n,i,r,s,t*o,a),l=l.reshape([r,s,t,o]),t===1||s===1?l:e.compute(Kr(l,Ol.perm),{inputs:[l],outputs:[-1]})[0]}else return n.dims.length===3&&(l=n.reshape([r,s,t,o])),t===1||s===1?l:e.compute(Kr(l,Ol.perm),{inputs:[l],outputs:[-1]})[0]},Sf=(e,r)=>{let t=Ef(e.inputs,r),s=e.inputs[0],o=Br(e.inputs,1),n=Br(e.inputs,2),i=Br(e.inputs,3),a=Br(e.inputs,4),l=Br(e.inputs,5),u=Br(e.inputs,6),p=Br(e.inputs,7);if(s.dims.length===5)throw new Error("Packed QKV is not implemented");if((o==null?void 0:o.dims.length)===5)throw new Error("Packed KV is not implemented");let c=o&&n&&o.dims.length===4&&n.dims.length===4,d=Mo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,i,0);if(c)return mo(e,d,o,n,a,void 0,u,p,l,t);if(!o||!n)throw new Error("key and value must be provided");let _=Mo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,o,i,t.hiddenSize),f=Mo(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,i,2*t.hiddenSize);mo(e,d,_,f,a,void 0,u,p,l,t)}}),kf,If,Af,Ff,Dl,Of,Df,Lf=ze(()=>{ft(),yt(),or(),xt(),kf=e=>{if(!e||e.length<1)throw new Error("too few inputs")},If=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(o=>t.push(Number(o))),s=t.length),Bt({numOutputs:s,axis:r.axis,splitSizes:t})},Af=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${ot("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,Ff=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=Me.size(t),o=e[0].dataType,n=Me.normalizeAxis(r.axis,t.length),i=new Array(r.numOutputs),a=Te("input",o,t.length),l=new Array(r.numOutputs),u=[],p=[],c=0,d=[{type:12,data:s}];for(let f=0;f` + ${f.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...i)} + ${Af(l.length)} + ${Ff(i)} + + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${a.offsetToIndices("global_idx")}; + var index = ${a.indicesGet("indices",n)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${ot("uniforms.size_in_split_axis","output_number - 1u",l.length)}; + ${a.indicesSet("indices",n,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:d})}},Of=(e,r)=>{kf(e.inputs);let t=e.inputs.length===1?r:If(e.inputs,r);e.compute(Dl(e.inputs,t),{inputs:[0]})},Df=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 Bt({axis:r,numOutputs:s,splitSizes:t})}}),zf,_i,Bf,Rf=ze(()=>{ft(),yt(),or(),xt(),zf=(e,r)=>{let[t,s,o,n]=e,{numHeads:i,rotaryEmbeddingDim:a}=r;if(t.dims.length!==3&&t.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${t.dims.length}`);if(!Me.areEqual(s.dims,[])&&!Me.areEqual(s.dims,[1])&&s.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${s.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(!Me.areEqual(o.dims,n.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&i===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],u=t.dims[t.dims.length-2],p=o.dims[0],c=Me.sizeFromDimension(t.dims,1)/u,d=a===0?o.dims[1]*2:c/i;if(a>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(u!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(d/2!==o.dims[1]&&a/2!==o.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${o.dims[1]}`);if(u>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},_i=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:o,scale:n}=r,i=e[0].dims[0],a=Me.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],u=a/l,p=e[2].dims[1],c=o===0?p*2:u/s,d=new Array(i,l,u/c,c-p),_=Me.computeStrides(d),f=[{type:1,data:n},{type:12,data:d},{type:12,data:_},...e[0].dims.length===3?new Array({type:12,data:[a,u,c,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,c,l*c,1]}):[],...lt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],T=k=>{let w=Te("input",e[0].dataType,e[0].dims.length),g=Te("position_ids",e[1].dataType,e[1].dims.length),S=Te("cos_cache",e[2].dataType,e[2].dims.length),E=Te("sin_cache",e[3].dataType,e[3].dims.length),y=rt("output",e[0].dataType,e[0].dims.length);return k.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:d.length},{name:"global_strides",type:"u32",length:_.length},{name:"input_output_strides",type:"u32",length:_.length}]),` + ${k.declareVariables(w,g,S,E,y)} + + ${k.mainStart(Vn)} + 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]; + ${k.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${g.broadcastedIndicesToOffset("bsnh.xy",rt("",g.type.tensor,2))}; + let position_id = + u32(${g.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${t}); + let j = i + select(half_rotary_emb_dim, 1, ${t}); + let re = ${w.getByOffset("i")} * ${S.get("position_id","bsnh[3]")} - + ${w.getByOffset("j")} * ${E.get("position_id","bsnh[3]")}; + ${y.setByOffset("i","re")} + let im = ${w.getByOffset("i")} * ${E.get("position_id","bsnh[3]")} + + ${w.getByOffset("j")} * ${S.get("position_id","bsnh[3]")}; + ${y.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${y.setByOffset("k",w.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Bt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:T,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Me.size(d)/Vn)},programUniforms:f})}},Bf=(e,r)=>{zf(e.inputs,r),e.compute(_i(e.inputs,r))}}),jf,Nf,Ll,Vf,Uf,Zv=ze(()=>{or(),ft(),dl(),$f(),Lf(),Us(),Rf(),xt(),jf=(e,r)=>{if(r.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let t=e[0],s=e[1],o=e[2],n=e[3],i=e[4];if(r.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(r.localWindowSize!==-1)throw new Error("Local attention is not supported");if(r.softcap!==0)throw new Error("Softcap is not supported");if(r.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(r.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let a=!1,l=t.dims[0],u=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],c=u,d=0,_=!s||s.dims.length===0,f=Math.floor(_?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);_&&(p=f*r.numHeads);let T=n&&n.dims.length!==0,k=i&&i.dims.length!==0;if(T&&n.dims.length===4&&n.dims[0]===l&&n.dims[1]!==r.kvNumHeads&&n.dims[2]===r.kvNumHeads&&n.dims[3]===f)throw new Error("BSNH pastKey/pastValue is not supported");if(T&&k){if(n.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(i.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');d=n.dims[2]}else if(T||k)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w=1;if(s&&s.dims.length>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(t.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');c=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==f)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(o)throw new Error('Expect "value" be none when "key" has packed kv format.');c=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==f)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');c=s.dims[2]}}else{if(t.dims.length!==3&&t.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(t.dims.length===5&&(t.dims[2]!==r.numHeads||t.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}let g=0,S=!1,E=r.kvNumHeads?f*r.kvNumHeads:p;if(o&&o.dims.length>0){if(o.dims.length!==3&&o.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(t.dims[0]!==o.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(o.dims.length===3){if(c!==o.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');E=o.dims[2]}else{if(c!==o.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');E=o.dims[1]*o.dims[3],S=!0}}let y=e.length>4?e[5]:void 0;if(y&&y.dims.length!==1&&y.dims[0]!==l)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:l,sequenceLength:u,pastSequenceLength:d,kvSequenceLength:c,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:E,headSize:f,vHeadSize:Math.floor(E/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:g,scale:r.scale,broadcastResPosBias:!1,passPastInKv:S,qkvFormat:w}},Nf=Bt({perm:[0,2,1,3]}),Ll=(e,r,t)=>{let s=r,o=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,o,t.headSize]),s=e.compute(Kr(s,Nf.perm),{inputs:[s],outputs:[-1]})[0]),s},Vf=(e,r,t,s)=>{let o=7,n=["type","type"],i=[e*r],a=e*r,l=[{type:12,data:a},{type:12,data:r},{type:12,data:e}],u=p=>{let c=Te("seq_lens",t.dataType,t.dims),d=Te("total_seq_lens",s.dataType,s.dims),_=rt("pos_ids",o,i),f=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` + ${p.registerUniforms(f).declareVariables(c,d,_)} + ${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 = ${c.getByOffset("batch_idx")}; + let total_seqlen = seqlen + 1; + if (is_first_prompt) { + if (sequence_idx < total_seqlen) { + pos_id = sequence_idx; + } else { + pos_id = 1; + } + ${_.setByOffset("global_idx","pos_id")} + } else if (is_subsequent_prompt) { + let past_seqlen = total_seqlen - i32(uniforms.sequence_length); + if (past_seqlen + sequence_idx < total_seqlen) { + pos_id = past_seqlen + sequence_idx; + } else { + pos_id = 1; + } + ${_.setByOffset("global_idx","pos_id")} + } else if (global_idx < uniforms.batch_size) { + ${_.setByOffset("global_idx","seqlen")} + }; + } + `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${r}`,inputDependencies:n},getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:l}),getShaderSource:u}},Uf=(e,r)=>{var E;let t=jf(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((E=e.inputs[1])==null?void 0:E.dims.length)===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],o=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,n=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,i=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,u=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,c=Bt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[d,_,f]=!o&&!n?e.compute(Dl([s],c),{inputs:[s],outputs:[-1,-1,-1]}):[s,o,n],T,k;if(r.doRotary){let y=e.compute(Vf(t.batchSize,t.sequenceLength,l,u),{inputs:[l,u],outputs:[-1]})[0],M=e.inputs[7],v=e.inputs[8],C=Bt({interleaved:r.rotaryInterleaved!==0,numHeads:t.numHeads,rotaryEmbeddingDim:0,scale:r.scale}),A=[d,y,M,v],z=[-1];T=e.compute(_i(A,C),{inputs:A,outputs:z})[0],A.splice(0,1,_);let K=Bt({interleaved:r.rotaryInterleaved!==0,numHeads:t.kvNumHeads,rotaryEmbeddingDim:0,scale:r.scale});k=e.compute(_i(A,K),{inputs:A,outputs:z})[0]}let w=Mo(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,r.doRotary?T:d,void 0,0),g=Ll(e,r.doRotary?k:_,t),S=Ll(e,f,t);mo(e,w,g,S,void 0,void 0,i,a,void 0,t,l,u)}}),zl,Wf,Gf,Kf,ex=ze(()=>{ft(),yt(),Us(),xt(),zl=(e,r,t,s,o,n,i,a)=>{let l=rr(n),u=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,c=o*i,d=64;c===1&&(d=256);let _=[o,i,n/l],f=[o,i,2],T=["rank","type","type"],k=[];k.push(...lt(_,f));let w=g=>{let S=Te("x",r.dataType,3,l),E=Te("scale",t.dataType,t.dims),y=Te("bias",s.dataType,s.dims),M=rt("output",1,3,2),v=[S,E,y,M];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 = ${u}(0); + var squared_sum = ${u}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${u}(${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 = ${Vs("workgroup_shared[0][0]",l)} / f32(hight * ${l}); + let squared_sum_final = ${Vs("workgroup_shared[0][1]",l)} / f32(hight * ${l}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${a})); + let channel_scale = inv_std_dev * f32(scale[channel]); + let channel_shift = f32(bias[channel]) - sum_final * channel_scale; + output[workgroup_index] = vec2f(channel_scale, channel_shift); + } + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${a};${d}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:f,dataType:1}],dispatchGroup:{x:c},programUniforms:k}),getShaderSource:w},{inputs:[r,t,s],outputs:[-1]})[0]},Wf=(e,r,t)=>{let s=r[0].dims,o=s,n=2,i=s[0],a=s[1],l=Me.sizeFromDimension(s,n),u=rr(l),p=Me.size(o)/u,c=zl(e,r[0],r[1],r[2],i,l,a,t.epsilon),d=[i,a,l/u],_=[i,a],f=["type","none"],T=k=>{let w=Te("x",r[0].dataType,d.length,u),g=Te("scale_shift",1,_.length,2),S=rt("output",r[0].dataType,d.length,u),E=[w,g,S];return` + ${k.registerUniform("output_size","u32").declareVariables(...E)} + ${k.mainStart()} + ${k.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 = ${w.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:`${u}`,inputDependencies:f},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...lt(d,_,d)]}),getShaderSource:T},{inputs:[r[0],c]})},Gf=(e,r,t)=>{let s=r[0].dims,o=s,n=s[0],i=s[s.length-1],a=Me.sizeFromDimension(s,1)/i,l=rr(i),u=Me.size(o)/l,p=[{type:12,data:a},{type:12,data:Math.floor(i/l)}],c=["type","type"],d=!1,_=[0,s.length-1];for(let w=0;ws[_[g]])),T=zl(e,f,r[1],r[2],n,a,i,t.epsilon),k=w=>{let g=br(r[0].dataType),S=l===1?"vec2f":`mat${l}x2f`,E=v=>{let C=v===0?"x":"y",A=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${g}(${A}(scale.${C}))`;case 2:return`vec2<${g}>(${A}(scale[0].${C}, scale[1].${C}))`;case 4:return`vec4<${g}>(${A}(scale[0].${C}, scale[1].${C}, scale[2].${C}, scale[3].${C}))`;default:throw new Error(`Not supported compoents ${l}`)}},y=Te("input",r[0].dataType,r[0].dims,l),M=rt("output",r[0].dataType,o,l);return` + @group(0) @binding(0) var input : array<${y.type.storage}>; + @group(0) @binding(1) var scale_input : array<${S}>; + @group(0) @binding(2) var output : array<${M.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${w.mainStart()} + let current_image_number = global_idx / (uniforms.C * uniforms.H); + let current_channel_number = global_idx % uniforms.C; + + let scale_offset = current_image_number * uniforms.C + current_channel_number; + let scale = scale_input[scale_offset]; + output[global_idx] = fma(input[global_idx], ${E(0)}, ${E(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:o,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:p}),getShaderSource:k},{inputs:[r[0],T]})},Kf=(e,r)=>{r.format==="NHWC"?Gf(e,e.inputs,r):Wf(e,e.inputs,r)}}),Hf,qf,Qf,tx=ze(()=>{ft(),yt(),xt(),Hf=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},qf=(e,r,t)=>{let s=r.simplified,o=e[0].dims,n=e[1],i=!s&&e[2],a=o,l=Me.normalizeAxis(r.axis,o.length),u=Me.sizeToDimension(o,l),p=Me.sizeFromDimension(o,l),c=Me.size(n.dims),d=i?Me.size(i.dims):0;if(c!==p||i&&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 ${c} and bias size of ${d}`);let _=[];for(let y=0;y1,g=t>2,S=y=>{let M=br(e[0].dataType),v=[Te("x",e[0].dataType,e[0].dims,f),Te("scale",n.dataType,n.dims,f)];i&&v.push(Te("bias",i.dataType,i.dims,f)),v.push(rt("output",e[0].dataType,a,f)),w&&v.push(rt("mean_data_output",1,_)),g&&v.push(rt("inv_std_output",1,_));let C=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${y.registerUniforms(C).declareVariables(...v)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${nl("f32",f)}; + var mean_square_vector = ${nl("f32",f)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${Un(M,f,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Vs("mean_vector",f)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Vs("mean_square_vector",f)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${Un(M,f,"x[j + offset]")}; + let f32scale = ${Un(M,f,"scale[j]")}; + output[j + offset] = ${v[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale + ${i?`+ ${Un(M,f,"bias[j]")}`:""} + ); + } + + ${w?"mean_data_output[global_idx] = mean":""}; + ${g?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},E=[{dims:a,dataType:e[0].dataType}];return w&&E.push({dims:_,dataType:1}),g&&E.push({dims:_,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${f};${t};${s}`,inputDependencies:T},getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:k}),getShaderSource:S}},Qf=(e,r)=>{Hf(e.inputs),e.compute(qf(e.inputs,r,e.outputCount))}}),Xf,Jf,rx=ze(()=>{yt(),Ml(),xl(),Xf=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.")},Jf=e=>{Xf(e.inputs);let r=Nn.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!r)throw new Error("Can't use matmul on the given tensors");let t=r[r.length-1],s=e.inputs[0].dims[e.inputs[0].dims.length-1];if(t<8&&s<8)e.compute(wl(e.inputs,{activation:""},r));else{let o=r[r.length-2],n=Me.size(e.inputs[0].dims.slice(0,-2)),i=Me.size(e.inputs[1].dims.slice(0,-2));if(n!==1&&o===1&&i===1){let a=e.inputs[0].reshape([1,n,s]),l=e.inputs[1].reshape([1,s,t]),u=[1,n,t],p=[a,l];e.compute(pi(p,{activation:""},r,u),{inputs:p})}else e.compute(pi(e.inputs,{activation:""},r))}}}),Yf,Zf,e_,t_,r_,sx=ze(()=>{ft(),yt(),or(),xt(),Yf=(e,r)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=e[0],s=t.dims.length;if(t.dims[s-1]!==r.k)throw new Error("The last dim of input shape does not match the k value");let o=Math.floor((r.k+r.blockSize-1)/r.blockSize),n=r.blockSize/8*r.bits,i=e[1];if(!Me.areEqual(i.dims,[r.n,o,n]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(Me.size(a)!==r.n*o)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,u=r.bits>4?r.n*o:r.n*Math.floor((o+1)/2);if(Me.size(l)!==u)throw new Error("zeroPoints input size error.")}},Zf=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=Me.size(a),u=e[1].dims[2]/4,p=e[0].dataType,c=rr(r.k),d=rr(u),_=rr(i),f=a.concat([o,i]),T=o>1&&i/_%2===0?2:1,k=Me.size(f)/_/T,w=64,g=[],S=[l,o,n/c],E=Me.convertShape(e[1].dims).slice();E.splice(-1,1,u/d),g.push(...lt(S)),g.push(...lt(E)),g.push(...lt(e[2].dims)),e.length===4&&g.push(...lt(Me.convertShape(e[3].dims)));let y=[l,o,i/_];g.push(...lt(y));let M=v=>{let C=S.length,A=Te("a",e[0].dataType,C,c),z=Te("b",12,E.length,d),K=Te("scales",e[2].dataType,e[2].dims.length),G=[A,z,K],j=e.length===4?Te("zero_points",12,e[3].dims.length):void 0;j&&G.push(j);let Y=y.length,H=rt("output",e[0].dataType,Y,_),J=br(e[0].dataType),Q=(()=>{switch(c){case 1:return`array<${J}, 8>`;case 2:return`mat4x2<${J}>`;case 4:return`mat2x4<${J}>`;default:throw new Error(`${c}-component is not supported.`)}})(),oe=()=>{let V=` + // reuse a data + var input_offset = ${A.indicesToOffset(`${A.type.indices}(batch, row, word_offset)`)}; + var a_data: ${Q}; + for (var j: u32 = 0; j < ${8/c}; j++) { + a_data[j] = ${A.getByOffset("input_offset")}; + input_offset++; + } + `;for(let F=0;F<_*T;F++)V+=` + b_value = ${d===1?`b${F}_data`:`b${F}_data[i]`}; + b_value_lower = unpack4xU8(b_value & b_mask); + b_value_upper = unpack4xU8((b_value >> 4) & b_mask); + b_quantized_values = ${Q}(${Array.from({length:4},(W,ee)=>`${J}(b_value_lower[${ee}]), ${J}(b_value_upper[${ee}])`).join(", ")}); + b_dequantized_values = ${c===1?`${Q}(${Array.from({length:8},(W,ee)=>`(b_quantized_values[${ee}] - ${j?`zero_point${F}`:"zero_point"}) * scale${F}`).join(", ")});`:`(b_quantized_values - ${Q}(${Array(8).fill(`${j?`zero_point${F}`:"zero_point"}`).join(",")})) * scale${F};`}; + workgroup_shared[local_id.x * ${T} + ${Math.floor(F/_)}]${_>1?`[${F%_}]`:""} += ${Array.from({length:8/c},(W,ee)=>`${c===1?`a_data[${ee}] * b_dequantized_values[${ee}]`:`dot(a_data[${ee}], b_dequantized_values[${ee}])`}`).join(" + ")}; + `;return V},he=()=>{let V=` + var col_index = col * ${_}; + ${j?` + let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; + var zero_point_byte_count: u32; + var zero_point_word_index: u32; + var zero_point_byte_offset: u32; + let zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32; + var zero_point_word: u32;`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${J}(8);`} + `;for(let F=0;F<_*T;F++)V+=` + let scale${F} = ${K.getByOffset("col_index * nBlocksPerCol + block")}; + ${j?` + zero_point_byte_count = col_index * zero_point_bytes_per_col + (block >> 0x1u); + zero_point_word_index = zero_point_byte_count >> 0x2u; + zero_point_byte_offset = zero_point_byte_count & 0x3u; + zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + zero_point_word = ${j.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${F} = ${J}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return V},ae=()=>{let V=`col_index = col * ${_};`;for(let F=0;F<_*T;F++)V+=` + let b${F}_data = ${z.getByIndices(`${z.type.indices}(col_index, block, word)`)}; + col_index += 1;`;return V+=` + var b_value: u32; + let b_mask: u32 = 0x0F0F0F0Fu; + var b_value_lower: vec4; + var b_value_upper: vec4; + var b_quantized_values: ${Q}; + var b_dequantized_values: ${Q};`,V};return` + var workgroup_shared: array<${H.type.value}, ${T*w}>; + ${v.declareVariables(...G,H)} + ${v.mainStart([w,1,1])} + let output_indices = ${H.offsetToIndices(`(global_idx / ${w}) * ${T}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let nBlocksPerCol = uniforms.b_shape[1]; + + for (var block = local_id.x; block < nBlocksPerCol; block += ${w}) { + //process one block + var word_offset: u32 = block * ${r.blockSize/c}; + ${he()} + for (var word: u32 = 0; word < ${u}; word += ${d}) { + ${ae()} + for (var i: u32 = 0; i < ${d}; i++) { + ${oe()} + word_offset += ${8/c}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${T}) { + var output_value: ${H.type.value} = ${H.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${w}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${T}; + } + ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${c};${d};${_};${T};${w}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:f,dataType:p}],dispatchGroup:{x:k},programUniforms:g}),getShaderSource:M}},e_=(e,r)=>{let t=e[0].dims,s=t.length,o=t[s-2],n=r.k,i=r.n,a=t.slice(0,s-2),l=Me.size(a),u=e[1].dims[2]/4,p=e[0].dataType,c=rr(r.k),d=rr(u),_=a.concat([o,i]),f=128,T=i%8===0?8:i%4===0?4:1,k=f/T,w=k*d*8,g=w/c,S=w/r.blockSize,E=Me.size(_)/T,y=[],M=[l,o,n/c],v=Me.convertShape(e[1].dims).slice();v.splice(-1,1,u/d),y.push(...lt(M)),y.push(...lt(v)),y.push(...lt(e[2].dims)),e.length===4&&y.push(...lt(Me.convertShape(e[3].dims)));let C=[l,o,i];y.push(...lt(C));let A=z=>{let K=M.length,G=Te("a",e[0].dataType,K,c),j=Te("b",12,v.length,d),Y=Te("scales",e[2].dataType,e[2].dims.length),H=[G,j,Y],J=e.length===4?Te("zero_points",12,e[3].dims.length):void 0;J&&H.push(J);let Q=C.length,oe=rt("output",e[0].dataType,Q),he=br(e[0].dataType),ae=()=>{switch(c){case 1:return` + let a_data0 = vec4<${he}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${he}>(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<${he}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${he}>(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(`${c}-component is not supported.`)}};return` + var sub_a: array<${G.type.value}, ${g}>; + var inter_results: array, ${T}>; + ${z.declareVariables(...H,oe)} + ${z.mainStart([k,T,1])} + let output_indices = ${oe.offsetToIndices(`workgroup_index * ${T}`)}; + 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 += ${f}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${G.getByIndices(`${G.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${G.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${S} + local_id.x; + ${J?` + let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; + let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); + let zero_point_word_index = zero_point_byte_count >> 0x2u; + let zero_point_byte_offset = zero_point_byte_count & 0x3u; + let zero_point_nibble_offset: u32 = block & 0x1u; + let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + let zero_point_word = ${J.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${he}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${he}(8);`} + let scale = ${Y.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${j.getByIndices(`${j.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${r.blockSize/c}; + for (var i: u32 = 0; i < ${d}; i++) { + ${ae()} + 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<${he}>(${Array.from({length:4},(V,F)=>`${he}(b_value_lower[${F}]), ${he}(b_value_upper[${F}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${he}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(V,F)=>`${`dot(a_data${F}, b_dequantized_values[${F}])`}`).join(" + ")}; + word_offset += ${8/c}; + } + workgroupBarrier(); + } + + if (local_idx < ${T}) { + var output_value: ${oe.type.value} = ${oe.type.value}(0); + for (var b = 0u; b < ${k}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${oe.setByIndices(`${oe.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${c};${d};${k};${T}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:E},programUniforms:y}),getShaderSource:A}},t_=(e,r)=>{Yf(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(e_(e.inputs,r)):e.compute(Zf(e.inputs,r))},r_=e=>Bt(e)}),s_,n_,o_,i_,a_,l_,u_,c_,d_,nx=ze(()=>{ft(),yt(),xt(),s_=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].")}},n_=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${ot("uniforms.pads",o,t)}; + if (k < 0) { + break; + } + if (k >= i32(${ot("uniforms.x_shape",o,r)})) { + break; + } + offset += k * i32(${ot("uniforms.x_strides",o,r)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + } + `},o_=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${ot("uniforms.pads",o,t)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${ot("uniforms.x_shape",o,r)}) - 1); + k = k % _2n_1; + if(k >= i32(${ot("uniforms.x_shape",o,r)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${ot("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},i_=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${ot("uniforms.pads",o,t)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${ot("uniforms.x_shape",o,r)})) { + k = i32(${ot("uniforms.x_shape",o,r)}) - 1; + } + offset += k * i32(${ot("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},a_=(e,r,t)=>{let s="";for(let o=r-1;o>=0;--o)s+=` + k = i32(${e.indicesGet("indices",o)}) - ${ot("uniforms.pads",o,t)}; + if (k < 0) { + k += i32(${ot("uniforms.x_shape",o,r)}]); + } + if (k >= i32(${ot("uniforms.x_shape",o,r)})) { + k -= i32(${ot("uniforms.x_shape",o,r)}); + } + offset += k * i32(${ot("uniforms.x_strides",o,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},l_=(e,r,t)=>{switch(t.mode){case 0:return n_(e,r,t.pads.length);case 1:return o_(e,r,t.pads.length);case 2:return i_(e,r,t.pads.length);case 3:return a_(e,r,t.pads.length);default:throw new Error("Invalid mode")}},u_=(e,r)=>{let t=Me.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,o=Me.size(t),n=[{type:12,data:o},{type:6,data:r.pads}],i=e.length>=3&&e[2].data;r.mode===0&&n.push({type:i?e[2].dataType:1,data:r.value}),n.push(...lt(e[0].dims,t));let a=["rank"],l=u=>{let p=rt("output",e[0].dataType,t.length),c=Te("x",e[0].dataType,s.length),d=c.type.value,_=l_(p,s.length,r),f=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&f.push({name:"constant_value",type:i?d:"f32"}),` + ${u.registerUniforms(f).declareVariables(c,p)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${p.offsetToIndices("global_idx")}; + + var value = ${d}(0); + ${_} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${i}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Me.size(t)/64)},programUniforms:n}),getShaderSource:l}},c_=(e,r)=>{if(e.length>1){let t=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,o=e[0].dims.length,n=new Int32Array(2*o).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;ln[Number(l)]=Number(a));let i=[];return n.forEach(a=>i.push(a)),{mode:r.mode,value:s,pads:i}}else return r},d_=(e,r)=>{s_(e.inputs);let t=c_(e.inputs,r);e.compute(u_(e.inputs,t),{inputs:[0]})}}),bo,Bl,Rl,jl,Nl,p_,h_,Vl,Ul,m_,f_,Wl,__,g_,Gl,w_,M_,b_,y_,ox=ze(()=>{ds(),ft(),yt(),xt(),bo=e=>{if(Xt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Bl=(e,r,t)=>{let s=r.format==="NHWC",o=e.dims.slice();s&&o.splice(1,0,o.pop());let n=Object.hasOwnProperty.call(r,"dilations"),i=r.kernelShape.slice(),a=r.strides.slice(),l=n?r.dilations.slice():[],u=r.pads.slice();ni.adjustPoolAttributes(t,o,i,a,l,u);let p=ni.computePoolOutputShape(t,o,a,l,i,u,r.autoPad),c=Object.assign({},r);n?Object.assign(c,{kernelShape:i,strides:a,pads:u,dilations:l,cacheKey:r.cacheKey}):Object.assign(c,{kernelShape:i,strides:a,pads:u,cacheKey:r.cacheKey});let d=p.slice();return d.push(d.splice(1,1)[0]),[c,s?d:p]},Rl=(e,r)=>{let t=r.format==="NHWC",s=Me.size(e),o=Me.size(r.kernelShape),n=[{type:12,data:s},{type:12,data:o}],i=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let a=r.kernelShape[r.kernelShape.length-1],l=r.strides[r.strides.length-1],u=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],c=!!(u+p);n.push({type:12,data:a},{type:12,data:l},{type:12,data:u},{type:12,data:p}),i.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let d=!1;if(r.kernelShape.length===2){let _=r.kernelShape[r.kernelShape.length-2],f=r.strides[r.strides.length-2],T=r.pads[r.pads.length/2-2],k=r.pads[r.pads.length-2];d=!!(T+k),n.push({type:12,data:_},{type:12,data:f},{type:12,data:T},{type:12,data:k}),i.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,i,!0,c,d]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=Me.computeStrides(r.kernelShape);n.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),i.push({name:"kernelStrides",type:"u32",length:a.length},{name:"pads",type:"u32",length:r.pads.length},{name:"strides",type:"u32",length:r.strides.length});let l=r.pads.reduce((u,p)=>u+p);return[n,i,!!l,!1,!1]}},jl=(e,r,t,s,o,n,i,a,l,u,p,c)=>{let d=o.format==="NHWC",_=r.type.value,f=rt("output",r.type.tensor,s);if(o.kernelShape.length<=2){let T="",k="",w="",g=t-(d?2:1);if(p?T=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${g}] < 0 || xIndices[${g}] + >= uniforms.x_shape[${g}]) { + pad++; + continue; + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:T=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${g}] = indices[${g}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`,o.kernelShape.length===2){let S=t-(d?3:2);c?k=` + 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; + } + `:k=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${S}] = indices[${S}] * uniforms.sh - uniforms.phStart + j; + `,w=` + } + `}return` + ${e.registerUniforms(l).declareVariables(r,f)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${f.offsetToIndices("global_idx")}; + var xIndices = ${f.offsetToIndices("global_idx")}; + + var value = ${_}(${a}); + var pad = 0; + ${k} + ${T} + ${w} + ${i} + + output[global_idx] = value; + }`}else{if(d)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let T=o.kernelShape.length,k=o.pads.length,w="";return u?w=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:w=` + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + `,` + ${e.registerUniforms(l).declareVariables(r,f)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${f.offsetToIndices("global_idx")}; + var xIndices = ${f.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${_}(${a}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${T-1}u; j++) { + offsets[j] = offset / ${ot("uniforms.kernelStrides","j",T)}; + offset -= offsets[j] * ${ot("uniforms.kernelStrides","j",T)}; + } + offsets[${T-1}] = offset; + + isPad = false; + for (var j = ${t-T}u; j < ${t}u; j++) { + xIndices[j] = indices[j] * ${ot("uniforms.strides",`j - ${t-T}u`,T)} + + offsets[j - ${t-T}u] - ${ot("uniforms.pads","j - 2u",k)}; + ${w} + } + ${i} + + output[global_idx] = value; + }`}},Nl=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,p_=e=>`${Nl(e)};${e.countIncludePad}`,h_=e=>`${Nl(e)};${e.storageOrder};${e.dilations}`,Vl=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}),Ul=(e,r,t,s)=>{let[o,n]=Bl(r,s,t),i=Te("x",r.dataType,r.dims.length),a=i.type.value,l="value += x_val;",u="";o.countIncludePad?u+=`value /= ${a}(uniforms.kernelSize);`:u+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,c,d,_,f]=Rl(n,o);p.push(...lt(r.dims,n));let T=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${d};${_};${f}`,inputDependencies:T},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Me.size(n)/64)},programUniforms:p}),getShaderSource:k=>jl(k,i,r.dims.length,n.length,o,l,u,0,c,d,_,f)}},m_=e=>{let r=e.count_include_pad!==0,t=Vl(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:p_(s)}},f_=(e,r)=>{bo(e.inputs),e.compute(Ul("AveragePool",e.inputs[0],!1,r))},Wl={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},__=e=>{let r=e.format;return{format:r,...Wl,cacheKey:r}},g_=(e,r)=>{bo(e.inputs),e.compute(Ul("GlobalAveragePool",e.inputs[0],!0,r))},Gl=(e,r,t,s)=>{let[o,n]=Bl(r,s,t),i=` + value = max(x_val, value); + `,a="",l=Te("x",r.dataType,r.dims.length),u=["rank"],[p,c,d,_,f]=Rl(n,o);return p.push(...lt(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${d};${_};${f}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(Me.size(n)/64)},programUniforms:p}),getShaderSource:T=>jl(T,l,r.dims.length,n.length,o,i,a,r.dataType===10?-65504:-1e5,c,d,_,f)}},w_=(e,r)=>{bo(e.inputs),e.compute(Gl("MaxPool",e.inputs[0],!1,r))},M_=e=>{let r=e.storage_order,t=e.dilations,s=Vl(e);if(r!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let o={storageOrder:r,dilations:t,...s,cacheKey:""};return{...o,cacheKey:h_(o)}},b_=e=>{let r=e.format;return{format:r,...Wl,cacheKey:r}},y_=(e,r)=>{bo(e.inputs),e.compute(Gl("GlobalMaxPool",e.inputs[0],!0,r))}}),v_,x_,T_,E_,ix=ze(()=>{ft(),yt(),or(),xt(),v_=(e,r)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((t,s)=>t===e[2].dims[s]).reduce((t,s)=>t&&s,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(r.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((o,n)=>n===r.axis||o===e[0].dims[n]).reduce((o,n)=>o&&n,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let t=e[0].dims[r.axis],s=e[1].dims[r.axis];if(r.blockSizeMath.ceil(t/(s-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},x_=(e,r)=>{let t=Me.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,o=s===3,n=e[0].dims,i=e[1].dataType,a=Me.size(n),l=s===3||s===2,u=l?[Math.ceil(Me.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,c=e.length>2?e[2]:void 0,d=c?l?[Math.ceil(Me.size(c.dims)/4)]:c.dims:void 0,_=p.length===0||p.length===1&&p[0]===1,f=_===!1&&p.length===1,T=rr(a),k=_&&(!l||T===4),w=k?T:1,g=k&&!l?T:1,S=Te("input",l?12:s,u.length,g),E=Te("scale",i,p.length),y=c?Te("zero_point",l?12:s,d.length):void 0,M=rt("output",i,n.length,w),v=[S,E];y&&v.push(y);let C=[u,p];c&&C.push(d);let A=[{type:12,data:a/w},{type:12,data:t},{type:12,data:r.blockSize},...lt(...C,n)],z=K=>{let G=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${K.registerUniforms(G).declareVariables(...v,M)} + ${K.mainStart()} + ${K.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${M.offsetToIndices("global_idx")}; + + // Set input x + ${l?` + let input = ${S.getByOffset("global_idx / 4")}; + let x_vec = ${o?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${w===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${S.getByOffset("global_idx")};`}; + + // Set scale input + ${_?`let scale_value= ${E.getByOffset("0")}`:f?` + let scale_index = ${M.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${E.getByOffset("scale_index")};`:` + var scale_indices: ${E.type.indices} = output_indices; + let index = ${E.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${E.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${E.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${y?_?l?` + let zero_point_input = ${y.getByOffset("0")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${y.getByOffset("0")}`:f?l?` + let zero_point_index = ${M.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${y.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${M.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${y.getByOffset("zero_point_index")};`:l?` + let zero_point_offset = ${E.indicesToOffset("scale_indices")}; + let zero_point_input = ${y.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${o?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${y.getByIndices("scale_indices")};`:`let zero_point_value = ${l?o?"i32":"u32":S.type.value}(0);`}; + // Compute and write output + ${M.setByOffset("global_idx",`${M.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:y?["rank","rank","rank"]:["rank","rank"]},getShaderSource:z,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(a/w/64),y:1,z:1},programUniforms:A})}},T_=(e,r)=>{v_(e.inputs,r),e.compute(x_(e.inputs,r))},E_=e=>Bt({axis:e.axis,blockSize:e.blockSize})}),P_,C_,S_,ax=ze(()=>{ds(),ft(),xt(),P_=(e,r,t)=>{let s=e===r,o=er&&t>0;if(s||o||n)throw new Error("Range these inputs' contents are invalid.")},C_=(e,r,t,s)=>{let o=Math.abs(Math.ceil((r-e)/t)),n=[o],i=o,a=[{type:12,data:i},{type:s,data:e},{type:s,data:t},...lt(n)],l=u=>{let p=rt("output",s,n.length),c=p.type.value,d=[{name:"outputSize",type:"u32"},{name:"start",type:c},{name:"delta",type:c}];return` + ${u.registerUniforms(d).declareVariables(p)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${c}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:a})}},S_=e=>{let r=0,t=0,s=0;e.inputs[0].dataType===6?(r=e.inputs[0].getInt32Array()[0],t=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(r=e.inputs[0].getFloat32Array()[0],t=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),Xt.webgpu.validateInputContent&&P_(r,t,s),e.compute(C_(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),$_,Kl,Hl,k_,I_,A_,lx=ze(()=>{ft(),yt(),or(),xt(),$_=(e,r,t,s)=>{if(e!=="none"&&s!=="i32"&&s!=="u32"&&s!=="f32")throw new Error(`Input ${s} is not supported with reduction ${e}.`);let o=`{ + var oldValue = 0; + loop { + let newValueF32 =`,n=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${r}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${r}=${t};`;case"add":return s==="i32"||s==="u32"?`atomicAdd(&${r}, bitcast<${s}>(${t}));`:` + ${o}bitcast<${s}>(oldValue) + (${t})${n}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` + ${o}max(bitcast(oldValue), (${t}))${n}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${o}min(bitcast<${s}>(oldValue), (${t}))${n}`;case"mul":return`${o}(bitcast<${s}>(oldValue) * (${t}))${n}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Kl=(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));`,Hl=(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]; + ${$_(e.reduction,"output[data_offset + i]","value",r)} + }`,k_=(e,r)=>{let t=e[0].dims,s=e[1].dims,o=t,n=1,i=Math.ceil(Me.size(s)/n),a=s[s.length-1],l=Me.sizeFromDimension(t,a),u=Me.sizeFromDimension(s,0)/a,p=[{type:12,data:i},{type:12,data:a},{type:12,data:l},...lt(e[1].dims,e[2].dims,o)],c=d=>{let _=Te("indices",e[1].dataType,e[1].dims.length),f=Te("updates",e[2].dataType,e[2].dims.length,n),T=r.reduction!=="none"&&r.reduction!==""?zd("output",e[0].dataType,o.length):rt("output",e[0].dataType,o.length,n);return` + ${d.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(_,f,T)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var hasDuplicates = false; + if (${r.reduction==="none"}) { + for (var i = 0; i < ${u}; i = i + 1) { + for (var j = i + 1; j < ${u}; j = j + 1) { + var index_i = i32(indices[i].x); + var index_j = i32(indices[j].x); + if (index_i == index_j) { + hasDuplicates = true; + break; + } + } + if (hasDuplicates) { + break; + } + } + } + + if (${r.reduction==="none"} && hasDuplicates) { + if (global_idx != 0u) { + return; + } + // Process each index-update pair individually when duplicates exist + for (var idx = 0u; idx < ${u}u; idx++) { + var data_offset = 0u; + for (var i = 0u; i < uniforms.last_index_dimension; i++) { + var index = i32(indices[idx * uniforms.last_index_dimension + i].x); + ${Kl(t.length,!1)} + } + ${Hl(r,T.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); + ${Kl(t.length,!0)} + } + ${Hl(r,T.type.value,!0)} + }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:c}},I_=e=>Bt({reduction:e.reduction}),A_=(e,r)=>{e.compute(k_(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),F_,O_,D_,ql,L_,z_,B_,R_,j_,N_,V_,U_,Ql,W_,G_,K_,H_,q_,Q_,X_,ux=ze(()=>{ft(),yt(),or(),xt(),F_=(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")}},O_=(e,r,t)=>{r.every(o=>o>=0&&o{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(t).fill(1);return r.forEach((o,n)=>s[o]=e[n]),s},D_=(e,r,t,s,o,n)=>{let[i,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],u=e[0].dims.length;if(i>0&&e.length>i&&e[i].dims.length>0)e[i].getFloat32Array().forEach(p=>n.push(p));else if(r.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(a>0&&e.length>a&&e[a].dims.length===1&&e[a].dims[0]>0){if(e[a].getFloat32Array().forEach(p=>s.push(p)),s.length!==0&&s.length!==u&&t>=18&&s.length!==r.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");F_(s,r),r.axes.length>0&&O_(s,r.axes,u).forEach((p,c)=>s[c]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>o.push(Number(p))),o.length!==0&&o.length!==u&&t>=18&&o.length!==r.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(r.axes.length>0){if(s.length!==0&&s.length!==r.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(o.length!==0&&o.length!==r.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof s<"u"&&typeof o<"u"&&s.length>0&&o.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},ql=(e,r,t,s)=>` + // The whole part and the fractional part are calculated separately due to inaccuracy of floating + // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an + // offset-by-one error later in floor(). + let big = (${e}) * (${r}); + let whole = ${s}(big / (${t})); + let fract = ${s}(big % (${t})) / ${s}(${t}); + return whole + fract; +`,L_=(e,r)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${r} { `+(()=>{switch(e){case"asymmetric":return` + if (xScale < 1.0 || floor(xScale) != xScale) { + return ${r}(xResized) / ${r}(xScale); + } else { + ${ql("xResized","lengthOriginal","lengthResized",r)} + } + `;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${r}(xResized) + 0.5) / ${r}(xScale);`;case"align_corners":return`if (lengthResized == 1) { + return 0.0; + } else { + ${ql("xResized","lengthOriginal - 1","lengthResized - 1",r)} + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${r}(roiStart) * ${r}(lengthOriginal - 1) + + (${r}(xResized) * ${r}(roiEnd - roiStart) * ${r}(lengthOriginal - 1)) / + ${r}(lengthResized - 1); + } else { + return 0.5 * ${r}(roiStart + roiEnd) * ${r}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${r}xScale * ${r}(lengthResized); + const adjustment = ${r}(lengthResized) / outputWidth; + const center = ${r}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + return offset + ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;case"half_pixel":return`return ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",z_=(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`)}})()+"}",B_=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),o=e.length===0?s:e.slice();return r.length>0?(r.forEach((n,i)=>{s[n]=o[i],s[i+t]=o[r.length+i]}),s):o},R_=(e,r,t,s)=>{let o=[];if(t.length>0)if(s.length>0){if(e.forEach(n=>o.push(n)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((n,i)=>o[n]=t[i])}else t.forEach(n=>o.push(n));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");o=e.map((n,i)=>Math.round(n*r[i]))}return o},j_=(e,r,t)=>{let s=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(n=>r[n]),Number.MAX_VALUE):Math.min(...r,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(n=>r[n]),Number.MIN_VALUE):Math.max(...r,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${t.keepAspectRatioPolicy} is not supported`)}})();r.fill(1,0,r.length);let o=e.slice();return t.axes.length>0?(t.axes.forEach(n=>r[n]=s),t.axes.forEach(n=>o[n]=Math.round(e[n]*r[n]))):(r.fill(s,0,r.length),o.forEach((n,i)=>o[i]=Math.round(n*r[i]))),o},N_=(e,r,t,s,o)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${t.length}> { + var original_indices: array<${e.type.value}, ${t.length}>; + for (var i:u32 = 0; i < ${t.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${ot("uniforms.scales","i",s)}; + var roi_low = ${ot("uniforms.roi","i",o)}; + var roi_hi = ${ot("uniforms.roi",`i + ${r.length}`,o)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${ot("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${ot("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; + }`,V_=(e,r,t,s,o,n,i)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${r.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${ot("uniforms.scales","i",o)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${ot("uniforms.roi","i",n)}; + var roi_hi = ${ot("uniforms.roi",`i + ${t.length}`,n)}; + var input_shape_i = ${ot("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${ot("uniforms.output_shape","i",s.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${i} || (original_idx >= 0 && original_idx < ${r.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${r.type.value}(input_shape_i - 1)) { + input_index = input_shape_i - 1; + } else { + input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); + } + } else { + input_index = u32(original_idx); + } + } + ${e.indicesSet("input_indices","i","input_index")} + } + return input_indices; + }`,U_=(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 >= ${ot("uniforms.input_shape","i",r.length)}) { + return false; + } + } + return true; + }`,Ql=(e,r,t,s)=>e.rank>s?` + ${e.indicesSet("input_indices",r,"channel")}; + ${e.indicesSet("input_indices",t,"batch")}; +`:"",W_=(e,r,t,s,o)=>{let[n,i,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],u=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${u} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(row, ${t[i]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; + ${Ql(e,l,n,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${u} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${u} = originalIndices[${i}]; + var col:${u} = originalIndices[${a}]; + ${s?`if (row < 0 || row > (${t[i]} - 1) || col < 0 || col > (${t[a]} - 1)) { + return ${o}; + }`:""}; + row = max(0, min(row, ${t[i]} - 1)); + col = max(0, min(col, ${t[a]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${t.length>2?`u32(originalIndices[${l}])`:"0"}; + var batch: u32 = ${t.length>2?`u32(originalIndices[${n}])`:"0"}; + var x11: ${u} = getInputValue(batch, channel, row1, col1); + var x12: ${u} = getInputValue(batch, channel, row1, col2); + var x21: ${u} = getInputValue(batch, channel, row2, col1); + var x22: ${u} = getInputValue(batch, channel, row2, col2); + var dx1: ${u} = abs(row - ${u}(row1)); + var dx2: ${u} = abs(${u}(row2) - row); + var dy1: ${u} = abs(col - ${u}(col1)); + var dy2: ${u} = abs(${u}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},G_=(e,r,t,s,o,n,i,a,l,u)=>{let p=t.length===2,[c,d]=p?[0,1]:[2,3],_=e.type.value,f=T=>{let k=T===c?"row":"col";return` + fn ${k}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${_} { + var output_index = ${r.indicesGet("output_indices",T)}; + var originalIdx: ${_} = getOriginalCoordinateFromResizedCoordinate(output_index, ${o[T]}, + ${s[T]}, ${t[T]}, ${n[T]}, ${n[T]} + ${t.length}); + var fractOriginalIdx: ${_} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${a} && (originalIdx < 0 || originalIdx > (${t[T]} - 1))) { + return ${l}; + } + var data: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${k}: ${_} = originalIdx + ${_}(i); + if (${k} < 0 || ${k} >= ${t[T]}) { + ${u?`coefs[i + 1] = 0.0; + continue;`:a?`return ${l};`:`${k} = max(0, min(${k}, ${t[T]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",T,`u32(${k})`)}; + data[i + 1] = ${T===c?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${f(c)}; + ${f(d)}; + fn getCubicInterpolationCoefs(s: ${_}) -> array<${_}, 4> { + var absS = abs(s); + var coeffs: array<${_}, 4> = array<${_}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${_} = 1.0 - absS; + var twoMinusAbsS: ${_} = 2.0 - absS; + var onePlusAbsS: ${_} = 1.0 + absS; + coeffs[0] = ((${i} * onePlusAbsS - 5 * ${i}) * onePlusAbsS + 8 * ${i}) * onePlusAbsS - 4 * ${i}; + coeffs[1] = ((${i} + 2) * absS - (${i} + 3)) * absS * absS + 1; + coeffs[2] = ((${i} + 2) * oneMinusAbsS - (${i} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${i} * twoMinusAbsS - 5 * ${i}) * twoMinusAbsS + 8 * ${i}) * twoMinusAbsS - 4 * ${i}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${_}, 4>, coefs: array<${_}, 4>) -> ${_} { + var coefsSum: ${_} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; + return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; + } + + fn bicubicInterpolation(output_indices: ${r.type.indices}) -> ${_} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},K_=(e,r,t,s,o)=>{let[n,i,a,l,u]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${p} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",i,`max(0, min(depth, ${t[i]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(height, ${t[a]} - 1))`)}; + ${e.indicesSet("input_indices",l,`max(0, min(width, ${t[l]} - 1))`)}; + ${Ql(e,u,n,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${r.type.indices}) -> ${p} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${p} = originalIndices[${i}]; + var height:${p} = originalIndices[${a}]; + var width:${p} = originalIndices[${l}]; + ${s?`if (depth < 0 || depth > (${t[i]} - 1) || height < 0 || height > (${t[a]} - 1) || width < 0 || (width > ${t[l]} - 1)) { + return ${o}; + }`:""}; + + depth = max(0, min(depth, ${t[i]} - 1)); + height = max(0, min(height, ${t[a]} - 1)); + width = max(0, min(width, ${t[l]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${t.length>3?`u32(originalIndices[${u}])`:"0"}; + var batch: u32 = ${t.length>3?`u32(originalIndices[${n}])`:"0"}; + + var x111: ${p} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${p} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${p} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${p} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${p} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${p} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${p} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${p} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${p} = abs(depth - ${p}(depth1)); + var dx2: ${p} = abs(${p}(depth2) - depth); + var dy1: ${p} = abs(height - ${p}(height1)); + var dy2: ${p} = abs(${p}(height2) - height); + var dz1: ${p} = abs(width - ${p}(width1)); + var dz2: ${p} = abs(${p}(width2) - width); + if (depth1 == depth2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (height1 == height2) { + dy1 = 0.5; + dy2 = 0.5; + } + if (width1 == width2) { + dz1 = 0.5; + dz2 = 0.5; + } + return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); + }`},H_=(e,r,t,s,o,n)=>{let i=e.dims,a=B_(n,r.axes,i.length),l=R_(i,s,o,r.axes),u=s.slice();s.length===0&&(u=i.map((g,S)=>g===0?1:l[S]/g),r.keepAspectRatioPolicy!=="stretch"&&(l=j_(i,u,r)));let p=rt("output",e.dataType,l.length),c=Te("input",e.dataType,i.length),d=Me.size(l),_=i.length===l.length&&i.every((g,S)=>g===l[S]),f=r.coordinateTransformMode==="tf_crop_and_resize",T=r.extrapolationValue,k=c.type.value,w=g=>` + ${_?"":` + ${L_(r.coordinateTransformMode,k)}; + ${(()=>{switch(r.mode){case"nearest":return` + ${U_(c,i)}; + ${z_(r.nearestMode,t,k)}; + ${V_(c,p,i,l,u.length,a.length,f)}; + `;case"linear":return` + ${N_(p,i,l,u.length,a.length)}; + ${(()=>{if(i.length===2||i.length===4)return`${W_(c,p,i,f,T)}`;if(i.length===3||i.length===5)return`${K_(c,p,i,f,T)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(i.length===2||i.length===4)return`${G_(c,p,i,l,u,a,r.cubicCoeffA,f,r.extrapolationValue,r.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${g.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",a.length).declareVariables(c,p)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${_?"output[global_idx] = input[global_idx];":` + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${c.type.indices}; + ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${c.getByIndices("input_indices")}; + } else { + output[global_idx] = ${r.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${i.length===2||i.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${r.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${r.cacheKey}|${t}|${u.length>0?r.mode==="cubic"?u:u.length:""}|${o.length>0?o:""}|${a.length>0?a:""}|${_}|${r.mode==="nearest"?i.length:i}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:[{type:12,data:d},{type:1,data:u},{type:1,data:a},...lt(i,l)]})}},q_=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},Q_=(e,r)=>{let t=[],s=[],o=[],n=q_(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");D_(e.inputs,r,n,t,s,o),e.compute(H_(e.inputs[0],r,n,t,s,o),{inputs:[0]})},X_=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,o=e.cubicCoeffA,n=e.excludeOutside!==0,i=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,u=e.nearestMode===""?"simple":e.nearestMode;return Bt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:o,excludeOutside:n,extrapolationValue:i,keepAspectRatioPolicy:a,mode:l,nearestMode:u})}}),J_,Y_,Z_,cx=ze(()=>{ft(),yt(),xt(),J_=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let r=e[0],t=e[1],s=e[2];if(r.dataType!==t.dataType||r.dataType!==s.dataType)throw new Error("All inputs must have the same data type");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Input must be 2D or 3D");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Skip must be 2D or 3D");let o=r.dims[r.dims.length-1],n=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==o)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==n)throw new Error("Skip must have the same sequence length as input");if(s.dims.length!==1)throw new Error("Gamma must be 1D");if(s.dims[s.dims.length-1]!==o)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let i=e[3];if(i.dims.length!==1)throw new Error("Beta must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let i=e[4];if(i.dims.length!==1)throw new Error("Bias must be 1D");if(i.dims[i.dims.length-1]!==o)throw new Error("Bias must have the same hidden size as input")}},Y_=(e,r,t,s)=>{let o=r.simplified,n=e[0].dims,i=Me.size(n),a=n,l=i,u=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],c=!o&&e.length>3,d=e.length>4,_=s&&t>1,f=s&&t>2,T=t>3,k=64,w=rr(u),g=[{type:12,data:l},{type:12,data:w},{type:12,data:u},{type:1,data:r.epsilon}],S=y=>{let M=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],v=[Te("x",e[0].dataType,e[0].dims,w),Te("skip",e[1].dataType,e[1].dims,w),Te("gamma",e[2].dataType,e[2].dims,w)];c&&v.push(Te("beta",e[3].dataType,e[3].dims,w)),d&&v.push(Te("bias",e[4].dataType,e[4].dims,w)),v.push(rt("output",e[0].dataType,a,w)),_&&v.push(rt("mean_output",1,p)),f&&v.push(rt("inv_std_output",1,p)),T&&v.push(rt("input_skip_bias_sum",e[0].dataType,a,w));let C=br(e[0].dataType),A=br(1,w);return` + + ${y.registerUniforms(M).declareVariables(...v)} + var sum_shared : array<${A}, ${k}>; + var sum_squared_shared : array<${A}, ${k}>; + + ${y.mainStart([k,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${k}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${k}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${k-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${d?"bias[offset1d + i]":C+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${T?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${Un(C,w,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${k}; + for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { + reduce_size = curr_size + (reduce_size & 1); + if (ix < curr_size) { + sum_shared[ix] += sum_shared[ix + reduce_size]; + sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; + } + workgroupBarrier(); + } + + let sum = sum_shared[0]; + let square_sum = sum_squared_shared[0]; + let mean = ${Vs("sum",w)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Vs("square_sum",w)} / f32(uniforms.hidden_size) ${o?"":"- mean * mean"} + uniforms.epsilon); + ${_?"mean_output[global_idx] = mean;":""} + ${f?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${o?"":`- ${C}(mean)`}) * + ${C}(inv_std_dev) * gamma[offset1d + i] + ${c?"+ beta[offset1d + i]":""}; + } + }`},E=[{dims:a,dataType:e[0].dataType}];return t>1&&E.push({dims:p,dataType:1}),t>2&&E.push({dims:p,dataType:1}),t>3&&E.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${w};${_};${f};${T}`,inputDependencies:e.map((y,M)=>"type")},getShaderSource:S,getRunData:()=>({outputs:E,dispatchGroup:{x:Math.ceil(l/u)},programUniforms:g})}},Z_=(e,r)=>{J_(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(Y_(e.inputs,r,e.outputCount,!1),{outputs:t})}}),eg,yo,tg,Xl,rg,sg,ng,og,dx=ze(()=>{ft(),yt(),or(),xt(),eg=(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`)})},yo=(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},tg=(e,r)=>{if(e.length>1){let t=yo(e,1),s=yo(e,2),o=yo(e,3);return o.length===0&&(o=[...Array(e[0].dims.length).keys()]),Bt({starts:t,ends:s,axes:o})}else return r},Xl=(e,r,t,s,o)=>{let n=e;return e<0&&(n+=t[s[r]]),o[r]<0?Math.max(0,Math.min(n,t[s[r]]-1)):Math.max(0,Math.min(n,t[s[r]]))},rg=(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 = ${ot("uniforms.input_shape","i",t.length)}; + let steps_i = ${ot("uniforms.steps","i",t.length)}; + let signs_i = ${ot("uniforms.signs","i",t.length)}; + let starts_i = ${ot("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; + }`,sg=(e,r)=>{let t=e[0].dims,s=Me.size(t),o=r.axes.length>0?Me.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=yo(e,4);n.forEach(w=>w!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(o.length).fill(1));let i=r.starts.map((w,g)=>Xl(w,g,t,o,n)),a=r.ends.map((w,g)=>Xl(w,g,t,o,n));if(o.length!==i.length||o.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(o.length!==t.length)for(let w=0;wMath.sign(w));n.forEach((w,g,S)=>{if(w<0){let E=(a[g]-i[g])/w,y=i[g],M=y+E*n[g];i[g]=M,a[g]=y,S[g]=-w}});let u=t.slice(0);o.forEach((w,g)=>{u[w]=Math.ceil((a[w]-i[w])/n[w])});let p={dims:u,dataType:e[0].dataType},c=rt("output",e[0].dataType,u.length),d=Te("input",e[0].dataType,e[0].dims.length),_=Me.size(u),f=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:i.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:n.length}],T=[{type:12,data:_},{type:12,data:i},{type:6,data:l},{type:12,data:n},...lt(e[0].dims,u)],k=w=>` + ${w.registerUniforms(f).declareVariables(d,c)} + ${rg(d,c,t)} + ${w.mainStart()} + ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${c.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${c.setByOffset("global_idx",d.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${i.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:T})}},ng=(e,r)=>{eg(e.inputs,r);let t=tg(e.inputs,r);e.compute(sg(e.inputs,t),{inputs:[0]})},og=e=>{let r=e.starts,t=e.ends,s=e.axes;return Bt({starts:r,ends:t,axes:s})}}),ig,ag,lg,ug,px=ze(()=>{ft(),yt(),or(),Us(),xt(),ig=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},ag=(e,r)=>{let t=e.inputs[0],s=t.dims,o=Me.size(s),n=s.length,i=Me.normalizeAxis(r.axis,n),a=iC),u[i]=n-1,u[n-1]=i,l=e.compute(Kr(t,u),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,c=p[n-1],d=o/c,_=rr(c),f=c/_,T=64;d===1&&(T=256);let k=(v,C)=>C===4?`max(max(${v}.x, ${v}.y), max(${v}.z, ${v}.w))`:C===2?`max(${v}.x, ${v}.y)`:C===3?`max(max(${v}.x, ${v}.y), ${v}.z)`:v,w=Te("x",l.dataType,l.dims,_),g=rt("result",l.dataType,l.dims,_),S=w.type.value,E=br(l.dataType)==="f32"?`var threadMax = ${S}(-3.402823e+38f);`:`var threadMax = ${S}(-65504.0h);`,y=v=>` + var rowMaxShared : ${S}; + var rowSumShared : ${S}; + var threadShared : array<${S}, ${T}>; + + 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(w,g)} + ${v.mainStart(T)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${T}; + 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}(${k("threadShared[0]",_)}); + } + 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}(${Vs("threadShared[0]",_)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`,M=e.compute({name:"Softmax",shaderCache:{hint:`${_};${T}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:d},programUniforms:[{type:6,data:f}]}),getShaderSource:y},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(Kr(M,u),{inputs:[M]})},lg=(e,r)=>{ig(e.inputs),ag(e,r)},ug=e=>Bt({axis:e.axis})}),Jl,cg,dg,pg,hg,hx=ze(()=>{ft(),yt(),xt(),Jl=e=>Array.from(e.getBigInt64Array(),Number),cg=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(Jl(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")},dg=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??Jl(e[1]),o=dg(t,s),n=Me.size(o),i=e[0].dataType,a=Te("input",i,t.length),l=rt("output",i,o.length),u=p=>` + const inputShape = ${a.indices(...t)}; + ${p.registerUniform("output_size","u32").declareVariables(a,l)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${l.offsetToIndices("global_idx")}; + var input_indices: ${a.type.indices}; + for (var i = 0; i < ${t.length}; i++) { + let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i; + + ${a.indicesSet("input_indices","i","input_dim_value")} + } + ${l.setByOffset("global_idx",a.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...lt(e[0].dims,o)]}),getShaderSource:u}},hg=e=>{cg(e.inputs),e.compute(pg(e.inputs),{inputs:[0]})}}),mg,fg,_g,mx=ze(()=>{ft(),yt(),xt(),mg=(e,r,t,s,o)=>{let n=rt("output_data",o,t.length,4),i=Te("a_data",r[1].dataType,r[1].dims.length,4),a=Te("b_data",r[2].dataType,r[2].dims.length,4),l=Te("c_data",r[0].dataType,r[0].dims.length,4),u,p=(c,d,_)=>`select(${d}, ${c}, ${_})`;if(!s)u=n.setByOffset("global_idx",p(i.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let c=(d,_,f="")=>{let T=`a_data[index_a${_}][component_a${_}]`,k=`b_data[index_b${_}][component_b${_}]`,w=`bool(c_data[index_c${_}] & (0xffu << (component_c${_} * 8)))`;return` + let output_indices${_} = ${n.offsetToIndices(`global_idx * 4u + ${_}u`)}; + let offset_a${_} = ${i.broadcastedIndicesToOffset(`output_indices${_}`,n)}; + let offset_b${_} = ${a.broadcastedIndicesToOffset(`output_indices${_}`,n)}; + let offset_c${_} = ${l.broadcastedIndicesToOffset(`output_indices${_}`,n)}; + let index_a${_} = offset_a${_} / 4u; + let index_b${_} = offset_b${_} / 4u; + let index_c${_} = offset_c${_} / 4u; + let component_a${_} = offset_a${_} % 4u; + let component_b${_} = offset_b${_} % 4u; + let component_c${_} = offset_c${_} % 4u; + ${d}[${_}] = ${f}(${p(T,k,w)}); + `};o===9?u=` + var data = vec4(0); + ${c("data",0,"u32")} + ${c("data",1,"u32")} + ${c("data",2,"u32")} + ${c("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:u=` + ${c("output_data[global_idx]",0)} + ${c("output_data[global_idx]",1)} + ${c("output_data[global_idx]",2)} + ${c("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(l,i,a,n)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${u} + }`},fg=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,o=e[1].dataType,n=!(Me.areEqual(r,t)&&Me.areEqual(t,s)),i=r,a=Me.size(r);if(n){let u=Nn.calcShape(Nn.calcShape(r,t,!1),s,!1);if(!u)throw new Error("Can't perform where op on the given tensors");i=u,a=Me.size(i)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:u=>mg(u,e,i,n,o),getRunData:()=>({outputs:[{dims:i,dataType:o}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...lt(s,r,t,i)]})}},_g=e=>{e.compute(fg(e.inputs))}}),gg,fx=ze(()=>{$v(),dl(),kv(),Iv(),Av(),Fv(),Ov(),Rv(),Nv(),Vv(),Uv(),Wv(),Gv(),Kv(),Hv(),qv(),Qv(),Xv(),Jv(),Yv(),Zv(),ex(),tx(),rx(),sx(),$f(),nx(),ox(),ix(),ax(),lx(),ll(),ux(),Rf(),cx(),dx(),px(),Lf(),hx(),Us(),fl(),mx(),gg=new Map([["Abs",[Xp]],["Acos",[Jp]],["Acosh",[Yp]],["Add",[Rh]],["ArgMax",[Dp,cl]],["ArgMin",[Op,cl]],["Asin",[Zp]],["Asinh",[eh]],["Atan",[th]],["Atanh",[rh]],["Attention",[Np]],["AveragePool",[f_,m_]],["BatchNormalization",[Gp]],["BiasAdd",[qp]],["BiasSplitGelu",[Lh]],["Cast",[nh,sh]],["Ceil",[ah]],["Clip",[ih]],["Concat",[Zh,em]],["Conv",[Sl,Pl]],["ConvTranspose",[Cm,Tm]],["Cos",[lh]],["Cosh",[uh]],["CumSum",[$m,km]],["DepthToSpace",[Om,Dm]],["DequantizeLinear",[T_,E_]],["Div",[jh]],["Einsum",[Nm,Vm]],["Elu",[ch,fo]],["Equal",[Nh]],["Erf",[dh]],["Exp",[ph]],["Expand",[Km]],["FastGelu",[qm]],["Floor",[hh]],["FusedConv",[Sl,Pl]],["Gather",[Ym,Jm]],["GatherElements",[cf,uf]],["GatherBlockQuantized",[nf,of]],["GatherND",[ef,tf]],["Gelu",[mh]],["Gemm",[mf,hf]],["GlobalAveragePool",[g_,__]],["GlobalMaxPool",[y_,b_]],["Greater",[Gh]],["GreaterOrEqual",[Hh]],["GridSample",[xf,Tf]],["GroupQueryAttention",[Uf]],["HardSigmoid",[vh,yh]],["InstanceNormalization",[Kf]],["LayerNormalization",[Qf]],["LeakyRelu",[fh,fo]],["Less",[Kh]],["LessOrEqual",[qh]],["Log",[kh]],["MatMul",[Jf]],["MatMulNBits",[t_,r_]],["MaxPool",[w_,M_]],["Mul",[Vh]],["MultiHeadAttention",[Sf,Pf]],["Neg",[gh]],["Not",[_h]],["Pad",[d_]],["Pow",[Uh]],["QuickGelu",[Fh,fo]],["Range",[S_]],["Reciprocal",[wh]],["ReduceMin",[$p]],["ReduceMean",[Tp]],["ReduceMax",[Sp]],["ReduceSum",[Ip]],["ReduceProd",[kp]],["ReduceL1",[Ep]],["ReduceL2",[Pp]],["ReduceLogSum",[Fp]],["ReduceLogSumExp",[Cp]],["ReduceSumSquare",[Ap]],["Relu",[Mh]],["Resize",[Q_,X_]],["RotaryEmbedding",[Bf]],["ScatterND",[A_,I_]],["Sigmoid",[bh]],["Sin",[xh]],["Sinh",[Th]],["Slice",[ng,og]],["SkipLayerNormalization",[Z_]],["Split",[Of,Df]],["Sqrt",[Eh]],["Softmax",[lg,ug]],["Sub",[Wh]],["Tan",[Ph]],["Tanh",[Ch]],["ThresholdedRelu",[$h,fo]],["Tile",[hg]],["Transpose",[Gd,Kd]],["Where",[_g]]])}),wg,_x=ze(()=>{ds(),Os(),xt(),wg=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t,s,o){cs(e.programInfo.name);let n=this.backend.device,i=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let u of r)a.push({binding:a.length,resource:{buffer:u.buffer}});for(let u of t)a.push({binding:a.length,resource:{buffer:u.buffer}});o&&a.push({binding:a.length,resource:o});let l=n.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let u={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(u)}i.setPipeline(e.computePipeline),i.setBindGroup(0,l),i.dispatchWorkgroups(...s),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),es(e.programInfo.name)}dispose(){}build(e,r){cs(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(u=>{t.features.has(u.feature)&&s.push(`enable ${u.extension};`)});let o=Rd(r,this.backend.device.limits),n=e.getShaderSource(o),i=`${s.join(` +`)} +${o.additionalImplementations} +${n}`,a=t.createShaderModule({code:i,label:e.name});kt("verbose",()=>`[WebGPU] ${e.name} shader code: ${i}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return es(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:o.variablesInfo}}normalizeDispatchGroupSize(e){let r=typeof e=="number"?e:e.x,t=typeof e=="number"?1:e.y||1,s=typeof e=="number"?1:e.z||1,o=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=o&&t<=o&&s<=o)return[r,t,s];let n=r*t*s,i=Math.ceil(Math.sqrt(n));if(i>o){if(i=Math.ceil(Math.cbrt(n)),i>o)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[i,i,i]}else return[i,i,1]}}}),Mg={};Rn(Mg,{WebGpuBackend:()=>xg});var bg,yg,vg,xg,gx=ze(()=>{ds(),ft(),Os(),Ed(),Cv(),fx(),_x(),bg=(e,r)=>{if(r.length!==e.length)throw new Error(`inputDependencies length ${r.length} is not equal to inputTensors length ${e.length}.`);let t=[];for(let s=0;s{var o,n;let s=e.name;return(o=e.shaderCache)!=null&&o.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${bg(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},vg=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},xg=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,r){this.env=e;let t=[],s={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},o=n=>r.features.has(n)&&t.push(n)&&!0;o("chromium-experimental-timestamp-query-inside-passes")||o("timestamp-query"),o("shader-f16"),o("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new vg(r.info||await r.requestAdapterInfo()),this.gpuDataManager=Dd(this),this.programManager=new wg(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ka(e.logLevel,!!e.debug),this.device.onuncapturederror=n=>{n.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${n.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;cs(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var s;let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let o=0;o"u"&&(this.queryTimeBase=_);let T=Number(_-this.queryTimeBase),k=Number(f-this.queryTimeBase);if(!Number.isSafeInteger(T)||!Number.isSafeInteger(k))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:c.map(w=>({dims:w.dims,dataType:Fs(w.dataType)})),outputsMetadata:d.map(w=>({dims:w.dims,dataType:Fs(w.dataType)})),kernelId:i,kernelType:l,kernelName:u,programName:p,startTime:T,endTime:k});else{let w="";c.forEach((S,E)=>{w+=`input[${E}]: [${S.dims}] | ${Fs(S.dataType)}, `});let g="";d.forEach((S,E)=>{g+=`output[${E}]: [${S.dims}] | ${Fs(S.dataType)}, `}),console.log(`[profiling] kernel "${i}|${l}|${u}|${p}" ${w}${g}execution time: ${k-T} ns`)}uo("GPU",`${p}::${_}::${f}`)}e.unmap(),this.pendingQueries.delete(e)}),es()}run(e,r,t,s,o,n){cs(e.name);let i=[];for(let g=0;gS):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let c=[],d=[];for(let g=0;g=n)throw new Error(`Invalid output index: ${p[g]}`);if(p[g]===-3)continue;let S=p[g]===-1,E=p[g]===-2,y=S||E?o(a[g].dataType,a[g].dims):s(p[g],a[g].dataType,a[g].dims);if(c.push(y),y.data===0)continue;let M=this.gpuDataManager.get(y.data);if(!M)throw new Error(`no GPU data for output: ${y.data}`);if(S&&this.temporaryData.push(M),E){let v=this.kernelPersistentData.get(this.currentKernelId);v||(v=[],this.kernelPersistentData.set(this.currentKernelId,v)),v.push(M)}d.push(M)}if(i.length!==r.length||d.length!==c.length){if(d.length===0)return es(e.name),c;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let _;if(u){let g=0,S=[];u.forEach(v=>{let C=typeof v.data=="number"?[v.data]:v.data;if(C.length===0)return;let A=v.type===10?2:4,z,K;v.type===10?(K=C.length>4?16:C.length>2?8:C.length*A,z=C.length>4?16:A*C.length):(K=C.length<=2?C.length*A:16,z=16),g=Math.ceil(g/K)*K,S.push(g);let G=v.type===10?8:4;g+=C.length>4?Math.ceil(C.length/G)*z:C.length*A});let E=16;g=Math.ceil(g/E)*E;let y=new ArrayBuffer(g);u.forEach((v,C)=>{let A=S[C],z=typeof v.data=="number"?[v.data]:v.data;if(v.type===6)new Int32Array(y,A,z.length).set(z);else if(v.type===12)new Uint32Array(y,A,z.length).set(z);else if(v.type===10)new Uint16Array(y,A,z.length).set(z);else if(v.type===1)new Float32Array(y,A,z.length).set(z);else throw new Error(`Unsupported uniform type: ${Fs(v.type)}`)});let M=this.gpuDataManager.create(g,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(M.buffer,0,y,0,g),this.gpuDataManager.release(M.id),_={offset:0,size:g,buffer:M.buffer}}let f=this.programManager.normalizeDispatchGroupSize(l),T=f[1]===1&&f[2]===1,k=yg(e,r,T),w=this.programManager.getArtifact(k);if(w||(w=this.programManager.build(e,f),this.programManager.setArtifact(k,w),kt("info",()=>`[artifact] key: ${k}, programName: ${e.name}`)),u&&w.uniformVariablesInfo){if(u.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${u.length} in program "${w.programInfo.name}".`);for(let g=0;g`[ProgramManager] run "${e.name}" (key=${k}) with ${f[0]}x${f[1]}x${f[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let g={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:r,outputTensorViews:c};this.pendingKernels.push(g),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(g)}return this.programManager.run(w,i,d,f,_),es(e.name),c}upload(e,r){this.gpuDataManager.upload(e,r)}memcpy(e,r){this.gpuDataManager.memcpy(e,r)}async download(e,r){await this.gpuDataManager.download(e,r)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,r,t,s){let o=gg.get(e);if(!o)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:s,kernelEntry:o[0],attributes:[o[1],t]};this.kernels.set(r,n)}releaseKernel(e){let r=this.kernelPersistentData.get(e);if(r){for(let t of r)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,r,t){let s=this.kernels.get(e);if(!s)throw new Error(`kernel not created: ${e}`);let o=s.kernelType,n=s.kernelName,i=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${o}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),kt("info",()=>`[WebGPU] Start to run kernel "[${o}] ${n}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),i(r,a[1]),0}catch(u){return t.push(Promise.resolve(`[WebGPU] Kernel "[${o}] ${n}" failed. ${u}`)),1}finally{l&&t.push(this.device.popErrorScope().then(u=>u?`GPU validation error for kernel "[${o}] ${n}": ${u.message}`:null));for(let u of this.temporaryData)this.gpuDataManager.release(u.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let o=this.sessionExternalDataMapping.get(e);o||(o=new Map,this.sessionExternalDataMapping.set(e,o));let n=o.get(r),i=this.gpuDataManager.registerExternalBuffer(t,s,n);return o.set(r,[i,t]),i}unregisterBuffers(e){let r=this.sessionExternalDataMapping.get(e);r&&(r.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let r=this.gpuDataManager.get(e);if(!r)throw new Error(`no GPU data for buffer: ${e}`);return r.buffer}createDownloader(e,r,t){return async()=>{let s=await sl(this,e,r);return Ha(s.buffer,t)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){kt("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(){kt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){kt("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()}}}),Tg={};Rn(Tg,{init:()=>Pg});var gi,Eg,Pg,wx=ze(()=>{ft(),Os(),yt(),Pv(),gi=class N0{constructor(r,t,s,o){this.module=r,this.dataType=t,this.data=s,this.dims=o}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=Me.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=Me.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=Me.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=Me.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(Me.size(r)!==Me.size(this.dims))throw new Error("Invalid new shape");return new N0(this.module,this.dataType,this.data,r)}},Eg=class{constructor(e,r,t){this.module=e,this.backend=r,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=r.adapterInfo;let s=e.PTR_SIZE,o=t/e.PTR_SIZE,n=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*o++,n));let i=Number(e.getValue(s*o++,n));this.outputCount=Number(e.getValue(s*o++,n)),this.customDataOffset=Number(e.getValue(s*o++,"*")),this.customDataSize=Number(e.getValue(s*o++,n));let a=[];for(let l=0;ltypeof a=="number"?this.inputs[a]:a))??this.inputs,s=(r==null?void 0:r.outputs)??[],o=(a,l,u)=>new gi(this.module,l,this.output(a,u),u),n=(a,l)=>{let u=nn(a,l);if(!u)throw new Error(`Unsupported data type: ${a}`);let p=u>0?this.backend.gpuDataManager.create(u).id:0;return new gi(this.module,a,p,l)};return this.backend.run(e,t,s,o,n,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,o=s===4?"i32":"i64",n=this.module.stackAlloc((1+r.length)*s);this.module.setValue(n,r.length,o);for(let i=0;i{let o=r.jsepInit;if(!o)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let n=(gx(),io(Mg)).WebGpuBackend,i=new n;await i.initialize(t,s),o("webgpu",[i,a=>i.alloc(Number(a)),a=>i.free(a),(a,l,u,p=!1)=>{if(p)kt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(a)}, dst=${Number(l)}, size=${Number(u)}`),i.memcpy(Number(a),Number(l));else{kt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(a)}, gpuDataId=${Number(l)}, size=${Number(u)}`);let c=r.HEAPU8.subarray(Number(a>>>0),Number(a>>>0)+Number(u));i.upload(Number(l),c)}},async(a,l,u)=>{kt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${a}, dataOffset=${l}, size=${u}`),await i.download(Number(a),()=>r.HEAPU8.subarray(Number(l)>>>0,Number(l+u)>>>0))},(a,l,u)=>i.createKernel(a,Number(l),u,r.UTF8ToString(r._JsepGetNodeName(Number(l)))),a=>i.releaseKernel(a),(a,l,u,p)=>{kt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${u}, kernel=${a}, contextDataOffset=${l}`);let c=new Eg(r,i,Number(l));return i.computeKernel(Number(a),c,p)},()=>i.captureBegin(),()=>i.captureEnd(),()=>i.replay()])}else{let n=new Id(t);o("webnn",[n,()=>n.reserveTensorId(),i=>n.releaseTensorId(i),async(i,a,l,u,p)=>n.ensureTensor(i,a,l,u,p),(i,a)=>{n.uploadTensor(i,a)},async(i,a)=>n.downloadTensor(i,a)])}}}),Cg,Yl,Zl,Ws,Sg,eu,wi,tu,ru,su,nu,ou,iu,$g=ze(()=>{xv(),Tv(),ft(),sn(),ja(),fd(),Cg=(e,r)=>{qt()._OrtInit(e,r)!==0&&Wt("Can't initialize onnxruntime.")},Yl=async e=>{Cg(e.wasm.numThreads,si(e.logLevel))},Zl=async(e,r)=>{var t,s;(s=(t=qt()).asyncInit)==null||s.call(t);{let o=(wx(),io(Tg)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let n=e.webgpu.adapter;if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let a=e.webgpu.forceFallbackAdapter;if(a!==void 0&&typeof a!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${a}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:a}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await o("webgpu",qt(),e,n)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await o("webnn",qt(),e)}}},Ws=new Map,Sg=e=>{let r=qt(),t=r.stackSave();try{let s=r.PTR_SIZE,o=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,o,o+s)!==0&&Wt("Can't get session input/output count.");let n=s===4?"i32":"i64";return[Number(r.getValue(o,n)),Number(r.getValue(o+s,n))]}finally{r.stackRestore(t)}},eu=(e,r)=>{let t=qt(),s=t.stackSave(),o=0;try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputMetadata(e,r,i,i+n)!==0&&Wt("Can't get session input/output metadata.");let a=Number(t.getValue(i,"*"));o=Number(t.getValue(i+n,"*"));let l=t.HEAP32[o/4];if(l===0)return[a,0];let u=t.HEAPU32[o/4+1],p=[];for(let c=0;c{let r=qt(),t=r._malloc(e.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return r.HEAPU8.set(e,t),[t,e.byteLength]},tu=async(e,r)=>{var c,d,_,f;let t,s,o=qt();Array.isArray(e)?[t,s]=e:e.buffer===o.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=wi(e);let n=0,i=0,a=0,l=[],u=[],p=[];try{if([i,l]=await md(r),(r==null?void 0:r.externalData)&&o.mountExternalData){let C=[];for(let A of r.externalData){let z=typeof A=="string"?A:A.path;C.push(Ga(typeof A=="string"?A:A.data).then(K=>{o.mountExternalData(z,K)}))}await Promise.all(C)}for(let C of(r==null?void 0:r.executionProviders)??[])if((typeof C=="string"?C:C.name)==="webnn"){if(o.shouldTransferToMLTensor=!1,typeof C!="string"){let A=C,z=A==null?void 0:A.context,K=A==null?void 0:A.gpuDevice,G=A==null?void 0:A.deviceType,j=A==null?void 0:A.powerPreference;z?o.currentContext=z:K?o.currentContext=await o.webnnCreateMLContext(K):o.currentContext=await o.webnnCreateMLContext({deviceType:G,powerPreference:j})}else o.currentContext=await o.webnnCreateMLContext();break}n=await o._OrtCreateSession(t,s,i),(c=o.webgpuOnCreateSession)==null||c.call(o,n),n===0&&Wt("Can't create a session."),(d=o.jsepOnCreateSession)==null||d.call(o),o.currentContext&&(o.webnnRegisterMLContext(n,o.currentContext),o.currentContext=void 0,o.shouldTransferToMLTensor=!0);let[T,k]=Sg(n),w=!!(r!=null&&r.enableGraphCapture),g=[],S=[],E=[],y=[],M=[];for(let C=0;CC==="gpu-buffer"||C==="ml-tensor")&&(a=o._OrtCreateBinding(n),a===0&&Wt("Can't create IO binding."),v={handle:a,outputPreferredLocations:M,outputPreferredLocationsEncoded:M.map(C=>Wa(C))}),Ws.set(n,[n,u,p,v,w,!1]),[n,g,S,E,y]}catch(T){throw u.forEach(k=>o._OrtFree(k)),p.forEach(k=>o._OrtFree(k)),a!==0&&o._OrtReleaseBinding(a)!==0&&Wt("Can't release IO binding."),n!==0&&o._OrtReleaseSession(n)!==0&&Wt("Can't release session."),T}finally{o._free(t),i!==0&&o._OrtReleaseSessionOptions(i)!==0&&Wt("Can't release session options."),l.forEach(T=>o._free(T)),(f=o.unmountExternalData)==null||f.call(o)}},ru=e=>{var l,u,p;let r=qt(),t=Ws.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,o,n,i,a]=t;i&&(a&&r._OrtClearBoundOutputs(i.handle)!==0&&Wt("Can't clear bound outputs."),r._OrtReleaseBinding(i.handle)!==0&&Wt("Can't release IO binding.")),(l=r.jsepOnReleaseSession)==null||l.call(r,e),(u=r.webnnOnReleaseSession)==null||u.call(r,e),(p=r.webgpuOnReleaseSession)==null||p.call(r,e),o.forEach(c=>r._OrtFree(c)),n.forEach(c=>r._OrtFree(c)),r._OrtReleaseSession(s)!==0&&Wt("Can't release session."),Ws.delete(e)},su=async(e,r,t,s,o,n,i=!1)=>{if(!e){r.push(0);return}let a=qt(),l=a.PTR_SIZE,u=e[0],p=e[1],c=e[3],d=c,_,f;if(u==="string"&&(c==="gpu-buffer"||c==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(i&&c!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${n} when enableGraphCapture is true.`);if(c==="gpu-buffer"){let w=e[2].gpuBuffer;f=nn(jn(u),p);{let g=a.jsepRegisterBuffer;if(!g)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');_=g(s,n,w,f)}}else if(c==="ml-tensor"){let w=e[2].mlTensor;f=nn(jn(u),p);let g=a.webnnRegisterMLTensor;if(!g)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');_=g(s,w,jn(u),p)}else{let w=e[2];if(Array.isArray(w)){f=l*w.length,_=a._malloc(f),t.push(_);for(let g=0;ga.setValue(k+S*l,g,l===4?"i32":"i64"));let w=a._OrtCreateTensor(jn(u),_,f,k,p.length,Wa(d));w===0&&Wt(`Can't create tensor for input/output. session=${s}, index=${n}.`),r.push(w)}finally{a.stackRestore(T)}},nu=async(e,r,t,s,o,n)=>{var K,G,j,Y;let i=qt(),a=i.PTR_SIZE,l=Ws.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=l[0],p=l[1],c=l[2],d=l[3],_=l[4],f=l[5],T=r.length,k=s.length,w=0,g=[],S=[],E=[],y=[],M=i.stackSave(),v=i.stackAlloc(T*a),C=i.stackAlloc(T*a),A=i.stackAlloc(k*a),z=i.stackAlloc(k*a);try{[w,g]=ud(n);for(let Q=0;Qq*R,1);F=Fs(me);let we=d==null?void 0:d.outputPreferredLocations[s[Q]];if(F==="string"){if(we==="gpu-buffer"||we==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let q=[];for(let R=0;R0){let q=i.jsepGetBuffer;if(!q)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let R=q(W),de=nn(me,Ne);if(de===void 0||!Va(F))throw new Error(`Unsupported data type: ${F}`);V=!0,J.push([F,Pe,{gpuBuffer:R,download:i.jsepCreateDownloader(R,de,F),dispose:()=>{i._OrtReleaseTensor(oe)!==0&&Wt("Can't release tensor.")}},"gpu-buffer"])}else if(we==="ml-tensor"&&Ne>0){let q=i.webnnEnsureTensor,R=i.webnnIsInt64Supported;if(!q||!R)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(nn(me,Ne)===void 0||!Ua(F))throw new Error(`Unsupported data type: ${F}`);if(F==="int64"&&!R(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let de=await q(e,W,me,Pe,!1);V=!0,J.push([F,Pe,{mlTensor:de,download:i.webnnCreateMLTensorDownloader(W,F),dispose:()=>{i.webnnReleaseTensorId(W),i._OrtReleaseTensor(oe)}},"ml-tensor"])}else{let q=Na(F),R=new q(Ne);new Uint8Array(R.buffer,R.byteOffset,R.byteLength).set(i.HEAPU8.subarray(W,W+R.byteLength)),J.push([F,Pe,R,"cpu"])}}finally{i.stackRestore(he),F==="string"&&W&&i._free(W),V||i._OrtReleaseTensor(oe),(Y=i.webnnOnRunEnd)==null||Y.call(i,u)}}return d&&!_&&(i._OrtClearBoundOutputs(d.handle)!==0&&Wt("Can't clear bound outputs."),Ws.set(e,[u,p,c,d,_,!1])),J}finally{i.stackRestore(M),S.forEach(H=>i._OrtReleaseTensor(H)),E.forEach(H=>i._OrtReleaseTensor(H)),y.forEach(H=>i._free(H)),w!==0&&i._OrtReleaseRunOptions(w),g.forEach(H=>i._free(H))}},ou=e=>{let r=qt(),t=Ws.get(e);if(!t)throw new Error("invalid session id");let s=t[0],o=r._OrtEndProfiling(s);o===0&&Wt("Can't get an profile file name."),r._OrtFree(o)},iu=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),Gs,Vr,Wn,vo,xo,Mi,au,bi,pn,hn,kg,Ig,Ag,Fg,Og,Dg,Lg,zg,Bg=ze(()=>{ds(),$g(),sn(),La(),Gs=()=>!!Xt.wasm.proxy&&typeof document<"u",Wn=!1,vo=!1,xo=!1,bi=new Map,pn=(e,r)=>{let t=bi.get(e);t?t.push(r):bi.set(e,[r])},hn=()=>{if(Wn||!vo||xo||!Vr)throw new Error("worker not ready")},kg=e=>{switch(e.data.type){case"init-wasm":Wn=!1,e.data.err?(xo=!0,au[1](e.data.err)):(vo=!0,au[0]()),Mi&&(URL.revokeObjectURL(Mi),Mi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=bi.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},Ig=async()=>{if(!vo){if(Wn)throw new Error("multiple calls to 'initWasm()' detected.");if(xo)throw new Error("previous call to 'initWasm()' failed.");if(Wn=!0,Gs())return new Promise((e,r)=>{Vr==null||Vr.terminate(),nd().then(([t,s])=>{try{Vr=s,Vr.onerror=n=>r(n),Vr.onmessage=kg,au=[e,r];let o={type:"init-wasm",in:Xt};!o.in.wasm.wasmPaths&&(t||Aa)&&(o.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm",self.location.href).href}),Vr.postMessage(o),Mi=t}catch(o){r(o)}},r)});try{await Ra(Xt.wasm),await Yl(Xt),vo=!0}catch(e){throw xo=!0,e}finally{Wn=!1}}},Ag=async e=>{if(Gs())return hn(),new Promise((r,t)=>{pn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Xt}};Vr.postMessage(s)});await Zl(Xt,e)},Fg=async e=>Gs()?(hn(),new Promise((r,t)=>{pn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};Vr.postMessage(s,[e.buffer])})):wi(e),Og=async(e,r)=>{if(Gs()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return hn(),new Promise((t,s)=>{pn("create",[t,s]);let o={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),Vr.postMessage(o,n)})}else return tu(e,r)},Dg=async e=>{if(Gs())return hn(),new Promise((r,t)=>{pn("release",[r,t]);let s={type:"release",in:e};Vr.postMessage(s)});ru(e)},Lg=async(e,r,t,s,o,n)=>{if(Gs()){if(t.some(i=>i[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(o.some(i=>i))throw new Error("pre-allocated output tensor is not supported for proxy.");return hn(),new Promise((i,a)=>{pn("run",[i,a]);let l=t,u={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};Vr.postMessage(u,iu(l))})}else return nu(e,r,t,s,o,n)},zg=async e=>{if(Gs())return hn(),new Promise((r,t)=>{pn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};Vr.postMessage(s)});ou(e)}}),lu,Rg,jg,Mx=ze(()=>{ds(),Bg(),ft(),Pa(),fd(),lu=(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()}`)}},Rg=e=>{switch(e[3]){case"cpu":return new us(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!Va(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:o}=e[2];return us.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:o})}case"ml-tensor":{let r=e[0];if(!Ua(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:o}=e[2];return us.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:o})}default:throw new Error(`invalid data location: ${e[3]}`)}},jg=class{async fetchModelAndCopyToWasmMemory(e){return Fg(await Ga(e))}async loadModel(e,r){cs();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Og(t,r),es()}async dispose(){return Dg(this.sessionId)}async run(e,r,t){cs();let s=[],o=[];Object.entries(e).forEach(c=>{let d=c[0],_=c[1],f=this.inputNames.indexOf(d);if(f===-1)throw new Error(`invalid input '${d}'`);s.push(_),o.push(f)});let n=[],i=[];Object.entries(r).forEach(c=>{let d=c[0],_=c[1],f=this.outputNames.indexOf(d);if(f===-1)throw new Error(`invalid output '${d}'`);n.push(_),i.push(f)});let a=s.map((c,d)=>lu(c,()=>`input "${this.inputNames[o[d]]}"`)),l=n.map((c,d)=>c?lu(c,()=>`output "${this.outputNames[i[d]]}"`):null),u=await Lg(this.sessionId,o,a,i,l,t),p={};for(let c=0;ccu,initializeFlags:()=>uu,wasmBackend:()=>Vg});var uu,cu,Vg,bx=ze(()=>{ds(),Bg(),Mx(),uu=()=>{(typeof Xt.wasm.initTimeout!="number"||Xt.wasm.initTimeout<0)&&(Xt.wasm.initTimeout=0);let e=Xt.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),Xt.wasm.simd=!1),typeof Xt.wasm.proxy!="boolean"&&(Xt.wasm.proxy=!1),typeof Xt.wasm.trace!="boolean"&&(Xt.wasm.trace=!1),typeof Xt.wasm.numThreads!="number"||!Number.isInteger(Xt.wasm.numThreads)||Xt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Xt.wasm.numThreads=1;else{let r=typeof navigator>"u"?iv("node:os").cpus().length:navigator.hardwareConcurrency;Xt.wasm.numThreads=Math.min(4,Math.ceil((r||1)/2))}},cu=class{async init(e){uu(),await Ig(),await Ag(e)}async createInferenceSessionHandler(e,r){let t=new jg;return await t.loadModel(e,r),t}},Vg=new cu});ds(),ds(),ds();var yx="1.22.0-dev.20250409-89f8206ba4",vx=Hc;{let e=(bx(),io(Ng)).wasmBackend;tn("webgpu",e,5),tn("webnn",e,5),tn("cpu",e,10),tn("wasm",e,10)}Object.defineProperty(Xt.versions,"web",{value:yx,enumerable:!0});/** +* @license +* Copyright 2021 Google LLC. All Rights Reserved. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============================================================================= +*//** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var xx=Object.freeze({__proto__:null,get InferenceSession(){return Ea},get TRACE(){return uo},get TRACE_FUNC_BEGIN(){return cs},get TRACE_FUNC_END(){return es},get Tensor(){return us},default:vx,get env(){return Xt},get registerBackend(){return tn}}),Ls={},Tx={"onnxruntime-common":e=>{e.exports=rv},"onnxruntime-web":e=>{e.exports=xx},"?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:()=>Se,Template:()=>jt,parse:()=>V,tokenize:()=>c});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndSet:"EndSet",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),o=Object.freeze({set:s.Set,for:s.For,in:s.In,is:s.Is,if:s.If,else:s.Else,endset:s.EndSet,endif:s.EndIf,elif:s.ElseIf,endfor:s.EndFor,and:s.And,or:s.Or,not:s.Not,"not in":s.NotIn,macro:s.Macro,endmacro:s.EndMacro,true:s.BooleanLiteral,false:s.BooleanLiteral,none:s.NullLiteral,True:s.BooleanLiteral,False:s.BooleanLiteral,None:s.NullLiteral}),n=class{constructor(O,se){this.value=O,this.type=se}};function i(O){return/\w/.test(O)}function a(O){return/[0-9]/.test(O)}var l=[["{%",s.OpenStatement],["%}",s.CloseStatement],["{{",s.OpenExpression],["}}",s.CloseExpression],["(",s.OpenParen],[")",s.CloseParen],["{",s.OpenCurlyBracket],["}",s.CloseCurlyBracket],["[",s.OpenSquareBracket],["]",s.CloseSquareBracket],[",",s.Comma],[".",s.Dot],[":",s.Colon],["|",s.Pipe],["<=",s.ComparisonBinaryOperator],[">=",s.ComparisonBinaryOperator],["==",s.ComparisonBinaryOperator],["!=",s.ComparisonBinaryOperator],["<",s.ComparisonBinaryOperator],[">",s.ComparisonBinaryOperator],["+",s.AdditiveBinaryOperator],["-",s.AdditiveBinaryOperator],["*",s.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],u=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function p(O,se={}){return O.endsWith(` +`)&&(O=O.slice(0,-1)),O=O.replace(/{#.*?#}/gs,"{##}"),se.lstrip_blocks&&(O=O.replace(/^[ \t]*({[#%])/gm,"$1")),se.trim_blocks&&(O=O.replace(/([#%]})\n/g,"$1")),O.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function c(O,se={}){var Ve,Tt,Nt;const B=[],re=p(O,se);let fe=0;const Ae=mt=>{let Ge="";for(;mt(re[fe]);){if(re[fe]==="\\"){if(++fe,fe>=re.length)throw new SyntaxError("Unexpected end of input");const ct=re[fe++],It=u.get(ct);if(It===void 0)throw new SyntaxError(`Unexpected escaped character: ${ct}`);Ge+=It;continue}if(Ge+=re[fe++],fe>=re.length)throw new SyntaxError("Unexpected end of input")}return Ge};e:for(;fe0){B.push(new n(ct,s.Text));continue}}Ae(ct=>/\s/.test(ct));const Ge=re[fe];if(Ge==="-"||Ge==="+"){const ct=(Tt=B.at(-1))==null?void 0:Tt.type;if(ct===s.Text||ct===void 0)throw new SyntaxError(`Unexpected character: ${Ge}`);switch(ct){case s.Identifier:case s.NumericLiteral:case s.BooleanLiteral:case s.NullLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++fe;const It=Ae(a);B.push(new n(`${Ge}${It}`,It.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[ct,It]of l)if(re.slice(fe,fe+ct.length)===ct){B.push(new n(ct,It)),fe+=ct.length;continue e}if(Ge==="'"||Ge==='"'){++fe;const ct=Ae(It=>It!==Ge);B.push(new n(ct,s.StringLiteral)),++fe;continue}if(a(Ge)){const ct=Ae(a);B.push(new n(ct,s.NumericLiteral));continue}if(i(Ge)){const ct=Ae(i),It=Object.hasOwn(o,ct)?o[ct]:s.Identifier;It===s.In&&((Nt=B.at(-1))==null?void 0:Nt.type)===s.Not?(B.pop(),B.push(new n("not in",s.NotIn))):B.push(new n(ct,It));continue}throw new SyntaxError(`Unexpected character: ${Ge}`)}return B}var d=class{constructor(){Z(this,"type","Statement")}},_=class extends d{constructor(se){super();Z(this,"type","Program");this.body=se}},f=class extends d{constructor(se,B,re){super();Z(this,"type","If");this.test=se,this.body=B,this.alternate=re}},T=class extends d{constructor(se,B,re,fe){super();Z(this,"type","For");this.loopvar=se,this.iterable=B,this.body=re,this.defaultBlock=fe}},k=class extends d{constructor(se,B,re){super();Z(this,"type","Set");this.assignee=se,this.value=B,this.body=re}},w=class extends d{constructor(se,B,re){super();Z(this,"type","Macro");this.name=se,this.args=B,this.body=re}},g=class extends d{constructor(){super(...arguments);Z(this,"type","Expression")}},S=class extends g{constructor(se,B,re){super();Z(this,"type","MemberExpression");this.object=se,this.property=B,this.computed=re}},E=class extends g{constructor(se,B){super();Z(this,"type","CallExpression");this.callee=se,this.args=B}},y=class extends g{constructor(se){super();Z(this,"type","Identifier");this.value=se}},M=class extends g{constructor(se){super();Z(this,"type","Literal");this.value=se}},v=class extends M{constructor(){super(...arguments);Z(this,"type","NumericLiteral")}},C=class extends M{constructor(){super(...arguments);Z(this,"type","StringLiteral")}},A=class extends M{constructor(){super(...arguments);Z(this,"type","BooleanLiteral")}},z=class extends M{constructor(){super(...arguments);Z(this,"type","NullLiteral")}},K=class extends M{constructor(){super(...arguments);Z(this,"type","ArrayLiteral")}},G=class extends M{constructor(){super(...arguments);Z(this,"type","TupleLiteral")}},j=class extends M{constructor(){super(...arguments);Z(this,"type","ObjectLiteral")}},Y=class extends g{constructor(se,B,re){super();Z(this,"type","BinaryExpression");this.operator=se,this.left=B,this.right=re}},H=class extends g{constructor(se,B){super();Z(this,"type","FilterExpression");this.operand=se,this.filter=B}},J=class extends g{constructor(se,B){super();Z(this,"type","SelectExpression");this.iterable=se,this.test=B}},Q=class extends g{constructor(se,B,re){super();Z(this,"type","TestExpression");this.operand=se,this.negate=B,this.test=re}},oe=class extends g{constructor(se,B){super();Z(this,"type","UnaryExpression");this.operator=se,this.argument=B}},he=class extends g{constructor(se=void 0,B=void 0,re=void 0){super();Z(this,"type","SliceExpression");this.start=se,this.stop=B,this.step=re}},ae=class extends g{constructor(se,B){super();Z(this,"type","KeywordArgumentExpression");this.key=se,this.value=B}};function V(O){const se=new _([]);let B=0;function re(De,qe){const nt=O[B++];if(!nt||nt.type!==De)throw new Error(`Parser Error: ${qe}. ${nt.type} !== ${De}.`);return nt}function fe(){switch(O[B].type){case s.Text:return Tt();case s.OpenStatement:return Nt();case s.OpenExpression:return mt();default:throw new SyntaxError(`Unexpected token type: ${O[B].type}`)}}function Ae(...De){return B+De.length<=O.length&&De.some((qe,nt)=>qe!==O[B+nt].type)}function Ve(...De){return B+De.length<=O.length&&De.every((qe,nt)=>qe===O[B+nt].type)}function Tt(){return new C(re(s.Text,"Expected text token").value)}function Nt(){re(s.OpenStatement,"Expected opening statement token");let De;switch(O[B].type){case s.Set:++B,De=Ge(),re(s.CloseStatement,"Expected closing statement token");break;case s.If:++B,De=ct(),re(s.OpenStatement,"Expected {% token"),re(s.EndIf,"Expected endif token"),re(s.CloseStatement,"Expected %} token");break;case s.Macro:++B,De=It(),re(s.OpenStatement,"Expected {% token"),re(s.EndMacro,"Expected endmacro token"),re(s.CloseStatement,"Expected %} token");break;case s.For:++B,De=Ot(),re(s.OpenStatement,"Expected {% token"),re(s.EndFor,"Expected endfor token"),re(s.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${O[B].type}`)}return De}function mt(){re(s.OpenExpression,"Expected opening expression token");const De=ir();return re(s.CloseExpression,"Expected closing expression token"),De}function Ge(){var qe,nt;const De=ir();if(Ve(s.Equals)){++B;const Qt=ir();return new k(De,Qt,[])}else{const Qt=[];for(re(s.CloseStatement,"Expected %} token");!(((qe=O[B])==null?void 0:qe.type)===s.OpenStatement&&((nt=O[B+1])==null?void 0:nt.type)===s.EndSet);){const lr=fe();Qt.push(lr)}return re(s.OpenStatement,"Expected {% token"),re(s.EndSet,"Expected endset token"),new k(De,null,Qt)}}function ct(){var Qt,lr,ys,$s,Fr,ks,jr,vr;const De=ir();re(s.CloseStatement,"Expected closing statement token");const qe=[],nt=[];for(;!(((Qt=O[B])==null?void 0:Qt.type)===s.OpenStatement&&(((lr=O[B+1])==null?void 0:lr.type)===s.ElseIf||((ys=O[B+1])==null?void 0:ys.type)===s.Else||(($s=O[B+1])==null?void 0:$s.type)===s.EndIf));)qe.push(fe());if(((Fr=O[B])==null?void 0:Fr.type)===s.OpenStatement&&((ks=O[B+1])==null?void 0:ks.type)!==s.EndIf)if(++B,Ve(s.ElseIf))re(s.ElseIf,"Expected elseif token"),nt.push(ct());else for(re(s.Else,"Expected else token"),re(s.CloseStatement,"Expected closing statement token");!(((jr=O[B])==null?void 0:jr.type)===s.OpenStatement&&((vr=O[B+1])==null?void 0:vr.type)===s.EndIf);)nt.push(fe());return new f(De,qe,nt)}function It(){const De=ar();if(De.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const qe=Rr();re(s.CloseStatement,"Expected closing statement token");const nt=[];for(;Ae(s.OpenStatement,s.EndMacro);)nt.push(fe());return new w(De,qe,nt)}function Gt(De=!1){const qe=De?ar:ir,nt=[qe()],Qt=Ve(s.Comma);for(;Qt&&(++B,nt.push(qe()),!!Ve(s.Comma)););return Qt?new G(nt):nt[0]}function Ot(){const De=Gt(!0);if(!(De instanceof y||De instanceof G))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${De.type} instead`);re(s.In,"Expected `in` keyword following loop variable");const qe=ir();re(s.CloseStatement,"Expected closing statement token");const nt=[];for(;Ae(s.OpenStatement,s.EndFor)&&Ae(s.OpenStatement,s.Else);)nt.push(fe());const Qt=[];if(Ve(s.OpenStatement,s.Else))for(++B,++B,re(s.CloseStatement,"Expected closing statement token");Ae(s.OpenStatement,s.EndFor);)Qt.push(fe());return new T(De,qe,nt,Qt)}function ir(){return Ar()}function Ar(){const De=ts();if(Ve(s.If)){++B;const qe=ts();if(Ve(s.Else)){++B;const nt=ts();return new f(qe,[De],[nt])}else return new J(De,qe)}return De}function ts(){let De=yr();for(;Ve(s.Or);){const qe=O[B];++B;const nt=yr();De=new Y(qe,De,nt)}return De}function yr(){let De=rs();for(;Ve(s.And);){const qe=O[B];++B;const nt=rs();De=new Y(qe,De,nt)}return De}function rs(){let De;for(;Ve(s.Not);){const qe=O[B];++B;const nt=rs();De=new oe(qe,nt)}return De??Es()}function Es(){let De=ws();for(;Ve(s.ComparisonBinaryOperator)||Ve(s.In)||Ve(s.NotIn);){const qe=O[B];++B;const nt=ws();De=new Y(qe,De,nt)}return De}function ws(){let De=Ms();for(;Ve(s.AdditiveBinaryOperator);){const qe=O[B];++B;const nt=Ms();De=new Y(qe,De,nt)}return De}function Ps(){const De=ns(ar());return Ve(s.OpenParen)?ss(De):De}function ss(De){let qe=new E(De,Rr());return qe=ns(qe),Ve(s.OpenParen)&&(qe=ss(qe)),qe}function Rr(){re(s.OpenParen,"Expected opening parenthesis for arguments list");const De=Cs();return re(s.CloseParen,"Expected closing parenthesis for arguments list"),De}function Cs(){const De=[];for(;!Ve(s.CloseParen);){let qe=ir();if(Ve(s.Equals)){if(++B,!(qe instanceof y))throw new SyntaxError("Expected identifier for keyword argument");const nt=ir();qe=new ae(qe,nt)}De.push(qe),Ve(s.Comma)&&++B}return De}function Ss(){const De=[];let qe=!1;for(;!Ve(s.CloseSquareBracket);)Ve(s.Colon)?(De.push(void 0),++B,qe=!0):(De.push(ir()),Ve(s.Colon)&&(++B,qe=!0));if(De.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(qe){if(De.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new he(...De)}return De[0]}function ns(De){for(;Ve(s.Dot)||Ve(s.OpenSquareBracket);){const qe=O[B];++B;let nt;const Qt=qe.type!==s.Dot;if(Qt)nt=Ss(),re(s.CloseSquareBracket,"Expected closing square bracket");else if(nt=ar(),nt.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");De=new S(De,nt,Qt)}return De}function Ms(){let De=bs();for(;Ve(s.MultiplicativeBinaryOperator);){const qe=O[B];++B;const nt=bs();De=new Y(qe,De,nt)}return De}function bs(){let De=Ur();for(;Ve(s.Is);){++B;const qe=Ve(s.Not);qe&&++B;let nt=ar();if(nt instanceof A?nt=new y(nt.value.toString()):nt instanceof z&&(nt=new y("none")),!(nt instanceof y))throw new SyntaxError("Expected identifier for the test");De=new Q(De,qe,nt)}return De}function Ur(){let De=Ps();for(;Ve(s.Pipe);){++B;let qe=ar();if(!(qe instanceof y))throw new SyntaxError("Expected identifier for the filter");Ve(s.OpenParen)&&(qe=ss(qe)),De=new H(De,qe)}return De}function ar(){const De=O[B];switch(De.type){case s.NumericLiteral:return++B,new v(Number(De.value));case s.StringLiteral:return++B,new C(De.value);case s.BooleanLiteral:return++B,new A(De.value.toLowerCase()==="true");case s.NullLiteral:return++B,new z(null);case s.Identifier:return++B,new y(De.value);case s.OpenParen:{++B;const qe=Gt();if(O[B].type!==s.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${O[B].type} instead`);return++B,qe}case s.OpenSquareBracket:{++B;const qe=[];for(;!Ve(s.CloseSquareBracket);)qe.push(ir()),Ve(s.Comma)&&++B;return++B,new K(qe)}case s.OpenCurlyBracket:{++B;const qe=new Map;for(;!Ve(s.CloseCurlyBracket);){const nt=ir();re(s.Colon,"Expected colon between key and value in object literal");const Qt=ir();qe.set(nt,Qt),Ve(s.Comma)&&++B}return++B,new j(qe)}default:throw new SyntaxError(`Unexpected token: ${De.type}`)}}for(;B=0?(se=(se??(se=0))<0?Math.max(O.length+se,0):Math.min(se,O.length),B=(B??(B=O.length))<0?Math.max(O.length+B,0):Math.min(B,O.length)):(se=(se??(se=O.length-1))<0?Math.max(O.length+se,-1):Math.min(se,O.length-1),B=(B??(B=-1))<-1?Math.max(O.length+B,-1):Math.min(B,O.length-1));const Ae=[];for(let Ve=se;fe*Vese.toUpperCase())}var me=class{constructor(O=void 0){Z(this,"type","RuntimeValue");Z(this,"value");Z(this,"builtins",new Map);this.value=O}__bool__(){return new Pe(!!this.value)}},te=class extends me{constructor(){super(...arguments);Z(this,"type","NumericValue")}},ue=class extends me{constructor(){super(...arguments);Z(this,"type","StringValue");Z(this,"builtins",new Map([["upper",new de(()=>new ue(this.value.toUpperCase()))],["lower",new de(()=>new ue(this.value.toLowerCase()))],["strip",new de(()=>new ue(this.value.trim()))],["title",new de(()=>new ue(ee(this.value)))],["length",new te(this.value.length)],["rstrip",new de(()=>new ue(this.value.trimEnd()))],["lstrip",new de(()=>new ue(this.value.trimStart()))],["startswith",new de(se=>{if(se.length===0)throw new Error("startswith() requires at least one argument");const B=se[0];if(!(B instanceof ue))throw new Error("startswith() argument must be a string");return new Pe(this.value.startsWith(B.value))})],["endswith",new de(se=>{if(se.length===0)throw new Error("endswith() requires at least one argument");const B=se[0];if(!(B instanceof ue))throw new Error("endswith() argument must be a string");return new Pe(this.value.endsWith(B.value))})],["split",new de(se=>{const B=se[0]??new ve;if(!(B instanceof ue||B instanceof ve))throw new Error("sep argument must be a string or null");const re=se[1]??new te(-1);if(!(re instanceof te))throw new Error("maxsplit argument must be a number");let fe=[];if(B instanceof ve){const Ae=this.value.trimStart();for(const{0:Ve,index:Tt}of Ae.matchAll(/\S+/g)){if(re.value!==-1&&fe.length>=re.value&&Tt!==void 0){fe.push(Ve+Ae.slice(Tt+Ve.length));break}fe.push(Ve)}}else{if(B.value==="")throw new Error("empty separator");fe=this.value.split(B.value),re.value!==-1&&fe.length>re.value&&fe.push(fe.splice(re.value).join(B.value))}return new q(fe.map(Ae=>new ue(Ae)))})]]))}},Pe=class extends me{constructor(){super(...arguments);Z(this,"type","BooleanValue")}},Ne=class extends me{constructor(){super(...arguments);Z(this,"type","ObjectValue");Z(this,"builtins",new Map([["get",new de(([se,B])=>{if(!(se instanceof ue))throw new Error(`Object key must be a string: got ${se.type}`);return this.value.get(se.value)??B??new ve})],["items",new de(()=>new q(Array.from(this.value.entries()).map(([se,B])=>new q([new ue(se),B]))))]]))}__bool__(){return new Pe(this.value.size>0)}},we=class extends Ne{constructor(){super(...arguments);Z(this,"type","KeywordArgumentsValue")}},q=class extends me{constructor(){super(...arguments);Z(this,"type","ArrayValue");Z(this,"builtins",new Map([["length",new te(this.value.length)]]))}__bool__(){return new Pe(this.value.length>0)}},R=class extends q{constructor(){super(...arguments);Z(this,"type","TupleValue")}},de=class extends me{constructor(){super(...arguments);Z(this,"type","FunctionValue")}},ve=class extends me{constructor(){super(...arguments);Z(this,"type","NullValue")}},be=class extends me{constructor(){super(...arguments);Z(this,"type","UndefinedValue")}},Ce=class{constructor(O){Z(this,"variables",new Map([["namespace",new de(O=>{if(O.length===0)return new Ne(new Map);if(O.length!==1||!(O[0]instanceof Ne))throw new Error("`namespace` expects either zero arguments or a single object argument");return O[0]})]]));Z(this,"tests",new Map([["boolean",O=>O.type==="BooleanValue"],["callable",O=>O instanceof de],["odd",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${O.type}`);return O.value%2!==0}],["even",O=>{if(O.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${O.type}`);return O.value%2===0}],["false",O=>O.type==="BooleanValue"&&!O.value],["true",O=>O.type==="BooleanValue"&&O.value],["none",O=>O.type==="NullValue"],["string",O=>O.type==="StringValue"],["number",O=>O.type==="NumericValue"],["integer",O=>O.type==="NumericValue"&&Number.isInteger(O.value)],["iterable",O=>O.type==="ArrayValue"||O.type==="StringValue"],["mapping",O=>O.type==="ObjectValue"],["lower",O=>{const se=O.value;return O.type==="StringValue"&&se===se.toLowerCase()}],["upper",O=>{const se=O.value;return O.type==="StringValue"&&se===se.toUpperCase()}],["none",O=>O.type==="NullValue"],["defined",O=>O.type!=="UndefinedValue"],["undefined",O=>O.type==="UndefinedValue"],["equalto",(O,se)=>O.value===se.value],["eq",(O,se)=>O.value===se.value]]));this.parent=O}set(O,se){return this.declareVariable(O,$e(se))}declareVariable(O,se){if(this.variables.has(O))throw new SyntaxError(`Variable already declared: ${O}`);return this.variables.set(O,se),se}setVariable(O,se){return this.variables.set(O,se),se}resolve(O){if(this.variables.has(O))return this;if(this.parent)return this.parent.resolve(O);throw new Error(`Unknown variable: ${O}`)}lookupVariable(O){try{return this.resolve(O).variables.get(O)??new be}catch{return new be}}},Se=class{constructor(O){Z(this,"global");this.global=O??new Ce}run(O){return this.evaluate(O,this.global)}evaluateBinaryExpression(O,se){const B=this.evaluate(O.left,se);switch(O.operator.value){case"and":return B.__bool__().value?this.evaluate(O.right,se):B;case"or":return B.__bool__().value?B:this.evaluate(O.right,se)}const re=this.evaluate(O.right,se);switch(O.operator.value){case"==":return new Pe(B.value==re.value);case"!=":return new Pe(B.value!=re.value)}if(B instanceof be||re instanceof be)throw new Error("Cannot perform operation on undefined values");if(B instanceof ve||re instanceof ve)throw new Error("Cannot perform operation on null values");if(B instanceof te&&re instanceof te)switch(O.operator.value){case"+":return new te(B.value+re.value);case"-":return new te(B.value-re.value);case"*":return new te(B.value*re.value);case"/":return new te(B.value/re.value);case"%":return new te(B.value%re.value);case"<":return new Pe(B.value":return new Pe(B.value>re.value);case">=":return new Pe(B.value>=re.value);case"<=":return new Pe(B.value<=re.value)}else if(B instanceof q&&re instanceof q)switch(O.operator.value){case"+":return new q(B.value.concat(re.value))}else if(re instanceof q){const fe=re.value.find(Ae=>Ae.value===B.value)!==void 0;switch(O.operator.value){case"in":return new Pe(fe);case"not in":return new Pe(!fe)}}if(B instanceof ue||re instanceof ue)switch(O.operator.value){case"+":return new ue(B.value.toString()+re.value.toString())}if(B instanceof ue&&re instanceof ue)switch(O.operator.value){case"in":return new Pe(re.value.includes(B.value));case"not in":return new Pe(!re.value.includes(B.value))}if(B instanceof ue&&re instanceof Ne)switch(O.operator.value){case"in":return new Pe(re.value.has(B.value));case"not in":return new Pe(!re.value.has(B.value))}throw new SyntaxError(`Unknown operator "${O.operator.value}" between ${B.type} and ${re.type}`)}evaluateArguments(O,se){const B=[],re=new Map;for(const fe of O)if(fe.type==="KeywordArgumentExpression"){const Ae=fe;re.set(Ae.key.value,this.evaluate(Ae.value,se))}else{if(re.size>0)throw new Error("Positional arguments must come before keyword arguments");B.push(this.evaluate(fe,se))}return[B,re]}evaluateFilterExpression(O,se){const B=this.evaluate(O.operand,se);if(O.filter.type==="Identifier"){const re=O.filter;if(re.value==="tojson")return new ue(Le(B));if(B instanceof q)switch(re.value){case"list":return B;case"first":return B.value[0];case"last":return B.value[B.value.length-1];case"length":return new te(B.value.length);case"reverse":return new q(B.value.reverse());case"sort":return new q(B.value.sort((fe,Ae)=>{if(fe.type!==Ae.type)throw new Error(`Cannot compare different types: ${fe.type} and ${Ae.type}`);switch(fe.type){case"NumericValue":return fe.value-Ae.value;case"StringValue":return fe.value.localeCompare(Ae.value);default:throw new Error(`Cannot compare type: ${fe.type}`)}}));case"join":return new ue(B.value.map(fe=>fe.value).join(""));case"string":return new ue(Le(B));default:throw new Error(`Unknown ArrayValue filter: ${re.value}`)}else if(B instanceof ue)switch(re.value){case"length":return new te(B.value.length);case"upper":return new ue(B.value.toUpperCase());case"lower":return new ue(B.value.toLowerCase());case"title":return new ue(ee(B.value));case"capitalize":return new ue(B.value.charAt(0).toUpperCase()+B.value.slice(1));case"trim":return new ue(B.value.trim());case"indent":return new ue(B.value.split(` +`).map((fe,Ae)=>Ae===0||fe.length===0?fe:" "+fe).join(` +`));case"join":case"string":return B;default:throw new Error(`Unknown StringValue filter: ${re.value}`)}else if(B instanceof te)switch(re.value){case"abs":return new te(Math.abs(B.value));default:throw new Error(`Unknown NumericValue filter: ${re.value}`)}else if(B instanceof Ne)switch(re.value){case"items":return new q(Array.from(B.value.entries()).map(([fe,Ae])=>new q([new ue(fe),Ae])));case"length":return new te(B.value.size);default:throw new Error(`Unknown ObjectValue filter: ${re.value}`)}throw new Error(`Cannot apply filter "${re.value}" to type: ${B.type}`)}else if(O.filter.type==="CallExpression"){const re=O.filter;if(re.callee.type!=="Identifier")throw new Error(`Unknown filter: ${re.callee.type}`);const fe=re.callee.value;if(fe==="tojson"){const[,Ae]=this.evaluateArguments(re.args,se),Ve=Ae.get("indent")??new ve;if(!(Ve instanceof te||Ve instanceof ve))throw new Error("If set, indent must be a number");return new ue(Le(B,Ve.value))}else if(fe==="join"){let Ae;if(B instanceof ue)Ae=Array.from(B.value);else if(B instanceof q)Ae=B.value.map(mt=>mt.value);else throw new Error(`Cannot apply filter "${fe}" to type: ${B.type}`);const[Ve,Tt]=this.evaluateArguments(re.args,se),Nt=Ve.at(0)??Tt.get("separator")??new ue("");if(!(Nt instanceof ue))throw new Error("separator must be a string");return new ue(Ae.join(Nt.value))}if(B instanceof q){switch(fe){case"selectattr":case"rejectattr":{const Ae=fe==="selectattr";if(B.value.some(ct=>!(ct instanceof Ne)))throw new Error(`\`${fe}\` can only be applied to array of objects`);if(re.args.some(ct=>ct.type!=="StringLiteral"))throw new Error(`arguments of \`${fe}\` must be strings`);const[Ve,Tt,Nt]=re.args.map(ct=>this.evaluate(ct,se));let mt;if(Tt){const ct=se.tests.get(Tt.value);if(!ct)throw new Error(`Unknown test: ${Tt.value}`);mt=ct}else mt=(...ct)=>ct[0].__bool__().value;const Ge=B.value.filter(ct=>{const It=ct.value.get(Ve.value),Gt=It?mt(It,Nt):!1;return Ae?Gt:!Gt});return new q(Ge)}case"map":{const[,Ae]=this.evaluateArguments(re.args,se);if(Ae.has("attribute")){const Ve=Ae.get("attribute");if(!(Ve instanceof ue))throw new Error("attribute must be a string");const Tt=Ae.get("default"),Nt=B.value.map(mt=>{if(!(mt instanceof Ne))throw new Error("items in map must be an object");return mt.value.get(Ve.value)??Tt??new be});return new q(Nt)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${fe}`)}else if(B instanceof ue){switch(fe){case"indent":{const[Ae,Ve]=this.evaluateArguments(re.args,se),Tt=Ae.at(0)??Ve.get("width")??new te(4);if(!(Tt instanceof te))throw new Error("width must be a number");const Nt=Ae.at(1)??Ve.get("first")??new Pe(!1),mt=Ae.at(2)??Ve.get("blank")??new Pe(!1),Ge=B.value.split(` +`),ct=" ".repeat(Tt.value),It=Ge.map((Gt,Ot)=>!Nt.value&&Ot===0||!mt.value&&Gt.length===0?Gt:ct+Gt);return new ue(It.join(` +`))}}throw new Error(`Unknown StringValue filter: ${fe}`)}else throw new Error(`Cannot apply filter "${fe}" to type: ${B.type}`)}throw new Error(`Unknown filter: ${O.filter.type}`)}evaluateTestExpression(O,se){const B=this.evaluate(O.operand,se),re=se.tests.get(O.test.value);if(!re)throw new Error(`Unknown test: ${O.test.value}`);const fe=re(B);return new Pe(O.negate?!fe:fe)}evaluateUnaryExpression(O,se){const B=this.evaluate(O.argument,se);switch(O.operator.value){case"not":return new Pe(!B.value);default:throw new SyntaxError(`Unknown operator: ${O.operator.value}`)}}evalProgram(O,se){return this.evaluateBlock(O.body,se)}evaluateBlock(O,se){let B="";for(const re of O){const fe=this.evaluate(re,se);fe.type!=="NullValue"&&fe.type!=="UndefinedValue"&&(B+=fe.value)}return new ue(B)}evaluateIdentifier(O,se){return se.lookupVariable(O.value)}evaluateCallExpression(O,se){const[B,re]=this.evaluateArguments(O.args,se);re.size>0&&B.push(new we(re));const fe=this.evaluate(O.callee,se);if(fe.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${fe.type}`);return fe.value(B,se)}evaluateSliceExpression(O,se,B){if(!(O instanceof q||O instanceof ue))throw new Error("Slice object must be an array or string");const re=this.evaluate(se.start,B),fe=this.evaluate(se.stop,B),Ae=this.evaluate(se.step,B);if(!(re instanceof te||re instanceof be))throw new Error("Slice start must be numeric or undefined");if(!(fe instanceof te||fe instanceof be))throw new Error("Slice stop must be numeric or undefined");if(!(Ae instanceof te||Ae instanceof be))throw new Error("Slice step must be numeric or undefined");return O instanceof q?new q(W(O.value,re.value,fe.value,Ae.value)):new ue(W(Array.from(O.value),re.value,fe.value,Ae.value).join(""))}evaluateMemberExpression(O,se){const B=this.evaluate(O.object,se);let re;if(O.computed){if(O.property.type==="SliceExpression")return this.evaluateSliceExpression(B,O.property,se);re=this.evaluate(O.property,se)}else re=new ue(O.property.value);let fe;if(B instanceof Ne){if(!(re instanceof ue))throw new Error(`Cannot access property with non-string: got ${re.type}`);fe=B.value.get(re.value)??B.builtins.get(re.value)}else if(B instanceof q||B instanceof ue)if(re instanceof te)fe=B.value.at(re.value),B instanceof ue&&(fe=new ue(B.value.at(re.value)));else if(re instanceof ue)fe=B.builtins.get(re.value);else throw new Error(`Cannot access property with non-string/non-number: got ${re.type}`);else{if(!(re instanceof ue))throw new Error(`Cannot access property with non-string: got ${re.type}`);fe=B.builtins.get(re.value)}return fe instanceof me?fe:new be}evaluateSet(O,se){const B=O.value?this.evaluate(O.value,se):this.evaluateBlock(O.body,se);if(O.assignee.type==="Identifier"){const re=O.assignee.value;se.setVariable(re,B)}else if(O.assignee.type==="MemberExpression"){const re=O.assignee,fe=this.evaluate(re.object,se);if(!(fe instanceof Ne))throw new Error("Cannot assign to member of non-object");if(re.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");fe.value.set(re.property.value,B)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(O.assignee)}`);return new ve}evaluateIf(O,se){const B=this.evaluate(O.test,se);return this.evaluateBlock(B.__bool__().value?O.body:O.alternate,se)}evaluateFor(O,se){const B=new Ce(se);let re,fe;if(O.iterable.type==="SelectExpression"){const mt=O.iterable;fe=this.evaluate(mt.iterable,B),re=mt.test}else fe=this.evaluate(O.iterable,B);if(!(fe instanceof q))throw new Error(`Expected iterable type in for loop: got ${fe.type}`);const Ae=[],Ve=[];for(let mt=0;mtGt.setVariable(O.loopvar.value,ct);else if(O.loopvar.type==="TupleLiteral"){const Gt=O.loopvar;if(ct.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${ct.type}`);const Ot=ct;if(Gt.value.length!==Ot.value.length)throw new Error(`Too ${Gt.value.length>Ot.value.length?"few":"many"} items to unpack`);It=ir=>{for(let Ar=0;Ar0?Ae[mt-1]:new be],["nextitem",mt{var Ve;const fe=new Ce(re);B=B.slice();let Ae;((Ve=B.at(-1))==null?void 0:Ve.type)==="KeywordArgumentsValue"&&(Ae=B.pop());for(let Tt=0;Ttthis.evaluate(B,se)));case"TupleLiteral":return new R(O.value.map(B=>this.evaluate(B,se)));case"ObjectLiteral":{const B=new Map;for(const[re,fe]of O.value){const Ae=this.evaluate(re,se);if(!(Ae instanceof ue))throw new Error(`Object keys must be strings: got ${Ae.type}`);B.set(Ae.value,this.evaluate(fe,se))}return new Ne(B)}case"Identifier":return this.evaluateIdentifier(O,se);case"CallExpression":return this.evaluateCallExpression(O,se);case"MemberExpression":return this.evaluateMemberExpression(O,se);case"UnaryExpression":return this.evaluateUnaryExpression(O,se);case"BinaryExpression":return this.evaluateBinaryExpression(O,se);case"FilterExpression":return this.evaluateFilterExpression(O,se);case"TestExpression":return this.evaluateTestExpression(O,se);default:throw new SyntaxError(`Unknown node type: ${O.type}`)}}};function $e(O){switch(typeof O){case"number":return new te(O);case"string":return new ue(O);case"boolean":return new Pe(O);case"undefined":return new be;case"object":return O===null?new ve:Array.isArray(O)?new q(O.map($e)):new Ne(new Map(Object.entries(O).map(([se,B])=>[se,$e(B)])));case"function":return new de((se,B)=>{const re=O(...se.map(fe=>fe.value))??null;return $e(re)});default:throw new Error(`Cannot convert to runtime value: ${O}`)}}function Le(O,se,B){const re=B??0;switch(O.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(O.value);case"ArrayValue":case"ObjectValue":{const fe=se?" ".repeat(se):"",Ae=` +`+fe.repeat(re),Ve=Ae+fe;if(O.type==="ArrayValue"){const Tt=O.value.map(Nt=>Le(Nt,se,re+1));return se?`[${Ve}${Tt.join(`,${Ve}`)}${Ae}]`:`[${Tt.join(", ")}]`}else{const Tt=Array.from(O.value.entries()).map(([Nt,mt])=>{const Ge=`"${Nt}": ${Le(mt,se,re+1)}`;return se?`${Ve}${Ge}`:Ge});return se?`{${Tt.join(",")}${Ae}}`:`{${Tt.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${O.type}`)}}var Ie=` +`,Ke="{%- ",Ye=" -%}",ke={MultiplicativeBinaryOperator:2,AdditiveBinaryOperator:1,ComparisonBinaryOperator:0};function Ze(O,se=" "){const B=typeof se=="number"?" ".repeat(se):se;return tt(O.body,0,B).replace(/\n$/,"")}function Xe(...O){return Ke+O.join(" ")+Ye}function tt(O,se,B){return O.map(re=>ut(re,se,B)).join(Ie)}function ut(O,se,B){const re=B.repeat(se);switch(O.type){case"Program":return tt(O.body,se,B);case"If":return Ue(O,se,B);case"For":return Re(O,se,B);case"Set":return _t(O,se,B);case"Macro":return St(O,se,B);default:return re+"{{- "+at(O)+" -}}"}}function Ue(O,se,B){const re=B.repeat(se),fe=[];let Ae=O;for(;Ae&&(fe.push({test:Ae.test,body:Ae.body}),Ae.alternate.length===1&&Ae.alternate[0].type==="If");)Ae=Ae.alternate[0];let Ve=re+Xe("if",at(fe[0].test))+Ie+tt(fe[0].body,se+1,B);for(let Tt=1;Tt0&&(Ve+=Ie+re+Xe("else")+Ie+tt(Ae.alternate,se+1,B)),Ve+=Ie+re+Xe("endif"),Ve}function Re(O,se,B){const re=B.repeat(se);let fe="";if(O.iterable.type==="SelectExpression"){const Ve=O.iterable;fe=`${at(Ve.iterable)} if ${at(Ve.test)}`}else fe=at(O.iterable);let Ae=re+Xe("for",at(O.loopvar),"in",fe)+Ie+tt(O.body,se+1,B);return O.defaultBlock.length>0&&(Ae+=Ie+re+Xe("else")+Ie+tt(O.defaultBlock,se+1,B)),Ae+=Ie+re+Xe("endfor"),Ae}function _t(O,se,B){const re=B.repeat(se),fe=at(O.assignee),Ae=O.value?at(O.value):"",Ve=re+Xe("set",`${fe}${O.value?" = "+Ae:""}`);return O.body.length===0?Ve:Ve+Ie+tt(O.body,se+1,B)+Ie+re+Xe("endset")}function St(O,se,B){const re=B.repeat(se),fe=O.args.map(at).join(", ");return re+Xe("macro",`${O.name.value}(${fe})`)+Ie+tt(O.body,se+1,B)+Ie+re+Xe("endmacro")}function at(O,se=-1){switch(O.type){case"Identifier":return O.value;case"NullLiteral":return"none";case"NumericLiteral":case"BooleanLiteral":return`${O.value}`;case"StringLiteral":return JSON.stringify(O.value);case"BinaryExpression":{const B=O,re=ke[B.operator.type]??0,fe=at(B.left,re),Ae=at(B.right,re+1),Ve=`${fe} ${B.operator.value} ${Ae}`;return reat(fe,-1)).join(", ");return`${at(B.callee,-1)}(${re})`}case"MemberExpression":{const B=O;let re=at(B.object,-1);B.object.type!=="Identifier"&&(re=`(${re})`);let fe=at(B.property,-1);return!B.computed&&B.property.type!=="Identifier"&&(fe=`(${fe})`),B.computed?`${re}[${fe}]`:`${re}.${fe}`}case"FilterExpression":{const B=O,re=at(B.operand,1/0);return B.filter.type==="CallExpression"?`${re} | ${at(B.filter,-1)}`:`${re} | ${B.filter.value}`}case"SelectExpression":{const B=O;return`${at(B.iterable,-1)} | select(${at(B.test,-1)})`}case"TestExpression":{const B=O;return`${at(B.operand,-1)} is${B.negate?" not":""} ${B.test.value}`}case"ArrayLiteral":case"TupleLiteral":{const B=O.value.map(fe=>at(fe,-1)),re=O.type==="ArrayLiteral"?"[]":"()";return`${re[0]}${B.join(", ")}${re[1]}`}case"ObjectLiteral":return`{ ${Array.from(O.value.entries()).map(([re,fe])=>`${at(re,-1)}: ${at(fe,-1)}`).join(", ")} }`;case"SliceExpression":{const B=O,re=B.start?at(B.start,-1):"",fe=B.stop?at(B.stop,-1):"",Ae=B.step?`:${at(B.step,-1)}`:"";return`${re}:${fe}${Ae}`}case"KeywordArgumentExpression":{const B=O;return`${B.key.value}=${at(B.value,-1)}`}case"If":{const B=O,re=at(B.test,-1),fe=at(B.body[0],0),Ae=at(B.alternate[0],-1);return`${fe} if ${re} else ${Ae}`}default:throw new Error(`Unknown expression type: ${O.type}`)}}var jt=class{constructor(O){Z(this,"parsed");const se=c(O,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=V(se)}render(O){const se=new Ce;if(se.set("false",!1),se.set("true",!0),se.set("raise_exception",fe=>{throw new Error(fe)}),se.set("range",F),O)for(const[fe,Ae]of Object.entries(O))se.set(fe,Ae);return new Se(se).run(this.parsed).value}format(O){return Ze(this.parsed,(O==null?void 0:O.indent)||" ")}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>k,deviceToExecutionProviders:()=>f,isONNXProxy:()=>S,isONNXTensor:()=>w});var o=t("./src/env.js"),n=t("?2ce3"),i=t("onnxruntime-web"),a=t("onnxruntime-common");const l=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),u=[];let p,c;const d=Symbol.for("onnxruntime");if(d in globalThis)c=globalThis[d];else if(o.apis.IS_NODE_ENV){switch(c=n??(s||(s=t.t(n,2))),process.platform){case"win32":u.push("dml");break;case"linux":process.arch==="x64"&&u.push("cuda");break}u.push("cpu"),p=["cpu"]}else c=i,o.apis.IS_WEBNN_AVAILABLE&&u.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),o.apis.IS_WEBGPU_AVAILABLE&&u.push("webgpu"),u.push("wasm"),p=["wasm"];const _=c.InferenceSession;function f(E=null){if(!E)return p;switch(E){case"auto":return u;case"gpu":return u.filter(y=>["webgpu","cuda","dml","webnn-gpu"].includes(y))}if(u.includes(E))return[l[E]??E];throw new Error(`Unsupported device: "${E}". Should be one of: ${u.join(", ")}.`)}let T=null;async function k(E,y,M){T&&await T;const v=_.create(E,y);T??(T=v);const C=await v;return C.config=M,C}function w(E){return E instanceof c.Tensor}const g=c==null?void 0:c.env;g!=null&&g.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!g.wasm.wasmPaths&&(g.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${o.env.version}/dist/`),g.wasm.proxy=!1),g!=null&&g.webgpu&&(g.webgpu.powerPreference="high-performance");function S(){var E;return(E=g==null?void 0:g.wasm)==null?void 0:E.proxy}o.env.backends.onnx=g},"./src/base/feature_extraction_utils.js":(e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>i,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(u){super(),this.config=u}static async from_pretrained(u,p){const c=await(0,n.getModelJSON)(u,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(c)}}function a(l,u){var p;if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${u} expects input to be a Float32Array or a Float64Array, but got ${((p=l==null?void 0:l.constructor)==null?void 0:p.name)??typeof l} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(e,r,t)=>{t.r(r),t.d(r,{ImageProcessor:()=>E,center_to_corners_format:()=>c,post_process_instance_segmentation:()=>S,post_process_object_detection:()=>d,post_process_panoptic_segmentation:()=>g,post_process_semantic_segmentation:()=>_});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/utils/image.js");var i=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function u(y,M,v=0,C=null){const A=y/M;let z=(0,n.bankers_round)(A)*M;return C!==null&&z>C&&(z=Math.floor(A)*M),zM&&F.push(ee)}else{let ee=(0,n.max)(V.data)[1];if(ee===j-1||(W=(0,n.softmax)(V.data),W[ee]te*J[(ue+1)%2])),Q.boxes.push(me),Q.classes.push(ee),Q.scores.push(W[ee])}}Y.push(Q)}return Y}function _(y,M=null){const v=y.logits,C=v.dims[0];if(M!==null&&M.length!==C)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const A=[];for(let z=0;zJ[F]&&(J[F]=V[F],Q[F]=ae)}const oe=new Array(G.dims[0]);for(let ae=0;aeae!==void 0);A.push({segmentation:H,labels:he})}return A}function f(y,M,v,C){const A=[],z=[],K=[];for(let G=0;Gv&&(A.push(Y),z.push(Q),K.push(H))}return[A,z,K]}function T(y,M,v,C=.5,A=.8){const z=[];let K=0,G=0;const j=M[v].data;for(let H=0;H=C&&++G;let Y=K>0&&G>0;return Y&&(Y=K/G>A),[Y,z]}function k(y,M,v,C,A,z=null,K=null){const[G,j]=K??y[0].dims,Y=new o.Tensor("int32",new Int32Array(G*j),[G,j]),H=[];if(K!==null)for(let ae=0;aeQ[W]&&(J[W]=ae,Q[W]=F[W])}let oe=0;const he=Y.data;for(let ae=0;ae200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(y,M)/Math.min(y,M)}`);let z=Math.round(y/v)*v,K=Math.round(M/v)*v;if(z*K>A){const G=Math.sqrt(y*M/A);z=Math.floor(y/G/v)*v,K=Math.floor(M/G/v)*v}else if(z*Kz?Y=Math.floor(z*j/A):z>A&&(j=Math.floor(A*Y/z)),await M.resize(Y,j,{resample:C}))}async crop_margin(M,v=200){const C=M.clone().grayscale(),A=(0,n.min)(C.data)[0],K=(0,n.max)(C.data)[0]-A;if(K===0)return M;const G=v/255;let j=C.width,Y=C.height,H=0,J=0;const Q=C.data;for(let oe=0;oethis.preprocess(z)));return{pixel_values:(0,o.stack)(C.map(z=>z.pixel_values),0),original_sizes:C.map(z=>z.original_size),reshaped_input_sizes:C.map(z=>z.reshaped_input_size)}}static async from_pretrained(M,v){const C=await(0,a.getModelJSON)(M,l.IMAGE_PROCESSOR_NAME,!0,v);return new this(C)}}},"./src/base/processing_utils.js":(e,r,t)=>{t.r(r),t.d(r,{Processor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class i extends o.Callable{constructor(l,u){super(),this.config=l,this.components=u}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(l,u={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,...u})}batch_decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...l)}decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...l)}async _call(l,...u){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...u);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,u){const[p,c]=await Promise.all([this.uses_processor_config?(0,n.getModelJSON)(l,s.PROCESSOR_NAME,!0,u):{},Promise.all(this.classes.filter(d=>d in this).map(async d=>{const _=await this[d].from_pretrained(l,u);return[d.replace(/_class$/,""),_]})).then(Object.fromEntries)]);return new this(p,c)}}Z(i,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),Z(i,"uses_processor_config",!1)},"./src/configs.js":(e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>u,PretrainedConfig:()=>l,getKeyValueShapes:()=>a});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js");async function n(p,c){return await(0,o.getModelJSON)(p,"config.json",!0,c)}function i(p){const c={};let d={};switch(p.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":d=i(p.text_config);break;case"moondream1":d=i(p.phi_config);break;case"musicgen":d=i(p.decoder);break;case"multi_modality":d=i(p.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":c.num_heads="n_head",c.num_layers="n_layer",c.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":c.num_heads="num_attention_heads",c.num_layers="num_hidden_layers",c.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":c.num_heads="num_key_value_heads",c.num_layers="num_hidden_layers",c.hidden_size="hidden_size",c.num_attention_heads="num_attention_heads";break;case"qwen3":case"gemma":case"gemma2":case"gemma3_text":case"glm":case"helium":c.num_heads="num_key_value_heads",c.num_layers="num_hidden_layers",c.dim_kv="head_dim";break;case"openelm":c.num_heads="num_kv_heads",c.num_layers="num_transformer_layers",c.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":c.num_heads="num_heads",c.num_layers="num_layers",c.hidden_size="hidden_size";break;case"bloom":c.num_heads="n_head",c.num_layers="n_layer",c.hidden_size="hidden_size";break;case"mpt":c.num_heads="n_heads",c.num_layers="n_layers",c.hidden_size="d_model";break;case"exaone":c.num_heads="num_key_value_heads",c.num_layers="num_layers",c.dim_kv="head_dim",c.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":c.num_decoder_layers="num_decoder_layers",c.num_decoder_heads="num_heads",c.decoder_dim_kv="d_kv",c.num_encoder_layers="num_layers",c.num_encoder_heads="num_heads",c.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":c.num_decoder_layers="decoder_layers",c.num_decoder_heads="decoder_attention_heads",c.decoder_hidden_size="d_model",c.num_encoder_layers="encoder_layers",c.num_encoder_heads="encoder_attention_heads",c.encoder_hidden_size="d_model";break;case"speecht5":c.num_decoder_layers="decoder_layers",c.num_decoder_heads="decoder_attention_heads",c.decoder_hidden_size="hidden_size",c.num_encoder_layers="encoder_layers",c.num_encoder_heads="encoder_attention_heads",c.encoder_hidden_size="hidden_size";break;case"trocr":c.num_encoder_layers=c.num_decoder_layers="decoder_layers",c.num_encoder_heads=c.num_decoder_heads="decoder_attention_heads",c.encoder_hidden_size=c.decoder_hidden_size="d_model";break;case"musicgen_decoder":c.num_encoder_layers=c.num_decoder_layers="num_hidden_layers",c.num_encoder_heads=c.num_decoder_heads="num_attention_heads",c.encoder_hidden_size=c.decoder_hidden_size="hidden_size";break;case"moonshine":c.num_decoder_layers="decoder_num_hidden_layers",c.num_decoder_heads="decoder_num_key_value_heads",c.num_encoder_layers="encoder_num_hidden_layers",c.num_encoder_heads="encoder_num_key_value_heads",c.encoder_hidden_size=c.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const f=i(p.decoder),T="num_decoder_layers"in f,k=(0,s.pick)(p,["model_type","is_encoder_decoder"]);return T?(k.num_decoder_layers=f.num_decoder_layers,k.num_decoder_heads=f.num_decoder_heads,k.decoder_hidden_size=f.decoder_hidden_size,k.num_encoder_layers=f.num_encoder_layers,k.num_encoder_heads=f.num_encoder_heads,k.encoder_hidden_size=f.encoder_hidden_size):(k.num_layers=f.num_layers,k.num_heads=f.num_heads,k.hidden_size=f.hidden_size),k}const _={...d,...(0,s.pick)(p,["model_type","multi_query","is_encoder_decoder"])};for(const f in c)_[f]=p[c[f]];return _}function a(p,{prefix:c="past_key_values",batch_size:d=1}={}){const _={},f=p.normalized_config;if(f.is_encoder_decoder&&"num_encoder_heads"in f&&"num_decoder_heads"in f){const T=f.encoder_dim_kv??f.encoder_hidden_size/f.num_encoder_heads,k=f.decoder_dim_kv??f.decoder_hidden_size/f.num_decoder_heads,w=[d,f.num_encoder_heads,0,T],g=[d,f.num_decoder_heads,0,k];for(let S=0;S{var C,A;t.r(r),t.d(r,{apis:()=>k,env:()=>M});var s=t("?569f"),o=t("?3f59"),n=t("?154a");const i="3.5.0",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&((C=self.constructor)==null?void 0:C.name)==="DedicatedWorkerGlobalScope",u=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,c=typeof navigator<"u"&&"ml"in navigator,d=typeof process<"u",_=d&&((A=process==null?void 0:process.release)==null?void 0:A.name)==="node",f=!v(s),T=!v(o),k=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:u,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:c,IS_PROCESS_AVAILABLE:d,IS_NODE_ENV:_,IS_FS_AVAILABLE:f,IS_PATH_AVAILABLE:T}),w=f&&T;let g="./";if(w){const z=Object({url:self.location.href}).url;z?g=o.dirname(o.dirname(n.fileURLToPath(z))):typeof __dirname<"u"&&(g=o.dirname(__dirname))}const S=w?o.join(g,"/.cache/"):null,E="/models/",y=w?o.join(g,E):E,M={version:i,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co./",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:y,useFS:f,useBrowserCache:u,useFSCache:f,cacheDir:S,useCustomCache:!1,customCache:null};function v(z){return Object.keys(z).length===0}},"./src/generation/configuration_utils.js":(e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>o});var s=t("./src/utils/core.js");class o{constructor(i){Z(this,"max_length",20);Z(this,"max_new_tokens",null);Z(this,"min_length",0);Z(this,"min_new_tokens",null);Z(this,"early_stopping",!1);Z(this,"max_time",null);Z(this,"do_sample",!1);Z(this,"num_beams",1);Z(this,"num_beam_groups",1);Z(this,"penalty_alpha",null);Z(this,"use_cache",!0);Z(this,"temperature",1);Z(this,"top_k",50);Z(this,"top_p",1);Z(this,"typical_p",1);Z(this,"epsilon_cutoff",0);Z(this,"eta_cutoff",0);Z(this,"diversity_penalty",0);Z(this,"repetition_penalty",1);Z(this,"encoder_repetition_penalty",1);Z(this,"length_penalty",1);Z(this,"no_repeat_ngram_size",0);Z(this,"bad_words_ids",null);Z(this,"force_words_ids",null);Z(this,"renormalize_logits",!1);Z(this,"constraints",null);Z(this,"forced_bos_token_id",null);Z(this,"forced_eos_token_id",null);Z(this,"remove_invalid_values",!1);Z(this,"exponential_decay_length_penalty",null);Z(this,"suppress_tokens",null);Z(this,"streamer",null);Z(this,"begin_suppress_tokens",null);Z(this,"forced_decoder_ids",null);Z(this,"guidance_scale",null);Z(this,"num_return_sequences",1);Z(this,"output_attentions",!1);Z(this,"output_hidden_states",!1);Z(this,"output_scores",!1);Z(this,"return_dict_in_generate",!1);Z(this,"pad_token_id",null);Z(this,"bos_token_id",null);Z(this,"eos_token_id",null);Z(this,"encoder_no_repeat_ngram_size",0);Z(this,"decoder_start_token_id",null);Z(this,"generation_kwargs",{});Object.assign(this,(0,s.pick)(i,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>w,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>u,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>i,MinLengthLogitsProcessor:()=>f,MinNewTokensLengthLogitsProcessor:()=>T,NoBadWordsLogitsProcessor:()=>k,NoRepeatNGramLogitsProcessor:()=>d,RepetitionPenaltyLogitsProcessor:()=>_,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>g,TopKLogitsWarper:()=>E,TopPLogitsWarper:()=>S,WhisperTimeStampLogitsProcessor:()=>c});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var o=t("./src/utils/maths.js");class n extends s.Callable{_call(M,v){throw Error("`_call` should be implemented in a subclass")}}class i extends s.Callable{_call(M,v){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(M){this.processors.push(M)}extend(M){this.processors.push(...M)}_call(M,v){let C=v;for(const A of this.processors)C=A(M,C);return C}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(M){super(),this.bos_token_id=M}_call(M,v){for(let C=0;C=1&&z[z.length-1]>=this.timestamp_begin,G=z.length<2||z[z.length-2]>=this.timestamp_begin;if(K&&(G?A.subarray(this.timestamp_begin).fill(-1/0):A.subarray(0,this.eos_token_id).fill(-1/0)),M[C].length===this.begin_index&&this.max_initial_timestamp_index!==null){const J=this.timestamp_begin+this.max_initial_timestamp_index;A.subarray(J+1).fill(-1/0)}const j=(0,o.log_softmax)(A),Y=Math.log(j.subarray(this.timestamp_begin).map(Math.exp).reduce((J,Q)=>J+Q)),H=(0,o.max)(j.subarray(0,this.timestamp_begin))[0];Y>H&&A.subarray(0,this.timestamp_begin).fill(-1/0)}return v}}class d extends n{constructor(M){super(),this.no_repeat_ngram_size=M}getNgrams(M){const v=M.length,C=[];for(let z=0;z1 to use the classifier free guidance processor, got guidance scale ${M}.`);this.guidance_scale=M}_call(M,v){if(v.dims[0]!==2*M.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 ${M.length} for the input ids.`);const C=M.length,A=v.slice([0,C],null),z=v.slice([C,v.dims[0]],null);for(let K=0;K1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${M}`);if(!Number.isInteger(C)||C<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${C}`);this.top_p=M,this.filter_value=v,this.min_tokens_to_keep=C}}class E extends i{constructor(M,{filter_value:v=-1/0,min_tokens_to_keep:C=1}={}){if(super(),!Number.isInteger(M)||M<0)throw new Error(`\`top_k\` must be a positive integer, but is ${M}`);this.top_k=Math.max(M,C),this.filter_value=v}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>i});var s=t("./src/utils/generic.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class i extends s.Callable{constructor(c){super(),this.generation_config=c}async _call(c){return this.sample(c)}async sample(c){throw Error("sample should be implemented in subclasses.")}getLogits(c,d){let _=c.dims.at(-1),f=c.data;if(d===-1)f=f.slice(-_);else{let T=d*_;f=f.slice(T,T+_)}return f}randomSelect(c){let d=0;for(let f=0;f1)return new u(c);if(c.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${c.num_return_sequences}.`);return new a(c)}}class a extends i{async sample(c){const d=(0,n.max)(c.data)[1];return[[BigInt(d),0]]}}class l extends i{async sample(c){let d=c.dims.at(-1);this.generation_config.top_k>0&&(d=Math.min(this.generation_config.top_k,d));const[_,f]=await(0,o.topk)(c,d),T=(0,n.softmax)(_.data);return Array.from({length:this.generation_config.num_beams},()=>{const k=this.randomSelect(T);return[f.data[k],Math.log(T[k])]})}}class u extends i{async sample(c){let d=c.dims.at(-1);this.generation_config.top_k>0&&(d=Math.min(this.generation_config.top_k,d));const[_,f]=await(0,o.topk)(c,d),T=(0,n.softmax)(_.data);return Array.from({length:this.generation_config.num_beams},(k,w)=>[f.data[w],Math.log(T[w])])}}},"./src/generation/stopping_criteria.js":(e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>i,StoppingCriteria:()=>o,StoppingCriteriaList:()=>n});var s=t("./src/utils/generic.js");class o extends s.Callable{_call(p,c){throw Error("StoppingCriteria needs to be subclassed")}}class n extends s.Callable{constructor(){super(),this.criteria=[]}push(p){this.criteria.push(p)}extend(p){p instanceof n?p=p.criteria:p instanceof o&&(p=[p]),this.criteria.push(...p)}_call(p,c){const d=new Array(p.length).fill(!1);for(const _ of this.criteria){const f=_(p,c);for(let T=0;Tc.length>=this.max_length)}}class a extends o{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,c){return p.map(d=>{const _=d.at(-1);return this.eos_token_id.some(f=>_==f)})}}class l extends o{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,c){return new Array(p.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>i,TextStreamer:()=>l,WhisperTextStreamer:()=>u});var s=t("./src/utils/core.js"),o=t("./src/tokenizers.js"),n=t("./src/env.js");class i{put(c){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const a=n.apis.IS_PROCESS_AVAILABLE?p=>process.stdout.write(p):p=>console.log(p);class l extends i{constructor(c,{skip_prompt:d=!1,callback_function:_=null,token_callback_function:f=null,skip_special_tokens:T=!0,decode_kwargs:k={},...w}={}){super(),this.tokenizer=c,this.skip_prompt=d,this.callback_function=_??a,this.token_callback_function=f,this.decode_kwargs={skip_special_tokens:T,...k,...w},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(c){var k;if(c.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 _=c[0];(k=this.token_callback_function)==null||k.call(this,_),this.token_cache=(0,s.mergeArrays)(this.token_cache,_);const f=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let T;d||f.endsWith(` +`)?(T=f.slice(this.print_len),this.token_cache=[],this.print_len=0):f.length>0&&(0,o.is_chinese_char)(f.charCodeAt(f.length-1))?(T=f.slice(this.print_len),this.print_len+=T.length):(T=f.slice(this.print_len,f.lastIndexOf(" ")+1),this.print_len+=T.length),this.on_finalized_text(T,!1)}end(){let c;this.token_cache.length>0?(c=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):c="",this.next_tokens_are_prompt=!0,this.on_finalized_text(c,!0)}on_finalized_text(c,d){var _,f;c.length>0&&((_=this.callback_function)==null||_.call(this,c)),d&&this.callback_function===a&&n.apis.IS_PROCESS_AVAILABLE&&((f=this.callback_function)==null||f.call(this,` +`))}}class u extends l{constructor(c,{skip_prompt:d=!1,callback_function:_=null,token_callback_function:f=null,on_chunk_start:T=null,on_chunk_end:k=null,on_finalize:w=null,time_precision:g=.02,skip_special_tokens:S=!0,decode_kwargs:E={}}={}){super(c,{skip_prompt:d,skip_special_tokens:S,callback_function:_,token_callback_function:f,decode_kwargs:E}),this.timestamp_begin=c.timestamp_begin,this.on_chunk_start=T,this.on_chunk_end=k,this.on_finalize=w,this.time_precision=g,this.waiting_for_timestamp=!1}put(c){var _,f;if(c.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const d=c[0];if(d.length===1){const T=Number(d[0])-this.timestamp_begin;if(T>=0){const k=T*this.time_precision;this.waiting_for_timestamp?(_=this.on_chunk_end)==null||_.call(this,k):(f=this.on_chunk_start)==null||f.call(this,k),this.waiting_for_timestamp=!this.waiting_for_timestamp,c=[[]]}}return super.put(c)}end(){var c;super.end(),(c=this.on_finalize)==null||c.call(this)}}},"./src/models.js":(e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>Ii,ASTModel:()=>ki,ASTPreTrainedModel:()=>To,AlbertForMaskedLM:()=>N,AlbertForQuestionAnswering:()=>$,AlbertForSequenceClassification:()=>pe,AlbertModel:()=>vn,AlbertPreTrainedModel:()=>As,AutoModel:()=>wc,AutoModelForAudioClassification:()=>x0,AutoModelForAudioFrameClassification:()=>E0,AutoModelForAudioTextToText:()=>O0,AutoModelForCTC:()=>v0,AutoModelForCausalLM:()=>d0,AutoModelForDepthEstimation:()=>$0,AutoModelForDocumentQuestionAnswering:()=>P0,AutoModelForImageClassification:()=>f0,AutoModelForImageFeatureExtraction:()=>A0,AutoModelForImageMatting:()=>C0,AutoModelForImageSegmentation:()=>_0,AutoModelForImageTextToText:()=>F0,AutoModelForImageToImage:()=>S0,AutoModelForMaskGeneration:()=>y0,AutoModelForMaskedLM:()=>p0,AutoModelForNormalEstimation:()=>k0,AutoModelForObjectDetection:()=>M0,AutoModelForPoseEstimation:()=>I0,AutoModelForQuestionAnswering:()=>h0,AutoModelForSemanticSegmentation:()=>g0,AutoModelForSeq2SeqLM:()=>a0,AutoModelForSequenceClassification:()=>o0,AutoModelForSpeechSeq2Seq:()=>l0,AutoModelForTextToSpectrogram:()=>u0,AutoModelForTextToWaveform:()=>c0,AutoModelForTokenClassification:()=>i0,AutoModelForUniversalSegmentation:()=>w0,AutoModelForVision2Seq:()=>m0,AutoModelForXVector:()=>T0,AutoModelForZeroShotObjectDetection:()=>b0,BartForConditionalGeneration:()=>Jt,BartForSequenceClassification:()=>Vt,BartModel:()=>Lt,BartPretrainedModel:()=>At,BaseModelOutput:()=>ve,BeitForImageClassification:()=>Uw,BeitModel:()=>Vw,BeitPreTrainedModel:()=>Lu,BertForMaskedLM:()=>Se,BertForQuestionAnswering:()=>Ie,BertForSequenceClassification:()=>$e,BertForTokenClassification:()=>Le,BertModel:()=>Ce,BertPreTrainedModel:()=>be,BlenderbotForConditionalGeneration:()=>mr,BlenderbotModel:()=>Kt,BlenderbotPreTrainedModel:()=>os,BlenderbotSmallForConditionalGeneration:()=>qr,BlenderbotSmallModel:()=>is,BlenderbotSmallPreTrainedModel:()=>kr,BloomForCausalLM:()=>dw,BloomModel:()=>cw,BloomPreTrainedModel:()=>Tu,CLIPModel:()=>Ni,CLIPPreTrainedModel:()=>Rs,CLIPSegForImageSegmentation:()=>zo,CLIPSegModel:()=>Lo,CLIPSegPreTrainedModel:()=>qn,CLIPTextModel:()=>hu,CLIPTextModelWithProjection:()=>Vi,CLIPVisionModel:()=>mu,CLIPVisionModelWithProjection:()=>Ui,CamembertForMaskedLM:()=>Ot,CamembertForQuestionAnswering:()=>ts,CamembertForSequenceClassification:()=>ir,CamembertForTokenClassification:()=>Ar,CamembertModel:()=>Gt,CamembertPreTrainedModel:()=>It,CausalLMOutput:()=>In,CausalLMOutputWithPast:()=>Kx,ChineseCLIPModel:()=>Gi,ChineseCLIPPreTrainedModel:()=>Wi,ClapAudioModelWithProjection:()=>Nb,ClapModel:()=>Rb,ClapPreTrainedModel:()=>ta,ClapTextModelWithProjection:()=>jb,CodeGenForCausalLM:()=>$n,CodeGenModel:()=>Go,CodeGenPreTrainedModel:()=>Zn,CohereForCausalLM:()=>Gg,CohereModel:()=>Wg,CoherePreTrainedModel:()=>fu,ConvBertForMaskedLM:()=>B,ConvBertForQuestionAnswering:()=>Ae,ConvBertForSequenceClassification:()=>re,ConvBertForTokenClassification:()=>fe,ConvBertModel:()=>se,ConvBertPreTrainedModel:()=>O,ConvNextForImageClassification:()=>DM,ConvNextModel:()=>OM,ConvNextPreTrainedModel:()=>Xu,ConvNextV2ForImageClassification:()=>zM,ConvNextV2Model:()=>LM,ConvNextV2PreTrainedModel:()=>Ju,DPTForDepthEstimation:()=>_M,DPTModel:()=>fM,DPTPreTrainedModel:()=>Hu,DacDecoderModel:()=>$y,DacDecoderOutput:()=>Py,DacEncoderModel:()=>Sy,DacEncoderOutput:()=>Ey,DacModel:()=>Cy,DacPreTrainedModel:()=>la,DebertaForMaskedLM:()=>Es,DebertaForQuestionAnswering:()=>ss,DebertaForSequenceClassification:()=>ws,DebertaForTokenClassification:()=>Ps,DebertaModel:()=>rs,DebertaPreTrainedModel:()=>yr,DebertaV2ForMaskedLM:()=>Ss,DebertaV2ForQuestionAnswering:()=>bs,DebertaV2ForSequenceClassification:()=>ns,DebertaV2ForTokenClassification:()=>Ms,DebertaV2Model:()=>Cs,DebertaV2PreTrainedModel:()=>Rr,DecisionTransformerModel:()=>ly,DecisionTransformerPreTrainedModel:()=>ay,DeiTForImageClassification:()=>oM,DeiTModel:()=>nM,DeiTPreTrainedModel:()=>Uu,DepthAnythingForDepthEstimation:()=>wM,DepthAnythingPreTrainedModel:()=>gM,DepthProForDepthEstimation:()=>xM,DepthProPreTrainedModel:()=>vM,DetrForObjectDetection:()=>Gw,DetrForSegmentation:()=>zu,DetrModel:()=>Ww,DetrObjectDetectionOutput:()=>Bu,DetrPreTrainedModel:()=>qi,DetrSegmentationOutput:()=>Kw,Dinov2ForImageClassification:()=>RM,Dinov2Model:()=>BM,Dinov2PreTrainedModel:()=>Yu,Dinov2WithRegistersForImageClassification:()=>NM,Dinov2WithRegistersModel:()=>jM,Dinov2WithRegistersPreTrainedModel:()=>Zu,DistilBertForMaskedLM:()=>Qt,DistilBertForQuestionAnswering:()=>nt,DistilBertForSequenceClassification:()=>De,DistilBertForTokenClassification:()=>qe,DistilBertModel:()=>ar,DistilBertPreTrainedModel:()=>Ur,DonutSwinModel:()=>FM,DonutSwinPreTrainedModel:()=>AM,EfficientNetForImageClassification:()=>qb,EfficientNetModel:()=>Hb,EfficientNetPreTrainedModel:()=>uc,ElectraForMaskedLM:()=>Nt,ElectraForQuestionAnswering:()=>ct,ElectraForSequenceClassification:()=>mt,ElectraForTokenClassification:()=>Ge,ElectraModel:()=>Tt,ElectraPreTrainedModel:()=>Ve,EsmForMaskedLM:()=>$s,EsmForSequenceClassification:()=>Fr,EsmForTokenClassification:()=>ks,EsmModel:()=>ys,EsmPreTrainedModel:()=>lr,ExaoneForCausalLM:()=>L,ExaoneModel:()=>I,ExaonePreTrainedModel:()=>x,FalconForCausalLM:()=>Bb,FalconModel:()=>zb,FalconPreTrainedModel:()=>ic,FastViTForImageClassification:()=>Iw,FastViTModel:()=>kw,FastViTPreTrainedModel:()=>Iu,Florence2ForConditionalGeneration:()=>ko,Florence2PreTrainedModel:()=>Li,GLPNForDepthEstimation:()=>IM,GLPNModel:()=>kM,GLPNPreTrainedModel:()=>Qu,GPT2LMHeadModel:()=>Bo,GPT2Model:()=>Ki,GPT2PreTrainedModel:()=>Qn,GPTBigCodeForCausalLM:()=>Wo,GPTBigCodeModel:()=>Yn,GPTBigCodePreTrainedModel:()=>Jn,GPTJForCausalLM:()=>Uo,GPTJModel:()=>Vo,GPTJPreTrainedModel:()=>Sn,GPTNeoForCausalLM:()=>No,GPTNeoModel:()=>jo,GPTNeoPreTrainedModel:()=>Ro,GPTNeoXForCausalLM:()=>Cn,GPTNeoXModel:()=>Xr,GPTNeoXPreTrainedModel:()=>Ys,Gemma2ForCausalLM:()=>Qg,Gemma2Model:()=>qg,Gemma2PreTrainedModel:()=>gu,Gemma3ForCausalLM:()=>Jg,Gemma3Model:()=>Xg,Gemma3PreTrainedModel:()=>wu,GemmaForCausalLM:()=>Hg,GemmaModel:()=>Kg,GemmaPreTrainedModel:()=>_u,GlmForCausalLM:()=>h,GlmModel:()=>Qo,GlmPreTrainedModel:()=>ro,GraniteForCausalLM:()=>Hi,GraniteModel:()=>js,GranitePreTrainedModel:()=>fr,GroundingDinoForObjectDetection:()=>UM,GroundingDinoPreTrainedModel:()=>VM,GroupViTModel:()=>$w,GroupViTPreTrainedModel:()=>Sw,HeliumForCausalLM:()=>qo,HeliumModel:()=>Ho,HeliumPreTrainedModel:()=>to,HieraForImageClassification:()=>aM,HieraModel:()=>iM,HieraPreTrainedModel:()=>Wu,HubertForCTC:()=>Mb,HubertForSequenceClassification:()=>bb,HubertModel:()=>wb,HubertPreTrainedModel:()=>Ax,IJepaForImageClassification:()=>Mw,IJepaModel:()=>ww,IJepaPreTrainedModel:()=>Su,Idefics3ForConditionalGeneration:()=>Qs,Idefics3PreTrainedModel:()=>Ri,ImageMattingOutput:()=>L0,JAISLMHeadModel:()=>dt,JAISModel:()=>Pn,JAISPreTrainedModel:()=>Xn,JinaCLIPModel:()=>Hn,JinaCLIPPreTrainedModel:()=>Js,JinaCLIPTextModel:()=>Oo,JinaCLIPVisionModel:()=>Do,LiteWhisperForConditionalGeneration:()=>Fi,LlamaForCausalLM:()=>Ko,LlamaModel:()=>eo,LlamaPreTrainedModel:()=>kn,LlavaForConditionalGeneration:()=>Tn,LlavaOnevisionForConditionalGeneration:()=>$o,LlavaPreTrainedModel:()=>Di,LongT5ForConditionalGeneration:()=>Qe,LongT5Model:()=>Be,LongT5PreTrainedModel:()=>ye,M2M100ForConditionalGeneration:()=>ZM,M2M100Model:()=>YM,M2M100PreTrainedModel:()=>rc,MBartForCausalLM:()=>Yt,MBartForConditionalGeneration:()=>Tr,MBartForSequenceClassification:()=>Er,MBartModel:()=>Or,MBartPreTrainedModel:()=>sr,MPNetForMaskedLM:()=>fn,MPNetForQuestionAnswering:()=>wn,MPNetForSequenceClassification:()=>_n,MPNetForTokenClassification:()=>gn,MPNetModel:()=>mn,MPNetPreTrainedModel:()=>Hr,MT5ForConditionalGeneration:()=>gt,MT5Model:()=>et,MT5PreTrainedModel:()=>We,MarianMTModel:()=>JM,MarianModel:()=>XM,MarianPreTrainedModel:()=>tc,MaskFormerForInstanceSegmentation:()=>$M,MaskFormerModel:()=>SM,MaskFormerPreTrainedModel:()=>qu,MaskedLMOutput:()=>Ir,Metric3DForDepthEstimation:()=>EM,Metric3DPreTrainedModel:()=>TM,Metric3Dv2ForDepthEstimation:()=>CM,Metric3Dv2PreTrainedModel:()=>PM,MgpstrForSceneTextRecognition:()=>hy,MgpstrModelOutput:()=>dy,MgpstrPreTrainedModel:()=>py,MimiDecoderModel:()=>Ty,MimiDecoderOutput:()=>yy,MimiEncoderModel:()=>xy,MimiEncoderOutput:()=>by,MimiModel:()=>vy,MimiPreTrainedModel:()=>aa,MistralForCausalLM:()=>Ob,MistralModel:()=>Fb,MistralPreTrainedModel:()=>nc,MobileBertForMaskedLM:()=>zs,MobileBertForQuestionAnswering:()=>$r,MobileBertForSequenceClassification:()=>xr,MobileBertModel:()=>vr,MobileBertPreTrainedModel:()=>jr,MobileLLMForCausalLM:()=>xe,MobileLLMModel:()=>le,MobileLLMPreTrainedModel:()=>U,MobileNetV1ForImageClassification:()=>Xb,MobileNetV1ForSemanticSegmentation:()=>Jb,MobileNetV1Model:()=>Qb,MobileNetV1PreTrainedModel:()=>sa,MobileNetV2ForImageClassification:()=>Zb,MobileNetV2ForSemanticSegmentation:()=>ey,MobileNetV2Model:()=>Yb,MobileNetV2PreTrainedModel:()=>na,MobileNetV3ForImageClassification:()=>ry,MobileNetV3ForSemanticSegmentation:()=>sy,MobileNetV3Model:()=>ty,MobileNetV3PreTrainedModel:()=>oa,MobileNetV4ForImageClassification:()=>oy,MobileNetV4ForSemanticSegmentation:()=>iy,MobileNetV4Model:()=>ny,MobileNetV4PreTrainedModel:()=>ia,MobileViTForImageClassification:()=>Dw,MobileViTModel:()=>Ow,MobileViTPreTrainedModel:()=>Au,MobileViTV2ForImageClassification:()=>zw,MobileViTV2Model:()=>Lw,MobileViTV2PreTrainedModel:()=>Fu,ModelOutput:()=>de,ModernBertForMaskedLM:()=>ke,ModernBertForSequenceClassification:()=>Ze,ModernBertForTokenClassification:()=>Xe,ModernBertModel:()=>Ye,ModernBertPreTrainedModel:()=>Ke,Moondream1ForConditionalGeneration:()=>qs,MoonshineForConditionalGeneration:()=>Co,MoonshineModel:()=>Oi,MoonshinePreTrainedModel:()=>Gn,MptForCausalLM:()=>hw,MptModel:()=>pw,MptPreTrainedModel:()=>Eu,MultiModalityCausalLM:()=>cy,MultiModalityPreTrainedModel:()=>uy,MusicgenForCausalLM:()=>Lx,MusicgenForConditionalGeneration:()=>dc,MusicgenModel:()=>Dx,MusicgenPreTrainedModel:()=>cc,NomicBertModel:()=>ut,NomicBertPreTrainedModel:()=>tt,OPTForCausalLM:()=>fw,OPTModel:()=>mw,OPTPreTrainedModel:()=>Pu,Olmo2ForCausalLM:()=>Ut,Olmo2Model:()=>Ft,Olmo2PreTrainedModel:()=>bt,OlmoForCausalLM:()=>st,OlmoModel:()=>He,OlmoPreTrainedModel:()=>Fe,OpenELMForCausalLM:()=>Zg,OpenELMModel:()=>Yg,OpenELMPreTrainedModel:()=>Mu,OwlViTForObjectDetection:()=>Rw,OwlViTModel:()=>Bw,OwlViTPreTrainedModel:()=>Ou,Owlv2ForObjectDetection:()=>Nw,Owlv2Model:()=>jw,Owlv2PreTrainedModel:()=>Du,PaliGemmaForConditionalGeneration:()=>Bi,PaliGemmaPreTrainedModel:()=>zi,PatchTSMixerForPrediction:()=>gy,PatchTSMixerModel:()=>_y,PatchTSMixerPreTrainedModel:()=>hc,PatchTSTForPrediction:()=>fy,PatchTSTModel:()=>my,PatchTSTPreTrainedModel:()=>pc,Phi3ForCausalLM:()=>uw,Phi3Model:()=>lw,Phi3PreTrainedModel:()=>xu,Phi3VForCausalLM:()=>Io,Phi3VPreTrainedModel:()=>ji,PhiForCausalLM:()=>aw,PhiModel:()=>iw,PhiPreTrainedModel:()=>vu,PreTrainedModel:()=>R,PretrainedMixin:()=>zt,PvtForImageClassification:()=>xw,PvtModel:()=>vw,PvtPreTrainedModel:()=>$u,PyAnnoteForAudioFrameClassification:()=>ob,PyAnnoteModel:()=>nb,PyAnnotePreTrainedModel:()=>sc,QuestionAnsweringModelOutput:()=>Lr,Qwen2ForCausalLM:()=>tw,Qwen2Model:()=>ew,Qwen2PreTrainedModel:()=>bu,Qwen2VLForConditionalGeneration:()=>ow,Qwen2VLPreTrainedModel:()=>nw,Qwen3ForCausalLM:()=>sw,Qwen3Model:()=>rw,Qwen3PreTrainedModel:()=>yu,RFDetrForObjectDetection:()=>Zw,RFDetrModel:()=>Yw,RFDetrObjectDetectionOutput:()=>eM,RFDetrPreTrainedModel:()=>Nu,RTDetrForObjectDetection:()=>qw,RTDetrModel:()=>Hw,RTDetrObjectDetectionOutput:()=>Qi,RTDetrPreTrainedModel:()=>Ru,RTDetrV2ForObjectDetection:()=>Xw,RTDetrV2Model:()=>Qw,RTDetrV2ObjectDetectionOutput:()=>Jw,RTDetrV2PreTrainedModel:()=>ju,ResNetForImageClassification:()=>uM,ResNetModel:()=>lM,ResNetPreTrainedModel:()=>Gu,RoFormerForMaskedLM:()=>_t,RoFormerForQuestionAnswering:()=>jt,RoFormerForSequenceClassification:()=>St,RoFormerForTokenClassification:()=>at,RoFormerModel:()=>Re,RoFormerPreTrainedModel:()=>Ue,RobertaForMaskedLM:()=>gr,RobertaForQuestionAnswering:()=>pr,RobertaForSequenceClassification:()=>Zt,RobertaForTokenClassification:()=>dr,RobertaModel:()=>Qr,RobertaPreTrainedModel:()=>cr,SamImageSegmentationOutput:()=>QM,SamModel:()=>qM,SamPreTrainedModel:()=>HM,SapiensForDepthEstimation:()=>bM,SapiensForNormalEstimation:()=>yM,SapiensForSemanticSegmentation:()=>MM,SapiensPreTrainedModel:()=>Ji,SegformerForImageClassification:()=>Ub,SegformerForSemanticSegmentation:()=>Wb,SegformerModel:()=>Ox,SegformerPreTrainedModel:()=>ra,Seq2SeqLMOutput:()=>Gx,SequenceClassifierOutput:()=>vt,SiglipModel:()=>En,SiglipPreTrainedModel:()=>Ao,SiglipTextModel:()=>Xs,SiglipVisionModel:()=>Fo,SmolVLMForConditionalGeneration:()=>Kn,SnacDecoderModel:()=>Ay,SnacEncoderModel:()=>Iy,SnacModel:()=>ky,SnacPreTrainedModel:()=>ua,SpeechT5ForSpeechToText:()=>Sb,SpeechT5ForTextToSpeech:()=>$b,SpeechT5HifiGan:()=>kb,SpeechT5Model:()=>Fx,SpeechT5PreTrainedModel:()=>ea,SqueezeBertForMaskedLM:()=>Ks,SqueezeBertForQuestionAnswering:()=>yn,SqueezeBertForSequenceClassification:()=>bn,SqueezeBertModel:()=>Mn,SqueezeBertPreTrainedModel:()=>Is,StableLmForCausalLM:()=>Kb,StableLmModel:()=>Gb,StableLmPreTrainedModel:()=>lc,Starcoder2ForCausalLM:()=>Lb,Starcoder2Model:()=>Db,Starcoder2PreTrainedModel:()=>oc,StyleTextToSpeech2Model:()=>Cb,StyleTextToSpeech2PreTrainedModel:()=>Pb,Swin2SRForImageSuperResolution:()=>mM,Swin2SRModel:()=>hM,Swin2SRPreTrainedModel:()=>Ku,SwinForImageClassification:()=>dM,SwinForSemanticSegmentation:()=>pM,SwinModel:()=>cM,SwinPreTrainedModel:()=>Xi,T5ForConditionalGeneration:()=>ce,T5Model:()=>ie,T5PreTrainedModel:()=>X,TableTransformerForObjectDetection:()=>rM,TableTransformerModel:()=>tM,TableTransformerObjectDetectionOutput:()=>sM,TableTransformerPreTrainedModel:()=>Vu,TokenClassifierOutput:()=>Pr,TrOCRForCausalLM:()=>Ab,TrOCRPreTrainedModel:()=>Ib,UltravoxModel:()=>My,UltravoxPreTrainedModel:()=>wy,UniSpeechForCTC:()=>ub,UniSpeechForSequenceClassification:()=>cb,UniSpeechModel:()=>lb,UniSpeechPreTrainedModel:()=>Yi,UniSpeechSatForAudioFrameClassification:()=>mb,UniSpeechSatForCTC:()=>pb,UniSpeechSatForSequenceClassification:()=>hb,UniSpeechSatModel:()=>db,UniSpeechSatPreTrainedModel:()=>Xo,ViTForImageClassification:()=>gw,ViTMAEModel:()=>Ew,ViTMAEPreTrainedModel:()=>Tw,ViTMSNForImageClassification:()=>Cw,ViTMSNModel:()=>Pw,ViTMSNPreTrainedModel:()=>ku,ViTModel:()=>_w,ViTPreTrainedModel:()=>Cu,VisionEncoderDecoderModel:()=>So,VitMatteForImageMatting:()=>Fw,VitMattePreTrainedModel:()=>Aw,VitPoseForPoseEstimation:()=>yw,VitPosePreTrainedModel:()=>bw,VitsModel:()=>ac,VitsModelOutput:()=>z0,VitsPreTrainedModel:()=>Vb,Wav2Vec2BertForCTC:()=>_b,Wav2Vec2BertForSequenceClassification:()=>gb,Wav2Vec2BertModel:()=>fb,Wav2Vec2BertPreTrainedModel:()=>Zi,Wav2Vec2ForAudioFrameClassification:()=>sb,Wav2Vec2ForCTC:()=>tb,Wav2Vec2ForSequenceClassification:()=>rb,Wav2Vec2Model:()=>eb,Wav2Vec2PreTrainedModel:()=>Zs,WavLMForAudioFrameClassification:()=>Eb,WavLMForCTC:()=>vb,WavLMForSequenceClassification:()=>xb,WavLMForXVector:()=>Tb,WavLMModel:()=>yb,WavLMPreTrainedModel:()=>so,WeSpeakerResNetModel:()=>ab,WeSpeakerResNetPreTrainedModel:()=>ib,WhisperForConditionalGeneration:()=>Po,WhisperModel:()=>Ai,WhisperPreTrainedModel:()=>Eo,XLMForQuestionAnswering:()=>Ti,XLMForSequenceClassification:()=>vi,XLMForTokenClassification:()=>xi,XLMModel:()=>Hs,XLMPreTrainedModel:()=>hr,XLMRobertaForMaskedLM:()=>Pi,XLMRobertaForQuestionAnswering:()=>$i,XLMRobertaForSequenceClassification:()=>Ci,XLMRobertaForTokenClassification:()=>Si,XLMRobertaModel:()=>Ei,XLMRobertaPreTrainedModel:()=>Bs,XLMWithLMHeadModel:()=>xn,XVectorOutput:()=>D0,YolosForObjectDetection:()=>GM,YolosModel:()=>WM,YolosObjectDetectionOutput:()=>KM,YolosPreTrainedModel:()=>ec});var s=t("./src/configs.js"),o=t("./src/backends/onnx.js"),n=t("./src/utils/dtypes.js"),i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),u=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),c=t("./src/generation/configuration_utils.js"),d=t("./src/utils/tensor.js"),_=t("./src/utils/image.js"),f=t("./src/utils/maths.js"),T=t("./src/generation/stopping_criteria.js"),k=t("./src/generation/logits_sampler.js"),w=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},y=new Map,M=new Map,v=new Map;async function C(b,P,D){var Cr;let ne=((Cr=D.config)==null?void 0:Cr["transformers.js_config"])??{},ge=D.device??ne.device;ge&&typeof ge!="string"&&(ge.hasOwnProperty(P)?ge=ge[P]:(console.warn(`device not specified for "${P}". Using the default device.`),ge=null));const _e=ge??(w.apis.IS_NODE_ENV?"cpu":"wasm"),Ee=(0,o.deviceToExecutionProviders)(_e),Oe=ne.device_config??{};Oe.hasOwnProperty(_e)&&(ne={...ne,...Oe[_e]});let je=D.dtype??ne.dtype;if(typeof je!="string"&&(je&&je.hasOwnProperty(P)?je=je[P]:(je=n.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??n.DATA_TYPES.fp32,console.warn(`dtype not specified for "${P}". Using the default dtype (${je}) for this device (${_e}).`))),je===n.DATA_TYPES.auto){let Ct=ne.dtype;typeof Ct!="string"&&(Ct=Ct==null?void 0:Ct[P]),Ct&&Ct!==n.DATA_TYPES.auto&&n.DATA_TYPES.hasOwnProperty(Ct)?je=Ct:je=n.DEFAULT_DEVICE_DTYPE_MAPPING[_e]??n.DATA_TYPES.fp32}const Je=je;if(n.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Je)){if(Je===n.DATA_TYPES.fp16&&_e==="webgpu"&&!await(0,n.isWebGpuFp16Supported)())throw new Error(`The device (${_e}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Je}. Should be one of: ${Object.keys(n.DATA_TYPES).join(", ")}`);const ht=ne.kv_cache_dtype,Mt=ht?typeof ht=="string"?ht:ht[Je]??"float32":void 0;if(Mt&&!["float32","float16"].includes(Mt))throw new Error(`Invalid kv_cache_dtype: ${Mt}. Should be one of: float32, float16`);const pt={dtype:Je,kv_cache_dtype:Mt},Pt=n.DEFAULT_DTYPE_SUFFIX_MAPPING[Je],wt=`${P}${Pt}.onnx`,Et=`${D.subfolder??""}/${wt}`,it={...D.session_options};it.executionProviders??(it.executionProviders=Ee);const $t=ne.free_dimension_overrides;$t?it.freeDimensionOverrides??(it.freeDimensionOverrides=$t):_e.startsWith("webnn")&&!it.freeDimensionOverrides&&console.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${_e}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);const Ht=w.apis.IS_NODE_ENV&&w.env.useFSCache,er=(0,l.getModelFile)(b,Et,!0,D,Ht),ur=D.use_external_data_format??ne.use_external_data_format;let nr=[];if(ur){let Ct;typeof ur=="object"?ur.hasOwnProperty(wt)?Ct=ur[wt]:ur.hasOwnProperty(P)?Ct=ur[P]:Ct=!1:Ct=ur;const wr=+Ct;if(wr>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${wr}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let Jr=0;Jr{const Fn=await(0,l.getModelFile)(b,Nr,!0,D,Ht);as(Fn instanceof Uint8Array?{path:An,data:Fn}:An)}))}}else it.externalData!==void 0&&(nr=it.externalData.map(async Ct=>{if(typeof Ct.data=="string"){const wr=await(0,l.getModelFile)(b,Ct.data,!0,D);return{...Ct,data:wr}}return Ct}));if(nr.length>0){const Ct=await Promise.all(nr);w.apis.IS_NODE_ENV||(it.externalData=Ct)}if(_e==="webgpu"){const Ct=(0,s.getKeyValueShapes)(D.config,{prefix:"present"});if(Object.keys(Ct).length>0&&!(0,o.isONNXProxy)()){const wr={};for(const Jr in Ct)wr[Jr]="gpu-buffer";it.preferredOutputLocation=wr}}return{buffer_or_path:await er,session_options:it,session_config:pt}}async function A(b,P,D){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const{buffer_or_path:ge,session_options:_e,session_config:Ee}=await C(b,P[ne],D),Oe=await(0,o.createInferenceSession)(ge,_e,Ee);return[ne,Oe]})))}async function z(b,P,D){return Object.fromEntries(await Promise.all(Object.keys(P).map(async ne=>{const ge=await(0,l.getModelJSON)(b,P[ne],!1,D);return[ne,ge]})))}function K(b,P){const D=Object.create(null),ne=[];for(const Ee of b.inputNames){const Oe=P[Ee];if(!(Oe instanceof d.Tensor)){ne.push(Ee);continue}D[Ee]=(0,o.isONNXProxy)()?Oe.clone():Oe}if(ne.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${ne.join(", ")}.`);const ge=Object.keys(P).length,_e=b.inputNames.length;if(ge>_e){let Ee=Object.keys(P).filter(Oe=>!b.inputNames.includes(Oe));console.warn(`WARNING: Too many inputs were provided (${ge} > ${_e}). The following inputs will be ignored: "${Ee.join(", ")}".`)}return D}async function G(b,P){const D=K(b,P);try{const ne=Object.fromEntries(Object.entries(D).map(([_e,Ee])=>[_e,Ee.ort_tensor]));let ge=await b.run(ne);return ge=j(ge),ge}catch(ne){const ge=Object.fromEntries(Object.entries(D).map(([_e,{type:Ee,dims:Oe,data:je}])=>[_e,{type:Ee,dims:Oe,data:je}]));throw console.error(`An error occurred during model execution: "${ne}".`),console.error("Inputs given to model:",ge),ne}}function j(b){for(let P in b)(0,o.isONNXTensor)(b[P])?b[P]=new d.Tensor(b[P]):typeof b[P]=="object"&&j(b[P]);return b}function Y(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(P=>P.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(P=>BigInt(P))),[b.length,b[0].length])}else return new d.Tensor("int64",BigInt64Array.from(b.map(P=>BigInt(P))),[1,b.length])}function H(b){return new d.Tensor("bool",[b],[1])}async function J(b,P){let{encoder_outputs:D,input_ids:ne,decoder_input_ids:ge,..._e}=P;if(!D){const Oe=(0,a.pick)(P,b.sessions.model.inputNames);D=(await Q(b,Oe)).last_hidden_state}return _e.input_ids=ge,_e.encoder_hidden_states=D,b.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(_e.encoder_attention_mask=P.attention_mask),await he(b,_e,!0)}async function Q(b,P){const D=b.sessions.model,ne=(0,a.pick)(P,D.inputNames);if(D.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds){if(!P.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");ne.inputs_embeds=await b.encode_text({input_ids:P.input_ids})}if(D.inputNames.includes("token_type_ids")&&!ne.token_type_ids){if(!ne.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");ne.token_type_ids=(0,d.zeros_like)(ne.input_ids)}if(D.inputNames.includes("pixel_mask")&&!ne.pixel_mask){if(!ne.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const ge=ne.pixel_values.dims;ne.pixel_mask=(0,d.ones)([ge[0],ge[2],ge[3]])}return await G(D,ne)}async function oe(b,P){const D=await b.encode(P);return await b.decode(D)}async function he(b,P,D=!1){const ne=b.sessions[D?"decoder_model_merged":"model"],{past_key_values:ge,..._e}=P;if(ne.inputNames.includes("use_cache_branch")&&(_e.use_cache_branch=H(!!ge)),ne.inputNames.includes("position_ids")&&_e.attention_mask&&!_e.position_ids){const Oe=["paligemma","gemma3_text","gemma3"].includes(b.config.model_type)?1:0;_e.position_ids=ue(_e,ge,Oe)}b.addPastKeyValues(_e,ge);const Ee=(0,a.pick)(_e,ne.inputNames);return await G(ne,Ee)}function ae({modality_token_id:b,inputs_embeds:P,modality_features:D,input_ids:ne,attention_mask:ge}){const _e=ne.tolist().map(Je=>Je.reduce((ht,Mt,pt)=>(Mt==b&&ht.push(pt),ht),[])),Ee=_e.reduce((Je,ht)=>Je+ht.length,0),Oe=D.dims[0];if(Ee!==Oe)throw new Error(`Number of tokens and features do not match: tokens: ${Ee}, features ${Oe}`);let je=0;for(let Je=0;Je<_e.length;++Je){const ht=_e[Je],Mt=P[Je];for(let pt=0;pt_e.dims[1])){if(ge<_e.dims[1])D.input_ids=_e.slice(null,[ge,null]);else if(b.config.image_token_index!=null&&_e.data.some(Oe=>Oe==b.config.image_token_index)){const Oe=b.config.num_image_tokens;if(!Oe)throw new Error("`num_image_tokens` is missing in the model configuration.");const je=_e.dims[1]-(ge-Oe);D.input_ids=_e.slice(null,[-je,null]),D.attention_mask=(0,d.ones)([1,ge+je])}}}return D}function Ne(b,P,D,ne){return D.past_key_values&&(P=P.map(ge=>[ge.at(-1)])),{...D,decoder_input_ids:Y(P)}}function we(b,...P){return b.config.is_encoder_decoder?Ne(b,...P):Pe(b,...P)}function q(b,P,D,ne){const ge=!!D.past_key_values;return ne.guidance_scale!==null&&ne.guidance_scale>1&&(ge?D.input_ids=(0,d.cat)([D.input_ids,D.input_ids],0):(D.input_ids=(0,d.cat)([D.input_ids,(0,d.full_like)(D.input_ids,BigInt(ne.pad_token_id))],0),D.attention_mask=(0,d.cat)([D.attention_mask,(0,d.full_like)(D.attention_mask,0n)],0))),(ge||!D.pixel_values)&&(D.pixel_values=(0,d.full)([0,0,3,384,384],1)),ge&&(D.images_seq_mask=new d.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),D.images_emb_mask=new d.Tensor("bool",new Array(0).fill(!1),[1,1,0])),D}class R extends i.Callable{constructor(D,ne,ge){super();Z(this,"main_input_name","input_ids");Z(this,"forward_params",["input_ids","attention_mask"]);this.config=D,this.sessions=ne,this.configs=ge;const _e=v.get(this.constructor),Ee=y.get(_e);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Ee){case E.DecoderOnly:this.can_generate=!0,this._forward=he,this._prepare_inputs_for_generation=Pe;break;case E.Seq2Seq:case E.Vision2Seq:case E.Musicgen:this.can_generate=!0,this._forward=J,this._prepare_inputs_for_generation=Ne;break;case E.EncoderDecoder:this._forward=J;break;case E.ImageTextToText:this.can_generate=!0,this._forward=me,this._prepare_inputs_for_generation=we;break;case E.AudioTextToText:this.can_generate=!0,this._forward=ee,this._prepare_inputs_for_generation=we;break;case E.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=we;break;case E.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=q;break;case E.AutoEncoder:this._forward=oe;break;default:this._forward=Q;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var ne;const D=[];for(const ge of Object.values(this.sessions))(ne=ge==null?void 0:ge.handler)!=null&&ne.dispose&&D.push(ge.handler.dispose());return await Promise.all(D)}static async from_pretrained(D,{progress_callback:ne=null,config:ge=null,cache_dir:_e=null,local_files_only:Ee=!1,revision:Oe="main",model_file_name:je=null,subfolder:Je="onnx",device:ht=null,dtype:Mt=null,use_external_data_format:pt=null,session_options:Pt={}}={}){let wt={progress_callback:ne,config:ge,cache_dir:_e,local_files_only:Ee,revision:Oe,model_file_name:je,subfolder:Je,device:ht,dtype:Mt,use_external_data_format:pt,session_options:Pt};const Et=v.get(this),it=y.get(Et);ge=wt.config=await s.AutoConfig.from_pretrained(D,wt);let $t;if(it===E.DecoderOnly)$t=await Promise.all([A(D,{model:wt.model_file_name??"model"},wt),z(D,{generation_config:"generation_config.json"},wt)]);else if(it===E.Seq2Seq||it===E.Vision2Seq)$t=await Promise.all([A(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},wt),z(D,{generation_config:"generation_config.json"},wt)]);else if(it===E.MaskGeneration)$t=await Promise.all([A(D,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},wt)]);else if(it===E.EncoderDecoder)$t=await Promise.all([A(D,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},wt)]);else if(it===E.ImageTextToText){const Ht={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};ge.is_encoder_decoder&&(Ht.model="encoder_model"),$t=await Promise.all([A(D,Ht,wt),z(D,{generation_config:"generation_config.json"},wt)])}else if(it===E.AudioTextToText){const Ht={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};$t=await Promise.all([A(D,Ht,wt),z(D,{generation_config:"generation_config.json"},wt)])}else if(it===E.Musicgen)$t=await Promise.all([A(D,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},wt),z(D,{generation_config:"generation_config.json"},wt)]);else if(it===E.MultiModality)$t=await Promise.all([A(D,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"},wt),z(D,{generation_config:"generation_config.json"},wt)]);else if(it===E.Phi3V)$t=await Promise.all([A(D,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},wt),z(D,{generation_config:"generation_config.json"},wt)]);else if(it===E.AutoEncoder)$t=await Promise.all([A(D,{encoder_model:"encoder_model",decoder_model:"decoder_model"},wt)]);else{if(it!==E.EncoderOnly){const Ht=Et??(ge==null?void 0:ge.model_type);Ht!=="custom"&&console.warn(`Model type for '${Ht}' not found, assuming encoder-only architecture. Please report this at ${u.GITHUB_ISSUE_URL}.`)}$t=await Promise.all([A(D,{model:wt.model_file_name??"model"},wt)])}return new this(ge,...$t)}async _call(D){return await this.forward(D)}async forward(D){return await this._forward(this,D)}get generation_config(){var D;return((D=this.configs)==null?void 0:D.generation_config)??null}_get_logits_warper(D){const ne=new p.LogitsProcessorList;return D.temperature!==null&&D.temperature!==1&&ne.push(new p.TemperatureLogitsWarper(D.temperature)),D.top_k!==null&&D.top_k!==0&&ne.push(new p.TopKLogitsWarper(D.top_k)),D.top_p!==null&&D.top_p<1&&ne.push(new p.TopPLogitsWarper(D.top_p)),ne}_get_logits_processor(D,ne,ge=null){const _e=new p.LogitsProcessorList;if(D.repetition_penalty!==null&&D.repetition_penalty!==1&&_e.push(new p.RepetitionPenaltyLogitsProcessor(D.repetition_penalty)),D.no_repeat_ngram_size!==null&&D.no_repeat_ngram_size>0&&_e.push(new p.NoRepeatNGramLogitsProcessor(D.no_repeat_ngram_size)),D.bad_words_ids!==null&&_e.push(new p.NoBadWordsLogitsProcessor(D.bad_words_ids,D.eos_token_id)),D.min_length!==null&&D.eos_token_id!==null&&D.min_length>0&&_e.push(new p.MinLengthLogitsProcessor(D.min_length,D.eos_token_id)),D.min_new_tokens!==null&&D.eos_token_id!==null&&D.min_new_tokens>0&&_e.push(new p.MinNewTokensLengthLogitsProcessor(ne,D.min_new_tokens,D.eos_token_id)),D.forced_bos_token_id!==null&&_e.push(new p.ForcedBOSTokenLogitsProcessor(D.forced_bos_token_id)),D.forced_eos_token_id!==null&&_e.push(new p.ForcedEOSTokenLogitsProcessor(D.max_length,D.forced_eos_token_id)),D.begin_suppress_tokens!==null){const Ee=ne>1||D.forced_bos_token_id===null?ne:ne+1;_e.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ee))}return D.guidance_scale!==null&&D.guidance_scale>1&&_e.push(new p.ClassifierFreeGuidanceLogitsProcessor(D.guidance_scale)),ge!==null&&_e.extend(ge),_e}_prepare_generation_config(D,ne,ge=c.GenerationConfig){const _e={...this.config};for(const Oe of["decoder","generator","text_config"])Oe in _e&&Object.assign(_e,_e[Oe]);const Ee=new ge(_e);return Object.assign(Ee,this.generation_config??{}),D&&Object.assign(Ee,D),ne&&Object.assign(Ee,(0,a.pick)(ne,Object.getOwnPropertyNames(Ee))),Ee}_get_stopping_criteria(D,ne=null){const ge=new T.StoppingCriteriaList;return D.max_length!==null&&ge.push(new T.MaxLengthCriteria(D.max_length,this.config.max_position_embeddings??null)),D.eos_token_id!==null&&ge.push(new T.EosTokenCriteria(D.eos_token_id)),ne&&ge.extend(ne),ge}_validate_model_class(){if(!this.can_generate){const D=[_c,gc,fc,mc],ne=v.get(this.constructor),ge=new Set,_e=this.config.model_type;for(const Oe of D){const je=Oe.get(_e);je&&ge.add(je[0])}let Ee=`The current model class (${ne}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw ge.size>0&&(Ee+=` Please use the following class instead: ${[...ge].join(", ")}`),Error(Ee)}}prepare_inputs_for_generation(...D){return this._prepare_inputs_for_generation(this,...D)}_update_model_kwargs_for_generation({generated_input_ids:D,outputs:ne,model_inputs:ge,is_encoder_decoder:_e}){return ge.past_key_values=this.getPastKeyValues(ne,ge.past_key_values),ge.input_ids=new d.Tensor("int64",D.flat(),[D.length,1]),_e||(ge.attention_mask=(0,d.cat)([ge.attention_mask,(0,d.ones)([ge.attention_mask.dims[0],1])],1)),ge.position_ids=null,ge}_prepare_model_inputs({inputs:D,bos_token_id:ne,model_kwargs:ge}){const _e=(0,a.pick)(ge,this.forward_params),Ee=this.main_input_name;if(Ee in _e){if(D)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else _e[Ee]=D;return{inputs_tensor:_e[Ee],model_inputs:_e,model_input_name:Ee}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:D,model_inputs:ne,model_input_name:ge,generation_config:_e}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!ne.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:Oe,pixel_values:je,attention_mask:Je,...ht}=ne,Mt=await this._prepare_inputs_embeds(ne);ne={...ht,...(0,a.pick)(Mt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Ee}=await Q(this,ne);if(_e.guidance_scale!==null&&_e.guidance_scale>1)Ee=(0,d.cat)([Ee,(0,d.full_like)(Ee,0)],0),"attention_mask"in ne&&(ne.attention_mask=(0,d.cat)([ne.attention_mask,(0,d.zeros_like)(ne.attention_mask)],0));else if(ne.decoder_input_ids){const Oe=Y(ne.decoder_input_ids).dims[0];if(Oe!==Ee.dims[0]){if(Ee.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Ee.dims[0]}) than the decoder inputs (${Oe}).`);Ee=(0,d.cat)(Array.from({length:Oe},()=>Ee),0)}}return ne.encoder_outputs=Ee,ne}_prepare_decoder_input_ids_for_generation({batch_size:D,model_input_name:ne,model_kwargs:ge,decoder_start_token_id:_e,bos_token_id:Ee,generation_config:Oe}){let{decoder_input_ids:je,...Je}=ge;if(!(je instanceof d.Tensor)){if(je)Array.isArray(je[0])||(je=Array.from({length:D},()=>je));else if(_e??(_e=Ee),this.config.model_type==="musicgen")je=Array.from({length:D*this.config.decoder.num_codebooks},()=>[_e]);else if(Array.isArray(_e)){if(_e.length!==D)throw new Error(`\`decoder_start_token_id\` expcted to have length ${D} but got ${_e.length}`);je=_e}else je=Array.from({length:D},()=>[_e]);je=Y(je)}return ge.decoder_attention_mask=(0,d.ones_like)(je),{input_ids:je,model_inputs:Je}}async generate({inputs:D=null,generation_config:ne=null,logits_processor:ge=null,stopping_criteria:_e=null,streamer:Ee=null,...Oe}){this._validate_model_class(),ne=this._prepare_generation_config(ne,Oe);let{inputs_tensor:je,model_inputs:Je,model_input_name:ht}=this._prepare_model_inputs({inputs:D,model_kwargs:Oe});const Mt=this.config.is_encoder_decoder;Mt&&("encoder_outputs"in Je||(Je=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:je,model_inputs:Je,model_input_name:ht,generation_config:ne})));let pt;Mt?{input_ids:pt,model_inputs:Je}=this._prepare_decoder_input_ids_for_generation({batch_size:Je[ht].dims.at(0),model_input_name:ht,model_kwargs:Je,decoder_start_token_id:ne.decoder_start_token_id,bos_token_id:ne.bos_token_id,generation_config:ne}):pt=Je[ht];let Pt=pt.dims.at(-1);ne.max_new_tokens!==null&&(ne.max_length=Pt+ne.max_new_tokens);const wt=this._get_logits_processor(ne,Pt,ge),Et=this._get_stopping_criteria(ne,_e),it=Je[ht].dims.at(0),$t=k.LogitsSampler.getSampler(ne),Ht=new Array(it).fill(0),er=pt.tolist();Ee&&Ee.put(er);let ur,nr={};for(;;){if(Je=this.prepare_inputs_for_generation(er,Je,ne),ur=await this.forward(Je),ne.output_attentions&&ne.return_dict_in_generate){const Nr=this.getAttentions(ur);for(const as in Nr)as in nr||(nr[as]=[]),nr[as].push(Nr[as])}const Ct=ur.logits.slice(null,-1,null),wr=wt(er,Ct),Jr=[];for(let Nr=0;NrNr))break;Je=this._update_model_kwargs_for_generation({generated_input_ids:Jr,outputs:ur,model_inputs:Je,is_encoder_decoder:Mt})}Ee&&Ee.end();const _r=this.getPastKeyValues(ur,Je.past_key_values,!0),Cr=new d.Tensor("int64",er.flat(),[er.length,er[0].length]);if(ne.return_dict_in_generate)return{sequences:Cr,past_key_values:_r,...nr};for(const Ct of Object.values(ur))Ct.location==="gpu-buffer"&&Ct.dispose();return Cr}getPastKeyValues(D,ne,ge=!1){const _e=Object.create(null);for(const Ee in D)if(Ee.startsWith("present")){const Oe=Ee.replace("present","past_key_values"),je=Ee.includes("encoder");if(je&&ne?_e[Oe]=ne[Oe]:_e[Oe]=D[Ee],ne&&(!je||ge)){const Je=ne[Oe];Je.location==="gpu-buffer"&&Je.dispose()}}return _e}getAttentions(D){const ne={};for(const ge of["cross_attentions","encoder_attentions","decoder_attentions"])for(const _e in D)_e.startsWith(ge)&&(ge in ne||(ne[ge]=[]),ne[ge].push(D[_e]));return ne}addPastKeyValues(D,ne){var ge,_e,Ee;if(ne)Object.assign(D,ne);else{const Oe=this.sessions.decoder_model_merged??this.sessions.model,je=((ge=Oe==null?void 0:Oe.config)==null?void 0:ge.kv_cache_dtype)??"float32",Je=je==="float16"?new d.DataTypeMap.float16:[],ht=((Ee=(_e=D[this.main_input_name]??D.attention_mask)==null?void 0:_e.dims)==null?void 0:Ee[0])??1,Mt=(0,s.getKeyValueShapes)(this.config,{batch_size:ht});for(const pt in Mt)D[pt]=new d.Tensor(je,Je,Mt[pt])}}async encode_image({pixel_values:D}){const ne=(await G(this.sessions.vision_encoder,{pixel_values:D})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${ne.dims[1]}).`),this.config.num_image_tokens=ne.dims[1]),ne}async encode_text({input_ids:D}){return(await G(this.sessions.embed_tokens,{input_ids:D})).inputs_embeds}async encode_audio({audio_values:D}){return(await G(this.sessions.audio_encoder,{audio_values:D})).audio_features}}class de{}class ve extends de{constructor({last_hidden_state:P,hidden_states:D=null,attentions:ne=null}){super(),this.last_hidden_state=P,this.hidden_states=D,this.attentions=ne}}class be extends R{}class Ce extends be{}class Se extends be{async _call(P){return new Ir(await super._call(P))}}class $e extends be{async _call(P){return new vt(await super._call(P))}}class Le extends be{async _call(P){return new Pr(await super._call(P))}}class Ie extends be{async _call(P){return new Lr(await super._call(P))}}class Ke extends R{}class Ye extends Ke{}class ke extends Ke{async _call(P){return new Ir(await super._call(P))}}class Ze extends Ke{async _call(P){return new vt(await super._call(P))}}class Xe extends Ke{async _call(P){return new Pr(await super._call(P))}}class tt extends R{}class ut extends tt{}class Ue extends R{}class Re extends Ue{}class _t extends Ue{async _call(P){return new Ir(await super._call(P))}}class St extends Ue{async _call(P){return new vt(await super._call(P))}}class at extends Ue{async _call(P){return new Pr(await super._call(P))}}class jt extends Ue{async _call(P){return new Lr(await super._call(P))}}class O extends R{}class se extends O{}class B extends O{async _call(P){return new Ir(await super._call(P))}}class re extends O{async _call(P){return new vt(await super._call(P))}}class fe extends O{async _call(P){return new Pr(await super._call(P))}}class Ae extends O{async _call(P){return new Lr(await super._call(P))}}class Ve extends R{}class Tt extends Ve{}class Nt extends Ve{async _call(P){return new Ir(await super._call(P))}}class mt extends Ve{async _call(P){return new vt(await super._call(P))}}class Ge extends Ve{async _call(P){return new Pr(await super._call(P))}}class ct extends Ve{async _call(P){return new Lr(await super._call(P))}}class It extends R{}class Gt extends It{}class Ot extends It{async _call(P){return new Ir(await super._call(P))}}class ir extends It{async _call(P){return new vt(await super._call(P))}}class Ar extends It{async _call(P){return new Pr(await super._call(P))}}class ts extends It{async _call(P){return new Lr(await super._call(P))}}class yr extends R{}class rs extends yr{}class Es extends yr{async _call(P){return new Ir(await super._call(P))}}class ws extends yr{async _call(P){return new vt(await super._call(P))}}class Ps extends yr{async _call(P){return new Pr(await super._call(P))}}class ss extends yr{async _call(P){return new Lr(await super._call(P))}}class Rr extends R{}class Cs extends Rr{}class Ss extends Rr{async _call(P){return new Ir(await super._call(P))}}class ns extends Rr{async _call(P){return new vt(await super._call(P))}}class Ms extends Rr{async _call(P){return new Pr(await super._call(P))}}class bs extends Rr{async _call(P){return new Lr(await super._call(P))}}class Ur extends R{}class ar extends Ur{}class De extends Ur{async _call(P){return new vt(await super._call(P))}}class qe extends Ur{async _call(P){return new Pr(await super._call(P))}}class nt extends Ur{async _call(P){return new Lr(await super._call(P))}}class Qt extends Ur{async _call(P){return new Ir(await super._call(P))}}class lr extends R{}class ys extends lr{}class $s extends lr{async _call(P){return new Ir(await super._call(P))}}class Fr extends lr{async _call(P){return new vt(await super._call(P))}}class ks extends lr{async _call(P){return new Pr(await super._call(P))}}class jr extends R{}class vr extends jr{}class zs extends jr{async _call(P){return new Ir(await super._call(P))}}class xr extends jr{async _call(P){return new vt(await super._call(P))}}class $r extends jr{async _call(P){return new Lr(await super._call(P))}}class Hr extends R{}class mn extends Hr{}class fn extends Hr{async _call(P){return new Ir(await super._call(P))}}class _n extends Hr{async _call(P){return new vt(await super._call(P))}}class gn extends Hr{async _call(P){return new Pr(await super._call(P))}}class wn extends Hr{async _call(P){return new Lr(await super._call(P))}}class Is extends R{}class Mn extends Is{}class Ks extends Is{async _call(P){return new Ir(await super._call(P))}}class bn extends Is{async _call(P){return new vt(await super._call(P))}}class yn extends Is{async _call(P){return new Lr(await super._call(P))}}class As extends R{}class vn extends As{}class pe extends As{async _call(P){return new vt(await super._call(P))}}class $ extends As{async _call(P){return new Lr(await super._call(P))}}class N extends As{async _call(P){return new Ir(await super._call(P))}}class X extends R{constructor(){super(...arguments);Z(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class ie extends X{}class ce extends X{}class ye extends R{}class Be extends ye{}class Qe extends ye{}class We extends R{}class et extends We{}class gt extends We{}class At extends R{}class Lt extends At{}class Jt extends At{}class Vt extends At{async _call(P){return new vt(await super._call(P))}}class sr extends R{}class Or extends sr{}class Tr extends sr{}class Er extends sr{async _call(P){return new vt(await super._call(P))}}class Yt extends sr{}class os extends R{}class Kt extends os{}class mr extends os{}class kr extends R{}class is extends kr{}class qr extends kr{}class cr extends R{}class Qr extends cr{}class gr extends cr{async _call(P){return new Ir(await super._call(P))}}class Zt extends cr{async _call(P){return new vt(await super._call(P))}}class dr extends cr{async _call(P){return new Pr(await super._call(P))}}class pr extends cr{async _call(P){return new Lr(await super._call(P))}}class hr extends R{}class Hs extends hr{}class xn extends hr{async _call(P){return new Ir(await super._call(P))}}class vi extends hr{async _call(P){return new vt(await super._call(P))}}class xi extends hr{async _call(P){return new Pr(await super._call(P))}}class Ti extends hr{async _call(P){return new Lr(await super._call(P))}}class Bs extends R{}class Ei extends Bs{}class Pi extends Bs{async _call(P){return new Ir(await super._call(P))}}class Ci extends Bs{async _call(P){return new vt(await super._call(P))}}class Si extends Bs{async _call(P){return new Pr(await super._call(P))}}class $i extends Bs{async _call(P){return new Lr(await super._call(P))}}class To extends R{}class ki extends To{}class Ii extends To{}class Eo extends R{constructor(){super(...arguments);Z(this,"requires_attention_mask",!1);Z(this,"main_input_name","input_features");Z(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Ai extends Eo{}class Po extends Eo{_prepare_generation_config(P,D){return super._prepare_generation_config(P,D,g.WhisperGenerationConfig)}_retrieve_init_tokens(P){const D=[P.decoder_start_token_id];let ne=P.language;const ge=P.task;if(P.is_multilingual){ne||(console.warn("No language specified - defaulting to English (en)."),ne="en");const Ee=`<|${(0,S.whisper_language_to_code)(ne)}|>`;D.push(P.lang_to_id[Ee]),D.push(P.task_to_id[ge??"transcribe"])}else if(ne||ge)throw new Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!P.return_timestamps&&P.no_timestamps_token_id&&D.at(-1)!==P.no_timestamps_token_id?D.push(P.no_timestamps_token_id):P.return_timestamps&&D.at(-1)===P.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),D.pop()),D.filter(_e=>_e!=null)}async generate({inputs:P=null,generation_config:D=null,logits_processor:ne=null,stopping_criteria:ge=null,..._e}){D=this._prepare_generation_config(D,_e);const Ee=_e.decoder_input_ids??this._retrieve_init_tokens(D);if(D.return_timestamps&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.WhisperTimeStampLogitsProcessor(D,Ee))),D.begin_suppress_tokens&&(ne??(ne=new p.LogitsProcessorList),ne.push(new p.SuppressTokensAtBeginLogitsProcessor(D.begin_suppress_tokens,Ee.length))),D.return_token_timestamps){if(!D.alignment_heads)throw new Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");D.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),D.output_attentions=!0,D.return_dict_in_generate=!0}const Oe=await super.generate({inputs:P,generation_config:D,logits_processor:ne,decoder_input_ids:Ee,..._e});return D.return_token_timestamps&&(Oe.token_timestamps=this._extract_token_timestamps(Oe,D.alignment_heads,D.num_frames)),Oe}_extract_token_timestamps(P,D,ne=null,ge=.02){if(!P.cross_attentions)throw new Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");ne==null&&console.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let _e=this.config.median_filter_width;_e===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),_e=7);const Ee=P.cross_attentions,Oe=Array.from({length:this.config.decoder_layers},(Et,it)=>(0,d.cat)(Ee.map($t=>$t[it]),2)),je=(0,d.stack)(D.map(([Et,it])=>{if(Et>=Oe.length)throw new Error(`Layer index ${Et} is out of bounds for cross attentions (length ${Oe.length}).`);return ne?Oe[Et].slice(null,it,null,[0,ne]):Oe[Et].slice(null,it)})).transpose(1,0,2,3),[Je,ht]=(0,d.std_mean)(je,-2,0,!0),Mt=je.clone();for(let Et=0;Et$t[Cr+1]-$t[Cr]),ur=(0,a.mergeArrays)([1],er).map(_r=>!!_r),nr=[];for(let _r=0;_rpt.findIndex(Pt=>Pt==_e)),je=Oe.every(pt=>pt===-1),Je=Oe.every(pt=>pt!==-1);if(!je&&!Je)throw new Error("Every input should contain either 0 or 1 image token.");if(je)return{inputs_embeds:P,attention_mask:ge};const ht=[],Mt=[];for(let pt=0;ptArray.from({length:P.dims[0]},er=>Array.from({length:P.dims[1]},ur=>1))),wt=D?D.tolist():[],Et=ne?ne.tolist():[];let it=0,$t=0;for(let Ht=0;Htpt[Ht][Mr]==1),nr=er.reduce((tr,Mr,en)=>(Mr==je&&tr.push(en),tr),[]).map(tr=>er[tr+1]),_r=nr.filter(tr=>tr==Ee).length,Cr=nr.filter(tr=>tr==Oe).length;let Ct=[],wr=0,Jr=_r,An=Cr;for(let tr=0;trvs>wr&&Dn==Ee),en=er.findIndex((Dn,vs)=>vs>wr&&Dn==Oe),On=Jr>0&&Mr!==-1?Mr:er.length+1,oo=An>0&&en!==-1?en:er.length+1;let ha,Mc,bc,yc;On0?(0,f.max)(Ct.at(-1))[0]+1:0;Ct.push(Array.from({length:3*xc},(Dn,vs)=>B0+vs%xc));const Tc=xc+B0,fa=Hx*vc*ma,qx=Array.from({length:fa},(Dn,vs)=>Tc+Math.floor(vs/(vc*ma))),Qx=Array.from({length:fa},(Dn,vs)=>Tc+Math.floor(vs/ma)%vc),Xx=Array.from({length:fa},(Dn,vs)=>Tc+vs%ma);Ct.push([qx,Qx,Xx].flat()),wr=ha+fa}if(wr0?(0,f.max)(Ct.at(-1))[0]+1:0,Mr=er.length-wr;Ct.push(Array.from({length:3*Mr},(en,On)=>tr+On%Mr))}const Nr=Ct.reduce((tr,Mr)=>tr+Mr.length,0),as=new Array(Nr);let ca=0;for(let tr=0;tr<3;++tr)for(let Mr=0;MrMt[it%Mt.length]),wt=Array.from({length:pt[0]},(Et,it)=>(0,f.max)(Mt.subarray(pt[1]*it,pt[1]*(it+1)))[0]+1n+BigInt(pt[1]));return[new d.Tensor("int64",Pt,[3,...pt]),new d.Tensor("int64",wt,[wt.length,1])]}else{const[Mt,pt]=P.dims,Pt=BigInt64Array.from({length:3*Mt*pt},(wt,Et)=>BigInt(Math.floor(Et%pt/Mt)));return[new d.Tensor("int64",Pt,[3,...P.dims]),(0,d.zeros)([Mt,1])]}}async encode_image({pixel_values:P,image_grid_thw:D}){return(await G(this.sessions.vision_encoder,{pixel_values:P,grid_thw:D})).image_features}_merge_input_ids_with_image_features(P){return V({image_token_id:this.config.image_token_id,...P})}prepare_inputs_for_generation(P,D,ne){if(D.attention_mask&&!D.position_ids)if(!D.past_key_values)[D.position_ids,D.rope_deltas]=this.get_rope_index(D.input_ids,D.image_grid_thw,D.video_grid_thw,D.attention_mask);else{D.pixel_values=null;const ge=BigInt(Object.values(D.past_key_values)[0].dims.at(-2)),_e=D.rope_deltas.map(Ee=>ge+Ee);D.position_ids=(0,d.stack)([_e,_e,_e],0)}return D}}class vu extends R{}class iw extends vu{}class aw extends vu{}class xu extends R{}class lw extends xu{}class uw extends xu{}class Tu extends R{}class cw extends Tu{}class dw extends Tu{}class Eu extends R{}class pw extends Eu{}class hw extends Eu{}class Pu extends R{}class mw extends Pu{}class fw extends Pu{}class Cu extends R{}class _w extends Cu{}class gw extends Cu{async _call(P){return new vt(await super._call(P))}}class Su extends R{}class ww extends Su{}class Mw extends Su{async _call(P){return new vt(await super._call(P))}}class bw extends R{}class yw extends bw{}class $u extends R{}class vw extends $u{}class xw extends $u{async _call(P){return new vt(await super._call(P))}}class Tw extends R{}class Ew extends Tw{}class ku extends R{}class Pw extends ku{}class Cw extends ku{async _call(P){return new vt(await super._call(P))}}class Sw extends R{}class $w extends Sw{}class Iu extends R{}class kw extends Iu{}class Iw extends Iu{async _call(P){return new vt(await super._call(P))}}class Aw extends R{}class Fw extends Aw{async _call(P){return new L0(await super._call(P))}}class Au extends R{}class Ow extends Au{}class Dw extends Au{async _call(P){return new vt(await super._call(P))}}class Fu extends R{}class Lw extends Fu{}class zw extends Fu{async _call(P){return new vt(await super._call(P))}}class Ou extends R{}class Bw extends Ou{}class Rw extends Ou{}class Du extends R{}class jw extends Du{}class Nw extends Du{}class Lu extends R{}class Vw extends Lu{}class Uw extends Lu{async _call(P){return new vt(await super._call(P))}}class qi extends R{}class Ww extends qi{}class Gw extends qi{async _call(P){return new Bu(await super._call(P))}}class zu extends qi{async _call(P){return new Kw(await super._call(P))}}class Bu extends de{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class Kw extends de{constructor({logits:P,pred_boxes:D,pred_masks:ne}){super(),this.logits=P,this.pred_boxes=D,this.pred_masks=ne}}class Ru extends R{}class Hw extends Ru{}class qw extends Ru{async _call(P){return new Qi(await super._call(P))}}class Qi extends de{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class ju extends R{}class Qw extends ju{}class Xw extends ju{async _call(P){return new Jw(await super._call(P))}}class Jw extends Qi{}class Nu extends R{}class Yw extends Nu{}class Zw extends Nu{async _call(P){return new eM(await super._call(P))}}class eM extends Qi{}class Vu extends R{}class tM extends Vu{}class rM extends Vu{async _call(P){return new sM(await super._call(P))}}class sM extends Bu{}class Uu extends R{}class nM extends Uu{}class oM extends Uu{async _call(P){return new vt(await super._call(P))}}class Wu extends R{}class iM extends Wu{}class aM extends Wu{async _call(P){return new vt(await super._call(P))}}class Gu extends R{}class lM extends Gu{}class uM extends Gu{async _call(P){return new vt(await super._call(P))}}class Xi extends R{}class cM extends Xi{}class dM extends Xi{async _call(P){return new vt(await super._call(P))}}class pM extends Xi{}class Ku extends R{}class hM extends Ku{}class mM extends Ku{}class Hu extends R{}class fM extends Hu{}class _M extends Hu{}class gM extends R{}class wM extends gM{}class Ji extends R{}class MM extends Ji{}class bM extends Ji{}class yM extends Ji{}class vM extends R{}class xM extends vM{}class TM extends R{}class EM extends TM{}class PM extends R{}class CM extends PM{}class qu extends R{}class SM extends qu{}class $M extends qu{}class Qu extends R{}class kM extends Qu{}class IM extends Qu{}class AM extends R{}class FM extends AM{}class Xu extends R{}class OM extends Xu{}class DM extends Xu{async _call(P){return new vt(await super._call(P))}}class Ju extends R{}class LM extends Ju{}class zM extends Ju{async _call(P){return new vt(await super._call(P))}}class Yu extends R{}class BM extends Yu{}class RM extends Yu{async _call(P){return new vt(await super._call(P))}}class Zu extends R{}class jM extends Zu{}class NM extends Zu{async _call(P){return new vt(await super._call(P))}}class VM extends R{}class UM extends VM{}class ec extends R{}class WM extends ec{}class GM extends ec{async _call(P){return new KM(await super._call(P))}}class KM extends de{constructor({logits:P,pred_boxes:D}){super(),this.logits=P,this.pred_boxes=D}}class HM extends R{}class qM extends HM{async get_image_embeddings({pixel_values:P}){return await Q(this,{pixel_values:P})}async forward(P){if((!P.image_embeddings||!P.image_positional_embeddings)&&(P={...P,...await this.get_image_embeddings(P)}),!P.input_labels&&P.input_points){const ne=P.input_points.dims.slice(0,-1),ge=ne.reduce((_e,Ee)=>_e*Ee,1);P.input_labels=new d.Tensor("int64",new BigInt64Array(ge).fill(1n),ne)}const D={image_embeddings:P.image_embeddings,image_positional_embeddings:P.image_positional_embeddings};return P.input_points&&(D.input_points=P.input_points),P.input_labels&&(D.input_labels=P.input_labels),P.input_boxes&&(D.input_boxes=P.input_boxes),await G(this.sessions.prompt_encoder_mask_decoder,D)}async _call(P){return new QM(await super._call(P))}}class QM extends de{constructor({iou_scores:P,pred_masks:D}){super(),this.iou_scores=P,this.pred_masks=D}}class tc extends R{}class XM extends tc{}class JM extends tc{}class rc extends R{}class YM extends rc{}class ZM extends rc{}class Zs extends R{}class eb extends Zs{}class tb extends Zs{async _call(P){return new In(await super._call(P))}}class rb extends Zs{async _call(P){return new vt(await super._call(P))}}class sb extends Zs{async _call(P){return new Pr(await super._call(P))}}class sc extends R{}class nb extends sc{}class ob extends sc{async _call(P){return new Pr(await super._call(P))}}class ib extends R{}class ab extends ib{}class Yi extends R{}class lb extends Yi{}class ub extends Yi{async _call(P){return new In(await super._call(P))}}class cb extends Yi{async _call(P){return new vt(await super._call(P))}}class Xo extends R{}class db extends Xo{}class pb extends Xo{async _call(P){return new In(await super._call(P))}}class hb extends Xo{async _call(P){return new vt(await super._call(P))}}class mb extends Xo{async _call(P){return new Pr(await super._call(P))}}class Zi extends R{}class fb extends Zi{}class _b extends Zi{async _call(P){return new In(await super._call(P))}}class gb extends Zi{async _call(P){return new vt(await super._call(P))}}class Ax extends R{}class wb extends Zs{}class Mb extends Zs{async _call(P){return new In(await super._call(P))}}class bb extends Zs{async _call(P){return new vt(await super._call(P))}}class so extends R{}class yb extends so{}class vb extends so{async _call(P){return new In(await super._call(P))}}class xb extends so{async _call(P){return new vt(await super._call(P))}}class Tb extends so{async _call(P){return new D0(await super._call(P))}}class Eb extends so{async _call(P){return new Pr(await super._call(P))}}class Pb extends R{}class Cb extends Pb{}class ea extends R{}class Fx extends ea{}class Sb extends ea{}class $b extends ea{async generate_speech(P,D,{threshold:ne=.5,minlenratio:ge=0,maxlenratio:_e=20,vocoder:Ee=null}={}){const Oe={input_ids:P},{encoder_outputs:je,encoder_attention_mask:Je}=await Q(this,Oe),ht=je.dims[1]/this.config.reduction_factor,Mt=Math.floor(ht*_e),pt=Math.floor(ht*ge),Pt=this.config.num_mel_bins;let wt=[],Et=null,it=null,$t=0;for(;;){++$t;const ur=H(!!it);let nr;it?nr=it.output_sequence_out:nr=new d.Tensor("float32",new Float32Array(Pt),[1,1,Pt]);let _r={use_cache_branch:ur,output_sequence:nr,encoder_attention_mask:Je,speaker_embeddings:D,encoder_hidden_states:je};this.addPastKeyValues(_r,Et),it=await G(this.sessions.decoder_model_merged,_r),Et=this.getPastKeyValues(it,Et);const{prob:Cr,spectrum:Ct}=it;if(wt.push(Ct),$t>=pt&&(Array.from(Cr.data).filter(wr=>wr>=ne).length>0||$t>=Mt))break}const Ht=(0,d.cat)(wt),{waveform:er}=await G(Ee.sessions.model,{spectrogram:Ht});return{spectrogram:Ht,waveform:er}}}class kb extends R{constructor(){super(...arguments);Z(this,"main_input_name","spectrogram")}}class Ib extends R{}class Ab extends Ib{}class nc extends R{}class Fb extends nc{}class Ob extends nc{}class oc extends R{}class Db extends oc{}class Lb extends oc{}class ic extends R{}class zb extends ic{}class Bb extends ic{}class ta extends R{}class Rb extends ta{}class jb extends ta{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"text_model"})}}class Nb extends ta{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"audio_model"})}}class Vb extends R{}class ac extends Vb{async _call(P){return new z0(await super._call(P))}}class ra extends R{}class Ox extends ra{}class Ub extends ra{}class Wb extends ra{}class lc extends R{}class Gb extends lc{}class Kb extends lc{}class uc extends R{}class Hb extends uc{}class qb extends uc{async _call(P){return new vt(await super._call(P))}}class cc extends R{}class Dx extends cc{}class Lx extends cc{}class dc extends R{constructor(){super(...arguments);Z(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}_apply_and_filter_by_delay_pattern_mask(D){const[ne,ge]=D.dims,_e=this.config.decoder.num_codebooks,Ee=ge-_e;let Oe=0;for(let ht=0;ht0&&Pt<=Ee&&(D.data[Oe++]=D.data[ht])}const je=Math.floor(ne/_e),Je=Oe/(je*_e);return new d.Tensor(D.type,D.data.slice(0,Oe),[je,_e,Je])}prepare_inputs_for_generation(D,ne,ge){let _e=structuredClone(D);for(let Oe=0;Oe<_e.length;++Oe)for(let je=0;je<_e[Oe].length;++je)Oe%this.config.decoder.num_codebooks>=je&&(_e[Oe][je]=BigInt(this.config.decoder.pad_token_id));return ge.guidance_scale!==null&&ge.guidance_scale>1&&(_e=_e.concat(_e)),super.prepare_inputs_for_generation(_e,ne,ge)}async generate(D){const ne=await super.generate(D),ge=this._apply_and_filter_by_delay_pattern_mask(ne).unsqueeze_(0),{audio_values:_e}=await G(this.sessions.encodec_decode,{audio_codes:ge});return _e}}class sa extends R{}class Qb extends sa{}class Xb extends sa{async _call(P){return new vt(await super._call(P))}}class Jb extends sa{}class na extends R{}class Yb extends na{}class Zb extends na{async _call(P){return new vt(await super._call(P))}}class ey extends na{}class oa extends R{}class ty extends oa{}class ry extends oa{async _call(P){return new vt(await super._call(P))}}class sy extends oa{}class ia extends R{}class ny extends ia{}class oy extends ia{async _call(P){return new vt(await super._call(P))}}class iy extends ia{}class ay extends R{}class ly extends ay{}class uy extends R{}class cy extends uy{constructor(...D){super(...D);Z(this,"forward_params",["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"]);this._generation_mode="text"}async forward(D){const ne=this._generation_mode??"text";let ge;if(ne==="text"||!D.past_key_values){const Je=this.sessions.prepare_inputs_embeds,ht=(0,a.pick)(D,Je.inputNames);ge=await G(Je,ht)}else{const Je=this.sessions.gen_img_embeds,ht=(0,a.pick)({image_ids:D.input_ids},Je.inputNames);ge=await G(Je,ht)}const _e={...D,...ge},Ee=await he(this,_e),Oe=this.sessions[ne==="text"?"lm_head":"gen_head"];if(!Oe)throw new Error(`Unable to find "${Oe}" generation head`);const je=await G(Oe,(0,a.pick)(Ee,Oe.inputNames));return{...ge,...Ee,...je}}async generate(D){return this._generation_mode="text",super.generate(D)}async generate_images(D){this._generation_mode="image";const ne=(D.inputs??D[this.main_input_name]).dims[1],_e=(await super.generate(D)).slice(null,[ne,null]),Ee=this.sessions.image_decode,{decoded_image:Oe}=await G(Ee,{generated_tokens:_e}),je=Oe.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Je=[];for(const ht of je){const Mt=_.RawImage.fromTensor(ht);Je.push(Mt)}return Je}}class dy extends de{constructor({char_logits:P,bpe_logits:D,wp_logits:ne}){super(),this.char_logits=P,this.bpe_logits=D,this.wp_logits=ne}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class py extends R{}class hy extends py{async _call(P){return new dy(await super._call(P))}}class pc extends R{}class my extends pc{}class fy extends pc{}class hc extends R{}class _y extends hc{}class gy extends hc{}class wy extends R{constructor(){super(...arguments);Z(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class My extends wy{_merge_input_ids_with_audio_features(P){const D=P.audio_features.dims.at(-1),ne=P.audio_features.view(-1,D);return F({audio_token_id:this.config.ignore_index,...P,audio_features:ne})}}class aa extends R{constructor(){super(...arguments);Z(this,"main_input_name","input_values");Z(this,"forward_params",["input_values"])}}class by extends de{constructor({audio_codes:P}){super(),this.audio_codes=P}}class yy extends de{constructor({audio_values:P}){super(),this.audio_values=P}}class vy extends aa{async encode(P){return new by(await G(this.sessions.encoder_model,P))}async decode(P){return new yy(await G(this.sessions.decoder_model,P))}}class xy extends aa{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class Ty extends aa{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class la extends R{constructor(){super(...arguments);Z(this,"main_input_name","input_values");Z(this,"forward_params",["input_values"])}}class Ey extends de{constructor({audio_codes:P}){super(),this.audio_codes=P}}class Py extends de{constructor({audio_values:P}){super(),this.audio_values=P}}class Cy extends la{async encode(P){return new Ey(await G(this.sessions.encoder_model,P))}async decode(P){return new Py(await G(this.sessions.decoder_model,P))}}class Sy extends la{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class $y extends la{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class ua extends R{constructor(){super(...arguments);Z(this,"main_input_name","input_values");Z(this,"forward_params",["input_values"])}}class ky extends ua{async encode(P){return await G(this.sessions.encoder_model,P)}async decode(P){return await G(this.sessions.decoder_model,P)}}class Iy extends ua{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"encoder_model"})}}class Ay extends ua{static async from_pretrained(P,D={}){return super.from_pretrained(P,{...D,model_file_name:D.model_file_name??"decoder_model"})}}class zt{static async from_pretrained(P,{progress_callback:D=null,config:ne=null,cache_dir:ge=null,local_files_only:_e=!1,revision:Ee="main",model_file_name:Oe=null,subfolder:je="onnx",device:Je=null,dtype:ht=null,use_external_data_format:Mt=null,session_options:pt={}}={}){const Pt={progress_callback:D,config:ne,cache_dir:ge,local_files_only:_e,revision:Ee,model_file_name:Oe,subfolder:je,device:Je,dtype:ht,use_external_data_format:Mt,session_options:pt};if(Pt.config=await s.AutoConfig.from_pretrained(P,Pt),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const wt=Pt.config.model_type;for(const Et of this.MODEL_CLASS_MAPPINGS){let it=Et.get(wt);if(!it){for(const $t of Et.values())if($t[0]===wt){it=$t;break}if(!it)continue}return await it[1].from_pretrained(P,Pt)}if(this.BASE_IF_FAIL)return n0.has(wt)||console.warn(`Unknown model class "${wt}", attempting to construct from base class.`),await R.from_pretrained(P,Pt);throw Error(`Unsupported model type: ${wt}`)}}Z(zt,"MODEL_CLASS_MAPPINGS",null),Z(zt,"BASE_IF_FAIL",!1);const zx=new Map([["bert",["BertModel",Ce]],["modernbert",["ModernBertModel",Ye]],["nomic_bert",["NomicBertModel",ut]],["roformer",["RoFormerModel",Re]],["electra",["ElectraModel",Tt]],["esm",["EsmModel",ys]],["convbert",["ConvBertModel",se]],["camembert",["CamembertModel",Gt]],["deberta",["DebertaModel",rs]],["deberta-v2",["DebertaV2Model",Cs]],["mpnet",["MPNetModel",mn]],["albert",["AlbertModel",vn]],["distilbert",["DistilBertModel",ar]],["roberta",["RobertaModel",Qr]],["xlm",["XLMModel",Hs]],["xlm-roberta",["XLMRobertaModel",Ei]],["clap",["ClapModel",Rb]],["clip",["CLIPModel",Ni]],["clipseg",["CLIPSegModel",Lo]],["chinese_clip",["ChineseCLIPModel",Gi]],["siglip",["SiglipModel",En]],["jina_clip",["JinaCLIPModel",Hn]],["mobilebert",["MobileBertModel",vr]],["squeezebert",["SqueezeBertModel",Mn]],["wav2vec2",["Wav2Vec2Model",eb]],["wav2vec2-bert",["Wav2Vec2BertModel",fb]],["unispeech",["UniSpeechModel",lb]],["unispeech-sat",["UniSpeechSatModel",db]],["hubert",["HubertModel",wb]],["wavlm",["WavLMModel",yb]],["audio-spectrogram-transformer",["ASTModel",ki]],["vits",["VitsModel",ac]],["pyannote",["PyAnnoteModel",nb]],["wespeaker-resnet",["WeSpeakerResNetModel",ab]],["detr",["DetrModel",Ww]],["rt_detr",["RTDetrModel",Hw]],["rt_detr_v2",["RTDetrV2Model",Qw]],["rf_detr",["RFDetrModel",Yw]],["table-transformer",["TableTransformerModel",tM]],["vit",["ViTModel",_w]],["ijepa",["IJepaModel",ww]],["pvt",["PvtModel",vw]],["vit_msn",["ViTMSNModel",Pw]],["vit_mae",["ViTMAEModel",Ew]],["groupvit",["GroupViTModel",$w]],["fastvit",["FastViTModel",kw]],["mobilevit",["MobileViTModel",Ow]],["mobilevitv2",["MobileViTV2Model",Lw]],["owlvit",["OwlViTModel",Bw]],["owlv2",["Owlv2Model",jw]],["beit",["BeitModel",Vw]],["deit",["DeiTModel",nM]],["hiera",["HieraModel",iM]],["convnext",["ConvNextModel",OM]],["convnextv2",["ConvNextV2Model",LM]],["dinov2",["Dinov2Model",BM]],["dinov2_with_registers",["Dinov2WithRegistersModel",jM]],["resnet",["ResNetModel",lM]],["swin",["SwinModel",cM]],["swin2sr",["Swin2SRModel",hM]],["donut-swin",["DonutSwinModel",FM]],["yolos",["YolosModel",WM]],["dpt",["DPTModel",fM]],["glpn",["GLPNModel",kM]],["hifigan",["SpeechT5HifiGan",kb]],["efficientnet",["EfficientNetModel",Hb]],["decision_transformer",["DecisionTransformerModel",ly]],["patchtst",["PatchTSTForPrediction",my]],["patchtsmixer",["PatchTSMixerForPrediction",_y]],["mobilenet_v1",["MobileNetV1Model",Qb]],["mobilenet_v2",["MobileNetV2Model",Yb]],["mobilenet_v3",["MobileNetV3Model",ty]],["mobilenet_v4",["MobileNetV4Model",ny]],["maskformer",["MaskFormerModel",SM]],["mgp-str",["MgpstrForSceneTextRecognition",hy]],["style_text_to_speech_2",["StyleTextToSpeech2Model",Cb]]]),Bx=new Map([["t5",["T5Model",ie]],["longt5",["LongT5Model",Be]],["mt5",["MT5Model",et]],["bart",["BartModel",Lt]],["mbart",["MBartModel",Or]],["marian",["MarianModel",XM]],["whisper",["WhisperModel",Ai]],["m2m_100",["M2M100Model",YM]],["blenderbot",["BlenderbotModel",Kt]],["blenderbot-small",["BlenderbotSmallModel",is]]]),Rx=new Map([["mimi",["MimiModel",vy]],["dac",["DacModel",Cy]],["snac",["SnacModel",ky]]]),jx=new Map([["bloom",["BloomModel",cw]],["jais",["JAISModel",Pn]],["gpt2",["GPT2Model",Ki]],["gptj",["GPTJModel",Vo]],["gpt_bigcode",["GPTBigCodeModel",Yn]],["gpt_neo",["GPTNeoModel",jo]],["gpt_neox",["GPTNeoXModel",Xr]],["codegen",["CodeGenModel",Go]],["llama",["LlamaModel",eo]],["exaone",["ExaoneModel",I]],["olmo",["OlmoModel",He]],["olmo2",["Olmo2Model",Ft]],["mobilellm",["MobileLLMModel",le]],["granite",["GraniteModel",js]],["cohere",["CohereModel",Wg]],["gemma",["GemmaModel",Kg]],["gemma2",["Gemma2Model",qg]],["gemma3_text",["Gemma3Model",Xg]],["helium",["HeliumModel",Ho]],["glm",["GlmModel",Qo]],["openelm",["OpenELMModel",Yg]],["qwen2",["Qwen2Model",ew]],["qwen3",["Qwen3Model",rw]],["phi",["PhiModel",iw]],["phi3",["Phi3Model",lw]],["mpt",["MptModel",pw]],["opt",["OPTModel",mw]],["mistral",["MistralModel",Fb]],["starcoder2",["Starcoder2Model",Db]],["falcon",["FalconModel",zb]],["stablelm",["StableLmModel",Gb]]]),mc=new Map([["speecht5",["SpeechT5ForSpeechToText",Sb]],["whisper",["WhisperForConditionalGeneration",Po]],["lite-whisper",["LiteWhisperForConditionalGeneration",Fi]],["moonshine",["MoonshineForConditionalGeneration",Co]]]),Fy=new Map([["speecht5",["SpeechT5ForTextToSpeech",$b]]]),Oy=new Map([["vits",["VitsModel",ac]],["musicgen",["MusicgenForConditionalGeneration",dc]]]),Dy=new Map([["bert",["BertForSequenceClassification",$e]],["modernbert",["ModernBertForSequenceClassification",Ze]],["roformer",["RoFormerForSequenceClassification",St]],["electra",["ElectraForSequenceClassification",mt]],["esm",["EsmForSequenceClassification",Fr]],["convbert",["ConvBertForSequenceClassification",re]],["camembert",["CamembertForSequenceClassification",ir]],["deberta",["DebertaForSequenceClassification",ws]],["deberta-v2",["DebertaV2ForSequenceClassification",ns]],["mpnet",["MPNetForSequenceClassification",_n]],["albert",["AlbertForSequenceClassification",pe]],["distilbert",["DistilBertForSequenceClassification",De]],["roberta",["RobertaForSequenceClassification",Zt]],["xlm",["XLMForSequenceClassification",vi]],["xlm-roberta",["XLMRobertaForSequenceClassification",Ci]],["bart",["BartForSequenceClassification",Vt]],["mbart",["MBartForSequenceClassification",Er]],["mobilebert",["MobileBertForSequenceClassification",xr]],["squeezebert",["SqueezeBertForSequenceClassification",bn]]]),Ly=new Map([["bert",["BertForTokenClassification",Le]],["modernbert",["ModernBertForTokenClassification",Xe]],["roformer",["RoFormerForTokenClassification",at]],["electra",["ElectraForTokenClassification",Ge]],["esm",["EsmForTokenClassification",ks]],["convbert",["ConvBertForTokenClassification",fe]],["camembert",["CamembertForTokenClassification",Ar]],["deberta",["DebertaForTokenClassification",Ps]],["deberta-v2",["DebertaV2ForTokenClassification",Ms]],["mpnet",["MPNetForTokenClassification",gn]],["distilbert",["DistilBertForTokenClassification",qe]],["roberta",["RobertaForTokenClassification",dr]],["xlm",["XLMForTokenClassification",xi]],["xlm-roberta",["XLMRobertaForTokenClassification",Si]]]),fc=new Map([["t5",["T5ForConditionalGeneration",ce]],["longt5",["LongT5ForConditionalGeneration",Qe]],["mt5",["MT5ForConditionalGeneration",gt]],["bart",["BartForConditionalGeneration",Jt]],["mbart",["MBartForConditionalGeneration",Tr]],["marian",["MarianMTModel",JM]],["m2m_100",["M2M100ForConditionalGeneration",ZM]],["blenderbot",["BlenderbotForConditionalGeneration",mr]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",qr]]]),_c=new Map([["bloom",["BloomForCausalLM",dw]],["gpt2",["GPT2LMHeadModel",Bo]],["jais",["JAISLMHeadModel",dt]],["gptj",["GPTJForCausalLM",Uo]],["gpt_bigcode",["GPTBigCodeForCausalLM",Wo]],["gpt_neo",["GPTNeoForCausalLM",No]],["gpt_neox",["GPTNeoXForCausalLM",Cn]],["codegen",["CodeGenForCausalLM",$n]],["llama",["LlamaForCausalLM",Ko]],["exaone",["ExaoneForCausalLM",L]],["olmo",["OlmoForCausalLM",st]],["olmo2",["Olmo2ForCausalLM",Ut]],["mobilellm",["MobileLLMForCausalLM",xe]],["granite",["GraniteForCausalLM",Hi]],["cohere",["CohereForCausalLM",Gg]],["gemma",["GemmaForCausalLM",Hg]],["gemma2",["Gemma2ForCausalLM",Qg]],["gemma3_text",["Gemma3ForCausalLM",Jg]],["helium",["HeliumForCausalLM",qo]],["glm",["GlmForCausalLM",h]],["openelm",["OpenELMForCausalLM",Zg]],["qwen2",["Qwen2ForCausalLM",tw]],["qwen3",["Qwen3ForCausalLM",sw]],["phi",["PhiForCausalLM",aw]],["phi3",["Phi3ForCausalLM",uw]],["mpt",["MptForCausalLM",hw]],["opt",["OPTForCausalLM",fw]],["mbart",["MBartForCausalLM",Yt]],["mistral",["MistralForCausalLM",Ob]],["starcoder2",["Starcoder2ForCausalLM",Lb]],["falcon",["FalconForCausalLM",Bb]],["trocr",["TrOCRForCausalLM",Ab]],["stablelm",["StableLmForCausalLM",Kb]],["phi3_v",["Phi3VForCausalLM",Io]]]),Nx=new Map([["multi_modality",["MultiModalityCausalLM",cy]]]),zy=new Map([["bert",["BertForMaskedLM",Se]],["modernbert",["ModernBertForMaskedLM",ke]],["roformer",["RoFormerForMaskedLM",_t]],["electra",["ElectraForMaskedLM",Nt]],["esm",["EsmForMaskedLM",$s]],["convbert",["ConvBertForMaskedLM",B]],["camembert",["CamembertForMaskedLM",Ot]],["deberta",["DebertaForMaskedLM",Es]],["deberta-v2",["DebertaV2ForMaskedLM",Ss]],["mpnet",["MPNetForMaskedLM",fn]],["albert",["AlbertForMaskedLM",N]],["distilbert",["DistilBertForMaskedLM",Qt]],["roberta",["RobertaForMaskedLM",gr]],["xlm",["XLMWithLMHeadModel",xn]],["xlm-roberta",["XLMRobertaForMaskedLM",Pi]],["mobilebert",["MobileBertForMaskedLM",zs]],["squeezebert",["SqueezeBertForMaskedLM",Ks]]]),By=new Map([["bert",["BertForQuestionAnswering",Ie]],["roformer",["RoFormerForQuestionAnswering",jt]],["electra",["ElectraForQuestionAnswering",ct]],["convbert",["ConvBertForQuestionAnswering",Ae]],["camembert",["CamembertForQuestionAnswering",ts]],["deberta",["DebertaForQuestionAnswering",ss]],["deberta-v2",["DebertaV2ForQuestionAnswering",bs]],["mpnet",["MPNetForQuestionAnswering",wn]],["albert",["AlbertForQuestionAnswering",$]],["distilbert",["DistilBertForQuestionAnswering",nt]],["roberta",["RobertaForQuestionAnswering",pr]],["xlm",["XLMForQuestionAnswering",Ti]],["xlm-roberta",["XLMRobertaForQuestionAnswering",$i]],["mobilebert",["MobileBertForQuestionAnswering",$r]],["squeezebert",["SqueezeBertForQuestionAnswering",yn]]]),gc=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",So]],["idefics3",["Idefics3ForConditionalGeneration",Qs]],["smolvlm",["SmolVLMForConditionalGeneration",Kn]]]),Ry=new Map([["llava",["LlavaForConditionalGeneration",Tn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",$o]],["moondream1",["Moondream1ForConditionalGeneration",qs]],["florence2",["Florence2ForConditionalGeneration",ko]],["qwen2-vl",["Qwen2VLForConditionalGeneration",ow]],["idefics3",["Idefics3ForConditionalGeneration",Qs]],["smolvlm",["SmolVLMForConditionalGeneration",Kn]],["paligemma",["PaliGemmaForConditionalGeneration",Bi]]]),jy=new Map([["ultravox",["UltravoxModel",My]]]),Vx=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",So]]]),Ny=new Map([["vit",["ViTForImageClassification",gw]],["ijepa",["IJepaForImageClassification",Mw]],["pvt",["PvtForImageClassification",xw]],["vit_msn",["ViTMSNForImageClassification",Cw]],["fastvit",["FastViTForImageClassification",Iw]],["mobilevit",["MobileViTForImageClassification",Dw]],["mobilevitv2",["MobileViTV2ForImageClassification",zw]],["beit",["BeitForImageClassification",Uw]],["deit",["DeiTForImageClassification",oM]],["hiera",["HieraForImageClassification",aM]],["convnext",["ConvNextForImageClassification",DM]],["convnextv2",["ConvNextV2ForImageClassification",zM]],["dinov2",["Dinov2ForImageClassification",RM]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",NM]],["resnet",["ResNetForImageClassification",uM]],["swin",["SwinForImageClassification",dM]],["segformer",["SegformerForImageClassification",Ub]],["efficientnet",["EfficientNetForImageClassification",qb]],["mobilenet_v1",["MobileNetV1ForImageClassification",Xb]],["mobilenet_v2",["MobileNetV2ForImageClassification",Zb]],["mobilenet_v3",["MobileNetV3ForImageClassification",ry]],["mobilenet_v4",["MobileNetV4ForImageClassification",oy]]]),Vy=new Map([["detr",["DetrForObjectDetection",Gw]],["rt_detr",["RTDetrForObjectDetection",qw]],["rt_detr_v2",["RTDetrV2ForObjectDetection",Xw]],["rf_detr",["RFDetrForObjectDetection",Zw]],["table-transformer",["TableTransformerForObjectDetection",rM]],["yolos",["YolosForObjectDetection",GM]]]),Uy=new Map([["owlvit",["OwlViTForObjectDetection",Rw]],["owlv2",["Owlv2ForObjectDetection",Nw]],["grounding-dino",["GroundingDinoForObjectDetection",UM]]]),no=new Map([["detr",["DetrForSegmentation",zu]],["clipseg",["CLIPSegForImageSegmentation",zo]]]),Wy=new Map([["segformer",["SegformerForSemanticSegmentation",Wb]],["sapiens",["SapiensForSemanticSegmentation",MM]],["swin",["SwinForSemanticSegmentation",pM]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",Jb]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",ey]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",sy]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",iy]]]),Gy=new Map([["detr",["DetrForSegmentation",zu]],["maskformer",["MaskFormerForInstanceSegmentation",$M]]]),Ky=new Map([["sam",["SamModel",qM]]]),Hy=new Map([["wav2vec2",["Wav2Vec2ForCTC",tb]],["wav2vec2-bert",["Wav2Vec2BertForCTC",_b]],["unispeech",["UniSpeechForCTC",ub]],["unispeech-sat",["UniSpeechSatForCTC",pb]],["wavlm",["WavLMForCTC",vb]],["hubert",["HubertForCTC",Mb]]]),qy=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",rb]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",gb]],["unispeech",["UniSpeechForSequenceClassification",cb]],["unispeech-sat",["UniSpeechSatForSequenceClassification",hb]],["wavlm",["WavLMForSequenceClassification",xb]],["hubert",["HubertForSequenceClassification",bb]],["audio-spectrogram-transformer",["ASTForAudioClassification",Ii]]]),Qy=new Map([["wavlm",["WavLMForXVector",Tb]]]),Xy=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",mb]],["wavlm",["WavLMForAudioFrameClassification",Eb]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",sb]],["pyannote",["PyAnnoteForAudioFrameClassification",ob]]]),Jy=new Map([["vitmatte",["VitMatteForImageMatting",Fw]]]),Ux=new Map([["patchtst",["PatchTSTForPrediction",fy]],["patchtsmixer",["PatchTSMixerForPrediction",gy]]]),Yy=new Map([["swin2sr",["Swin2SRForImageSuperResolution",mM]]]),Zy=new Map([["dpt",["DPTForDepthEstimation",_M]],["depth_anything",["DepthAnythingForDepthEstimation",wM]],["glpn",["GLPNForDepthEstimation",IM]],["sapiens",["SapiensForDepthEstimation",bM]],["depth_pro",["DepthProForDepthEstimation",xM]],["metric3d",["Metric3DForDepthEstimation",EM]],["metric3dv2",["Metric3Dv2ForDepthEstimation",CM]]]),e0=new Map([["sapiens",["SapiensForNormalEstimation",yM]]]),t0=new Map([["vitpose",["VitPoseForPoseEstimation",yw]]]),r0=new Map([["clip",["CLIPVisionModelWithProjection",Ui]],["siglip",["SiglipVisionModel",Fo]],["jina_clip",["JinaCLIPVisionModel",Do]]]),s0=[[zx,E.EncoderOnly],[Bx,E.EncoderDecoder],[jx,E.DecoderOnly],[Rx,E.AutoEncoder],[Dy,E.EncoderOnly],[Ly,E.EncoderOnly],[fc,E.Seq2Seq],[mc,E.Seq2Seq],[_c,E.DecoderOnly],[Nx,E.MultiModality],[zy,E.EncoderOnly],[By,E.EncoderOnly],[gc,E.Vision2Seq],[Ry,E.ImageTextToText],[jy,E.AudioTextToText],[Ny,E.EncoderOnly],[no,E.EncoderOnly],[Gy,E.EncoderOnly],[Wy,E.EncoderOnly],[Jy,E.EncoderOnly],[Ux,E.EncoderOnly],[Yy,E.EncoderOnly],[Zy,E.EncoderOnly],[e0,E.EncoderOnly],[t0,E.EncoderOnly],[Vy,E.EncoderOnly],[Uy,E.EncoderOnly],[Ky,E.MaskGeneration],[Hy,E.EncoderOnly],[qy,E.EncoderOnly],[Fy,E.Seq2Seq],[Oy,E.EncoderOnly],[Qy,E.EncoderOnly],[Xy,E.EncoderOnly],[r0,E.EncoderOnly]];for(const[b,P]of s0)for(const[D,ne]of b.values())y.set(D,P),v.set(ne,D),M.set(D,ne);const Wx=[["MusicgenForConditionalGeneration",dc,E.Musicgen],["Phi3VForCausalLM",Io,E.Phi3V],["CLIPTextModelWithProjection",Vi,E.EncoderOnly],["SiglipTextModel",Xs,E.EncoderOnly],["JinaCLIPTextModel",Oo,E.EncoderOnly],["ClapTextModelWithProjection",jb,E.EncoderOnly],["ClapAudioModelWithProjection",Nb,E.EncoderOnly],["DacEncoderModel",Sy,E.EncoderOnly],["DacDecoderModel",$y,E.EncoderOnly],["MimiEncoderModel",xy,E.EncoderOnly],["MimiDecoderModel",Ty,E.EncoderOnly],["SnacEncoderModel",Iy,E.EncoderOnly],["SnacDecoderModel",Ay,E.EncoderOnly]];for(const[b,P,D]of Wx)y.set(b,D),v.set(P,b),M.set(b,P);const n0=new Map([["modnet",no],["birefnet",no],["isnet",no],["ben",no]]);for(const[b,P]of n0.entries())P.set(b,["PreTrainedModel",R]),y.set(b,E.EncoderOnly),v.set(R,b),M.set(b,R);class wc extends zt{}Z(wc,"MODEL_CLASS_MAPPINGS",s0.map(P=>P[0])),Z(wc,"BASE_IF_FAIL",!0);class o0 extends zt{}Z(o0,"MODEL_CLASS_MAPPINGS",[Dy]);class i0 extends zt{}Z(i0,"MODEL_CLASS_MAPPINGS",[Ly]);class a0 extends zt{}Z(a0,"MODEL_CLASS_MAPPINGS",[fc]);class l0 extends zt{}Z(l0,"MODEL_CLASS_MAPPINGS",[mc]);class u0 extends zt{}Z(u0,"MODEL_CLASS_MAPPINGS",[Fy]);class c0 extends zt{}Z(c0,"MODEL_CLASS_MAPPINGS",[Oy]);class d0 extends zt{}Z(d0,"MODEL_CLASS_MAPPINGS",[_c]);class p0 extends zt{}Z(p0,"MODEL_CLASS_MAPPINGS",[zy]);class h0 extends zt{}Z(h0,"MODEL_CLASS_MAPPINGS",[By]);class m0 extends zt{}Z(m0,"MODEL_CLASS_MAPPINGS",[gc]);class f0 extends zt{}Z(f0,"MODEL_CLASS_MAPPINGS",[Ny]);class _0 extends zt{}Z(_0,"MODEL_CLASS_MAPPINGS",[no]);class g0 extends zt{}Z(g0,"MODEL_CLASS_MAPPINGS",[Wy]);class w0 extends zt{}Z(w0,"MODEL_CLASS_MAPPINGS",[Gy]);class M0 extends zt{}Z(M0,"MODEL_CLASS_MAPPINGS",[Vy]);class b0 extends zt{}Z(b0,"MODEL_CLASS_MAPPINGS",[Uy]);class y0 extends zt{}Z(y0,"MODEL_CLASS_MAPPINGS",[Ky]);class v0 extends zt{}Z(v0,"MODEL_CLASS_MAPPINGS",[Hy]);class x0 extends zt{}Z(x0,"MODEL_CLASS_MAPPINGS",[qy]);class T0 extends zt{}Z(T0,"MODEL_CLASS_MAPPINGS",[Qy]);class E0 extends zt{}Z(E0,"MODEL_CLASS_MAPPINGS",[Xy]);class P0 extends zt{}Z(P0,"MODEL_CLASS_MAPPINGS",[Vx]);class C0 extends zt{}Z(C0,"MODEL_CLASS_MAPPINGS",[Jy]);class S0 extends zt{}Z(S0,"MODEL_CLASS_MAPPINGS",[Yy]);class $0 extends zt{}Z($0,"MODEL_CLASS_MAPPINGS",[Zy]);class k0 extends zt{}Z(k0,"MODEL_CLASS_MAPPINGS",[e0]);class I0 extends zt{}Z(I0,"MODEL_CLASS_MAPPINGS",[t0]);class A0 extends zt{}Z(A0,"MODEL_CLASS_MAPPINGS",[r0]);class F0 extends zt{}Z(F0,"MODEL_CLASS_MAPPINGS",[Ry]);class O0 extends zt{}Z(O0,"MODEL_CLASS_MAPPINGS",[jy]);class Gx extends de{constructor({logits:P,past_key_values:D,encoder_outputs:ne,decoder_attentions:ge=null,cross_attentions:_e=null}){super(),this.logits=P,this.past_key_values=D,this.encoder_outputs=ne,this.decoder_attentions=ge,this.cross_attentions=_e}}class vt extends de{constructor({logits:P,...D}){super(),this.logits=P;const ne=Object.values(D);ne.length>0&&(this.attentions=ne)}}class D0 extends de{constructor({logits:P,embeddings:D}){super(),this.logits=P,this.embeddings=D}}class Pr extends de{constructor({logits:P}){super(),this.logits=P}}class Ir extends de{constructor({logits:P}){super(),this.logits=P}}class Lr extends de{constructor({start_logits:P,end_logits:D}){super(),this.start_logits=P,this.end_logits=D}}class In extends de{constructor({logits:P}){super(),this.logits=P}}class Kx extends de{constructor({logits:P,past_key_values:D}){super(),this.logits=P,this.past_key_values=D}}class L0 extends de{constructor({alphas:P}){super(),this.alphas=P}}class z0 extends de{constructor({waveform:P,spectrogram:D}){super(),this.waveform=P,this.spectrogram=D}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,this.window=(0,o.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(a,l){return(0,o.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:l,transpose:!0})}async _call(a){(0,s.validate_audio_inputs)(a,"ASTFeatureExtractor");const l=await this._extract_fbank_features(a,this.config.max_length);if(this.config.do_normalize){const u=this.std*2,p=l.data;for(let c=0;c{t.r(r),t.d(r,{AutoFeatureExtractor:()=>i});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var n=t("./src/models/feature_extractors.js");class i{static async from_pretrained(l,u={}){const p=await(0,o.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,u),c=p.feature_extractor_type,d=n[c];if(!d)throw new Error(`Unknown feature_extractor_type: '${c}'. 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:()=>a});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js"),n=t("./src/base/image_processors_utils.js"),i=t("./src/models/image_processors.js");class a{static async from_pretrained(u,p={}){const c=await(0,o.getModelJSON)(u,s.IMAGE_PROCESSOR_NAME,!0,p),d=c.image_processor_type??c.feature_extractor_type;let _=i[d];return _||(d!==void 0&&console.warn(`Image processor type '${d}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),_=n.ImageProcessor),new _(c)}}},"./src/models/auto/processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>u});var s=t("./src/utils/constants.js"),o=t("./src/utils/hub.js"),n=t("./src/base/processing_utils.js"),i=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class u{static async from_pretrained(c,d={}){const _=await(0,o.getModelJSON)(c,s.IMAGE_PROCESSOR_NAME,!0,d),{image_processor_type:f,feature_extractor_type:T,processor_class:k}=_;if(k&&i[k])return i[k].from_pretrained(c,d);if(!f&&!T)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const w={};if(f){const S=a[f];if(!S)throw new Error(`Unknown image_processor_type: '${f}'.`);w.image_processor=new S(_)}if(T){const S=a[T];if(S)w.image_processor=new S(_);else{const E=l[T];if(!E)throw new Error(`Unknown feature_extractor_type: '${T}'.`);w.feature_extractor=new E(_)}}const g={};return new n.Processor(g,w)}}},"./src/models/beit/image_processing_beit.js":(e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(e,r,t)=>{t.r(r),t.d(r,{ClapFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,o.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,null,"htk"),this.mel_filters_slaney=(0,o.mel_filter_bank)(this.config.nb_frequency_bins,this.config.feature_size,this.config.frequency_min,this.config.frequency_max,this.config.sampling_rate,"slaney","slaney"),this.window=(0,o.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,u,p){let c;const d=a.length-l;if(d>0)if(u==="rand_trunc"){const _=Math.floor(Math.random()*(d+1));a=a.subarray(_,_+l),c=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${u}" not implemented`);else{if(d<0){let _=new Float64Array(l);if(_.set(a),p==="repeat")for(let f=a.length;f{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>n,CLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/convnext/image_processing_convnext.js":(e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>n,ConvNextImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){var u;const l=(u=this.size)==null?void 0:u.shortest_edge;if(l===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(l<384){const p=Math.floor(l/this.crop_pct),[c,d]=this.get_resize_output_image_size(a,{shortest_edge:p});a=await a.resize(c,d,{resample:this.resample}),a=await a.center_crop(l,l)}else a=await a.resize(l,l,{resample:this.resample});return a}}class n extends o{}},"./src/models/dac/feature_extraction_dac.js":(e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>o});var s=t("./src/models/encodec/feature_extraction_encodec.js");class o extends s.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>n,DeiTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/detr/image_processing_detr.js":(e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>i,DetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(l){const u=await super._call(l),p=[u.pixel_values.dims[0],64,64],c=(0,o.full)(p,1n);return{...u,pixel_mask:c}}post_process_object_detection(...l){return(0,s.post_process_object_detection)(...l)}post_process_panoptic_segmentation(...l){return(0,s.post_process_panoptic_segmentation)(...l)}post_process_instance_segmentation(...l){return(0,s.post_process_instance_segmentation)(...l)}}class i extends n{}},"./src/models/donut/image_processing_donut.js":(e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>n,DonutImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(a,l,u,p={}){const[c,d,_]=l;let f=this.image_mean;Array.isArray(this.image_mean)||(f=new Array(_).fill(f));let T=this.image_std;Array.isArray(T)||(T=new Array(_).fill(f));const k=f.map((w,g)=>-w/T[g]);return super.pad_image(a,l,u,{center:!0,constant_values:k,...p})}}class n extends o{}},"./src/models/dpt/image_processing_dpt.js":(e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>n,DPTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/efficientnet/image_processing_efficientnet.js":(e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super(i),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(a=>a*a))}}},"./src/models/encodec/feature_extraction_encodec.js":(e,r,t)=>{t.r(r),t.d(r,{EncodecFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"EncodecFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=this.config.feature_size;if(a.length%l!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${l}).`);const u=[1,l,a.length/l];return{input_values:new o.Tensor("float32",a,u)}}}},"./src/models/feature_extractors.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>n.ClapFeatureExtractor,DacFeatureExtractor:()=>i.DacFeatureExtractor,EncodecFeatureExtractor:()=>o.EncodecFeatureExtractor,ImageFeatureExtractor:()=>T.ImageProcessor,MoonshineFeatureExtractor:()=>a.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>l.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>u.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>p.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>c.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>d.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>_.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>f.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),o=t("./src/models/encodec/feature_extraction_encodec.js"),n=t("./src/models/clap/feature_extraction_clap.js"),i=t("./src/models/dac/feature_extraction_dac.js"),a=t("./src/models/moonshine/feature_extraction_moonshine.js"),l=t("./src/models/pyannote/feature_extraction_pyannote.js"),u=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),p=t("./src/models/snac/feature_extraction_snac.js"),c=t("./src/models/speecht5/feature_extraction_speecht5.js"),d=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),_=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),f=t("./src/models/whisper/feature_extraction_whisper.js"),T=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{constructor(l,u){super(l,u);const{tasks_answer_post_processing_type:p,task_prompts_without_inputs:c,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(c??{})),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 u=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))u.push(this.task_prompts_without_inputs.get(p));else{for(const[c,d]of this.task_prompts_with_input)if(p.includes(c)){u.push(d.replaceAll("{input}",p).replaceAll(c,""));break}u.length!==l.length&&u.push(p)}return u}post_process_generation(l,u,p){const c=this.tasks_answer_post_processing_type.get(u)??"pure_text";l=l.replaceAll("","").replaceAll("","");let d;switch(c){case"pure_text":d=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const _=c==="ocr"?"quad_boxes":"bboxes",f=l.matchAll(this.regexes[_]),T=[],k=[];for(const[w,g,...S]of f)T.push(g?g.trim():T.at(-1)??""),k.push(S.map((E,y)=>(Number(E)+.5)/this.size_per_bin*p[y%2]));d={labels:T,[_]:k};break;default:throw new Error(`Task "${u}" (of type "${c}") not yet implemented.`)}return{[u]:d}}async _call(l,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const c=await this.image_processor(l,p),d=u?this.tokenizer(u,p):{};return{...c,...d}}}Z(i,"tokenizer_class",n.AutoTokenizer),Z(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a){const l=await super._call(a),u=l.pixel_values.dims,p=(0,o.ones)([u[0],u[2],u[3]]);return{...l,pixel_mask:p}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/base/image_processors_utils.js");function a(u,p){const d=u.dims.at(-1)-1,_=u.tolist();_.fill(!1,0,1),_.fill(!1,d);const f=p.tolist();return _.map((T,k)=>T?k:null).filter(T=>T!==null).map(T=>f[T])}class l extends s.Processor{async _call(p,c,d={}){const _=p?await this.image_processor(p,d):{};return{...c?this.tokenizer(c,d):{},..._}}post_process_grounded_object_detection(p,c,{box_threshold:d=.25,text_threshold:_=.25,target_sizes:f=null}={}){const{logits:T,pred_boxes:k}=p,w=T.dims[0];if(f!==null&&f.length!==w)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const g=T.dims.at(1),S=T.sigmoid(),E=S.max(-1).tolist(),y=k.tolist().map(v=>v.map(C=>(0,i.center_to_corners_format)(C))),M=[];for(let v=0;vj.map((Y,H)=>Y*C[(H+1)%2])));const A=E[v],z=[],K=[],G=[];for(let j=0;j{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{constructor(a){super(a),this.do_image_splitting=a.do_image_splitting??!0,this.max_image_size=a.max_image_size}get_resize_for_vision_encoder(a,l){let[u,p]=a.dims.slice(-2);const c=p/u;return p>=u?(p=Math.ceil(p/l)*l,u=Math.floor(p/c),u=Math.ceil(u/l)*l):(u=Math.ceil(u/l)*l,p=Math.floor(u*c),p=Math.ceil(p/l)*l),{height:u,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:u=!1}={}){let p;if(!Array.isArray(a))p=[[a]];else{if(a.length===0||!a[0])throw new Error("No images provided.");Array.isArray(a[0])?p=a:p=[a]}let c=[],d=[],_=[];const f=[],T=[];for(const v of p){let C=await Promise.all(v.map(K=>this.preprocess(K)));f.push(...C.map(K=>K.original_size)),T.push(...C.map(K=>K.reshaped_input_size)),C.forEach(K=>K.pixel_values.unsqueeze_(0));const{longest_edge:A}=this.max_image_size;let z;if(l??this.do_image_splitting){let K=new Array(C.length),G=new Array(C.length);z=await Promise.all(C.map(async(j,Y)=>{const H=this.get_resize_for_vision_encoder(j.pixel_values,A),J=await(0,o.interpolate_4d)(j.pixel_values,{size:[H.height,H.width]}),{frames:Q,num_splits_h:oe,num_splits_w:he}=await this.split_image(J,this.max_image_size);return K[Y]=oe,G[Y]=he,(0,o.cat)(Q,0)})),d.push(K),_.push(G)}else{const K=[A,A];z=await Promise.all(C.map(G=>(0,o.interpolate_4d)(G.pixel_values,{size:K}))),d.push(new Array(C.length).fill(0)),_.push(new Array(C.length).fill(0))}c.push((0,o.cat)(z,0))}const k=c.length,[w,g,S,E]=c[0].dims;let y,M;if(k===1)y=c[0].unsqueeze_(0),M=(0,o.full)([k,w,S,E],!0);else{const v=Math.max(...c.map(z=>z.dims.at(0)));M=(0,o.full)([k,v,S,E],!0);const C=M.data,A=v*S*E;for(let z=0;zu||_>p){f=Math.ceil(d/u),T=Math.ceil(_/p);const k=Math.ceil(d/f),w=Math.ceil(_/T);for(let E=0;E{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");var i=t("./src/utils/core.js");function a(c,d,_,f,T,k){let w="";for(let g=0;g`+T.repeat(c);w+=` +`}return w+=` +${f}${k}`+T.repeat(c)+`${f}`,w}function l(c,d,_,f){return`${d}${f}`+_.repeat(c)+`${d}`}function u(c,d,_,f,T,k){return c===0&&d===0?l(_,f,T,k):a(_,c,d,f,T,k)}class p extends s.Processor{constructor(){super(...arguments);Z(this,"fake_image_token","");Z(this,"image_token","");Z(this,"global_img_token","")}async _call(_,f=null,T={}){T.return_row_col_info??(T.return_row_col_info=!0);let k;f&&(k=await this.image_processor(f,T)),Array.isArray(_)||(_=[_]);const w=k.rows??[new Array(_.length).fill(0)],g=k.cols??[new Array(_.length).fill(0)],S=this.config.image_seq_len,E=[],y=[];for(let v=0;v<_.length;++v){const C=_[v],A=w[v],z=g[v];E.push((0,i.count)(C,this.image_token));const K=A.map((Y,H)=>u(Y,z[H],S,this.fake_image_token,this.image_token,this.global_img_token)),G=C.split(this.image_token);if(G.length===0)throw new Error("The image token should be present in the text.");let j=G[0];for(let Y=0;Y{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>o.BitImageProcessor,CLIPFeatureExtractor:()=>i.CLIPFeatureExtractor,CLIPImageProcessor:()=>i.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>n.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>c.DPTFeatureExtractor,DPTImageProcessor:()=>c.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>u.DetrFeatureExtractor,DetrImageProcessor:()=>u.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>d.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>f.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>T.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>w.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>g.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>S.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>E.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>E.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>y.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>y.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>M.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>M.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>v.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>v.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>C.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>C.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>A.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>A.MobileViTImageProcessor,NougatImageProcessor:()=>z.NougatImageProcessor,OwlViTFeatureExtractor:()=>G.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>G.OwlViTImageProcessor,Owlv2ImageProcessor:()=>K.Owlv2ImageProcessor,Phi3VImageProcessor:()=>j.Phi3VImageProcessor,PvtImageProcessor:()=>Y.PvtImageProcessor,Qwen2VLImageProcessor:()=>H.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>J.RTDetrImageProcessor,SamImageProcessor:()=>Q.SamImageProcessor,SegformerFeatureExtractor:()=>oe.SegformerFeatureExtractor,SegformerImageProcessor:()=>oe.SegformerImageProcessor,SiglipImageProcessor:()=>he.SiglipImageProcessor,SmolVLMImageProcessor:()=>ae.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>V.Swin2SRImageProcessor,VLMImageProcessor:()=>k.VLMImageProcessor,ViTFeatureExtractor:()=>F.ViTFeatureExtractor,ViTImageProcessor:()=>F.ViTImageProcessor,VitMatteImageProcessor:()=>W.VitMatteImageProcessor,VitPoseImageProcessor:()=>ee.VitPoseImageProcessor,YolosFeatureExtractor:()=>me.YolosFeatureExtractor,YolosImageProcessor:()=>me.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),o=t("./src/models/bit/image_processing_bit.js"),n=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),i=t("./src/models/clip/image_processing_clip.js"),a=t("./src/models/convnext/image_processing_convnext.js"),l=t("./src/models/deit/image_processing_deit.js"),u=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/donut/image_processing_donut.js"),c=t("./src/models/dpt/image_processing_dpt.js"),d=t("./src/models/efficientnet/image_processing_efficientnet.js"),_=t("./src/models/glpn/image_processing_glpn.js"),f=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),T=t("./src/models/idefics3/image_processing_idefics3.js"),k=t("./src/models/janus/image_processing_janus.js"),w=t("./src/models/jina_clip/image_processing_jina_clip.js"),g=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),S=t("./src/models/mask2former/image_processing_mask2former.js"),E=t("./src/models/maskformer/image_processing_maskformer.js"),y=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),M=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),v=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),C=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),A=t("./src/models/mobilevit/image_processing_mobilevit.js"),z=t("./src/models/nougat/image_processing_nougat.js"),K=t("./src/models/owlv2/image_processing_owlv2.js"),G=t("./src/models/owlvit/image_processing_owlvit.js"),j=t("./src/models/phi3_v/image_processing_phi3_v.js"),Y=t("./src/models/pvt/image_processing_pvt.js"),H=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),J=t("./src/models/rt_detr/image_processing_rt_detr.js"),Q=t("./src/models/sam/image_processing_sam.js"),oe=t("./src/models/segformer/image_processing_segformer.js"),he=t("./src/models/siglip/image_processing_siglip.js"),ae=t("./src/models/smolvlm/image_processing_smolvlm.js"),V=t("./src/models/swin2sr/image_processing_swin2sr.js"),F=t("./src/models/vit/image_processing_vit.js"),W=t("./src/models/vitmatte/image_processing_vitmatte.js"),ee=t("./src/models/vitpose/image_processing_vitpose.js"),me=t("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLMImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){super({do_pad:!0,pad_size:{width:i.image_size,height:i.image_size},...i}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(i,a,l,u){return super.pad_image(i,a,l,{constant_values:this.constant_values,center:!0,...u})}}},"./src/models/janus/processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>u});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class u extends s.Processor{constructor(c,d){super(c,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(c,{images:d=null,chat_template:_="default"}={}){d?Array.isArray(d)||(d=[d]):d=await Promise.all(c.filter(z=>z.images).flatMap(z=>z.images).map(z=>l.RawImage.read(z)));const f=this.tokenizer,T=f.apply_chat_template(c,{tokenize:!1,add_generation_prompt:!0,chat_template:_}),k=z=>f.encode(z,{add_special_tokens:!1}),w=T.split(this.image_tag),g=w.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,y]=f.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let M=k(w[0]),v=new Array(M.length).fill(!1);for(let z=1;z0){const z=await this.image_processor(d);return z.pixel_values.unsqueeze_(0),{...A,...z}}return A}}Z(u,"image_processor_class",o.AutoImageProcessor),Z(u,"tokenizer_class",n.AutoTokenizer),Z(u,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{constructor(i){const{resize_mode:a,fill_color:l,interpolation:u,size:p,...c}=i,d=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},_=u==="bicubic"?3:2;super({...c,size:d,resample:_,do_center_crop:!0,crop_size:p,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{async _call(l=null,u=null,p={}){if(!l&&!u)throw new Error("Either text or images must be provided");const c=l?this.tokenizer(l,p):{},d=u?await this.image_processor(u,p):{};return{...c,...d}}}Z(i,"tokenizer_class",n.AutoTokenizer),Z(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(e,r,t)=>{t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>o});var s=t("./src/models/maskformer/image_processing_maskformer.js");class o extends s.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>n,MaskFormerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_panoptic_segmentation(...a){return(0,s.post_process_panoptic_segmentation)(...a)}post_process_instance_segmentation(...a){return(0,s.post_process_instance_segmentation)(...a)}}class n extends o{}},"./src/models/mgp_str/processing_mgp_str.js":(e,r,t)=>{t.r(r),t.d(r,{MgpstrProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),i=t("./src/utils/maths.js");const a={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class l extends s.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(p,c){if(!a.hasOwnProperty(c))throw new Error(`Format ${c} is not supported.`);const[d,_]=a[c],f=this[d].bind(this),[T,k]=p.dims,w=[],g=[],S=p.tolist();for(let y=0;y0?C.reduce((z,K)=>z*K,1):0;g.push(v),w.push(A)}return[f(g),w]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(c=>c.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(c=>c.replaceAll(" ",""))}batch_decode([p,c,d]){const[_,f]=this._decode_helper(p,"char"),[T,k]=this._decode_helper(c,"bpe"),[w,g]=this._decode_helper(d,"wp"),S=[],E=[];for(let y=0;y<_.length;++y){const[M,v]=(0,i.max)([f[y],k[y],g[y]]);S.push([_[y],T[y],w[y]][v]),E.push(M)}return{generated_text:S,scores:E,char_preds:_,bpe_preds:T,wp_preds:w}}static async from_pretrained(...p){const c=await super.from_pretrained(...p),d=await n.AutoTokenizer.from_pretrained("Xenova/gpt2"),_=await n.AutoTokenizer.from_pretrained("Xenova/bert-base-uncased");return c.components={image_processor:c.image_processor,char_tokenizer:c.tokenizer,bpe_tokenizer:d,wp_tokenizer:_},c}async _call(p,c=null){const d=await this.image_processor(p);return c&&(d.labels=this.tokenizer(c).input_ids),d}}Z(l,"tokenizer_class",n.AutoTokenizer),Z(l,"image_processor_class",o.AutoImageProcessor)},"./src/models/mobilenet_v1/image_processing_mobilenet_v1.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>n,MobileNetV1ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>n,MobileNetV2ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>n,MobileNetV3ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>n,MobileNetV4ImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/mobilevit/image_processing_mobilevit.js":(e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>n,MobileViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/moonshine/feature_extraction_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"MoonshineFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=[1,a.length];return{input_values:new o.Tensor("float32",a,l)}}}},"./src/models/moonshine/processing_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}Z(i,"tokenizer_class",o.AutoTokenizer),Z(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>o});var s=t("./src/models/donut/image_processing_donut.js");class o extends s.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>o});var s=t("./src/models/owlvit/image_processing_owlvit.js");class o extends s.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>n,OwlViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/models/owlvit/processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class i extends s.Processor{}Z(i,"tokenizer_class",n.AutoTokenizer),Z(i,"image_processor_class",o.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(e,r,t)=>{t.r(r),t.d(r,{PaliGemmaProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");const i="";function a(u,p,c,d,_){return`${d.repeat(c*_)}${p}${u} +`}class l extends s.Processor{async _call(p,c=null,d={}){c||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),c=""),Array.isArray(p)||(p=[p]),Array.isArray(c)||(c=[c]);const _=this.tokenizer.bos_token,f=this.image_processor.config.image_seq_length;let T;c.some(g=>g.includes(i))?T=c.map(g=>{const S=g.replaceAll(i,i.repeat(f)),E=S.lastIndexOf(i),y=E===-1?0:E+i.length;return S.slice(0,y)+_+S.slice(y)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),T=c.map(g=>a(g,_,f,i,p.length)));const k=this.tokenizer(T,d);return{...await this.image_processor(p,d),...k}}}Z(l,"tokenizer_class",n.AutoTokenizer),Z(l,"image_processor_class",o.AutoImageProcessor),Z(l,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VImageProcessor:()=>p});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");const n=336,i=[2,3],{ceil:a,floor:l,sqrt:u}=Math;class p extends s.ImageProcessor{constructor(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,_){const{num_img_tokens:f}=this.config;return l((l(_/n)*l(d/n)+1)*f+1+(l(_/n)+1)*u(f))}get_resize_output_image_size(d,_){const f=this._num_crops,[T,k]=d.size;let w=T/k,g=1;for(;g*Math.ceil(g/w)<=f;)g+=1;g-=1;const S=Math.floor(g*336),E=Math.floor(S/w);return[S,E]}pad_image(d,_,f,T={}){const[k,w]=_,g=n*a(k/n),S=n*a(w/n),E=[1,1,1].map((y,M)=>(y-this.image_mean[M])/this.image_std[M]);return super.pad_image(d,_,{width:S,height:g},{center:!0,constant_values:E,...T})}async _call(d,{num_crops:_=null}={}){if(this._num_crops=_??(_=this.config.num_crops),_<4||u(_)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(d)||(d=[d]);const f=d.length,T=await Promise.all(d.map(v=>this.preprocess(v))),k=T.map(v=>v.original_size),w=T.map(v=>v.reshaped_input_size),g=[];for(const{pixel_values:v}of T){v.unsqueeze_(0);const[C,A]=v.dims.slice(-2),z=await(0,o.interpolate_4d)(v,{size:[n,n],mode:"bicubic"});if(_>0){const K=[],G=u(_),j=l(A/G),Y=l(C/G);for(let J=0;Jv.map(C=>n*a(C/n))),y=new o.Tensor("int64",E.flat(),[f,2]),M=E.map(([v,C])=>this.calc_num_image_tokens_from_image_size(C,v));return{pixel_values:S,original_sizes:k,reshaped_input_sizes:w,image_sizes:y,num_img_tokens:M}}}},"./src/models/phi3_v/processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VProcessor:()=>l});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");const i="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{async _call(p,c=null,{padding:d=!0,truncation:_=!0,num_crops:f=null}={}){Array.isArray(p)||(p=[p]);let T,k;if(c){k=await this.image_processor(c,{num_crops:f});const{num_img_tokens:w}=k,g=p.map((E,y)=>E.split(a).join(i.repeat(w[y])));T=this.tokenizer(g,{padding:d,truncation:_});const S=this.tokenizer.model.convert_tokens_to_ids([i])[0];T.input_ids.map_(E=>E==S?-E:E)}else T=this.tokenizer(p);return{...T,...k}}}Z(l,"image_processor_class",o.AutoImageProcessor),Z(l,"tokenizer_class",n.AutoTokenizer)},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,GroundingDinoProcessor:()=>o.GroundingDinoProcessor,Idefics3Processor:()=>n.Idefics3Processor,JinaCLIPProcessor:()=>a.JinaCLIPProcessor,MgpstrProcessor:()=>l.MgpstrProcessor,MoonshineProcessor:()=>u.MoonshineProcessor,OwlViTProcessor:()=>p.OwlViTProcessor,PaliGemmaProcessor:()=>d.PaliGemmaProcessor,Phi3VProcessor:()=>c.Phi3VProcessor,PyAnnoteProcessor:()=>_.PyAnnoteProcessor,Qwen2VLProcessor:()=>f.Qwen2VLProcessor,SamProcessor:()=>T.SamProcessor,SmolVLMProcessor:()=>k.SmolVLMProcessor,SpeechT5Processor:()=>w.SpeechT5Processor,UltravoxProcessor:()=>g.UltravoxProcessor,VLChatProcessor:()=>i.VLChatProcessor,Wav2Vec2Processor:()=>S.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>E.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>y.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),o=t("./src/models/grounding_dino/processing_grounding_dino.js"),n=t("./src/models/idefics3/processing_idefics3.js"),i=t("./src/models/janus/processing_janus.js"),a=t("./src/models/jina_clip/processing_jina_clip.js"),l=t("./src/models/mgp_str/processing_mgp_str.js"),u=t("./src/models/moonshine/processing_moonshine.js"),p=t("./src/models/owlvit/processing_owlvit.js"),c=t("./src/models/phi3_v/processing_phi3_v.js"),d=t("./src/models/paligemma/processing_paligemma.js"),_=t("./src/models/pyannote/processing_pyannote.js"),f=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),T=t("./src/models/sam/processing_sam.js"),k=t("./src/models/smolvlm/processing_smolvlm.js"),w=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"),y=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const u=[1,1,l.length];return{input_values:new o.Tensor("float32",l,u)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,u){const p=u/this.samples_to_frames(u)/this.config.sampling_rate,c=[];for(const d of l.tolist()){const _=[];let f=-1;for(let T=0;T({id:T,start:k*p,end:w*p,confidence:g/(w-k)})))}return c}}},"./src/models/pyannote/processing_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteProcessor:()=>n});var s=t("./src/base/processing_utils.js"),o=t("./src/models/pyannote/feature_extraction_pyannote.js");class n extends s.Processor{async _call(a){return await this.feature_extractor(a)}post_process_speaker_diarization(...a){return this.feature_extractor.post_process_speaker_diarization(...a)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}Z(n,"feature_extractor_class",o.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,...l){const{pixel_values:u,original_sizes:p,reshaped_input_sizes:c}=await super._call(a,...l);let d=u;const{temporal_patch_size:_,merge_size:f,patch_size:T}=this.config;d.dims[0]===1&&(d=(0,o.cat)(Array.from({length:_},()=>d),0));const k=d.dims[0]/_,w=d.dims[1],g=Math.floor(d.dims[2]/T),S=Math.floor(d.dims[3]/T),E=d.view(k,_,w,Math.floor(g/f),f,T,Math.floor(S/f),f,T).permute(0,3,6,4,7,2,1,5,8).view(k*g*S,w*_*T*T),y=new o.Tensor("int64",[k,g,S],[1,3]);return{pixel_values:E,image_grid_thw:y,original_sizes:p,reshaped_input_sizes:c}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");class i extends s.Processor{async _call(l,u=null,...p){Array.isArray(l)||(l=[l]);let c,d;if(u&&(c=await this.image_processor(u),d=c.image_grid_thw),d){let f=this.image_processor.config.merge_size**2,T=0;const k=d.tolist();l=l.map(w=>{for(;w.includes("<|image_pad|>");){const g=Number(k[T++].reduce((S,E)=>S*E,1n));w=w.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(g/f)))}return w.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...c}}}Z(i,"image_processor_class",o.AutoImageProcessor),Z(i,"tokenizer_class",n.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...i){return(0,s.post_process_object_detection)(...i)}}},"./src/models/sam/image_processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/core.js"),n=t("./src/utils/tensor.js");class i extends s.ImageProcessor{reshape_input_points(l,u,p,c=!1){l=structuredClone(l);let d=(0,o.calculateDimensions)(l);if(d.length===3)c||(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 _=0;_c!==u.dims[d]))throw Error(`The first ${p.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new n.Tensor("int64",l.flat(1/0).map(BigInt),p)}async _call(l,{input_points:u=null,input_labels:p=null,input_boxes:c=null}={}){const d=await super._call(l);if(u&&(d.input_points=this.reshape_input_points(u,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 c&&(d.input_boxes=this.reshape_input_points(c,d.original_sizes,d.reshaped_input_sizes,!0)),d}async post_process_masks(l,u,p,{mask_threshold:c=0,binarize:d=!0,pad_size:_=null}={}){const f=[];_=_??this.pad_size;const T=[_.height,_.width];for(let k=0;kc&&(y[M]=1);S=new n.Tensor("bool",y,S.dims)}f.push(S)}return f}generate_crop_boxes(l,u,{crop_n_layers:p=0,overlap_ratio:c=512/1500,points_per_crop:d=32,crop_n_points_downscale_factor:_=1}={}){}}},"./src/models/sam/processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamProcessor:()=>n});var s=t("./src/base/processing_utils.js"),o=t("./src/models/auto/image_processing_auto.js");class n extends s.Processor{async _call(...a){return await this.image_processor(...a)}post_process_masks(...a){return this.image_processor.post_process_masks(...a)}reshape_input_points(...a){return this.image_processor.reshape_input_points(...a)}}Z(n,"image_processor_class",o.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class i extends s.FeatureExtractor{constructor(l){super(l);const u=this.config.sampling_rate,p=(0,n.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(u/2),u,null,"kaldi",!0);this.mel_filters=p,this.window=(0,n.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(l,u){return l=l.map(p=>p*32768),(0,n.spectrogram)(l,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:u,transpose:!0})}async _call(l,{padding:u=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:c=!0,return_attention_mask:d=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let _=await this._extract_fbank_features(l,this.config.max_length);if(c){const[y,M]=_.dims,v=_.data;for(let C=0;C0){const A=new Float32Array(M*(y+C));A.set(v),A.fill(this.config.padding_value,v.length);const z=y+C;_=new o.Tensor(_.type,A,[z,M]),d&&(f=new o.Tensor("int64",new BigInt64Array(z),[1,z]),f.data.fill(1n,0,y))}}const[T,k]=_.dims,w=this.config.stride;if(T%w!==0)throw new Error(`The number of frames (${T}) must be a multiple of the stride (${w}).`);const S=_.view(1,Math.floor(T/w),k*w),E={input_features:S};if(d){const y=S.dims[1],M=new BigInt64Array(y);if(f){const v=f.data;for(let C=1,A=0;C{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>n,SegformerImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class n extends o{}},"./src/models/siglip/image_processing_siglip.js":(e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}},"./src/models/smolvlm/image_processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMImageProcessor:()=>s.Idefics3ImageProcessor});var s=t("./src/models/idefics3/image_processing_idefics3.js")},"./src/models/smolvlm/processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMProcessor:()=>s.Idefics3Processor});var s=t("./src/models/idefics3/processing_idefics3.js")},"./src/models/snac/feature_extraction_snac.js":(e,r,t)=>{t.r(r),t.d(r,{SnacFeatureExtractor:()=>o});var s=t("./src/models/dac/feature_extraction_dac.js");class o extends s.DacFeatureExtractor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");class o extends s.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>i});var s=t("./src/base/processing_utils.js"),o=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js");class i extends s.Processor{async _call(l){return await this.feature_extractor(l)}}Z(i,"tokenizer_class",o.AutoTokenizer),Z(i,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{pad_image(i,a,l,u={}){const[p,c,d]=a;return super.pad_image(i,a,{width:c+(l-c%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...u})}}},"./src/models/ultravox/processing_ultravox.js":(e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l,u=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let c={};if(u){const _=u.length,{input_features:f}=await this.feature_extractor(u,{...p,max_length:_}),T=Math.round(_/this.config.encoder_ds_factor+1e-4),k=1+Math.ceil(T/this.config.stack_factor);c.audio_token_len=[k],c.audio_values=f;const w=this.config.audio_placeholder;if(!l.includes(w))throw new Error(`The input text does not contain the image token ${w}.`);l=l.replaceAll(w,w.repeat(k))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...c}}}Z(i,"tokenizer_class",o.AutoTokenizer),Z(i,"feature_extractor_class",s.AutoFeatureExtractor),Z(i,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>n,ViTImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{}class n extends o{}},"./src/models/vitmatte/image_processing_vitmatte.js":(e,r,t)=>{t.r(r),t.d(r,{VitMatteImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),o=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,l){Array.isArray(a)||(a=[a]),Array.isArray(l)||(l=[l]);const u=await Promise.all(a.map(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,o.stack)(u.map((d,_)=>(0,o.cat)([d.pixel_values,p[_].pixel_values],0)),0),original_sizes:u.map(d=>d.original_size),reshaped_input_sizes:u.map(d=>d.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_pose_estimation(i,a,{threshold:l=null}={}){const u=i.tolist(),[p,c,d,_]=i.dims,f=[];for(let T=0;T{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),o=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const u=a.reduce((c,d)=>c+d,0)/a.length,p=a.reduce((c,d)=>c+(d-u)**2,0)/a.length;return a.map(c=>(c-u)/Math.sqrt(p+1e-7))}async _call(a){(0,s.validate_audio_inputs)(a,"Wav2Vec2FeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));let l=a;this.config.do_normalize&&(l=this._zero_mean_unit_var_norm(l));const u=[1,l.length];return{input_values:new o.Tensor("float32",l,u),attention_mask:new o.Tensor("int64",new BigInt64Array(l.length).fill(1n),u)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}Z(i,"tokenizer_class",s.AutoTokenizer),Z(i,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>i});var s=t("./src/tokenizers.js"),o=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}Z(i,"tokenizer_class",s.AutoTokenizer),Z(i,"feature_extractor_class",o.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(e,r,t)=>{t.r(r),t.d(r,{WeSpeakerFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,u=(0,o.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);this.mel_filters=u,this.window=(0,o.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(a){return a=a.map(l=>l*32768),(0,o.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(a){(0,s.validate_audio_inputs)(a,"WeSpeakerFeatureExtractor");const l=(await this._extract_fbank_features(a)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const u=l.mean(1).data,p=l.data,[c,d,_]=l.dims;for(let f=0;f{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>o,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>n,whisper_language_to_code:()=>i});const s=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],o=new Map(s),n=new Map([...s.map(([a,l])=>[l,a]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function i(a){a=a.toLowerCase();let l=n.get(a);if(l===void 0){const u=a.match(/^<\|([a-z]{2})\|>$/);if(u&&(a=u[1]),o.has(a))l=a;else{const c=a.length===2?o.keys():o.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(c))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var o=t("./src/utils/audio.js"),n=t("./src/utils/maths.js");class i extends s.FeatureExtractor{constructor(l){var u;super(l),(u=this.config).mel_filters??(u.mel_filters=(0,o.mel_filter_bank)(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8e3,this.config.sampling_rate,"slaney","slaney")),this.window=(0,o.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const u=await(0,o.spectrogram)(l,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(l.length/this.config.hop_length),this.config.nb_max_frames)}),p=u.data,c=(0,n.max)(p)[0];for(let d=0;dc?(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,c)):(p=new Float32Array(c),p.set(l)),{input_features:(await this._extract_fbank_features(p)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperGenerationConfig:()=>o});var s=t("./src/generation/configuration_utils.js");class o extends s.GenerationConfig{constructor(){super(...arguments);Z(this,"return_timestamps",null);Z(this,"return_token_timestamps",null);Z(this,"num_frames",null);Z(this,"alignment_heads",null);Z(this,"task",null);Z(this,"language",null);Z(this,"no_timestamps_token_id",null);Z(this,"prompt_ids",null);Z(this,"is_multilingual",null);Z(this,"lang_to_id",null);Z(this,"task_to_id",null);Z(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>i});var s=t("./src/models/auto/feature_extraction_auto.js"),o=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class i extends n.Processor{async _call(l){return await this.feature_extractor(l)}}Z(i,"tokenizer_class",o.AutoTokenizer),Z(i,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>n,YolosImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js");class o extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends o{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),o=t("./src/utils/tensor.js"),n=t("./src/env.js");const i=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV,a=async(u,p,c)=>{const d=await(0,s.createInferenceSession)(new Uint8Array(u),p);let _=Promise.resolve();return async f=>{const T=(0,s.isONNXProxy)(),k=Object.fromEntries(Object.entries(f).map(([g,S])=>[g,(T?S.clone():S).ort_tensor])),w=await(_=i?_.then(()=>d.run(k)):d.run(k));return Array.isArray(c)?c.map(g=>new o.Tensor(w[g])):new o.Tensor(w[c])}};class l{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=a([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=a([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=a([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=a([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=a([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=a([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=a([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=a([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}Z(l,"session_options",{})},"./src/pipelines.js":(e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>G,AutomaticSpeechRecognitionPipeline:()=>Y,BackgroundRemovalPipeline:()=>oe,DepthEstimationPipeline:()=>me,DocumentQuestionAnsweringPipeline:()=>F,FeatureExtractionPipeline:()=>z,FillMaskPipeline:()=>S,ImageClassificationPipeline:()=>J,ImageFeatureExtractionPipeline:()=>K,ImageSegmentationPipeline:()=>Q,ImageToImagePipeline:()=>ee,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>ae,Pipeline:()=>T,QuestionAnsweringPipeline:()=>g,SummarizationPipeline:()=>y,Text2TextGenerationPipeline:()=>E,TextClassificationPipeline:()=>k,TextGenerationPipeline:()=>C,TextToAudioPipeline:()=>W,TokenClassificationPipeline:()=>w,TranslationPipeline:()=>M,ZeroShotAudioClassificationPipeline:()=>j,ZeroShotClassificationPipeline:()=>A,ZeroShotImageClassificationPipeline:()=>he,ZeroShotObjectDetectionPipeline:()=>V,pipeline:()=>Pe});var s=t("./src/tokenizers.js"),o=t("./src/models.js"),n=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var i=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),u=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),c=t("./src/utils/image.js");async function d(we){return Array.isArray(we)||(we=[we]),await Promise.all(we.map(q=>c.RawImage.read(q)))}async function _(we,q){return Array.isArray(we)||(we=[we]),await Promise.all(we.map(R=>typeof R=="string"||R instanceof URL?(0,u.read_audio)(R,q):R instanceof Float64Array?new Float32Array(R):R))}function f(we,q){q&&(we=we.map(Ce=>Ce|0));const[R,de,ve,be]=we;return{xmin:R,ymin:de,xmax:ve,ymax:be}}class T extends i.Callable{constructor({task:q,model:R,tokenizer:de=null,processor:ve=null}){super(),this.task=q,this.model=R,this.tokenizer=de,this.processor=ve}async dispose(){await this.model.dispose()}}class k extends T{constructor(q){super(q)}async _call(q,{top_k:R=1}={}){const de=this.tokenizer(q,{padding:!0,truncation:!0}),ve=await this.model(de),be=this.model.config.problem_type==="multi_label_classification"?$e=>$e.sigmoid():$e=>new p.Tensor("float32",(0,l.softmax)($e.data),$e.dims),Ce=this.model.config.id2label,Se=[];for(const $e of ve.logits){const Le=be($e),Ie=await(0,p.topk)(Le,R),Ke=Ie[0].tolist(),ke=Ie[1].tolist().map((Ze,Xe)=>({label:Ce?Ce[Ze]:`LABEL_${Ze}`,score:Ke[Xe]}));R===1?Se.push(...ke):Se.push(ke)}return Array.isArray(q)||R===1?Se:Se[0]}}class w extends T{constructor(q){super(q)}async _call(q,{ignore_labels:R=["O"]}={}){const de=Array.isArray(q),ve=this.tokenizer(de?q:[q],{padding:!0,truncation:!0}),Ce=(await this.model(ve)).logits,Se=this.model.config.id2label,$e=[];for(let Le=0;LeRe==this.tokenizer.sep_token_id);$e[Ke].map((Re,_t)=>Re==1&&(_t===0||_t>ke&&Le.findIndex(St=>St==Ye[_t])===-1));const Ze=be[Ke].tolist(),Xe=Ce[Ke].tolist();for(let Re=1;Re_t==Ye[Re])!==-1)&&(Ze[Re]=-1/0,Xe[Re]=-1/0);const tt=(0,l.softmax)(Ze).map((Re,_t)=>[Re,_t]),ut=(0,l.softmax)(Xe).map((Re,_t)=>[Re,_t]);tt[0][0]=0,ut[0][0]=0;const Ue=(0,a.product)(tt,ut).filter(Re=>Re[0][1]<=Re[1][1]).map(Re=>[Re[0][1],Re[1][1],Re[0][0]*Re[1][0]]).sort((Re,_t)=>_t[2]-Re[2]);for(let Re=0;ReZe==this.tokenizer.mask_token_id);if(Le===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ie=ve[Se][Le],Ke=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ie.data),Ie.dims),R),Ye=Ke[0].tolist(),ke=Ke[1].tolist();be.push(ke.map((Ze,Xe)=>{const tt=$e.slice();return tt[Le]=Ze,{score:Ye[Xe],token:Number(Ze),token_str:this.tokenizer.decode([Ze]),sequence:this.tokenizer.decode(tt,{skip_special_tokens:!0})}}))}return Array.isArray(q)?be:be[0]}}class E extends T{constructor(R){super(R);Z(this,"_key","generated_text")}async _call(R,de={}){Array.isArray(R)||(R=[R]),this.model.config.prefix&&(R=R.map(Le=>this.model.config.prefix+Le));const ve=this.model.config.task_specific_params;ve&&ve[this.task]&&ve[this.task].prefix&&(R=R.map(Le=>ve[this.task].prefix+Le));const be=this.tokenizer,Ce={padding:!0,truncation:!0};let Se;this instanceof M&&"_build_translation_inputs"in be?Se=be._build_translation_inputs(R,Ce,de):Se=be(R,Ce);const $e=await this.model.generate({...Se,...de});return be.batch_decode($e,{skip_special_tokens:!0}).map(Le=>({[this._key]:Le}))}}class y extends E{constructor(R){super(R);Z(this,"_key","summary_text")}}class M extends E{constructor(R){super(R);Z(this,"_key","translation_text")}}function v(we){return Array.isArray(we)&&we.every(q=>"role"in q&&"content"in q)}class C extends T{constructor(q){super(q)}async _call(q,R={}){let de=!1,ve=!1,be;if(typeof q=="string")be=q=[q];else if(Array.isArray(q)&&q.every(ke=>typeof ke=="string"))de=!0,be=q;else{if(v(q))q=[q];else if(Array.isArray(q)&&q.every(v))de=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");ve=!0,be=q.map(ke=>this.tokenizer.apply_chat_template(ke,{tokenize:!1,add_generation_prompt:!0}))}const Ce=R.add_special_tokens??!1,Se=ve?!1:R.return_full_text??!0;this.tokenizer.padding_side="left";const $e=this.tokenizer(be,{add_special_tokens:Ce,padding:!0,truncation:!0}),Le=await this.model.generate({...$e,...R}),Ie=this.tokenizer.batch_decode(Le,{skip_special_tokens:!0});let Ke;!Se&&$e.input_ids.dims.at(-1)>0&&(Ke=this.tokenizer.batch_decode($e.input_ids,{skip_special_tokens:!0}).map(ke=>ke.length));const Ye=Array.from({length:q.length},ke=>[]);for(let ke=0;ke[R.toLowerCase(),de])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(q,R,{hypothesis_template:de="This example is {}.",multi_label:ve=!1}={}){const be=Array.isArray(q);be||(q=[q]),Array.isArray(R)||(R=[R]);const Ce=R.map(Le=>de.replace("{}",Le)),Se=ve||R.length===1,$e=[];for(const Le of q){const Ie=[];for(const ke of Ce){const Ze=this.tokenizer(Le,{text_pair:ke,padding:!0,truncation:!0}),Xe=await this.model(Ze);Se?Ie.push([Xe.logits.data[this.contradiction_id],Xe.logits.data[this.entailment_id]]):Ie.push(Xe.logits.data[this.entailment_id])}const Ye=(Se?Ie.map(ke=>(0,l.softmax)(ke)[1]):(0,l.softmax)(Ie)).map((ke,Ze)=>[ke,Ze]).sort((ke,Ze)=>Ze[0]-ke[0]);$e.push({sequence:Le,labels:Ye.map(ke=>R[ke[1]]),scores:Ye.map(ke=>ke[0])})}return be?$e:$e[0]}}class z extends T{constructor(q){super(q)}async _call(q,{pooling:R="none",normalize:de=!1,quantize:ve=!1,precision:be="binary"}={}){const Ce=this.tokenizer(q,{padding:!0,truncation:!0}),Se=await this.model(Ce);let $e=Se.last_hidden_state??Se.logits??Se.token_embeddings;if(R!=="none")if(R==="mean")$e=(0,p.mean_pooling)($e,Ce.attention_mask);else if(R==="cls")$e=$e.slice(null,0);else throw Error(`Pooling method '${R}' not supported.`);return de&&($e=$e.normalize(2,-1)),ve&&($e=(0,p.quantize_embeddings)($e,be)),$e}}class K extends T{constructor(q){super(q)}async _call(q,{pool:R=null}={}){const de=await d(q),{pixel_values:ve}=await this.processor(de),be=await this.model({pixel_values:ve});let Ce;if(R){if(!("pooler_output"in be))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ce=be.pooler_output}else Ce=be.last_hidden_state??be.logits??be.image_embeds;return Ce}}class G extends T{constructor(q){super(q)}async _call(q,{top_k:R=5}={}){const de=this.processor.feature_extractor.config.sampling_rate,ve=await _(q,de),be=this.model.config.id2label,Ce=[];for(const Se of ve){const $e=await this.processor(Se),Ie=(await this.model($e)).logits[0],Ke=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ie.data),Ie.dims),R),Ye=Ke[0].tolist(),Ze=Ke[1].tolist().map((Xe,tt)=>({label:be?be[Xe]:`LABEL_${Xe}`,score:Ye[tt]}));Ce.push(Ze)}return Array.isArray(q)?Ce:Ce[0]}}class j extends T{constructor(q){super(q)}async _call(q,R,{hypothesis_template:de="This is a sound of {}."}={}){const ve=!Array.isArray(q);ve&&(q=[q]);const be=R.map(Ie=>de.replace("{}",Ie)),Ce=this.tokenizer(be,{padding:!0,truncation:!0}),Se=this.processor.feature_extractor.config.sampling_rate,$e=await _(q,Se),Le=[];for(const Ie of $e){const Ke=await this.processor(Ie),Ye=await this.model({...Ce,...Ke}),ke=(0,l.softmax)(Ye.logits_per_audio.data);Le.push([...ke].map((Ze,Xe)=>({score:Ze,label:R[Xe]})))}return ve?Le[0]:Le}}class Y extends T{constructor(q){super(q)}async _call(q,R={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(q,R);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(q,R);case"moonshine":return this._call_moonshine(q,R);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(q,R){R.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),R.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const de=!Array.isArray(q);de&&(q=[q]);const ve=this.processor.feature_extractor.config.sampling_rate,be=await _(q,ve),Ce=[];for(const Se of be){const $e=await this.processor(Se),Ie=(await this.model($e)).logits[0],Ke=[];for(const ke of Ie)Ke.push((0,l.max)(ke.data)[1]);const Ye=this.tokenizer.decode(Ke);Ce.push({text:Ye})}return de?Ce[0]:Ce}async _call_whisper(q,R){const de=R.return_timestamps??!1,ve=R.chunk_length_s??0,be=R.force_full_sequences??!1;let Ce=R.stride_length_s??null;const Se={...R};de==="word"&&(Se.return_token_timestamps=!0,Se.return_timestamps=!1);const $e=!Array.isArray(q);$e&&(q=[q]);const Le=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ie=this.processor.feature_extractor.config.hop_length,Ke=this.processor.feature_extractor.config.sampling_rate,Ye=await _(q,Ke),ke=[];for(const Ze of Ye){let Xe=[];if(ve>0){if(Ce===null)Ce=ve/6;else if(ve<=Ce)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Ue=Ke*ve,Re=Ke*Ce,_t=Ue-2*Re;let St=0;for(;;){const at=St+Ue,jt=Ze.subarray(St,at),O=await this.processor(jt),se=St===0,B=at>=Ze.length;if(Xe.push({stride:[jt.length,se?0:Re,B?0:Re],input_features:O.input_features,is_last:B}),B)break;St+=_t}}else Xe=[{stride:[Ze.length,0,0],input_features:(await this.processor(Ze)).input_features,is_last:!0}];for(const Ue of Xe){Se.num_frames=Math.floor(Ue.stride[0]/Ie);const Re=await this.model.generate({inputs:Ue.input_features,...Se});de==="word"?(Ue.tokens=Re.sequences.tolist()[0],Ue.token_timestamps=Re.token_timestamps.tolist()[0].map(_t=>(0,l.round)(_t,2))):Ue.tokens=Re[0].tolist(),Ue.stride=Ue.stride.map(_t=>_t/Ke)}const[tt,ut]=this.tokenizer._decode_asr(Xe,{time_precision:Le,return_timestamps:de,force_full_sequences:be});ke.push({text:tt,...ut})}return $e?ke[0]:ke}async _call_moonshine(q,R){const de=!Array.isArray(q);de&&(q=[q]);const ve=this.processor.feature_extractor.config.sampling_rate,be=await _(q,ve),Ce=[];for(const Se of be){const $e=await this.processor(Se),Le=Math.floor(Se.length/ve)*6,Ie=await this.model.generate({max_new_tokens:Le,...R,...$e}),Ke=this.processor.batch_decode(Ie,{skip_special_tokens:!0})[0];Ce.push({text:Ke})}return de?Ce[0]:Ce}}class H extends T{constructor(q){super(q)}async _call(q,R={}){const de=Array.isArray(q),ve=await d(q),{pixel_values:be}=await this.processor(ve),Ce=[];for(const Se of be){Se.dims=[1,...Se.dims];const $e=await this.model.generate({inputs:Se,...R}),Le=this.tokenizer.batch_decode($e,{skip_special_tokens:!0}).map(Ie=>({generated_text:Ie.trim()}));Ce.push(Le)}return de?Ce:Ce[0]}}class J extends T{constructor(q){super(q)}async _call(q,{top_k:R=5}={}){const de=await d(q),{pixel_values:ve}=await this.processor(de),be=await this.model({pixel_values:ve}),Ce=this.model.config.id2label,Se=[];for(const $e of be.logits){const Le=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)($e.data),$e.dims),R),Ie=Le[0].tolist(),Ye=Le[1].tolist().map((ke,Ze)=>({label:Ce?Ce[ke]:`LABEL_${ke}`,score:Ie[Ze]}));Se.push(Ye)}return Array.isArray(q)?Se:Se[0]}}class Q extends T{constructor(q){super(q),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(q,{threshold:R=.5,mask_threshold:de=.5,overlap_mask_area_threshold:ve=.8,label_ids_to_fuse:be=null,target_sizes:Ce=null,subtask:Se=null}={}){if(Array.isArray(q)&&q.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const Le=await d(q),Ie=Le.map(Ue=>[Ue.height,Ue.width]),Ke=await this.processor(Le),{inputNames:Ye,outputNames:ke}=this.model.sessions.model;if(!Ye.includes("pixel_values")){if(Ye.length!==1)throw Error(`Expected a single input name, but got ${Ye.length} inputs: ${Ye}.`);const Ue=Ye[0];if(Ue in Ke)throw Error(`Input name ${Ue} already exists in the inputs.`);Ke[Ue]=Ke.pixel_values}const Ze=await this.model(Ke);let Xe=null;if(Se!==null)Xe=this.subtasks_mapping[Se];else if(this.processor.image_processor){for(const[Ue,Re]of Object.entries(this.subtasks_mapping))if(Re in this.processor.image_processor){Xe=this.processor.image_processor[Re].bind(this.processor.image_processor),Se=Ue;break}}const tt=this.model.config.id2label,ut=[];if(Se)if(Se==="panoptic"||Se==="instance"){const Ue=Xe(Ze,R,de,ve,be,Ce??Ie)[0],Re=Ue.segmentation;for(const _t of Ue.segments_info){const St=new Uint8ClampedArray(Re.data.length);for(let jt=0;jtO<-1e-5||O>1+1e-5)&&at.sigmoid_();const jt=await c.RawImage.fromTensor(at.mul_(255).to("uint8")).resize(St[1],St[0]);ut.push({label:null,score:null,mask:jt})}}return ut}}class oe extends Q{constructor(q){super(q)}async _call(q,R={}){if(Array.isArray(q)&&q.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const ve=await d(q),be=await super._call(q,R);return ve.map((Se,$e)=>{const Le=Se.clone();return Le.putAlpha(be[$e].mask),Le})}}class he extends T{constructor(q){super(q)}async _call(q,R,{hypothesis_template:de="This is a photo of {}"}={}){const ve=Array.isArray(q),be=await d(q),Ce=R.map(Ye=>de.replace("{}",Ye)),Se=this.tokenizer(Ce,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:$e}=await this.processor(be),Le=await this.model({...Se,pixel_values:$e}),Ie=this.model.config.model_type==="siglip"?Ye=>Ye.sigmoid().data:Ye=>(0,l.softmax)(Ye.data),Ke=[];for(const Ye of Le.logits_per_image){const Ze=[...Ie(Ye)].map((Xe,tt)=>({score:Xe,label:R[tt]}));Ze.sort((Xe,tt)=>tt.score-Xe.score),Ke.push(Ze)}return ve?Ke:Ke[0]}}class ae extends T{constructor(q){super(q)}async _call(q,{threshold:R=.9,percentage:de=!1}={}){const ve=Array.isArray(q);if(ve&&q.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const be=await d(q),Ce=de?null:be.map(ke=>[ke.height,ke.width]),{pixel_values:Se,pixel_mask:$e}=await this.processor(be),Le=await this.model({pixel_values:Se,pixel_mask:$e}),Ie=this.processor.image_processor.post_process_object_detection(Le,R,Ce),Ke=this.model.config.id2label,Ye=Ie.map(ke=>ke.boxes.map((Ze,Xe)=>({score:ke.scores[Xe],label:Ke[ke.classes[Xe]],box:f(Ze,!de)})));return ve?Ye:Ye[0]}}class V extends T{constructor(q){super(q)}async _call(q,R,{threshold:de=.1,top_k:ve=null,percentage:be=!1}={}){const Ce=Array.isArray(q),Se=await d(q),$e=this.tokenizer(R,{padding:!0,truncation:!0}),Le=await this.processor(Se),Ie=[];for(let Ke=0;Ke({score:ut.scores[Re],label:ut.labels[Re],box:f(Ue,!be)}))}else{const ut=this.processor.image_processor.post_process_object_detection(Xe,de,ke,!0)[0];tt=ut.boxes.map((Ue,Re)=>({score:ut.scores[Re],label:R[ut.classes[Re]],box:f(Ue,!be)}))}tt.sort((ut,Ue)=>Ue.score-ut.score),ve!==null&&(tt=tt.slice(0,ve)),Ie.push(tt)}return Ce?Ie:Ie[0]}}class F extends T{constructor(q){super(q)}async _call(q,R,de={}){const ve=(await d(q))[0],{pixel_values:be}=await this.processor(ve),Ce=`${R}`,Se=this.tokenizer(Ce,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,$e=await this.model.generate({inputs:be,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Se,...de}),Ie=this.tokenizer.batch_decode($e)[0].match(/(.*?)<\/s_answer>/);let Ke=null;return Ie&&Ie.length>=2&&(Ke=Ie[1].trim()),[{answer:Ke}]}}class W extends T{constructor(R){super(R);Z(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=R.vocoder??null}async _call(R,{speaker_embeddings:de=null}={}){return this.processor?this._call_text_to_spectrogram(R,{speaker_embeddings:de}):this._call_text_to_waveform(R)}async _call_text_to_waveform(R){const de=this.tokenizer(R,{padding:!0,truncation:!0}),{waveform:ve}=await this.model(de),be=this.model.config.sampling_rate;return new u.RawAudio(ve.data,be)}async _call_text_to_spectrogram(R,{speaker_embeddings:de}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await o.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof de=="string"||de instanceof URL)&&(de=new Float32Array(await(await fetch(de)).arrayBuffer())),de instanceof Float32Array)de=new p.Tensor("float32",de,[1,de.length]);else if(!(de instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:ve}=this.tokenizer(R,{padding:!0,truncation:!0}),{waveform:be}=await this.model.generate_speech(ve,de,{vocoder:this.vocoder}),Ce=this.processor.feature_extractor.config.sampling_rate;return new u.RawAudio(be.data,Ce)}}class ee extends T{constructor(q){super(q)}async _call(q){const R=await d(q),de=await this.processor(R),ve=await this.model(de),be=[];for(const Ce of ve.reconstruction){const Se=Ce.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");be.push(c.RawImage.fromTensor(Se))}return be.length>1?be:be[0]}}class me extends T{constructor(q){super(q)}async _call(q){const R=await d(q),de=await this.processor(R),{predicted_depth:ve}=await this.model(de),be=[];for(let Ce=0;Ce1?be:be[0]}}const te=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:k,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:w,model:o.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:g,model:o.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:S,model:o.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:y,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:M,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:E,model:o.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:C,model:o.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:A,model:o.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:G,model:o.AutoModelForAudioClassification,processor:n.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:j,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:Y,model:[o.AutoModelForSpeechSeq2Seq,o.AutoModelForCTC],processor:n.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:W,model:[o.AutoModelForTextToWaveform,o.AutoModelForTextToSpectrogram],processor:[n.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:H,model:o.AutoModelForVision2Seq,processor:n.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:J,model:o.AutoModelForImageClassification,processor:n.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Q,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:oe,model:[o.AutoModelForImageSegmentation,o.AutoModelForSemanticSegmentation,o.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:he,model:o.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ae,model:o.AutoModelForObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:V,model:o.AutoModelForZeroShotObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:F,model:o.AutoModelForDocumentQuestionAnswering,processor:n.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ee,model:o.AutoModelForImageToImage,processor:n.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:me,model:o.AutoModelForDepthEstimation,processor:n.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:z,model:o.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:n.AutoProcessor,pipeline:K,model:[o.AutoModelForImageFeatureExtraction,o.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),ue=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function Pe(we,q=null,{progress_callback:R=null,config:de=null,cache_dir:ve=null,local_files_only:be=!1,revision:Ce="main",device:Se=null,dtype:$e=null,subfolder:Le="onnx",use_external_data_format:Ie=null,model_file_name:Ke=null,session_options:Ye={}}={}){we=ue[we]??we;const ke=te[we.split("_",1)[0]];if(!ke)throw Error(`Unsupported pipeline: ${we}. Must be one of [${Object.keys(te)}]`);q||(q=ke.default.model,console.log(`No model specified. Using default model: "${q}".`));const Ze={progress_callback:R,config:de,cache_dir:ve,local_files_only:be,revision:Ce,device:Se,dtype:$e,subfolder:Le,use_external_data_format:Ie,model_file_name:Ke,session_options:Ye},Xe=new Map([["tokenizer",ke.tokenizer],["model",ke.model],["processor",ke.processor]]),tt=await Ne(Xe,q,Ze);tt.task=we,(0,a.dispatchCallback)(R,{status:"ready",task:we,model:q});const ut=ke.pipeline;return new ut(tt)}async function Ne(we,q,R){const de=Object.create(null),ve=[];for(const[be,Ce]of we.entries()){if(!Ce)continue;let Se;Array.isArray(Ce)?Se=new Promise(async($e,Le)=>{var Ke,Ye;let Ie;for(const ke of Ce){if(ke===null){$e(null);return}try{$e(await ke.from_pretrained(q,R));return}catch(Ze){if((Ke=Ze.message)!=null&&Ke.includes("Unsupported model type"))Ie=Ze;else if((Ye=Ze.message)!=null&&Ye.includes("Could not locate file"))Ie=Ze;else{Le(Ze);return}}}Le(Ie)}):Se=Ce.from_pretrained(q,R),de[be]=Se,ve.push(Se)}await Promise.all(ve);for(const[be,Ce]of Object.entries(de))de[be]=await Ce;return de}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>It,AutoTokenizer:()=>vn,BartTokenizer:()=>Ss,BertTokenizer:()=>ct,BlenderbotSmallTokenizer:()=>Is,BlenderbotTokenizer:()=>wn,BloomTokenizer:()=>Ur,CLIPTokenizer:()=>mn,CamembertTokenizer:()=>ws,CodeGenTokenizer:()=>Hr,CodeLlamaTokenizer:()=>qe,CohereTokenizer:()=>yn,ConvBertTokenizer:()=>yr,DebertaTokenizer:()=>ir,DebertaV2Tokenizer:()=>Ar,DistilBertTokenizer:()=>Es,ElectraTokenizer:()=>ss,EsmTokenizer:()=>$s,FalconTokenizer:()=>lr,GPT2Tokenizer:()=>Cs,GPTNeoXTokenizer:()=>ys,GemmaTokenizer:()=>ks,Grok1Tokenizer:()=>jr,HerbertTokenizer:()=>ts,LlamaTokenizer:()=>De,M2M100Tokenizer:()=>xr,MBart50Tokenizer:()=>Ms,MBartTokenizer:()=>ns,MPNetTokenizer:()=>Qt,MarianTokenizer:()=>_n,MgpstrTokenizer:()=>As,MobileBertTokenizer:()=>Gt,NllbTokenizer:()=>zs,NougatTokenizer:()=>Ks,PreTrainedTokenizer:()=>Ge,Qwen2Tokenizer:()=>Fr,RoFormerTokenizer:()=>rs,RobertaTokenizer:()=>bs,SiglipTokenizer:()=>fn,SpeechT5Tokenizer:()=>Mn,SqueezeBertTokenizer:()=>Ot,T5Tokenizer:()=>Rr,TokenizerModel:()=>K,VitsTokenizer:()=>bn,Wav2Vec2CTCTokenizer:()=>gn,WhisperTokenizer:()=>$r,XLMRobertaTokenizer:()=>nt,XLMTokenizer:()=>Ps,is_chinese_char:()=>S});var s=t("./src/utils/generic.js"),o=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),u=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function c(pe,$){const N=await Promise.all([(0,n.getModelJSON)(pe,"tokenizer.json",!0,$),(0,n.getModelJSON)(pe,"tokenizer_config.json",!0,$)]);return $.legacy!==null&&(N[1].legacy=$.legacy),N}function d(pe,$){const N=[];let X=0;for(const ie of pe.matchAll($)){const ce=ie[0];X0&&N.push(ce),X=ie.index+ce.length}return X=19968&&pe<=40959||pe>=13312&&pe<=19903||pe>=131072&&pe<=173791||pe>=173824&&pe<=177983||pe>=177984&&pe<=178207||pe>=178208&&pe<=183983||pe>=63744&&pe<=64255||pe>=194560&&pe<=195103}function E(pe,$,N){const X=[];let ie=0;for(;iethis.tokens_to_ids.get(N)??this.unk_token_id)}convert_ids_to_tokens($){return $.map(N=>this.vocab[N]??this.unk_token)}}class G extends K{constructor($){super($),this.tokens_to_ids=f($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.max_input_chars_per_word=$.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[N,X]of this.tokens_to_ids)this.vocab[X]=N}encode($){const N=[];for(const X of $){const ie=[...X];if(ie.length>this.max_input_chars_per_word){N.push(this.unk_token);continue}let ce=!1,ye=0;const Be=[];for(;ye0&&(et=this.config.continuing_subword_prefix+et),this.tokens_to_ids.has(et)){We=et;break}--Qe}if(We===null){ce=!0;break}Be.push(We),ye=Qe}ce?N.push(this.unk_token):N.push(...Be)}return N}}class j extends K{constructor($,N){super($);const X=$.vocab.length;this.vocab=new Array(X),this.scores=new Array(X);for(let ie=0;ie[ie,ce])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.minScore=(0,i.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes($){const N=$.chars,X=1;let ie=0;for(;ie{const pe=[...Array.from({length:94},(ie,ce)=>ce+33),...Array.from({length:12},(ie,ce)=>ce+161),...Array.from({length:82},(ie,ce)=>ce+174)],$=pe.slice();let N=0;for(let ie=0;ie<256;++ie)pe.includes(ie)||(pe.push(ie),$.push(256+N),N+=1);const X=$.map(ie=>String.fromCharCode(ie));return Object.fromEntries(pe.map((ie,ce)=>[ie,X[ce]]))})(),H=(0,o.reverseDictionary)(Y);class J extends K{constructor($){super($),this.tokens_to_ids=f($.vocab),this.unk_token_id=this.tokens_to_ids.get($.unk_token),this.unk_token=$.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[X,ie]of this.tokens_to_ids)this.vocab[ie]=X;const N=Array.isArray($.merges[0]);this.merges=N?$.merges:$.merges.map(X=>X.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((X,ie)=>[JSON.stringify(X),ie])),this.end_of_word_suffix=$.end_of_word_suffix,this.continuing_subword_suffix=$.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new l.LRUCache(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe($){if($.length===0)return[];const N=this.cache.get($);if(N!==void 0)return N;const X=Array.from($);this.end_of_word_suffix&&(X[X.length-1]+=this.end_of_word_suffix);let ie=[];if(X.length>1){const ce=new l.PriorityQueue((Qe,We)=>Qe.score`<0x${Be.toString(16).toUpperCase().padStart(2,"0")}>`);ye.every(Be=>this.tokens_to_ids.has(Be))?N.push(...ye):N.push(this.unk_token)}else N.push(this.unk_token)}return N}}class Q extends K{constructor($,N){super($),this.tokens_to_ids=f(N.target_lang?$.vocab[N.target_lang]:$.vocab),this.bos_token=N.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=N.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=N.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=N.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(const[X,ie]of this.tokens_to_ids)this.vocab[ie]=X}encode($){return $}}class oe extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"BertNormalizer":return new we($);case"Precompiled":return new B($);case"Sequence":return new Ne($);case"Replace":return new he($);case"NFC":return new V($);case"NFD":return new F($);case"NFKC":return new W($);case"NFKD":return new ee($);case"Strip":return new me($);case"StripAccents":return new te($);case"Lowercase":return new ue($);case"Prepend":return new Pe($);default:throw new Error(`Unknown Normalizer type: ${$.type}`)}}normalize($){throw Error("normalize should be implemented in subclass.")}_call($){return this.normalize($)}}class he extends oe{normalize($){const N=_(this.config.pattern);return N===null?$:$.replaceAll(N,this.config.content)}}class ae extends oe{constructor(){super(...arguments);Z(this,"form")}normalize(N){return N=N.normalize(this.form),N}}class V extends ae{constructor(){super(...arguments);Z(this,"form","NFC")}}class F extends ae{constructor(){super(...arguments);Z(this,"form","NFD")}}class W extends ae{constructor(){super(...arguments);Z(this,"form","NFKC")}}class ee extends ae{constructor(){super(...arguments);Z(this,"form","NFKD")}}class me extends oe{normalize($){return this.config.strip_left&&this.config.strip_right?$=$.trim():(this.config.strip_left&&($=$.trimStart()),this.config.strip_right&&($=$.trimEnd())),$}}class te extends oe{normalize($){return $=w($),$}}class ue extends oe{normalize($){return $=$.toLowerCase(),$}}class Pe extends oe{normalize($){return $=this.config.prepend+$,$}}class Ne extends oe{constructor($){super($),this.normalizers=$.normalizers.map(N=>oe.fromConfig(N))}normalize($){return this.normalizers.reduce((N,X)=>X.normalize(N),$)}}class we extends oe{_tokenize_chinese_chars($){const N=[];for(let X=0;X<$.length;++X){const ie=$[X],ce=ie.charCodeAt(0);S(ce)?(N.push(" "),N.push(ie),N.push(" ")):N.push(ie)}return N.join("")}stripAccents($){return $.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}_is_control($){switch($){case" ":case` +`:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test($)}}_clean_text($){const N=[];for(const X of $){const ie=X.charCodeAt(0);ie===0||ie===65533||this._is_control(X)||(/^\s$/.test(X)?N.push(" "):N.push(X))}return N.join("")}normalize($){return this.config.clean_text&&($=this._clean_text($)),this.config.handle_chinese_chars&&($=this._tokenize_chinese_chars($)),this.config.lowercase?($=$.toLowerCase(),this.config.strip_accents!==!1&&($=this.stripAccents($))):this.config.strip_accents&&($=this.stripAccents($)),$}}class q extends s.Callable{static fromConfig($){if($===null)return null;switch($.type){case"BertPreTokenizer":return new R($);case"Sequence":return new re($);case"Whitespace":return new fe($);case"WhitespaceSplit":return new Ae($);case"Metaspace":return new O($);case"ByteLevel":return new de($);case"Split":return new ve($);case"Punctuation":return new be($);case"Digits":return new Ce($);case"Replace":return new Ve($);default:throw new Error(`Unknown PreTokenizer type: ${$.type}`)}}pre_tokenize_text($,N){throw Error("pre_tokenize_text should be implemented in subclass.")}pre_tokenize($,N){return(Array.isArray($)?$.map(X=>this.pre_tokenize_text(X,N)):this.pre_tokenize_text($,N)).flat()}_call($,N){return this.pre_tokenize($,N)}}class R extends q{constructor($){super(),this.pattern=new RegExp(`[^\\s${M}]+|[${M}]`,"gu")}pre_tokenize_text($,N){return $.trim().match(this.pattern)||[]}}class de extends q{constructor($){super(),this.config=$,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Y,this.text_encoder=new TextEncoder}pre_tokenize_text($,N){return this.add_prefix_space&&!$.startsWith(" ")&&($=" "+$),(this.use_regex?$.match(this.pattern)||[]:[$]).map(ie=>Array.from(this.text_encoder.encode(ie),ce=>this.byte_encoder[ce]).join(""))}}class ve extends q{constructor($){super(),this.config=$,this.pattern=_(this.config.pattern,this.config.invert)}pre_tokenize_text($,N){var X;return this.pattern===null?[]:this.config.invert?$.match(this.pattern)||[]:((X=this.config.behavior)==null?void 0:X.toLowerCase())==="removed"?$.split(this.pattern).filter(ie=>ie):d($,this.pattern)}}class be extends q{constructor($){super(),this.config=$,this.pattern=new RegExp(`[^${M}]+|[${M}]+`,"gu")}pre_tokenize_text($,N){return $.match(this.pattern)||[]}}class Ce extends q{constructor($){super(),this.config=$;const N=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(N,"gu")}pre_tokenize_text($,N){return $.match(this.pattern)||[]}}class Se extends s.Callable{constructor($){super(),this.config=$}static fromConfig($){if($===null)return null;switch($.type){case"TemplateProcessing":return new Ie($);case"ByteLevel":return new Ke($);case"RobertaProcessing":return new Le($);case"BertProcessing":return new $e($);case"Sequence":return new Ye($);default:throw new Error(`Unknown PostProcessor type: ${$.type}`)}}post_process($,...N){throw Error("post_process should be implemented in subclass.")}_call($,...N){return this.post_process($,...N)}}class $e extends Se{constructor($){super($),this.cls=$.cls[0],this.sep=$.sep[0]}post_process($,N=null,{add_special_tokens:X=!0}={}){X&&($=(0,o.mergeArrays)([this.cls],$,[this.sep]));let ie=new Array($.length).fill(0);if(N!==null){const ce=X&&this instanceof Le?[this.sep]:[],ye=X?[this.sep]:[];$=(0,o.mergeArrays)($,ce,N,ye),ie=(0,o.mergeArrays)(ie,new Array(N.length+ce.length+ye.length).fill(1))}return{tokens:$,token_type_ids:ie}}}class Le extends $e{}class Ie extends Se{constructor($){super($),this.single=$.single,this.pair=$.pair}post_process($,N=null,{add_special_tokens:X=!0}={}){const ie=N===null?this.single:this.pair;let ce=[],ye=[];for(const Be of ie)"SpecialToken"in Be?X&&(ce.push(Be.SpecialToken.id),ye.push(Be.SpecialToken.type_id)):"Sequence"in Be&&(Be.Sequence.id==="A"?(ce=(0,o.mergeArrays)(ce,$),ye=(0,o.mergeArrays)(ye,new Array($.length).fill(Be.Sequence.type_id))):Be.Sequence.id==="B"&&(ce=(0,o.mergeArrays)(ce,N),ye=(0,o.mergeArrays)(ye,new Array(N.length).fill(Be.Sequence.type_id))));return{tokens:ce,token_type_ids:ye}}}class Ke extends Se{post_process($,N=null){return N&&($=(0,o.mergeArrays)($,N)),{tokens:$}}}class Ye extends Se{constructor($){super($),this.processors=$.processors.map(N=>Se.fromConfig(N))}post_process($,N=null,X={}){let ie;for(const ce of this.processors)if(ce instanceof Ke)$=ce.post_process($).tokens,N&&(N=ce.post_process(N).tokens);else{const ye=ce.post_process($,N,X);$=ye.tokens,ie=ye.token_type_ids}return{tokens:$,token_type_ids:ie}}}class ke extends s.Callable{constructor($){super(),this.config=$,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=$.trim_offsets}static fromConfig($){if($===null)return null;switch($.type){case"WordPiece":return new Ue($);case"Metaspace":return new se($);case"ByteLevel":return new Re($);case"Replace":return new Ze($);case"ByteFallback":return new Xe($);case"Fuse":return new tt($);case"Strip":return new ut($);case"Sequence":return new St($);case"CTC":return new _t($);case"BPEDecoder":return new at($);default:throw new Error(`Unknown Decoder type: ${$.type}`)}}_call($){return this.decode($)}decode($){return this.decode_chain($).join("")}decode_chain($){throw Error("`decode_chain` should be implemented in subclass.")}}class Ze extends ke{decode_chain($){const N=_(this.config.pattern);return N===null?$:$.map(X=>X.replaceAll(N,this.config.content))}}class Xe extends ke{constructor($){super($),this.text_decoder=new TextDecoder}decode_chain($){const N=[];let X=[];for(const ie of $){let ce=null;if(ie.length===6&&ie.startsWith("<0x")&&ie.endsWith(">")){const ye=parseInt(ie.slice(3,5),16);isNaN(ye)||(ce=ye)}if(ce!==null)X.push(ce);else{if(X.length>0){const ye=this.text_decoder.decode(Uint8Array.from(X));N.push(ye),X=[]}N.push(ie)}}if(X.length>0){const ie=this.text_decoder.decode(Uint8Array.from(X));N.push(ie),X=[]}return N}}class tt extends ke{decode_chain($){return[$.join("")]}}class ut extends ke{constructor($){super($),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain($){return $.map(N=>{let X=0;for(let ce=0;ce(X!==0&&(N.startsWith(this.config.prefix)?N=N.replace(this.config.prefix,""):N=" "+N),this.cleanup&&(N=k(N)),N))}}class Re extends ke{constructor($){super($),this.byte_decoder=H,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string($){const N=$.join(""),X=new Uint8Array([...N].map(ce=>this.byte_decoder[ce]));return this.text_decoder.decode(X)}decode_chain($){const N=[];let X=[];for(const ie of $)this.added_tokens.find(ce=>ce.content===ie)!==void 0?(X.length>0&&(N.push(this.convert_tokens_to_string(X)),X=[]),N.push(ie)):X.push(ie);return X.length>0&&N.push(this.convert_tokens_to_string(X)),N}}class _t extends ke{constructor($){super($),this.pad_token=this.config.pad_token,this.word_delimiter_token=this.config.word_delimiter_token,this.cleanup=this.config.cleanup}convert_tokens_to_string($){if($.length===0)return"";const N=[$[0]];for(let ce=1;ce<$.length;++ce)$[ce]!==N.at(-1)&&N.push($[ce]);let ie=N.filter(ce=>ce!==this.pad_token).join("");return this.cleanup&&(ie=k(ie).replaceAll(this.word_delimiter_token," ").trim()),ie}decode_chain($){return[this.convert_tokens_to_string($)]}}class St extends ke{constructor($){super($),this.decoders=$.decoders.map(N=>ke.fromConfig(N))}decode_chain($){return this.decoders.reduce((N,X)=>X.decode_chain(N),$)}}class at extends ke{constructor($){super($),this.suffix=this.config.suffix}decode_chain($){return $.map((N,X)=>N.replaceAll(this.suffix,X===$.length-1?"":" "))}}class jt extends ke{decode_chain($){let N="";for(let X=1;X<$.length;X+=2)N+=$[X];return[N]}}class O extends q{constructor($){super(),this.addPrefixSpace=$.add_prefix_space,this.replacement=$.replacement,this.strRep=$.str_rep||this.replacement,this.prepend_scheme=$.prepend_scheme??"always"}pre_tokenize_text($,{section_index:N=void 0}={}){let X=$.replaceAll(" ",this.strRep);return this.addPrefixSpace&&!X.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&N===0)&&(X=this.strRep+X),[X]}}class se extends ke{constructor($){super($),this.addPrefixSpace=$.add_prefix_space,this.replacement=$.replacement}decode_chain($){const N=[];for(let X=0;X<$.length;++X){let ie=$[X].replaceAll(this.replacement," ");this.addPrefixSpace&&X==0&&ie.startsWith(" ")&&(ie=ie.substring(1)),N.push(ie)}return N}}class B extends oe{constructor($){super($),this.charsmap=$.precompiled_charsmap}normalize($){return $=$.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),$=$.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),$.includes("~")?$=$.split("~").map(X=>X.normalize("NFKC")).join("~"):$=$.normalize("NFKC"),$}}class re extends q{constructor($){super(),this.tokenizers=$.pretokenizers.map(N=>q.fromConfig(N))}pre_tokenize_text($,N){return this.tokenizers.reduce((X,ie)=>ie.pre_tokenize(X,N),[$])}}class fe extends q{constructor($){super()}pre_tokenize_text($,N){return $.match(/\w+|[^\w\s]+/g)||[]}}class Ae extends q{constructor($){super()}pre_tokenize_text($,N){return y($)}}class Ve extends q{constructor($){super(),this.config=$,this.pattern=_(this.config.pattern),this.content=this.config.content}pre_tokenize_text($,N){return this.pattern===null?[$]:[$.replaceAll(this.pattern,this.config.content)]}}const Tt=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function Nt(pe,$,N,X){for(const ie of Object.keys(pe)){const ce=$-pe[ie].length,ye=N(ie),Be=new Array(ce).fill(ye);pe[ie]=X==="right"?(0,o.mergeArrays)(pe[ie],Be):(0,o.mergeArrays)(Be,pe[ie])}}function mt(pe,$){for(const N of Object.keys(pe))pe[N].length=$}class Ge extends s.Callable{constructor(N,X){super();Z(this,"return_token_type_ids",!1);Z(this,"padding_side","right");this._tokenizer_config=X,this.normalizer=oe.fromConfig(N.normalizer),this.pre_tokenizer=q.fromConfig(N.pre_tokenizer),this.model=K.fromConfig(N.model,X),this.post_processor=Se.fromConfig(N.post_processor),this.decoder=ke.fromConfig(N.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const ie of N.added_tokens){const ce=new z(ie);this.added_tokens.push(ce),this.model.tokens_to_ids.set(ce.content,ce.id),this.model.vocab[ce.id]=ce.content,ce.special&&(this.special_tokens.push(ce.content),this.all_special_ids.push(ce.id))}if(this.additional_special_tokens=X.additional_special_tokens??[],this.special_tokens.push(...this.additional_special_tokens),this.special_tokens=[...new Set(this.special_tokens)],this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.added_tokens_splitter=new l.DictionarySplitter(this.added_tokens.map(ie=>ie.content)),this.added_tokens_map=new Map(this.added_tokens.map(ie=>[ie.content,ie])),this.mask_token=this.getToken("mask_token"),this.mask_token_id=this.model.tokens_to_ids.get(this.mask_token),this.pad_token=this.getToken("pad_token","eos_token"),this.pad_token_id=this.model.tokens_to_ids.get(this.pad_token),this.sep_token=this.getToken("sep_token"),this.sep_token_id=this.model.tokens_to_ids.get(this.sep_token),this.unk_token=this.getToken("unk_token"),this.unk_token_id=this.model.tokens_to_ids.get(this.unk_token),this.bos_token=this.getToken("bos_token"),this.bos_token_id=this.model.tokens_to_ids.get(this.bos_token),this.eos_token=this.getToken("eos_token"),this.eos_token_id=this.model.tokens_to_ids.get(this.eos_token),this.model_max_length=X.model_max_length,this.remove_space=X.remove_space,this.clean_up_tokenization_spaces=X.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=X.do_lowercase_and_remove_accent??!1,X.padding_side&&(this.padding_side=X.padding_side),this.legacy=!1,this.chat_template=X.chat_template??null,Array.isArray(this.chat_template)){const ie=Object.create(null);for(const{name:ce,template:ye}of this.chat_template){if(typeof ce!="string"||typeof ye!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');ie[ce]=ye}this.chat_template=ie}this._compiled_template_cache=new Map}getToken(...N){for(const X of N){const ie=this._tokenizer_config[X];if(ie)if(typeof ie=="object"){if(ie.__type==="AddedToken")return ie.content;throw Error(`Unknown token: ${ie}`)}else return ie}return null}static async from_pretrained(N,{progress_callback:X=null,config:ie=null,cache_dir:ce=null,local_files_only:ye=!1,revision:Be="main",legacy:Qe=null}={}){const We=await c(N,{progress_callback:X,config:ie,cache_dir:ce,local_files_only:ye,revision:Be,legacy:Qe});return new this(...We)}_call(N,{text_pair:X=null,add_special_tokens:ie=!0,padding:ce=!1,truncation:ye=null,max_length:Be=null,return_tensor:Qe=!0,return_token_type_ids:We=null}={}){const et=Array.isArray(N);let gt;if(et){if(N.length===0)throw Error("text array must be non-empty");if(X!==null){if(Array.isArray(X)){if(N.length!==X.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");gt=N.map((Lt,Jt)=>this._encode_plus(Lt,{text_pair:X[Jt],add_special_tokens:ie,return_token_type_ids:We}))}else gt=N.map(Lt=>this._encode_plus(Lt,{add_special_tokens:ie,return_token_type_ids:We}))}else{if(N==null)throw Error("text may not be null or undefined");if(Array.isArray(X))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");gt=[this._encode_plus(N,{text_pair:X,add_special_tokens:ie,return_token_type_ids:We})]}if(Be===null?ce==="max_length"?Be=this.model_max_length:Be=(0,i.max)(gt.map(Lt=>Lt.input_ids.length))[0]:ye||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."),Be=Math.min(Be,this.model_max_length??1/0),ce||ye)for(let Lt=0;LtBe?ye&&mt(gt[Lt],Be):ce&&Nt(gt[Lt],Be,Jt=>Jt==="input_ids"?this.pad_token_id:0,this.padding_side));const At={};if(Qe){if(!(ce&&ye)&>.some(Jt=>{var Vt;for(const sr of Object.keys(Jt))if(Jt[sr].length!==((Vt=gt[0][sr])==null?void 0:Vt.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=[gt.length,gt[0].input_ids.length];for(const Jt of Object.keys(gt[0]))At[Jt]=new a.Tensor("int64",BigInt64Array.from(gt.flatMap(Vt=>Vt[Jt]).map(BigInt)),Lt)}else{for(const Lt of Object.keys(gt[0]))At[Lt]=gt.map(Jt=>Jt[Lt]);if(!et)for(const Lt of Object.keys(At))At[Lt]=At[Lt][0]}return At}_encode_text(N){if(N===null)return null;const X=this.added_tokens_splitter.split(N);for(let ce=0;ce0&&(X[ce-1]=X[ce-1].trimEnd()),ye.rstrip&&ce{if(ce.length===0)return[];if(this.added_tokens_map.has(ce))return[ce];if(this.remove_space===!0&&(ce=ce.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(ce=g(ce)),this.normalizer!==null&&(ce=this.normalizer(ce)),ce.length===0)return[];const Be=this.pre_tokenizer!==null?this.pre_tokenizer(ce,{section_index:ye}):[ce];return this.model(Be)})}_encode_plus(N,{text_pair:X=null,add_special_tokens:ie=!0,return_token_type_ids:ce=null}={}){const{tokens:ye,token_type_ids:Be}=this._tokenize_helper(N,{pair:X,add_special_tokens:ie}),Qe=this.model.convert_tokens_to_ids(ye),We={input_ids:Qe,attention_mask:new Array(Qe.length).fill(1)};return(ce??this.return_token_type_ids)&&Be&&(We.token_type_ids=Be),We}_tokenize_helper(N,{pair:X=null,add_special_tokens:ie=!1}={}){const ce=this._encode_text(N),ye=this._encode_text(X);return this.post_processor?this.post_processor(ce,ye,{add_special_tokens:ie}):{tokens:(0,o.mergeArrays)(ce??[],ye??[])}}tokenize(N,{pair:X=null,add_special_tokens:ie=!1}={}){return this._tokenize_helper(N,{pair:X,add_special_tokens:ie}).tokens}encode(N,{text_pair:X=null,add_special_tokens:ie=!0,return_token_type_ids:ce=null}={}){return this._encode_plus(N,{text_pair:X,add_special_tokens:ie,return_token_type_ids:ce}).input_ids}batch_decode(N,X={}){return N instanceof a.Tensor&&(N=N.tolist()),N.map(ie=>this.decode(ie,X))}decode(N,X={}){if(N instanceof a.Tensor&&(N=T(N)),!Array.isArray(N)||N.length===0||!(0,o.isIntegralNumber)(N[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(N,X)}decode_single(N,{skip_special_tokens:X=!1,clean_up_tokenization_spaces:ie=null}){let ce=this.model.convert_ids_to_tokens(N);X&&(ce=ce.filter(Be=>!this.special_tokens.includes(Be)));let ye=this.decoder?this.decoder(ce):ce.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(ye=ye.replaceAll(this.decoder.end_of_word_suffix," "),X&&(ye=ye.trim())),(ie??this.clean_up_tokenization_spaces)&&(ye=k(ye)),ye}get_chat_template({chat_template:N=null,tools:X=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const ie=this.chat_template;if(N!==null&&Object.hasOwn(ie,N))N=ie[N];else if(N===null)if(X!==null&&"tool_use"in ie)N=ie.tool_use;else if("default"in ie)N=ie.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(ie).sort()}.`)}else if(N===null)if(this.chat_template)N=this.chat_template;else throw Error("Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co./docs/transformers/main/en/chat_templating");return N}apply_chat_template(N,{tools:X=null,documents:ie=null,chat_template:ce=null,add_generation_prompt:ye=!1,tokenize:Be=!0,padding:Qe=!1,truncation:We=!1,max_length:et=null,return_tensor:gt=!0,return_dict:At=!1,tokenizer_kwargs:Lt={},...Jt}={}){if(ce=this.get_chat_template({chat_template:ce,tools:X}),typeof ce!="string")throw Error(`chat_template must be a string, but got ${typeof ce}`);let Vt=this._compiled_template_cache.get(ce);Vt===void 0&&(Vt=new u.Template(ce),this._compiled_template_cache.set(ce,Vt));const sr=Object.create(null);for(const Tr of Tt){const Er=this.getToken(Tr);Er&&(sr[Tr]=Er)}const Or=Vt.render({messages:N,add_generation_prompt:ye,tools:X,documents:ie,...sr,...Jt});if(Be){const Tr=this._call(Or,{add_special_tokens:!1,padding:Qe,truncation:We,max_length:et,return_tensor:gt,...Lt});return At?Tr:Tr.input_ids}return Or}}class ct extends Ge{constructor(){super(...arguments);Z(this,"return_token_type_ids",!0)}}class It extends Ge{constructor(){super(...arguments);Z(this,"return_token_type_ids",!0)}}class Gt extends Ge{constructor(){super(...arguments);Z(this,"return_token_type_ids",!0)}}class Ot extends Ge{constructor(){super(...arguments);Z(this,"return_token_type_ids",!0)}}class ir extends Ge{constructor(){super(...arguments);Z(this,"return_token_type_ids",!0)}}class Ar extends Ge{constructor(){super(...arguments);Z(this,"return_token_type_ids",!0)}}class ts extends Ge{constructor(){super(...arguments);Z(this,"return_token_type_ids",!0)}}class yr extends Ge{constructor(){super(...arguments);Z(this,"return_token_type_ids",!0)}}class rs extends Ge{constructor(){super(...arguments);Z(this,"return_token_type_ids",!0)}}class Es extends Ge{}class ws extends Ge{}class Ps extends Ge{constructor(N,X){super(N,X);Z(this,"return_token_type_ids",!0);console.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}}class ss extends Ge{constructor(){super(...arguments);Z(this,"return_token_type_ids",!0)}}class Rr extends Ge{}class Cs extends Ge{}class Ss extends Ge{}class ns extends Ge{constructor($,N){super($,N),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(X=>this.languageRegex.test(X)),this.lang_to_token=X=>X}_build_translation_inputs($,N,X){return vr(this,$,N,X)}}class Ms extends ns{}class bs extends Ge{}class Ur extends Ge{}const ar="▁";class De extends Ge{constructor(N,X){super(N,X);Z(this,"padding_side","left");this.legacy=X.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new O({replacement:ar,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(N){if(N===null)return null;if(this.legacy||N.length===0)return super._encode_text(N);let X=super._encode_text(ar+N.replaceAll(ar," "));return X.length>1&&X[0]===ar&&this.special_tokens.includes(X[1])&&(X=X.slice(1)),X}}class qe extends Ge{}class nt extends Ge{}class Qt extends Ge{}class lr extends Ge{}class ys extends Ge{}class $s extends Ge{}class Fr extends Ge{}class ks extends Ge{}class jr extends Ge{}function vr(pe,$,N,X){if(!("language_codes"in pe)||!Array.isArray(pe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in pe)||!(pe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in pe)||typeof pe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const ie=X.src_lang,ce=X.tgt_lang;if(!pe.language_codes.includes(ce))throw new Error(`Target language code "${ce}" is not valid. Must be one of: {${pe.language_codes.join(", ")}}`);if(ie!==void 0){if(!pe.language_codes.includes(ie))throw new Error(`Source language code "${ie}" is not valid. Must be one of: {${pe.language_codes.join(", ")}}`);for(const ye of pe.post_processor.config.single)if("SpecialToken"in ye&&pe.languageRegex.test(ye.SpecialToken.id)){ye.SpecialToken.id=pe.lang_to_token(ie);break}}return X.forced_bos_token_id=pe.model.convert_tokens_to_ids([pe.lang_to_token(ce)])[0],pe._call($,N)}class zs extends Ge{constructor($,N){super($,N),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(X=>this.languageRegex.test(X)),this.lang_to_token=X=>X}_build_translation_inputs($,N,X){return vr(this,$,N,X)}}class xr extends Ge{constructor($,N){super($,N),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(X=>this.languageRegex.test(X)).map(X=>X.slice(2,-2)),this.lang_to_token=X=>`__${X}__`}_build_translation_inputs($,N,X){return vr(this,$,N,X)}}class $r extends Ge{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr($,{return_timestamps:N=!1,return_language:X=!1,time_precision:ie=null,force_full_sequences:ce=!0}={}){if(ie===null)throw Error("Must specify time_precision");let ye=null;const Be=N==="word";function Qe(){return{language:ye,timestamp:[null,null],text:""}}const We=[];let et=Qe(),gt=0;const At=this.timestamp_begin,Jt=At+1500;let Vt=[],sr=[],Or=!1,Tr=null;const Er=new Set(this.all_special_ids);for(const Kt of $){const mr=Kt.tokens,kr=Be?Kt.token_timestamps:null;let is=null,qr=At;if("stride"in Kt){const[gr,Zt,dr]=Kt.stride;if(gt-=Zt,Tr=gr-dr,Zt&&(qr=Zt/ie+At),dr)for(let pr=mr.length-1;pr>=0;--pr){const hr=Number(mr[pr]);if(hr>=At){if(is!==null&&(hr-At)*ie=At&&Zt<=Jt){const dr=(Zt-At)*ie+gt,pr=(0,i.round)(dr,2);if(is!==null&&Zt>=is)Or=!0;else if(Or||Vt.length>0&&Zt0?(Vt.push(cr),Be&&sr.push(Qr)):Vt.every(gr=>gr.length===0)&&(et=Qe(),Vt=[],cr=[],sr=[],Qr=[])}if(Vt.length>0){if(ce&&N)throw new Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");const[Kt,mr]=this.findLongestCommonSequence(Vt,sr),kr=this.decode(Kt);et.text=kr,Be&&(et.words=this.collateWordTimestamps(Kt,mr,ye)),We.push(et)}let Yt=Object.create(null);const os=We.map(Kt=>Kt.text).join("");if(N||X){for(let Kt=0;Kt0;let Be=ye?[]:null,Qe=ye?N[0]:null;for(let We=1;We<$.length;++We){const et=$[We];let gt=0,At=[ie,ie,0,0];const Lt=et.length;for(let Yt=1;YtZt===qr[dr]&&Qe[os+dr]<=N[We][kr+dr]).length:cr=mr.filter((Zt,dr)=>Zt===qr[dr]).length;const Qr=Yt/1e4,gr=cr/Yt+Qr;cr>1&&gr>gt&&(gt=gr,At=[os,Kt,kr,is])}const[Jt,Vt,sr,Or]=At,Tr=Math.floor((Vt+Jt)/2),Er=Math.floor((Or+sr)/2);ce.push(...X.slice(0,Tr)),X=et.slice(Er),ie=X.length,ye&&(Be.push(...Qe.slice(0,Tr)),Qe=N[We].slice(Er))}return ce.push(...X),ye?(Be.push(...Qe),[ce,Be]):[ce,[]]}collateWordTimestamps($,N,X){const[ie,ce,ye]=this.combineTokensIntoWords($,X),Be=[];for(let Qe=0;Qe=ie){const Be=((ye-ie)*X).toFixed(2);ce.push(`<|${Be}|>`),ce.push([])}else ce[ce.length-1].push(ye);return ce=ce.map(ye=>typeof ye=="string"?ye:super.decode(ye,N)),ce.join("")}splitTokensOnUnicode($){const N=this.decode($,{decode_with_timestamps:!0}),X="�",ie=[],ce=[],ye=[];let Be=[],Qe=[],We=0;for(let et=0;et<$.length;++et){const gt=$[et];Be.push(gt),Qe.push(et);const At=this.decode(Be,{decode_with_timestamps:!0});(!At.includes(X)||N[We+At.indexOf(X)]===X)&&(ie.push(At),ce.push(Be),ye.push(Qe),Be=[],Qe=[],We+=At.length)}return[ie,ce,ye]}splitTokensOnSpaces($){const[N,X,ie]=this.splitTokensOnUnicode($),ce=[],ye=[],Be=[],Qe=new RegExp(`^[${M}]$`,"gu");for(let We=0;We=this.model.tokens_to_ids.get("<|endoftext|>"),Jt=et.startsWith(" "),Vt=et.trim(),sr=Qe.test(Vt);if(Lt||Jt||sr||ce.length===0)ce.push(et),ye.push(gt),Be.push(At);else{const Or=ce.length-1;ce[Or]+=et,ye[Or].push(...gt),Be[Or].push(...At)}}return[ce,ye,Be]}mergePunctuations($,N,X,ie,ce){const ye=structuredClone($),Be=structuredClone(N),Qe=structuredClone(X);let We=ye.length-2,et=ye.length-1;for(;We>=0;)ye[We].startsWith(" ")&&ie.includes(ye[We].trim())?(ye[et]=ye[We]+ye[et],Be[et]=(0,o.mergeArrays)(Be[We],Be[et]),Qe[et]=(0,o.mergeArrays)(Qe[We],Qe[et]),ye[We]="",Be[We]=[],Qe[We]=[]):et=We,--We;for(We=0,et=1;etgt),Be.filter(gt=>gt.length>0),Qe.filter(gt=>gt.length>0)]}}class Hr extends Ge{}class mn extends Ge{}class fn extends Ge{}class _n extends Ge{constructor($,N){super($,N),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(X=>this.languageRegex.test(X)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text($){if($===null)return null;const[N,...X]=$.trim().split(this.languageRegex);if(X.length===0)return super._encode_text(N);if(X.length===2){const[ie,ce]=X;return this.supported_language_codes.includes(ie)||console.warn(`Unsupported language code "${ie}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,o.mergeArrays)([ie],super._encode_text(ce))}}}class gn extends Ge{}class wn extends Ge{}class Is extends Ge{}class Mn extends Ge{}class Ks extends Ge{}class bn extends Ge{constructor($,N){super($,N),this.decoder=new jt({})}}class yn extends Ge{}class As extends Ge{}class vn{static async from_pretrained($,{progress_callback:N=null,config:X=null,cache_dir:ie=null,local_files_only:ce=!1,revision:ye="main",legacy:Be=null}={}){var At;const[Qe,We]=await c($,{progress_callback:N,config:X,cache_dir:ie,local_files_only:ce,revision:ye,legacy:Be}),et=((At=We.tokenizer_class)==null?void 0:At.replace(/Fast$/,""))??"PreTrainedTokenizer";let gt=this.TOKENIZER_CLASS_MAPPING[et];return gt||(console.warn(`Unknown tokenizer class "${et}", attempting to construct from base class.`),gt=Ge),new gt(Qe,We)}}Z(vn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Rr,DistilBertTokenizer:Es,CamembertTokenizer:ws,DebertaTokenizer:ir,DebertaV2Tokenizer:Ar,BertTokenizer:ct,HerbertTokenizer:ts,ConvBertTokenizer:yr,RoFormerTokenizer:rs,XLMTokenizer:Ps,ElectraTokenizer:ss,MobileBertTokenizer:Gt,SqueezeBertTokenizer:Ot,AlbertTokenizer:It,GPT2Tokenizer:Cs,BartTokenizer:Ss,MBartTokenizer:ns,MBart50Tokenizer:Ms,RobertaTokenizer:bs,WhisperTokenizer:$r,CodeGenTokenizer:Hr,CLIPTokenizer:mn,SiglipTokenizer:fn,MarianTokenizer:_n,BloomTokenizer:Ur,NllbTokenizer:zs,M2M100Tokenizer:xr,LlamaTokenizer:De,CodeLlamaTokenizer:qe,XLMRobertaTokenizer:nt,MPNetTokenizer:Qt,FalconTokenizer:lr,GPTNeoXTokenizer:ys,EsmTokenizer:$s,Wav2Vec2CTCTokenizer:gn,BlenderbotTokenizer:wn,BlenderbotSmallTokenizer:Is,SpeechT5Tokenizer:Mn,NougatTokenizer:Ks,VitsTokenizer:bn,Qwen2Tokenizer:Fr,GemmaTokenizer:ks,Grok1Tokenizer:jr,CohereTokenizer:yn,MgpstrTokenizer:As,PreTrainedTokenizer:Ge})},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>G,hamming:()=>d,hanning:()=>c,mel_filter_bank:()=>S,read_audio:()=>u,spectrogram:()=>C,window_function:()=>A});var s=t("./src/utils/hub.js"),o=t("./src/utils/maths.js"),n=t("./src/utils/core.js"),i=t("./src/env.js"),a=t("?7a2c"),l=t("./src/utils/tensor.js");async function u(j,Y){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co./docs/transformers.js/guides/node-audio-processing.");const H=await(await(0,s.getFile)(j)).arrayBuffer(),J=new AudioContext({sampleRate:Y});typeof Y>"u"&&console.warn(`No sampling rate provided, using default of ${J.sampleRate}Hz.`);const Q=await J.decodeAudioData(H);let oe;if(Q.numberOfChannels===2){const he=Math.sqrt(2),ae=Q.getChannelData(0),V=Q.getChannelData(1);oe=new Float32Array(ae.length);for(let F=0;F2595*Math.log10(1+j/700),kaldi:j=>1127*Math.log(1+j/700),slaney:(j,Y=1e3,H=15,J=27/Math.log(6.4))=>j>=Y?H+Math.log(j/Y)*J:3*j/200};function f(j,Y="htk"){const H=_[Y];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?H(j):j.map(J=>H(J))}const T={htk:j=>700*(10**(j/2595)-1),kaldi:j=>700*(Math.exp(j/1127)-1),slaney:(j,Y=1e3,H=15,J=Math.log(6.4)/27)=>j>=H?Y*Math.exp(J*(j-H)):200*j/3};function k(j,Y="htk"){const H=T[Y];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof j=="number"?H(j):j.map(J=>H(J))}function w(j,Y){const H=Float64Array.from({length:Y.length-1},(he,ae)=>Y[ae+1]-Y[ae]),J=Array.from({length:j.length},()=>new Array(Y.length));for(let he=0;henew Array(j.length));for(let he=0;hej+J*oe)}function S(j,Y,H,J,Q,oe=null,he="htk",ae=!1){if(oe!==null&&oe!=="slaney")throw new Error('norm must be one of null or "slaney"');if(j<2)throw new Error(`Require num_frequency_bins: ${j} >= 2`);if(H>J)throw new Error(`Require min_frequency: ${H} <= max_frequency: ${J}`);const V=f(H,he),F=f(J,he),W=g(V,F,Y+2);let ee=k(W,he),me;if(ae){const ue=Q/((j-1)*2);me=f(Float64Array.from({length:j},(Pe,Ne)=>Ne*ue),he),ee=W}else me=g(0,Math.floor(Q/2),j);const te=w(me,ee);if(oe!==null&&oe==="slaney")for(let ue=0;ueQ)throw Error(`frame_length (${H}) may not be larger than fft_length (${Q})`);if(ve!==H)throw new Error(`Length of the window (${ve}) must equal frame_length (${H})`);if(J<=0)throw new Error("hop_length must be greater than zero");if(oe===null&&W!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(he){if(ae!=="reflect")throw new Error(`pad_mode="${ae}" not implemented yet.`);const tt=Math.floor((Q-1)/2)+1;j=E(j,tt,tt)}let be=Math.floor(1+Math.floor((j.length-H)/J));we!==null&&bebe?R&&($e=q):$e=Se=q);const Le=new o.FFT(Q),Ie=new Float64Array(Q),Ke=new Float64Array(Le.outputBufferSize),Ye=new Float32Array(Ce*$e);for(let tt=0;tt=1;--Re)Ie[Re]-=F*Ie[Re-1];Ie[0]*=1-F}for(let Re=0;ReMath.pow(ae,.85));break;default:throw new Error(`Unknown window type ${Y}.`)}if(H&&(he=he.subarray(0,j)),J===null)return he;if(j>J)throw new Error(`Length of the window (${j}) may not be larger than frame_length (${J})`);return he}function z(j,Y){let H=44;const J=new ArrayBuffer(H+j.length*4),Q=new DataView(J);K(Q,0,"RIFF"),Q.setUint32(4,36+j.length*4,!0),K(Q,8,"WAVE"),K(Q,12,"fmt "),Q.setUint32(16,16,!0),Q.setUint16(20,3,!0),Q.setUint16(22,1,!0),Q.setUint32(24,Y,!0),Q.setUint32(28,Y*4,!0),Q.setUint16(32,4,!0),Q.setUint16(34,32,!0),K(Q,36,"data"),Q.setUint32(40,j.length*4,!0);for(let oe=0;oe{let oe=await Q.arrayBuffer();a.writeFileSync(J,Buffer.from(oe))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await H(Y,this.toBlob())}}},"./src/utils/constants.js":(e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>o,FEATURE_EXTRACTOR_NAME:()=>n,GENERATION_CONFIG_NAME:()=>u,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>i,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",o="config.json",n="preprocessor_config.json",i=n,a="processor_config.json",l="chat_template.json",u="generation_config.json"},"./src/utils/core.js":(e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>u,calculateReflectOffset:()=>_,count:()=>w,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>i,len:()=>k,mergeArrays:()=>c,pick:()=>T,pop:()=>p,product:()=>d,reverseDictionary:()=>o,saveBlob:()=>f});function s(g,S){g&&g(S)}function o(g){return Object.fromEntries(Object.entries(g).map(([S,E])=>[E,S]))}function n(g){return g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function i(g){var S,E,y;return((y=(E=(S=g==null?void 0:g.prototype)==null?void 0:S.__proto__)==null?void 0:E.constructor)==null?void 0:y.name)==="TypedArray"}function a(g){return Number.isInteger(g)||typeof g=="bigint"}function l(g){return g==null||g===-1}function u(g){const 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 y=g[S];if(y!==void 0)return delete g[S],y;if(E===void 0)throw Error(`Key ${S} does not exist in object.`);return E}function c(...g){return Array.prototype.concat.apply([],g)}function d(...g){return g.reduce((S,E)=>S.flatMap(y=>E.map(M=>[y,M])))}function _(g,S){return Math.abs((g+S)%(2*S)-S)}function f(g,S){const E=URL.createObjectURL(S),y=document.createElement("a");y.href=E,y.download=g,y.click(),y.remove(),URL.revokeObjectURL(E)}function T(g,S){return Object.assign({},...S.map(E=>{if(g[E]!==void 0)return{[E]:g[E]}}))}function k(g){let S=0;for(const E of g)++S;return S}function w(g,S){let E=0;for(const y of g)y===S&&++E;return E}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>o,DictionarySplitter:()=>l,LRUCache:()=>u,PriorityQueue:()=>s,TokenLattice:()=>i});class s{constructor(c=(_,f)=>_>f,d=1/0){this._heap=[],this._comparator=c,this._maxSize=d}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...c){return this.extend(c)}extend(c){for(const d of c)if(this.size0&&this._swap(0,d),this._heap.pop(),this._siftDown(),c}replace(c){const d=this.peek();return this._heap[0]=c,this._siftDown(),d}_parent(c){return(c+1>>>1)-1}_left(c){return(c<<1)+1}_right(c){return c+1<<1}_greater(c,d){return this._comparator(this._heap[c],this._heap[d])}_swap(c,d){const _=this._heap[c];this._heap[c]=this._heap[d],this._heap[d]=_}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(c){for(;c>0&&this._greater(c,this._parent(c));)this._swap(c,this._parent(c)),c=this._parent(c)}_siftDown(){let c=0;for(;this._left(c)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const f=new a(this.bosTokenId,0,0,0,0),T=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(f.clone()),this.nodes.push(T.clone()),this.beginNodes[this.len].push(T),this.endNodes[0].push(f)}insert(c,d,_,f){const T=this.nodes.length,k=new a(f,T,c,d,_);this.beginNodes[c].push(k),this.endNodes[c+d].push(k),this.nodes.push(k)}viterbi(){const c=this.len;let d=0;for(;d<=c;){if(this.beginNodes[d].length==0)return[];for(let w of this.beginNodes[d]){w.prev=null;let g=0,S=null;for(let E of this.endNodes[d]){const y=E.backtraceScore+w.score;(S===null||y>g)&&(S=E.clone(),g=y)}if(S!==null)w.prev=S,w.backtraceScore=g;else return[]}++d}const _=[],T=this.beginNodes[c][0].prev;if(T===null)return[];let k=T.clone();for(;k.prev!==null;)_.push(k.clone()),k=k.clone().prev.clone();return _.reverse(),_}piece(c){return this.chars.slice(c.pos,c.pos+c.length).join("")}tokens(){return this.viterbi().map(d=>this.piece(d))}tokenIds(){return this.viterbi().map(d=>d.tokenId)}}class a{constructor(c,d,_,f,T){this.tokenId=c,this.nodeId=d,this.pos=_,this.length=f,this.score=T,this.prev=null,this.backtraceScore=0}clone(){const c=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return c.prev=this.prev,c.backtraceScore=this.backtraceScore,c}}class l{constructor(c){this.trie=this._buildTrie(c)}_buildTrie(c){var _;const d=Object.create(null);for(const f of c){let T=d;for(let k=0;kf&&d.push(c.slice(f,T)),d.push(w),T+=w.length,f=T):++T}return f<_&&d.push(c.slice(f)),d}}class u{constructor(c){this.capacity=c,this.cache=new Map}get(c){if(!this.cache.has(c))return;const d=this.cache.get(c);return this.cache.delete(c),this.cache.set(c,d),d}put(c,d){this.cache.has(c)&&this.cache.delete(c),this.cache.set(c,d),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}},"./src/utils/devices.js":(e,r,t)=>{t.r(r),t.d(r,{DEVICE_TYPES:()=>s});const s=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(e,r,t)=>{t.r(r),t.d(r,{DATA_TYPES:()=>i,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>n});var s=t("./src/env.js"),o=t("./src/utils/devices.js");const n=function(){let u;return async function(){if(u===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)u=!1;else try{u=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{u=!1}return u}}(),i=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[o.DEVICE_TYPES.wasm]:i.q8}),l=Object.freeze({[i.fp32]:"",[i.fp16]:"_fp16",[i.int8]:"_int8",[i.uint8]:"_uint8",[i.q8]:"_quantized",[i.q4]:"_q4",[i.q4f16]:"_q4f16",[i.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let o=function(...n){return o._call(...n)};return Object.setPrototypeOf(o,new.target.prototype)}_call(...o){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(e,r,t)=>{t.r(r),t.d(r,{MAX_EXTERNAL_DATA_CHUNKS:()=>a,getFile:()=>_,getModelFile:()=>g,getModelJSON:()=>S});var s=t("?7a2c"),o=t("?a42a"),n=t("./src/env.js"),i=t("./src/utils/core.js");const a=100,l={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class u{constructor(v){if(this.filePath=v,this.headers=new Headers,this.exists=s.existsSync(v),this.exists){this.status=200,this.statusText="OK";let C=s.statSync(v);this.headers.set("content-length",C.size.toString()),this.updateContentType();const A=s.createReadStream(v);this.body=new ReadableStream({start(z){A.on("data",K=>z.enqueue(K)),A.on("end",()=>z.close()),A.on("error",K=>z.error(K))},cancel(){A.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 u(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(M,v=null,C=null){let A;try{A=new URL(M)}catch{return!1}return!(v&&!v.includes(A.protocol)||C&&!C.includes(A.hostname))}const c=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function d(M){return!(!c.test(M)||M.includes("..")||M.includes("--")||M.endsWith(".git")||M.endsWith(".ipynb"))}async function _(M){var v;if(n.env.useFS&&!p(M,["http:","https:","blob:"]))return new u(M.toString());if(typeof process<"u"&&((v=process==null?void 0:process.release)==null?void 0:v.name)==="node"){const C=!!(Ls!=null&&Ls.TESTING_REMOTELY),A=n.env.version,z=new Headers;if(z.set("User-Agent",`transformers.js/${A}; is_ci/${C};`),p(M,["http:","https:"],["huggingface.co","hf.co"])){const G=(Ls==null?void 0:Ls.HF_TOKEN)??(Ls==null?void 0:Ls.HF_ACCESS_TOKEN);G&&z.set("Authorization",`Bearer ${G}`)}return fetch(M,{headers:z})}else return fetch(M)}const f={400:"Bad request error occurred while trying to load file",401:"Unauthorized access to file",403:"Forbidden access to file",404:"Could not locate file",408:"Request timeout error occurred while trying to load file",500:"Internal server error error occurred while trying to load file",502:"Bad gateway error occurred while trying to load file",503:"Service unavailable error occurred while trying to load file",504:"Gateway timeout error occurred while trying to load file"};function T(M,v,C){if(!C)return null;const A=f[M]??`Error (${M}) occurred while trying to load file`;throw Error(`${A}: "${v}".`)}class k{constructor(v){this.path=v}async match(v){let C=o.join(this.path,v),A=new u(C);if(A.exists)return A}async put(v,C,A=void 0){let z=o.join(this.path,v);try{const K=C.headers.get("Content-Length"),G=parseInt(K??"0");let j=0;await s.promises.mkdir(o.dirname(z),{recursive:!0});const Y=s.createWriteStream(z),H=C.body.getReader();for(;;){const{done:J,value:Q}=await H.read();if(J)break;await new Promise((he,ae)=>{Y.write(Q,V=>{if(V){ae(V);return}he()})}),j+=Q.length;const oe=G?j/G*100:0;A==null||A({progress:oe,loaded:j,total:G})}Y.close()}catch(K){try{await s.promises.unlink(z)}catch{}throw K}}}async function w(M,...v){for(let C of v)try{let A=await M.match(C);if(A)return A}catch{continue}}async function g(M,v,C=!0,A={},z=!1){if(!n.env.allowLocalModels){if(A.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!n.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,i.dispatchCallback)(A.progress_callback,{status:"initiate",name:M,file:v});let K;if(!K&&n.env.useCustomCache){if(!n.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!n.env.customCache.match||!n.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");K=n.env.customCache}if(!K&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{K=await caches.open("transformers-cache")}catch(ee){console.warn("An error occurred while opening the browser cache:",ee)}}if(!K&&n.env.useFSCache){if(!n.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");K=new k(A.cache_dir??n.env.cacheDir)}const G=A.revision??"main",j=y(M,v),Y=d(M),H=Y?y(n.env.localModelPath,j):j,J=y(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",M).replaceAll("{revision}",encodeURIComponent(G)),v);let Q;const oe=K instanceof k?G==="main"?j:y(M,G,v):J;let he=!1,ae;K&&(ae=await w(K,H,oe));const V=ae!==void 0;if(ae===void 0){if(n.env.allowLocalModels)if(p(j,["http:","https:"])){if(A.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${j}.`);if(!n.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${j}.`)}else try{ae=await _(H),Q=H}catch(me){console.warn(`Unable to load from local path "${H}": "${me}"`)}if(ae===void 0||ae.status===404){if(A.local_files_only||!n.env.allowRemoteModels){if(C)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${H}".`);return null}if(!Y)throw Error(`Local file missing at "${H}" and download aborted due to invalid model ID "${M}".`);if(ae=await _(J),ae.status!==200)return T(ae.status,J,C);Q=oe}he=K&&typeof Response<"u"&&ae instanceof Response&&ae.status===200}(0,i.dispatchCallback)(A.progress_callback,{status:"download",name:M,file:v});let F;if(!(n.apis.IS_NODE_ENV&&z)){let ee;A.progress_callback?V&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(ee=new Uint8Array(await ae.arrayBuffer()),(0,i.dispatchCallback)(A.progress_callback,{status:"progress",name:M,file:v,progress:100,loaded:ee.length,total:ee.length})):ee=await E(ae,me=>{(0,i.dispatchCallback)(A.progress_callback,{status:"progress",name:M,file:v,...me})}):ee=new Uint8Array(await ae.arrayBuffer()),F=ee}if(he&&Q&&await K.match(Q)===void 0&&(F?await K.put(Q,new Response(F,{headers:ae.headers})).catch(ee=>{console.warn(`Unable to add response to browser cache: ${ee}.`)}):await K.put(Q,ae,A.progress_callback)),(0,i.dispatchCallback)(A.progress_callback,{status:"done",name:M,file:v}),F){if(!n.apis.IS_NODE_ENV&&z)throw new Error("Cannot return path in a browser environment.");return F}if(ae instanceof u)return ae.filePath;const W=await(K==null?void 0:K.match(Q));if(W instanceof u)return W.filePath;if(W instanceof Response)return new Uint8Array(await W.arrayBuffer());if(typeof W=="string")return W;throw new Error("Unable to get model file path or buffer.")}async function S(M,v,C=!0,A={}){const z=await g(M,v,C,A,!1);if(z===null)return{};const G=new TextDecoder("utf-8").decode(z);return JSON.parse(G)}async function E(M,v){const C=M.headers.get("Content-Length");C===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let A=parseInt(C??"0"),z=new Uint8Array(A),K=0;const G=M.body.getReader();async function j(){const{done:Y,value:H}=await G.read();if(Y)return;const J=K+H.length;if(J>A){A=J;const oe=new Uint8Array(A);oe.set(z),z=oe}z.set(H,K),K=J;const Q=K/A*100;return v({progress:Q,loaded:K,total:A}),j()}return await j(),z}function y(...M){return M=M.map((v,C)=>(C&&(v=v.replace(new RegExp("^/"),"")),C!==M.length-1&&(v=v.replace(new RegExp("/$"),"")),v)),M.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>f,load_image:()=>T});var s=t("./src/utils/core.js"),o=t("./src/utils/hub.js"),n=t("./src/env.js"),i=t("./src/utils/tensor.js"),a=t("?2b25");let l,u,p;const c=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;if(c)l=(k,w)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(k,w)},p=self.createImageBitmap,u=self.ImageData;else if(a)p=async k=>{const g=(await k.metadata()).channels,{data:S,info:E}=await k.rotate().raw().toBuffer({resolveWithObject:!0}),y=new f(new Uint8ClampedArray(S),E.width,E.height,E.channels);return g!==void 0&&g!==E.channels&&y.convert(g),y};else throw new Error("Unable to load image processing library.");const d={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},_=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class f{constructor(w,g,S,E){this.data=w,this.width=g,this.height=S,this.channels=E}get size(){return[this.width,this.height]}static async read(w){if(w instanceof f)return w;if(typeof w=="string"||w instanceof URL)return await this.fromURL(w);if(w instanceof Blob)return await this.fromBlob(w);if(typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&w instanceof OffscreenCanvas)return this.fromCanvas(w);throw new Error(`Unsupported input type: ${typeof w}`)}static fromCanvas(w){if(!c)throw new Error("fromCanvas() is only supported in browser environments.");const S=w.getContext("2d").getImageData(0,0,w.width,w.height).data;return new f(S,w.width,w.height,4)}static async fromURL(w){const g=await(0,o.getFile)(w);if(g.status!==200)throw new Error(`Unable to read image from "${w}" (${g.status} ${g.statusText})`);const S=await g.blob();return this.fromBlob(S)}static async fromBlob(w){if(c){const g=await p(w),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=a(await w.arrayBuffer());return await p(g)}}static fromTensor(w,g="CHW"){if(w.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${w.dims.length} dimensions.`);if(g==="CHW")w=w.transpose(1,2,0);else if(g!=="HWC")throw new Error(`Unsupported channel format: ${g}`);if(!(w.data instanceof Uint8ClampedArray||w.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${w.type}`);switch(w.dims[2]){case 1:case 2:case 3:case 4:return new f(w.data,w.dims[1],w.dims[0],w.dims[2]);default:throw new Error(`Unsupported number of channels: ${w.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const w=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let g=0,S=0;g=0?C=S:z=-S,E>=0?A=E:K=-E,v.drawImage(M,C,A,w,g,z,K,w,g),new f(v.getImageData(0,0,w,g).data,w,g,4).convert(y)}else{let y=this.toSharp();if(S>=0&&E>=0)y=y.extract({left:Math.floor(S),top:Math.floor(E),width:w,height:g});else if(S<=0&&E<=0){const M=Math.floor(-E),v=Math.floor(-S);y=y.extend({top:M,left:v,right:w-this.width-v,bottom:g-this.height-M})}else{let M=[0,0],v=0;E<0?(M[0]=Math.floor(-E),M[1]=g-this.height-M[0]):v=Math.floor(E);let C=[0,0],A=0;S<0?(C[0]=Math.floor(-S),C[1]=w-this.width-C[0]):A=Math.floor(S),y=y.extend({top:M[0],bottom:M[1],left:C[0],right:C[1]}).extract({left:A,top:v,width:w,height:g})}return await p(y)}}async toBlob(w="image/png",g=1){if(!c)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:w,quality:g})}toTensor(w="CHW"){let g=new i.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(w!=="HWC")if(w==="CHW")g=g.permute(2,0,1);else throw new Error(`Unsupported channel format: ${w}`);return g}toCanvas(){if(!c)throw new Error("toCanvas() is only supported in browser environments.");const w=this.clone().rgba(),g=l(w.width,w.height),S=new u(w.data,w.width,w.height);return g.getContext("2d").putImageData(S,0,0),g}split(){const{data:w,width:g,height:S,channels:E}=this,y=w.constructor,M=w.length/E,v=Array.from({length:E},()=>new y(M));for(let C=0;Cnew f(C,g,S,1))}_update(w,g,S,E=null){return this.data=w,this.width=g,this.height=S,E!==null&&(this.channels=E),this}clone(){return new f(this.data.slice(),this.width,this.height,this.channels)}convert(w){if(this.channels===w)return this;switch(w){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw new Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(w){if(c){if(n.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const g=w.split(".").pop().toLowerCase(),S=_.get(g)??"image/png",E=await this.toBlob(S);(0,s.saveBlob)(w,E)}else{if(n.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(w);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(c)throw new Error("toSharp() is only supported in server-side environments.");return a(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const T=f.read.bind(f)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>T,bankers_round:()=>g,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>S,interpolate_data:()=>s,log_softmax:()=>i,magnitude:()=>u,max:()=>c,medianFilter:()=>k,min:()=>p,permute_data:()=>o,round:()=>w,softmax:()=>n});function s(E,[y,M,v],[C,A],z="bilinear",K=!1){const G=A/v,j=C/M,Y=new E.constructor(C*A*y),H=M*v,J=C*A;for(let Q=0;Q=0;--K)C[K]=G,v[K]=y[M[K]],G*=v[K];const A=M.map((K,G)=>C[M.indexOf(G)]),z=new E.constructor(E.length);for(let K=0;K=0;--j)G+=Y%y[j]*A[j],Y=Math.floor(Y/y[j]);z[G]=E[K]}return[z,v]}function n(E){const y=c(E)[0],M=E.map(A=>Math.exp(A-y)),v=M.reduce((A,z)=>A+z,0);return M.map(A=>A/v)}function i(E){const y=c(E)[0];let M=0;for(let A=0;AA-y-v)}function a(E,y){let M=0;for(let v=0;vy+M*M,0))}function p(E){if(E.length===0)throw Error("Array must not be empty");let y=E[0],M=0;for(let v=1;vy&&(y=E[v],M=v);return[y,M]}function d(E){return E>0&&(E&E-1)===0}class _{constructor(y){if(this.size=y|0,this.size<=1||!d(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=y<<1,this.table=new Float64Array(this.size*2);for(let v=0;vv;v<<=1)++M;this._width=M%2===0?M-1:M,this._bitrev=new Int32Array(1<>>C&3)<>>1);for(let C=0;C>>1]=y[C];return v}toComplexArray(y,M){const v=M||this.createComplexArray();for(let C=0;C>>1],v[C+1]=0;return v}transform(y,M){if(y===M)throw new Error("Input and output buffers must be different");this._transform4(y,M,1)}realTransform(y,M){if(y===M)throw new Error("Input and output buffers must be different");this._realTransform4(y,M,1)}inverseTransform(y,M){if(y===M)throw new Error("Input and output buffers must be different");this._transform4(y,M,-1);for(let v=0;v>=2;z>=2;z>>=2){K=C/z<<1;const J=K>>>2;for(G=0;G>>1,z>>>1)}else for(G=0,j=0;G>>1,z>>>1,v)}const H=this.table;for(z>>=2;z>=2;z>>=2){K=C/z<<1;const Q=K>>>1,oe=Q>>>1,he=oe>>>1;for(G=0;G>>1;for(let Q=2;Q>1;++Y){const H=(Y+1-y)**2/2,J=Math.sqrt(G**2+j**2)**H,Q=H*Math.atan2(j,G),oe=2*Y;A[oe]=J*Math.cos(Q),A[oe+1]=J*Math.sin(Q),z[oe]=A[oe],z[oe+1]=-A[oe+1]}this._slicedChirpBuffer=A.subarray(M,v),this._f=new _(C>>1),this._f.transform(this._chirpBuffer,z)}_transform(y,M,v){const C=this._buffer1,A=this._buffer2,z=this._outBuffer1,K=this._outBuffer2,G=this._chirpBuffer,j=this._slicedChirpBuffer,Y=this._a;if(v)for(let H=0;H>1,oe=M[Q];C[H]=oe*j[H],C[J]=oe*j[J]}else for(let H=0;H=E.length&&(G=2*(E.length-1)-G),v[z++]=E[G]}v.sort(),M[A]=v[C]}return M}function w(E,y){const M=Math.pow(10,y);return Math.round(E*M)/M}function g(E){const y=Math.round(E);return Math.abs(E)%1===.5?y%2===0?y:y-1:y}function S(E){const y=E.length,M=E[0].length,v=[y+1,M+1],C=Array.from({length:v[0]},()=>Array(v[1]).fill(1/0));C[0][0]=0;const A=Array.from({length:v[0]},()=>Array(v[1]).fill(-1));for(let Y=1;Y0||K>0;)switch(G.push(z-1),j.push(K-1),A[z][K]){case 0:--z,--K;break;case 1:--z;break;case 2:--K;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${z}, ${K}]. Please file a bug report.`)}return G.reverse(),j.reverse(),[G,j]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>i,Tensor:()=>a,cat:()=>M,full:()=>j,full_like:()=>Y,interpolate:()=>p,interpolate_4d:()=>c,layer_norm:()=>g,matmul:()=>d,mean:()=>z,mean_pooling:()=>w,ones:()=>H,ones_like:()=>J,permute:()=>u,quantize_embeddings:()=>ae,rand:()=>he,rfft:()=>_,slice:()=>k,stack:()=>v,std_mean:()=>A,topk:()=>f,zeros:()=>Q,zeros_like:()=>oe});var s=t("./src/utils/maths.js"),o=t("./src/backends/onnx.js"),n=t("./src/ops/registry.js");const i=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class a{constructor(...F){Z(this,"ort_tensor");return(0,o.isONNXTensor)(F[0])?this.ort_tensor=F[0]:this.ort_tensor=new o.Tensor(F[0],F[1],F[2]),new Proxy(this,{get:(W,ee)=>{if(typeof ee=="string"){let me=Number(ee);if(Number.isInteger(me))return W._getitem(me)}return W[ee]},set:(W,ee,me)=>W[ee]=me})}get dims(){return this.ort_tensor.dims}set dims(F){this.ort_tensor.dims=F}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){const[F,...W]=this.dims;if(W.length>0){const ee=W.reduce((me,te)=>me*te);for(let me=0;me0){const me=ee.reduce((te,ue)=>te*ue);return this._subarray(F,me,ee)}else return new a(this.type,[this.data[F]],ee)}indexOf(F){const W=this.data;for(let ee=0;eede)throw new Error(`Invalid slice: ${q}`);const ve=[Math.max(R,0),Math.min(de,this.dims[we])];ee.push(ve),W.push(ve[1]-ve[0])}else throw new Error(`Invalid slice: ${q}`)}const me=ee.map(([we,q])=>q-we),te=me.reduce((we,q)=>we*q),ue=this.data,Pe=new ue.constructor(te),Ne=this.stride();for(let we=0;we=0;--R){const ve=me[R];q+=(de%ve+ee[R][0])*Ne[R],de=Math.floor(de/ve)}Pe[we]=ue[q]}return new a(this.type,Pe,W)}permute(...F){return u(this,F)}transpose(...F){return this.permute(...F)}sum(F=null,W=!1){return this.norm(1,F,W)}norm(F="fro",W=null,ee=!1){if(F==="fro")F=2;else if(typeof F=="string")throw Error(`Unsupported norm: ${F}`);const me=this.data,te=(we,q)=>we+q**F;if(W===null){const we=me.reduce(te,0)**(1/F);return new a(this.type,[we],[])}const[ue,Pe,Ne]=C(te,this,W,ee);if(F!==1)for(let we=0;we=0;--Ne){const R=this.dims[Ne];if(Ne!==W){const de=we%R;Pe+=de*q,q*=this.dims[Ne]}we=Math.floor(we/R)}me[ue]/=te[Pe]}return this}normalize(F=2,W=1){return this.clone().normalize_(F,W)}stride(){return K(this.dims)}squeeze(F=null){return new a(this.type,this.data,S(this.dims,F))}squeeze_(F=null){return this.dims=S(this.dims,F),this}unsqueeze(F=null){return new a(this.type,this.data,E(this.dims,F))}unsqueeze_(F=null){return this.dims=E(this.dims,F),this}flatten_(F=0,W=-1){W=(W+this.dims.length)%this.dims.length;let ee=this.dims.slice(0,F),me=this.dims.slice(F,W+1),te=this.dims.slice(W+1);return this.dims=[...ee,me.reduce((ue,Pe)=>ue*Pe,1),...te],this}flatten(F=0,W=-1){return this.clone().flatten_(F,W)}view(...F){let W=-1;for(let me=0;mePe!==W?te*ue:te,1);F[W]=ee.length/me}return new a(this.type,ee,F)}neg_(){const F=this.data;for(let W=0;WF?1:0;return new a("bool",W,this.dims)}lt(F){const W=new Uint8Array(this.data.length),ee=this.data;for(let me=0;meMath.min(ue,Pe),this,F,W,1/0);return new a(ee,me,te)}max(F=null,W=!1){if(F===null){const ue=(0,s.max)(this.data)[0];return new a(this.type,[ue],[])}const[ee,me,te]=C((ue,Pe)=>Math.max(ue,Pe),this,F,W,-1/0);return new a(ee,me,te)}argmin(F=null,W=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const ee=(0,s.min)(this.data)[1];return new a("int64",[BigInt(ee)],[])}argmax(F=null,W=!1){if(F!==null)throw new Error("`dim !== null` not yet implemented.");const ee=(0,s.max)(this.data)[1];return new a("int64",[BigInt(ee)],[])}to(F){if(this.type===F)return this;if(!i.hasOwnProperty(F))throw new Error(`Unsupported type: ${F}`);let W;const ee=["int64","uint64"].includes(this.type),me=["int64","uint64"].includes(F);return ee&&!me?W=Number:!ee&&me&&(W=BigInt),new a(F,i[F].from(this.data,W),this.dims)}}function l(V,F){const W=V.length,ee=F.reduce((te,ue)=>te*ue);if(W!==ee)throw Error(`cannot reshape array of size ${W} into shape (${F})`);let me=V;for(let te=F.length-1;te>=0;te--)me=me.reduce((ue,Pe)=>{let Ne=ue[ue.length-1];return Ne.lengthnew a("int64",V,[V.length]);async function k(V,F,W,ee,me){return await(await n.TensorOpRegistry.slice)({x:V,s:T(F),e:T(W),a:T(ee),t:T(me??new Array(ee.length).fill(1))})}function w(V,F){const W=V.data,ee=F.data,me=[V.dims[0],V.dims[2]],te=new W.constructor(me[0]*me[1]),[ue,Pe,Ne]=V.dims;let we=0;for(let q=0;qW!==1):typeof F=="number"?V[F]===1&&V.splice(F,1):Array.isArray(F)&&(V=V.filter((W,ee)=>W!==1||!F.includes(ee))),V}function E(V,F){return F=y(F,V.length+1),V=V.slice(),V.splice(F,0,1),V}function y(V,F,W=null,ee=!0){if(V<-F||V>=F){if(ee)throw new Error(`IndexError: index ${V} is out of bounds for dimension${W===null?"":" "+W} with size ${F}`);return V<-F?0:F}return V<0&&(V=(V%F+F)%F),V}function M(V,F=0){F=y(F,V[0].dims.length);const W=V[0].dims.slice();W[F]=V.reduce((ue,Pe)=>ue+Pe.dims[F],0);const ee=W.reduce((ue,Pe)=>ue*Pe,1),me=new V[0].data.constructor(ee),te=V[0].type;if(F===0){let ue=0;for(const Pe of V){const Ne=Pe.data;me.set(Ne,ue),ue+=Ne.length}}else{let ue=0;for(let Pe=0;Pe=0;--de){const Ce=we[de];let Se=ve%Ce;de===F&&(Se+=ue),R+=Se*be,be*=W[de],ve=Math.floor(ve/Ce)}me[R]=Ne[q]}ue+=we[F]}}return new a(te,me,W)}function v(V,F=0){return M(V.map(W=>W.unsqueeze(F)),F)}function C(V,F,W=null,ee=!1,me=null){const te=F.data,ue=F.dims;W=y(W,ue.length);const Pe=ue.slice();Pe[W]=1;const Ne=new te.constructor(te.length/ue[W]);me!==null&&Ne.fill(me);for(let we=0;we=0;--R){const be=ue[R];if(R!==W){const Ce=de%be;q+=Ce*ve,ve*=Pe[R]}de=Math.floor(de/be)}Ne[q]=V(Ne[q],te[we],we,q)}return ee||Pe.splice(W,1),[F.type,Ne,Pe]}function A(V,F=null,W=1,ee=!1){const me=V.data,te=V.dims;if(F===null){const ve=me.reduce(($e,Le)=>$e+Le,0)/me.length,be=Math.sqrt(me.reduce(($e,Le)=>$e+(Le-ve)**2,0)/(me.length-W)),Ce=new a(V.type,[ve],[]);return[new a(V.type,[be],[]),Ce]}F=y(F,te.length);const ue=z(V,F,ee),Pe=ue.data,[Ne,we,q]=C((de,ve,be,Ce)=>de+(ve-Pe[Ce])**2,V,F,ee);for(let de=0;dewe+q,0);return new a(V.type,[Ne/me.length],[])}F=y(F,ee.length);const[te,ue,Pe]=C((Ne,we)=>Ne+we,V,F,W);if(ee[F]!==1)for(let Ne=0;Ne=0;--W)F[W]=ee,ee*=V[W];return F}function G(V,F,W,ee){const me=V.reduce((te,ue)=>te*ue,1);return new a(W,new ee(me).fill(F),V)}function j(V,F){let W,ee;if(typeof F=="number")W="float32",ee=Float32Array;else if(typeof F=="bigint")W="int64",ee=BigInt64Array;else if(typeof F=="boolean")W="bool",ee=Uint8Array;else throw new Error(`Unsupported data type: ${typeof F}`);return G(V,F,W,ee)}function Y(V,F){return j(V.dims,F)}function H(V){return G(V,1n,"int64",BigInt64Array)}function J(V){return H(V.dims)}function Q(V){return G(V,0n,"int64",BigInt64Array)}function oe(V){return Q(V.dims)}function he(V){const F=V.reduce((W,ee)=>W*ee,1);return new a("float32",Float32Array.from({length:F},()=>Math.random()),V)}function ae(V,F){if(V.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(V.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(F))throw new Error("The precision must be either 'binary' or 'ubinary'");const W=F==="binary",ee=W?"int8":"uint8",me=W?Int8Array:Uint8Array,te=V.data,ue=new me(te.length/8);for(let Pe=0;Pe0?1:0,we=Math.floor(Pe/8),q=Pe%8;ue[we]|=Ne<<7-q,W&&q===0&&(ue[we]-=128)}return new a(ee,ue,[V.dims[0],V.dims[1]/8])}},"./src/utils/video.js":(e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>i,RawVideoFrame:()=>n,load_video:()=>a});var s=t("./src/utils/image.js"),o=t("./src/env.js");class n{constructor(u,p){this.image=u,this.timestamp=p}}class i{constructor(u,p){u.length>0&&u[0]instanceof s.RawImage&&(u=u.map((c,d)=>new n(c,(d+1)/(u.length+1)*p))),this.frames=u,this.duration=p}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function a(l,{num_frames:u=null,fps:p=null}={}){if(!o.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(u==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const c=[],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(y=>d.onloadedmetadata=y)}const _=d.duration;let f,T;u!=null?(f=u,T=u===1?0:_/(u-1)):(T=1/p,f=Math.floor(_/T));let k=[];for(let S=0;S{d.onseeked=v}),g.drawImage(d,0,0,w.width,w.height);const E=g.getImageData(0,0,w.width,w.height),y=new s.RawImage(E.data,w.width,w.height,4),M=new n(y,S);c.push(M)}return d.remove(),new i(c,_)}}},Ug={};function Rt(e){var r=Ug[e];if(r!==void 0)return r.exports;var t=Ug[e]={exports:{}};return Tx[e](t,t.exports,Rt),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;Rt.t=function(t,s){if(s&1&&(t=this(t)),s&8||typeof t=="object"&&t&&(s&4&&t.__esModule||s&16&&typeof t.then=="function"))return t;var o=Object.create(null);Rt.r(o);var n={};r=r||[null,e({}),e([]),e(e)];for(var i=s&2&&t;typeof i=="object"&&!~r.indexOf(i);i=e(i))Object.getOwnPropertyNames(i).forEach(a=>n[a]=()=>t[a]);return n.default=()=>t,Rt.d(o,n),o}})(),Rt.d=(e,r)=>{for(var t in r)Rt.o(r,t)&&!Rt.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})},Rt.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),Rt.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var m={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/Rt.r(m),Rt.d(m,{ASTFeatureExtractor:()=>c.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,AudioClassificationPipeline:()=>r.AudioClassificationPipeline,AutoConfig:()=>o.AutoConfig,AutoFeatureExtractor:()=>d.AutoFeatureExtractor,AutoImageProcessor:()=>T.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:()=>f.BeitFeatureExtractor,BeitForImageClassification:()=>t.BeitForImageClassification,BeitModel:()=>t.BeitModel,BeitPreTrainedModel:()=>t.BeitPreTrainedModel,BertForMaskedLM:()=>t.BertForMaskedLM,BertForQuestionAnswering:()=>t.BertForQuestionAnswering,BertForSequenceClassification:()=>t.BertForSequenceClassification,BertForTokenClassification:()=>t.BertForTokenClassification,BertModel:()=>t.BertModel,BertPreTrainedModel:()=>t.BertPreTrainedModel,BertTokenizer:()=>s.BertTokenizer,BitImageProcessor:()=>f.BitImageProcessor,BlenderbotForConditionalGeneration:()=>t.BlenderbotForConditionalGeneration,BlenderbotModel:()=>t.BlenderbotModel,BlenderbotPreTrainedModel:()=>t.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>t.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>t.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>t.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>s.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>s.BlenderbotTokenizer,BloomForCausalLM:()=>t.BloomForCausalLM,BloomModel:()=>t.BloomModel,BloomPreTrainedModel:()=>t.BloomPreTrainedModel,BloomTokenizer:()=>s.BloomTokenizer,CLIPFeatureExtractor:()=>f.CLIPFeatureExtractor,CLIPImageProcessor:()=>f.CLIPImageProcessor,CLIPModel:()=>t.CLIPModel,CLIPPreTrainedModel:()=>t.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>t.CLIPSegForImageSegmentation,CLIPSegModel:()=>t.CLIPSegModel,CLIPSegPreTrainedModel:()=>t.CLIPSegPreTrainedModel,CLIPTextModel:()=>t.CLIPTextModel,CLIPTextModelWithProjection:()=>t.CLIPTextModelWithProjection,CLIPTokenizer:()=>s.CLIPTokenizer,CLIPVisionModel:()=>t.CLIPVisionModel,CLIPVisionModelWithProjection:()=>t.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>t.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>t.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>t.CamembertForSequenceClassification,CamembertForTokenClassification:()=>t.CamembertForTokenClassification,CamembertModel:()=>t.CamembertModel,CamembertPreTrainedModel:()=>t.CamembertPreTrainedModel,CamembertTokenizer:()=>s.CamembertTokenizer,CausalLMOutput:()=>t.CausalLMOutput,CausalLMOutputWithPast:()=>t.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>f.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>c.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>y.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>s.CodeGenTokenizer,CodeLlamaTokenizer:()=>s.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>s.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>s.ConvBertTokenizer,ConvNextFeatureExtractor:()=>f.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>f.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>f.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>f.DPTImageProcessor,DPTModel:()=>t.DPTModel,DPTPreTrainedModel:()=>t.DPTPreTrainedModel,DacDecoderModel:()=>t.DacDecoderModel,DacDecoderOutput:()=>t.DacDecoderOutput,DacEncoderModel:()=>t.DacEncoderModel,DacEncoderOutput:()=>t.DacEncoderOutput,DacFeatureExtractor:()=>c.DacFeatureExtractor,DacModel:()=>t.DacModel,DacPreTrainedModel:()=>t.DacPreTrainedModel,DataTypeMap:()=>l.DataTypeMap,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>s.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>s.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>f.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>f.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>r.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>f.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>f.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>s.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>r.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>f.DonutFeatureExtractor,DonutImageProcessor:()=>f.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>f.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>s.ElectraTokenizer,EncodecFeatureExtractor:()=>c.EncodecFeatureExtractor,EosTokenCriteria:()=>E.EosTokenCriteria,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>s.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>u.FFT,FalconForCausalLM:()=>t.FalconForCausalLM,FalconModel:()=>t.FalconModel,FalconPreTrainedModel:()=>t.FalconPreTrainedModel,FalconTokenizer:()=>s.FalconTokenizer,FastViTForImageClassification:()=>t.FastViTForImageClassification,FastViTModel:()=>t.FastViTModel,FastViTPreTrainedModel:()=>t.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>r.FeatureExtractionPipeline,FeatureExtractor:()=>p.FeatureExtractor,FillMaskPipeline:()=>r.FillMaskPipeline,Florence2ForConditionalGeneration:()=>t.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>t.Florence2PreTrainedModel,Florence2Processor:()=>w.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>y.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>y.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>f.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>t.GLPNForDepthEstimation,GLPNModel:()=>t.GLPNModel,GLPNPreTrainedModel:()=>t.GLPNPreTrainedModel,GPT2LMHeadModel:()=>t.GPT2LMHeadModel,GPT2Model:()=>t.GPT2Model,GPT2PreTrainedModel:()=>t.GPT2PreTrainedModel,GPT2Tokenizer:()=>s.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>t.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>t.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>t.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>t.GPTJForCausalLM,GPTJModel:()=>t.GPTJModel,GPTJPreTrainedModel:()=>t.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>t.GPTNeoForCausalLM,GPTNeoModel:()=>t.GPTNeoModel,GPTNeoPreTrainedModel:()=>t.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>t.GPTNeoXForCausalLM,GPTNeoXModel:()=>t.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>t.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>s.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>t.Gemma2ForCausalLM,Gemma2Model:()=>t.Gemma2Model,Gemma2PreTrainedModel:()=>t.Gemma2PreTrainedModel,Gemma3ForCausalLM:()=>t.Gemma3ForCausalLM,Gemma3Model:()=>t.Gemma3Model,Gemma3PreTrainedModel:()=>t.Gemma3PreTrainedModel,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>s.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>f.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>w.GroundingDinoProcessor,GroupViTModel:()=>t.GroupViTModel,GroupViTPreTrainedModel:()=>t.GroupViTPreTrainedModel,HeliumForCausalLM:()=>t.HeliumForCausalLM,HeliumModel:()=>t.HeliumModel,HeliumPreTrainedModel:()=>t.HeliumPreTrainedModel,HerbertTokenizer:()=>s.HerbertTokenizer,HieraForImageClassification:()=>t.HieraForImageClassification,HieraModel:()=>t.HieraModel,HieraPreTrainedModel:()=>t.HieraPreTrainedModel,HubertForCTC:()=>t.HubertForCTC,HubertForSequenceClassification:()=>t.HubertForSequenceClassification,HubertModel:()=>t.HubertModel,HubertPreTrainedModel:()=>t.HubertPreTrainedModel,IJepaForImageClassification:()=>t.IJepaForImageClassification,IJepaModel:()=>t.IJepaModel,IJepaPreTrainedModel:()=>t.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>t.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>f.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>w.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>c.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>_.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>E.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>f.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>w.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>f.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LogitsProcessor:()=>y.LogitsProcessor,LogitsProcessorList:()=>y.LogitsProcessorList,LogitsWarper:()=>y.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,Mask2FormerImageProcessor:()=>f.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>f.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>f.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>E.MaxLengthCriteria,Metric3DForDepthEstimation:()=>t.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>t.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>t.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>t.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>w.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>y.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>y.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>f.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>f.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>f.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>f.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>f.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>f.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>f.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>f.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>f.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>f.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>c.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>w.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NllbTokenizer:()=>s.NllbTokenizer,NoBadWordsLogitsProcessor:()=>y.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>y.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>f.NougatImageProcessor,NougatTokenizer:()=>s.NougatTokenizer,OPTForCausalLM:()=>t.OPTForCausalLM,OPTModel:()=>t.OPTModel,OPTPreTrainedModel:()=>t.OPTPreTrainedModel,ObjectDetectionPipeline:()=>r.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>t.Olmo2ForCausalLM,Olmo2Model:()=>t.Olmo2Model,Olmo2PreTrainedModel:()=>t.Olmo2PreTrainedModel,OlmoForCausalLM:()=>t.OlmoForCausalLM,OlmoModel:()=>t.OlmoModel,OlmoPreTrainedModel:()=>t.OlmoPreTrainedModel,OpenELMForCausalLM:()=>t.OpenELMForCausalLM,OpenELMModel:()=>t.OpenELMModel,OpenELMPreTrainedModel:()=>t.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>f.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>f.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>w.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>f.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>w.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>f.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>w.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>o.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>k.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>f.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>c.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>w.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>t.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>r.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>t.Qwen2ForCausalLM,Qwen2Model:()=>t.Qwen2Model,Qwen2PreTrainedModel:()=>t.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>s.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>t.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>f.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>w.Qwen2VLProcessor,Qwen3ForCausalLM:()=>t.Qwen3ForCausalLM,Qwen3Model:()=>t.Qwen3Model,Qwen3PreTrainedModel:()=>t.Qwen3PreTrainedModel,RFDetrForObjectDetection:()=>t.RFDetrForObjectDetection,RFDetrModel:()=>t.RFDetrModel,RFDetrObjectDetectionOutput:()=>t.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>t.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>f.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>t.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>t.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>t.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>t.RTDetrV2PreTrainedModel,RawAudio:()=>n.RawAudio,RawImage:()=>i.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>y.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>s.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>s.RobertaTokenizer,SamImageProcessor:()=>f.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>w.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>c.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>f.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>f.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>f.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>s.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>f.SmolVLMImageProcessor,SmolVLMProcessor:()=>w.SmolVLMProcessor,SnacDecoderModel:()=>t.SnacDecoderModel,SnacEncoderModel:()=>t.SnacEncoderModel,SnacFeatureExtractor:()=>c.SnacFeatureExtractor,SnacModel:()=>t.SnacModel,SnacPreTrainedModel:()=>t.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>c.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>w.SpeechT5Processor,SpeechT5Tokenizer:()=>s.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>s.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>E.StoppingCriteria,StoppingCriteriaList:()=>E.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>y.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>f.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinForSemanticSegmentation:()=>t.SwinForSemanticSegmentation,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>s.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>y.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>S.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>y.TopKLogitsWarper,TopPLogitsWarper:()=>y.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>w.UltravoxProcessor,UniSpeechForCTC:()=>t.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>t.UniSpeechForSequenceClassification,UniSpeechModel:()=>t.UniSpeechModel,UniSpeechPreTrainedModel:()=>t.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>t.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>t.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>t.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>t.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>t.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>w.VLChatProcessor,VLMImageProcessor:()=>f.VLMImageProcessor,ViTFeatureExtractor:()=>f.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>f.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>f.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>f.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>s.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>c.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>w.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>w.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>c.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>c.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>w.WhisperProcessor,WhisperTextStreamer:()=>S.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>y.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>s.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>s.XLMRobertaTokenizer,XLMTokenizer:()=>s.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>f.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>f.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>r.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>r.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>r.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>r.ZeroShotObjectDetectionPipeline,bankers_round:()=>u.bankers_round,cat:()=>l.cat,cos_sim:()=>u.cos_sim,dot:()=>u.dot,dynamic_time_warping:()=>u.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getKeyValueShapes:()=>o.getKeyValueShapes,hamming:()=>n.hamming,hanning:()=>n.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>u.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>i.load_image,load_video:()=>a.load_video,log_softmax:()=>u.log_softmax,magnitude:()=>u.magnitude,matmul:()=>l.matmul,max:()=>u.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>u.medianFilter,mel_filter_bank:()=>n.mel_filter_bank,min:()=>u.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>u.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,read_audio:()=>n.read_audio,rfft:()=>l.rfft,round:()=>u.round,slice:()=>l.slice,softmax:()=>u.softmax,spectrogram:()=>n.spectrogram,stack:()=>l.stack,std_mean:()=>l.std_mean,topk:()=>l.topk,window_function:()=>n.window_function,zeros:()=>l.zeros,zeros_like:()=>l.zeros_like});var e=Rt("./src/env.js"),r=Rt("./src/pipelines.js"),t=Rt("./src/models.js"),s=Rt("./src/tokenizers.js"),o=Rt("./src/configs.js"),n=Rt("./src/utils/audio.js"),i=Rt("./src/utils/image.js"),a=Rt("./src/utils/video.js"),l=Rt("./src/utils/tensor.js"),u=Rt("./src/utils/maths.js"),p=Rt("./src/base/feature_extraction_utils.js"),c=Rt("./src/models/feature_extractors.js"),d=Rt("./src/models/auto/feature_extraction_auto.js"),_=Rt("./src/base/image_processors_utils.js"),f=Rt("./src/models/image_processors.js"),T=Rt("./src/models/auto/image_processing_auto.js"),k=Rt("./src/base/processing_utils.js"),w=Rt("./src/models/processors.js"),g=Rt("./src/models/auto/processing_auto.js"),S=Rt("./src/generation/streamers.js"),E=Rt("./src/generation/stopping_criteria.js"),y=Rt("./src/generation/logits_process.js")})(),m.ASTFeatureExtractor,m.ASTForAudioClassification,m.ASTModel,m.ASTPreTrainedModel,m.AlbertForMaskedLM,m.AlbertForQuestionAnswering,m.AlbertForSequenceClassification,m.AlbertModel,m.AlbertPreTrainedModel,m.AlbertTokenizer,m.AudioClassificationPipeline,m.AutoConfig,m.AutoFeatureExtractor,m.AutoImageProcessor,m.AutoModel,m.AutoModelForAudioClassification,m.AutoModelForAudioFrameClassification,m.AutoModelForAudioTextToText,m.AutoModelForCTC;var Ex=m.AutoModelForCausalLM;m.AutoModelForDepthEstimation,m.AutoModelForDocumentQuestionAnswering,m.AutoModelForImageClassification,m.AutoModelForImageFeatureExtraction,m.AutoModelForImageMatting,m.AutoModelForImageSegmentation,m.AutoModelForImageTextToText,m.AutoModelForImageToImage,m.AutoModelForMaskGeneration,m.AutoModelForMaskedLM,m.AutoModelForNormalEstimation,m.AutoModelForObjectDetection,m.AutoModelForPoseEstimation,m.AutoModelForQuestionAnswering,m.AutoModelForSemanticSegmentation,m.AutoModelForSeq2SeqLM,m.AutoModelForSequenceClassification,m.AutoModelForSpeechSeq2Seq,m.AutoModelForTextToSpectrogram,m.AutoModelForTextToWaveform,m.AutoModelForTokenClassification,m.AutoModelForUniversalSegmentation,m.AutoModelForVision2Seq,m.AutoModelForXVector,m.AutoModelForZeroShotObjectDetection,m.AutoProcessor;var Px=m.AutoTokenizer;m.AutomaticSpeechRecognitionPipeline,m.BackgroundRemovalPipeline,m.BartForConditionalGeneration,m.BartForSequenceClassification,m.BartModel,m.BartPretrainedModel,m.BartTokenizer,m.BaseModelOutput,m.BaseStreamer,m.BeitFeatureExtractor,m.BeitForImageClassification,m.BeitModel,m.BeitPreTrainedModel,m.BertForMaskedLM,m.BertForQuestionAnswering,m.BertForSequenceClassification,m.BertForTokenClassification,m.BertModel,m.BertPreTrainedModel,m.BertTokenizer,m.BitImageProcessor,m.BlenderbotForConditionalGeneration,m.BlenderbotModel,m.BlenderbotPreTrainedModel,m.BlenderbotSmallForConditionalGeneration,m.BlenderbotSmallModel,m.BlenderbotSmallPreTrainedModel,m.BlenderbotSmallTokenizer,m.BlenderbotTokenizer,m.BloomForCausalLM,m.BloomModel,m.BloomPreTrainedModel,m.BloomTokenizer,m.CLIPFeatureExtractor,m.CLIPImageProcessor,m.CLIPModel,m.CLIPPreTrainedModel,m.CLIPSegForImageSegmentation,m.CLIPSegModel,m.CLIPSegPreTrainedModel,m.CLIPTextModel,m.CLIPTextModelWithProjection,m.CLIPTokenizer,m.CLIPVisionModel,m.CLIPVisionModelWithProjection,m.CamembertForMaskedLM,m.CamembertForQuestionAnswering,m.CamembertForSequenceClassification,m.CamembertForTokenClassification,m.CamembertModel,m.CamembertPreTrainedModel,m.CamembertTokenizer,m.CausalLMOutput,m.CausalLMOutputWithPast,m.ChineseCLIPFeatureExtractor,m.ChineseCLIPModel,m.ChineseCLIPPreTrainedModel,m.ClapAudioModelWithProjection,m.ClapFeatureExtractor,m.ClapModel,m.ClapPreTrainedModel,m.ClapTextModelWithProjection,m.ClassifierFreeGuidanceLogitsProcessor,m.CodeGenForCausalLM,m.CodeGenModel,m.CodeGenPreTrainedModel,m.CodeGenTokenizer,m.CodeLlamaTokenizer,m.CohereForCausalLM,m.CohereModel,m.CoherePreTrainedModel,m.CohereTokenizer,m.ConvBertForMaskedLM,m.ConvBertForQuestionAnswering,m.ConvBertForSequenceClassification,m.ConvBertForTokenClassification,m.ConvBertModel,m.ConvBertPreTrainedModel,m.ConvBertTokenizer,m.ConvNextFeatureExtractor,m.ConvNextForImageClassification,m.ConvNextImageProcessor,m.ConvNextModel,m.ConvNextPreTrainedModel,m.ConvNextV2ForImageClassification,m.ConvNextV2Model,m.ConvNextV2PreTrainedModel,m.DPTFeatureExtractor,m.DPTForDepthEstimation,m.DPTImageProcessor,m.DPTModel,m.DPTPreTrainedModel,m.DacDecoderModel,m.DacDecoderOutput,m.DacEncoderModel,m.DacEncoderOutput,m.DacFeatureExtractor,m.DacModel,m.DacPreTrainedModel,m.DataTypeMap,m.DebertaForMaskedLM,m.DebertaForQuestionAnswering,m.DebertaForSequenceClassification,m.DebertaForTokenClassification,m.DebertaModel,m.DebertaPreTrainedModel,m.DebertaTokenizer,m.DebertaV2ForMaskedLM,m.DebertaV2ForQuestionAnswering,m.DebertaV2ForSequenceClassification,m.DebertaV2ForTokenClassification,m.DebertaV2Model,m.DebertaV2PreTrainedModel,m.DebertaV2Tokenizer,m.DecisionTransformerModel,m.DecisionTransformerPreTrainedModel,m.DeiTFeatureExtractor,m.DeiTForImageClassification,m.DeiTImageProcessor,m.DeiTModel,m.DeiTPreTrainedModel,m.DepthAnythingForDepthEstimation,m.DepthAnythingPreTrainedModel,m.DepthEstimationPipeline,m.DepthProForDepthEstimation,m.DepthProPreTrainedModel,m.DetrFeatureExtractor,m.DetrForObjectDetection,m.DetrForSegmentation,m.DetrImageProcessor,m.DetrModel,m.DetrObjectDetectionOutput,m.DetrPreTrainedModel,m.DetrSegmentationOutput,m.Dinov2ForImageClassification,m.Dinov2Model,m.Dinov2PreTrainedModel,m.Dinov2WithRegistersForImageClassification,m.Dinov2WithRegistersModel,m.Dinov2WithRegistersPreTrainedModel,m.DistilBertForMaskedLM,m.DistilBertForQuestionAnswering,m.DistilBertForSequenceClassification,m.DistilBertForTokenClassification,m.DistilBertModel,m.DistilBertPreTrainedModel,m.DistilBertTokenizer,m.DocumentQuestionAnsweringPipeline,m.DonutFeatureExtractor,m.DonutImageProcessor,m.DonutSwinModel,m.DonutSwinPreTrainedModel,m.EfficientNetForImageClassification,m.EfficientNetImageProcessor,m.EfficientNetModel,m.EfficientNetPreTrainedModel,m.ElectraForMaskedLM,m.ElectraForQuestionAnswering,m.ElectraForSequenceClassification,m.ElectraForTokenClassification,m.ElectraModel,m.ElectraPreTrainedModel,m.ElectraTokenizer,m.EncodecFeatureExtractor,m.EosTokenCriteria,m.EsmForMaskedLM,m.EsmForSequenceClassification,m.EsmForTokenClassification,m.EsmModel,m.EsmPreTrainedModel,m.EsmTokenizer,m.ExaoneForCausalLM,m.ExaoneModel,m.ExaonePreTrainedModel,m.FFT,m.FalconForCausalLM,m.FalconModel,m.FalconPreTrainedModel,m.FalconTokenizer,m.FastViTForImageClassification,m.FastViTModel,m.FastViTPreTrainedModel,m.FeatureExtractionPipeline,m.FeatureExtractor,m.FillMaskPipeline,m.Florence2ForConditionalGeneration,m.Florence2PreTrainedModel,m.Florence2Processor,m.ForcedBOSTokenLogitsProcessor,m.ForcedEOSTokenLogitsProcessor,m.GLPNFeatureExtractor,m.GLPNForDepthEstimation,m.GLPNModel,m.GLPNPreTrainedModel,m.GPT2LMHeadModel,m.GPT2Model,m.GPT2PreTrainedModel,m.GPT2Tokenizer,m.GPTBigCodeForCausalLM,m.GPTBigCodeModel,m.GPTBigCodePreTrainedModel,m.GPTJForCausalLM,m.GPTJModel,m.GPTJPreTrainedModel,m.GPTNeoForCausalLM,m.GPTNeoModel,m.GPTNeoPreTrainedModel,m.GPTNeoXForCausalLM,m.GPTNeoXModel,m.GPTNeoXPreTrainedModel,m.GPTNeoXTokenizer,m.Gemma2ForCausalLM,m.Gemma2Model,m.Gemma2PreTrainedModel,m.Gemma3ForCausalLM,m.Gemma3Model,m.Gemma3PreTrainedModel,m.GemmaForCausalLM,m.GemmaModel,m.GemmaPreTrainedModel,m.GemmaTokenizer,m.GlmForCausalLM,m.GlmModel,m.GlmPreTrainedModel,m.GraniteForCausalLM,m.GraniteModel,m.GranitePreTrainedModel,m.Grok1Tokenizer,m.GroundingDinoForObjectDetection,m.GroundingDinoImageProcessor,m.GroundingDinoPreTrainedModel,m.GroundingDinoProcessor,m.GroupViTModel,m.GroupViTPreTrainedModel,m.HeliumForCausalLM,m.HeliumModel,m.HeliumPreTrainedModel,m.HerbertTokenizer,m.HieraForImageClassification,m.HieraModel,m.HieraPreTrainedModel,m.HubertForCTC,m.HubertForSequenceClassification,m.HubertModel,m.HubertPreTrainedModel,m.IJepaForImageClassification,m.IJepaModel,m.IJepaPreTrainedModel,m.Idefics3ForConditionalGeneration,m.Idefics3ImageProcessor,m.Idefics3PreTrainedModel,m.Idefics3Processor,m.ImageClassificationPipeline,m.ImageFeatureExtractionPipeline,m.ImageFeatureExtractor,m.ImageMattingOutput,m.ImageProcessor,m.ImageSegmentationPipeline,m.ImageToImagePipeline,m.ImageToTextPipeline;var Cx=m.InterruptableStoppingCriteria;m.JAISLMHeadModel,m.JAISModel,m.JAISPreTrainedModel,m.JinaCLIPImageProcessor,m.JinaCLIPModel,m.JinaCLIPPreTrainedModel,m.JinaCLIPProcessor,m.JinaCLIPTextModel,m.JinaCLIPVisionModel,m.LiteWhisperForConditionalGeneration,m.LlamaForCausalLM,m.LlamaModel,m.LlamaPreTrainedModel,m.LlamaTokenizer,m.LlavaForConditionalGeneration,m.LlavaOnevisionForConditionalGeneration,m.LlavaOnevisionImageProcessor,m.LlavaPreTrainedModel,m.LogitsProcessor,m.LogitsProcessorList,m.LogitsWarper,m.LongT5ForConditionalGeneration,m.LongT5Model,m.LongT5PreTrainedModel,m.M2M100ForConditionalGeneration,m.M2M100Model,m.M2M100PreTrainedModel,m.M2M100Tokenizer,m.MBart50Tokenizer,m.MBartForCausalLM,m.MBartForConditionalGeneration,m.MBartForSequenceClassification,m.MBartModel,m.MBartPreTrainedModel,m.MBartTokenizer,m.MPNetForMaskedLM,m.MPNetForQuestionAnswering,m.MPNetForSequenceClassification,m.MPNetForTokenClassification,m.MPNetModel,m.MPNetPreTrainedModel,m.MPNetTokenizer,m.MT5ForConditionalGeneration,m.MT5Model,m.MT5PreTrainedModel,m.MarianMTModel,m.MarianModel,m.MarianPreTrainedModel,m.MarianTokenizer,m.Mask2FormerImageProcessor,m.MaskFormerFeatureExtractor,m.MaskFormerForInstanceSegmentation,m.MaskFormerImageProcessor,m.MaskFormerModel,m.MaskFormerPreTrainedModel,m.MaskedLMOutput,m.MaxLengthCriteria,m.Metric3DForDepthEstimation,m.Metric3DPreTrainedModel,m.Metric3Dv2ForDepthEstimation,m.Metric3Dv2PreTrainedModel,m.MgpstrForSceneTextRecognition,m.MgpstrModelOutput,m.MgpstrPreTrainedModel,m.MgpstrProcessor,m.MgpstrTokenizer,m.MimiDecoderModel,m.MimiDecoderOutput,m.MimiEncoderModel,m.MimiEncoderOutput,m.MimiModel,m.MimiPreTrainedModel,m.MinLengthLogitsProcessor,m.MinNewTokensLengthLogitsProcessor,m.MistralForCausalLM,m.MistralModel,m.MistralPreTrainedModel,m.MobileBertForMaskedLM,m.MobileBertForQuestionAnswering,m.MobileBertForSequenceClassification,m.MobileBertModel,m.MobileBertPreTrainedModel,m.MobileBertTokenizer,m.MobileLLMForCausalLM,m.MobileLLMModel,m.MobileLLMPreTrainedModel,m.MobileNetV1FeatureExtractor,m.MobileNetV1ForImageClassification,m.MobileNetV1ForSemanticSegmentation,m.MobileNetV1ImageProcessor,m.MobileNetV1Model,m.MobileNetV1PreTrainedModel,m.MobileNetV2FeatureExtractor,m.MobileNetV2ForImageClassification,m.MobileNetV2ForSemanticSegmentation,m.MobileNetV2ImageProcessor,m.MobileNetV2Model,m.MobileNetV2PreTrainedModel,m.MobileNetV3FeatureExtractor,m.MobileNetV3ForImageClassification,m.MobileNetV3ForSemanticSegmentation,m.MobileNetV3ImageProcessor,m.MobileNetV3Model,m.MobileNetV3PreTrainedModel,m.MobileNetV4FeatureExtractor,m.MobileNetV4ForImageClassification,m.MobileNetV4ForSemanticSegmentation,m.MobileNetV4ImageProcessor,m.MobileNetV4Model,m.MobileNetV4PreTrainedModel,m.MobileViTFeatureExtractor,m.MobileViTForImageClassification,m.MobileViTImageProcessor,m.MobileViTModel,m.MobileViTPreTrainedModel,m.MobileViTV2ForImageClassification,m.MobileViTV2Model,m.MobileViTV2PreTrainedModel,m.ModelOutput,m.ModernBertForMaskedLM,m.ModernBertForSequenceClassification,m.ModernBertForTokenClassification,m.ModernBertModel,m.ModernBertPreTrainedModel,m.Moondream1ForConditionalGeneration,m.MoonshineFeatureExtractor,m.MoonshineForConditionalGeneration,m.MoonshineModel,m.MoonshinePreTrainedModel,m.MoonshineProcessor,m.MptForCausalLM,m.MptModel,m.MptPreTrainedModel,m.MultiModalityCausalLM,m.MultiModalityPreTrainedModel,m.MusicgenForCausalLM,m.MusicgenForConditionalGeneration,m.MusicgenModel,m.MusicgenPreTrainedModel,m.NllbTokenizer,m.NoBadWordsLogitsProcessor,m.NoRepeatNGramLogitsProcessor,m.NomicBertModel,m.NomicBertPreTrainedModel,m.NougatImageProcessor,m.NougatTokenizer,m.OPTForCausalLM,m.OPTModel,m.OPTPreTrainedModel,m.ObjectDetectionPipeline,m.Olmo2ForCausalLM,m.Olmo2Model,m.Olmo2PreTrainedModel,m.OlmoForCausalLM,m.OlmoModel,m.OlmoPreTrainedModel,m.OpenELMForCausalLM,m.OpenELMModel,m.OpenELMPreTrainedModel,m.OwlViTFeatureExtractor,m.OwlViTForObjectDetection,m.OwlViTImageProcessor,m.OwlViTModel,m.OwlViTPreTrainedModel,m.OwlViTProcessor,m.Owlv2ForObjectDetection,m.Owlv2ImageProcessor,m.Owlv2Model,m.Owlv2PreTrainedModel,m.PaliGemmaForConditionalGeneration,m.PaliGemmaPreTrainedModel,m.PaliGemmaProcessor,m.PatchTSMixerForPrediction,m.PatchTSMixerModel,m.PatchTSMixerPreTrainedModel,m.PatchTSTForPrediction,m.PatchTSTModel,m.PatchTSTPreTrainedModel,m.Phi3ForCausalLM,m.Phi3Model,m.Phi3PreTrainedModel,m.Phi3VForCausalLM,m.Phi3VImageProcessor,m.Phi3VPreTrainedModel,m.Phi3VProcessor,m.PhiForCausalLM,m.PhiModel,m.PhiPreTrainedModel,m.Pipeline,m.PreTrainedModel,m.PreTrainedTokenizer,m.PretrainedConfig,m.PretrainedMixin,m.Processor,m.PvtForImageClassification,m.PvtImageProcessor,m.PvtModel,m.PvtPreTrainedModel,m.PyAnnoteFeatureExtractor,m.PyAnnoteForAudioFrameClassification,m.PyAnnoteModel,m.PyAnnotePreTrainedModel,m.PyAnnoteProcessor,m.QuestionAnsweringModelOutput,m.QuestionAnsweringPipeline,m.Qwen2ForCausalLM,m.Qwen2Model,m.Qwen2PreTrainedModel,m.Qwen2Tokenizer,m.Qwen2VLForConditionalGeneration,m.Qwen2VLImageProcessor,m.Qwen2VLPreTrainedModel,m.Qwen2VLProcessor,m.Qwen3ForCausalLM,m.Qwen3Model,m.Qwen3PreTrainedModel,m.RFDetrForObjectDetection,m.RFDetrModel,m.RFDetrObjectDetectionOutput,m.RFDetrPreTrainedModel,m.RTDetrForObjectDetection,m.RTDetrImageProcessor,m.RTDetrModel,m.RTDetrObjectDetectionOutput,m.RTDetrPreTrainedModel,m.RTDetrV2ForObjectDetection,m.RTDetrV2Model,m.RTDetrV2ObjectDetectionOutput,m.RTDetrV2PreTrainedModel,m.RawAudio,m.RawImage,m.RawVideo,m.RawVideoFrame,m.RepetitionPenaltyLogitsProcessor,m.ResNetForImageClassification,m.ResNetModel,m.ResNetPreTrainedModel,m.RoFormerForMaskedLM,m.RoFormerForQuestionAnswering,m.RoFormerForSequenceClassification,m.RoFormerForTokenClassification,m.RoFormerModel,m.RoFormerPreTrainedModel,m.RoFormerTokenizer,m.RobertaForMaskedLM,m.RobertaForQuestionAnswering,m.RobertaForSequenceClassification,m.RobertaForTokenClassification,m.RobertaModel,m.RobertaPreTrainedModel,m.RobertaTokenizer,m.SamImageProcessor,m.SamImageSegmentationOutput,m.SamModel,m.SamPreTrainedModel,m.SamProcessor,m.SapiensForDepthEstimation,m.SapiensForNormalEstimation,m.SapiensForSemanticSegmentation,m.SapiensPreTrainedModel,m.SeamlessM4TFeatureExtractor,m.SegformerFeatureExtractor,m.SegformerForImageClassification,m.SegformerForSemanticSegmentation,m.SegformerImageProcessor,m.SegformerModel,m.SegformerPreTrainedModel,m.Seq2SeqLMOutput,m.SequenceClassifierOutput,m.SiglipImageProcessor,m.SiglipModel,m.SiglipPreTrainedModel,m.SiglipTextModel,m.SiglipTokenizer,m.SiglipVisionModel,m.SmolVLMForConditionalGeneration,m.SmolVLMImageProcessor,m.SmolVLMProcessor,m.SnacDecoderModel,m.SnacEncoderModel,m.SnacFeatureExtractor,m.SnacModel,m.SnacPreTrainedModel,m.SpeechT5FeatureExtractor,m.SpeechT5ForSpeechToText,m.SpeechT5ForTextToSpeech,m.SpeechT5HifiGan,m.SpeechT5Model,m.SpeechT5PreTrainedModel,m.SpeechT5Processor,m.SpeechT5Tokenizer,m.SqueezeBertForMaskedLM,m.SqueezeBertForQuestionAnswering,m.SqueezeBertForSequenceClassification,m.SqueezeBertModel,m.SqueezeBertPreTrainedModel,m.SqueezeBertTokenizer,m.StableLmForCausalLM,m.StableLmModel,m.StableLmPreTrainedModel,m.Starcoder2ForCausalLM,m.Starcoder2Model,m.Starcoder2PreTrainedModel,m.StoppingCriteria,m.StoppingCriteriaList,m.StyleTextToSpeech2Model,m.StyleTextToSpeech2PreTrainedModel,m.SummarizationPipeline,m.SuppressTokensAtBeginLogitsProcessor,m.Swin2SRForImageSuperResolution,m.Swin2SRImageProcessor,m.Swin2SRModel,m.Swin2SRPreTrainedModel,m.SwinForImageClassification,m.SwinForSemanticSegmentation,m.SwinModel,m.SwinPreTrainedModel,m.T5ForConditionalGeneration,m.T5Model,m.T5PreTrainedModel,m.T5Tokenizer,m.TableTransformerForObjectDetection,m.TableTransformerModel,m.TableTransformerObjectDetectionOutput,m.TableTransformerPreTrainedModel,m.TemperatureLogitsWarper,m.Tensor,m.Text2TextGenerationPipeline,m.TextClassificationPipeline,m.TextGenerationPipeline;var Sx=m.TextStreamer;m.TextToAudioPipeline,m.TokenClassificationPipeline,m.TokenClassifierOutput,m.TokenizerModel,m.TopKLogitsWarper,m.TopPLogitsWarper,m.TrOCRForCausalLM,m.TrOCRPreTrainedModel,m.TranslationPipeline,m.UltravoxModel,m.UltravoxPreTrainedModel,m.UltravoxProcessor,m.UniSpeechForCTC,m.UniSpeechForSequenceClassification,m.UniSpeechModel,m.UniSpeechPreTrainedModel,m.UniSpeechSatForAudioFrameClassification,m.UniSpeechSatForCTC,m.UniSpeechSatForSequenceClassification,m.UniSpeechSatModel,m.UniSpeechSatPreTrainedModel,m.VLChatProcessor,m.VLMImageProcessor,m.ViTFeatureExtractor,m.ViTForImageClassification,m.ViTImageProcessor,m.ViTMAEModel,m.ViTMAEPreTrainedModel,m.ViTMSNForImageClassification,m.ViTMSNModel,m.ViTMSNPreTrainedModel,m.ViTModel,m.ViTPreTrainedModel,m.VisionEncoderDecoderModel,m.VitMatteForImageMatting,m.VitMatteImageProcessor,m.VitMattePreTrainedModel,m.VitPoseForPoseEstimation,m.VitPoseImageProcessor,m.VitPosePreTrainedModel,m.VitsModel,m.VitsModelOutput,m.VitsPreTrainedModel,m.VitsTokenizer,m.Wav2Vec2BertForCTC,m.Wav2Vec2BertForSequenceClassification,m.Wav2Vec2BertModel,m.Wav2Vec2BertPreTrainedModel,m.Wav2Vec2CTCTokenizer,m.Wav2Vec2FeatureExtractor,m.Wav2Vec2ForAudioFrameClassification,m.Wav2Vec2ForCTC,m.Wav2Vec2ForSequenceClassification,m.Wav2Vec2Model,m.Wav2Vec2PreTrainedModel,m.Wav2Vec2Processor,m.Wav2Vec2ProcessorWithLM,m.WavLMForAudioFrameClassification,m.WavLMForCTC,m.WavLMForSequenceClassification,m.WavLMForXVector,m.WavLMModel,m.WavLMPreTrainedModel,m.WeSpeakerFeatureExtractor,m.WeSpeakerResNetModel,m.WeSpeakerResNetPreTrainedModel,m.WhisperFeatureExtractor,m.WhisperForConditionalGeneration,m.WhisperModel,m.WhisperPreTrainedModel,m.WhisperProcessor,m.WhisperTextStreamer,m.WhisperTimeStampLogitsProcessor,m.WhisperTokenizer,m.XLMForQuestionAnswering,m.XLMForSequenceClassification,m.XLMForTokenClassification,m.XLMModel,m.XLMPreTrainedModel,m.XLMRobertaForMaskedLM,m.XLMRobertaForQuestionAnswering,m.XLMRobertaForSequenceClassification,m.XLMRobertaForTokenClassification,m.XLMRobertaModel,m.XLMRobertaPreTrainedModel,m.XLMRobertaTokenizer,m.XLMTokenizer,m.XLMWithLMHeadModel,m.XVectorOutput,m.YolosFeatureExtractor,m.YolosForObjectDetection,m.YolosImageProcessor,m.YolosModel,m.YolosObjectDetectionOutput,m.YolosPreTrainedModel,m.ZeroShotAudioClassificationPipeline,m.ZeroShotClassificationPipeline,m.ZeroShotImageClassificationPipeline,m.ZeroShotObjectDetectionPipeline,m.bankers_round,m.cat,m.cos_sim,m.dot,m.dynamic_time_warping,m.env,m.full,m.full_like,m.getKeyValueShapes,m.hamming,m.hanning,m.interpolate,m.interpolate_4d,m.interpolate_data,m.is_chinese_char,m.layer_norm,m.load_image,m.load_video,m.log_softmax,m.magnitude,m.matmul,m.max,m.mean,m.mean_pooling,m.medianFilter,m.mel_filter_bank,m.min,m.ones,m.ones_like,m.permute,m.permute_data,m.pipeline,m.quantize_embeddings,m.rand,m.read_audio,m.rfft,m.round,m.slice,m.softmax,m.spectrogram,m.stack,m.std_mean,m.topk,m.window_function,m.zeros,m.zeros_like;async function $x(){try{if(!await navigator.gpu.requestAdapter())throw new Error("WebGPU is not supported (no adapter found)")}catch(e){self.postMessage({status:"error",data:e.toString()})}}class du{static async getInstance(r=null){return this.tokenizer??(this.tokenizer=Px.from_pretrained(this.model_id,{progress_callback:r})),this.model??(this.model=Ex.from_pretrained(this.model_id,{dtype:"q4f16",device:"webgpu",progress_callback:r})),Promise.all([this.tokenizer,this.model])}}Z(du,"model_id","onnx-community/Qwen3-0.6B-ONNX");const yi=new Cx;let pu=null;async function kx({messages:e,reasonEnabled:r}){const[t,s]=await du.getInstance(),o=t.apply_chat_template(e,{add_generation_prompt:!0,return_dict:!0,enable_thinking:r}),[n,i]=t.encode("",{add_special_tokens:!1});let a="answering",l,u=0,p;const c=w=>{switch(l??(l=performance.now()),u++>0&&(p=u/(performance.now()-l)*1e3),Number(w[0])){case n:a="thinking";break;case i:a="answering";break}console.log(a,w,t.decode(w))},d=w=>{self.postMessage({status:"update",output:w,tps:p,numTokens:u,state:a})},_=new Sx(t,{skip_prompt:!0,skip_special_tokens:!0,callback_function:d,token_callback_function:c});self.postMessage({status:"start"});const{past_key_values:f,sequences:T}=await s.generate({...o,past_key_values:pu,do_sample:!0,top_k:20,temperature:r?.6:.7,max_new_tokens:16384,streamer:_,stopping_criteria:yi,return_dict_in_generate:!0});pu=f;const k=t.batch_decode(T,{skip_special_tokens:!0});self.postMessage({status:"complete",output:k})}async function Ix(){self.postMessage({status:"loading",data:"Loading model..."});const[e,r]=await du.getInstance(s=>{self.postMessage(s)});self.postMessage({status:"loading",data:"Compiling shaders and warming up model..."});const t=e("a");await r.generate({...t,max_new_tokens:1}),self.postMessage({status:"ready"})}self.addEventListener("message",async e=>{const{type:r,data:t}=e.data;switch(r){case"check":$x();break;case"load":Ix();break;case"generate":yi.reset(),kx(t);break;case"interrupt":yi.interrupt();break;case"reset":pu=null,yi.reset();break}})})();