diff --git "a/assets/worker-afe162b7.js" "b/assets/worker-afe162b7.js" new file mode 100644--- /dev/null +++ "b/assets/worker-afe162b7.js" @@ -0,0 +1,2888 @@ +var ph=Object.defineProperty;var hh=(sn,Wr,$r)=>Wr in sn?ph(sn,Wr,{enumerable:!0,configurable:!0,writable:!0,value:$r}):sn[Wr]=$r;var ie=(sn,Wr,$r)=>(hh(sn,typeof Wr!="symbol"?Wr+"":Wr,$r),$r);(function(){"use strict";var sn=typeof document<"u"?document.currentScript:null;function Wr(ae,m){return m.forEach(function(r){r&&typeof r!="string"&&!Array.isArray(r)&&Object.keys(r).forEach(function(w){if(w!=="default"&&!(w in ae)){var T=Object.getOwnPropertyDescriptor(r,w);Object.defineProperty(ae,w,T.get?T:{enumerable:!0,get:function(){return r[w]}})}})}),Object.freeze(ae)}const $r=new Map,fn=[],Vp=(ae,m,r)=>{if(m&&typeof m.init=="function"&&typeof m.createInferenceSessionHandler=="function"){const w=$r.get(ae);if(w===void 0)$r.set(ae,{backend:m,priority:r});else{if(w.priority>r)return;if(w.priority===r&&w.backend!==m)throw new Error(`cannot register backend "${ae}" using priority ${r}`)}if(r>=0){const T=fn.indexOf(ae);T!==-1&&fn.splice(T,1);for(let L=0;L{const m=$r.get(ae);if(!m)return"backend not found.";if(m.initialized)return m.backend;if(m.aborted)return m.error;{const r=!!m.initPromise;try{return r||(m.initPromise=m.backend.init(ae)),await m.initPromise,m.initialized=!0,m.backend}catch(w){return r||(m.error=`${w}`,m.aborted=!0),m.error}finally{delete m.initPromise}}},Wp=async ae=>{const m=ae.executionProviders||[],r=m.map(_=>typeof _=="string"?_:_.name),w=r.length===0?fn:r;let T;const L=[],H=new Set;for(const _ of w){const I=await Up(_);typeof I=="string"?L.push({name:_,err:I}):(T||(T=I),T===I&&H.add(_))}if(!T)throw new Error(`no available backend found. ERR: ${L.map(_=>`[${_.name}] ${_.err}`).join(", ")}`);for(const{name:_,err:I}of L)r.includes(_)&&console.warn(`removing requested execution provider "${_}" from session options because it is not available: ${I}`);const $=m.filter(_=>H.has(typeof _=="string"?_:_.name));return[T,new Proxy(ae,{get:(_,I)=>I==="executionProviders"?$:Reflect.get(_,I)})]},Gp="1.21.0";let Ip="warning";const gr={wasm:{},webgl:{},webgpu:{},versions:{common:Gp},set logLevel(ae){if(ae!==void 0){if(typeof ae!="string"||["verbose","info","warning","error","fatal"].indexOf(ae)===-1)throw new Error(`Unsupported logging level: ${ae}`);Ip=ae}},get logLevel(){return Ip}};Object.defineProperty(gr,"logLevel",{enumerable:!0});const Kp=gr,Hp=(ae,m)=>{const r=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);r.width=ae.dims[3],r.height=ae.dims[2];const w=r.getContext("2d");if(w!=null){let T,L;(m==null?void 0:m.tensorLayout)!==void 0&&m.tensorLayout==="NHWC"?(T=ae.dims[2],L=ae.dims[3]):(T=ae.dims[3],L=ae.dims[2]);const H=(m==null?void 0:m.format)!==void 0?m.format:"RGB",$=m==null?void 0:m.norm;let _,I;$===void 0||$.mean===void 0?_=[255,255,255,255]:typeof $.mean=="number"?_=[$.mean,$.mean,$.mean,$.mean]:(_=[$.mean[0],$.mean[1],$.mean[2],0],$.mean[3]!==void 0&&(_[3]=$.mean[3])),$===void 0||$.bias===void 0?I=[0,0,0,0]:typeof $.bias=="number"?I=[$.bias,$.bias,$.bias,$.bias]:(I=[$.bias[0],$.bias[1],$.bias[2],0],$.bias[3]!==void 0&&(I[3]=$.bias[3]));const D=L*T;let b=0,h=D,U=D*2,z=-1;H==="RGBA"?(b=0,h=D,U=D*2,z=D*3):H==="RGB"?(b=0,h=D,U=D*2):H==="RBG"&&(b=0,U=D,h=D*2);for(let Q=0;Q{const r=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let w;if(r!=null){let T,L,H;(m==null?void 0:m.tensorLayout)!==void 0&&m.tensorLayout==="NHWC"?(T=ae.dims[2],L=ae.dims[1],H=ae.dims[3]):(T=ae.dims[3],L=ae.dims[2],H=ae.dims[1]);const $=m!==void 0&&m.format!==void 0?m.format:"RGB",_=m==null?void 0:m.norm;let I,D;_===void 0||_.mean===void 0?I=[255,255,255,255]:typeof _.mean=="number"?I=[_.mean,_.mean,_.mean,_.mean]:(I=[_.mean[0],_.mean[1],_.mean[2],255],_.mean[3]!==void 0&&(I[3]=_.mean[3])),_===void 0||_.bias===void 0?D=[0,0,0,0]:typeof _.bias=="number"?D=[_.bias,_.bias,_.bias,_.bias]:(D=[_.bias[0],_.bias[1],_.bias[2],0],_.bias[3]!==void 0&&(D[3]=_.bias[3]));const b=L*T;if(m!==void 0&&(m.format!==void 0&&H===4&&m.format!=="RGBA"||H===3&&m.format!=="RGB"&&m.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const h=4;let U=0,z=1,Q=2,ge=3,j=0,G=b,Y=b*2,O=-1;$==="RGBA"?(j=0,G=b,Y=b*2,O=b*3):$==="RGB"?(j=0,G=b,Y=b*2):$==="RBG"&&(j=0,Y=b,G=b*2),w=r.createImageData(T,L);for(let S=0;S{if(ae===void 0)throw new Error("Image buffer must be defined");if(m.height===void 0||m.width===void 0)throw new Error("Image height and width must be defined");if(m.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:r,width:w}=m,T=m.norm??{mean:255,bias:0};let L,H;typeof T.mean=="number"?L=[T.mean,T.mean,T.mean,T.mean]:L=[T.mean[0],T.mean[1],T.mean[2],T.mean[3]??255],typeof T.bias=="number"?H=[T.bias,T.bias,T.bias,T.bias]:H=[T.bias[0],T.bias[1],T.bias[2],T.bias[3]??0];const $=m.format!==void 0?m.format:"RGBA",_=m.tensorFormat!==void 0&&m.tensorFormat!==void 0?m.tensorFormat:"RGB",I=r*w,D=_==="RGBA"?new Float32Array(I*4):new Float32Array(I*3);let b=4,h=0,U=1,z=2,Q=3,ge=0,j=I,G=I*2,Y=-1;$==="RGB"&&(b=3,h=0,U=1,z=2,Q=-1),_==="RGBA"?Y=I*3:_==="RBG"?(ge=0,G=I,j=I*2):_==="BGR"&&(G=0,j=I,ge=I*2);for(let S=0;S{const r=typeof HTMLImageElement<"u"&&ae instanceof HTMLImageElement,w=typeof ImageData<"u"&&ae instanceof ImageData,T=typeof ImageBitmap<"u"&&ae instanceof ImageBitmap,L=typeof ae=="string";let H,$=m??{};const _=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},I=D=>typeof HTMLCanvasElement<"u"&&D instanceof HTMLCanvasElement||D instanceof OffscreenCanvas?D.getContext("2d"):null;if(r){const D=_();D.width=ae.width,D.height=ae.height;const b=I(D);if(b!=null){let h=ae.height,U=ae.width;if(m!==void 0&&m.resizedHeight!==void 0&&m.resizedWidth!==void 0&&(h=m.resizedHeight,U=m.resizedWidth),m!==void 0){if($=m,m.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");$.tensorFormat="RGBA",$.height=h,$.width=U}else $.tensorFormat="RGBA",$.height=h,$.width=U;b.drawImage(ae,0,0),H=b.getImageData(0,0,U,h).data}else throw new Error("Can not access image data")}else if(w){let D,b;if(m!==void 0&&m.resizedWidth!==void 0&&m.resizedHeight!==void 0?(D=m.resizedHeight,b=m.resizedWidth):(D=ae.height,b=ae.width),m!==void 0&&($=m),$.format="RGBA",$.height=D,$.width=b,m!==void 0){const h=_();h.width=b,h.height=D;const U=I(h);if(U!=null)U.putImageData(ae,0,0),H=U.getImageData(0,0,b,D).data;else throw new Error("Can not access image data")}else H=ae.data}else if(T){if(m===void 0)throw new Error("Please provide image config with format for Imagebitmap");const D=_();D.width=ae.width,D.height=ae.height;const b=I(D);if(b!=null){const h=ae.height,U=ae.width;return b.drawImage(ae,0,0,U,h),H=b.getImageData(0,0,U,h).data,$.height=h,$.width=U,Pp(H,$)}else throw new Error("Can not access image data")}else{if(L)return new Promise((D,b)=>{const h=_(),U=I(h);if(!ae||!U)return b();const z=new Image;z.crossOrigin="Anonymous",z.src=ae,z.onload=()=>{h.width=z.width,h.height=z.height,U.drawImage(z,0,0,h.width,h.height);const Q=U.getImageData(0,0,h.width,h.height);$.height=h.height,$.width=h.width,D(Pp(Q.data,$))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(H!==void 0)return Pp(H,$);throw new Error("Input data provided is not supported - aborted tensor creation")},Xp=(ae,m)=>{const{width:r,height:w,download:T,dispose:L}=m,H=[1,w,r,4];return new cr({location:"texture",type:"float32",texture:ae,dims:H,download:T,dispose:L})},Jp=(ae,m)=>{const{dataType:r,dims:w,download:T,dispose:L}=m;return new cr({location:"gpu-buffer",type:r??"float32",gpuBuffer:ae,dims:w,download:T,dispose:L})},Yp=(ae,m)=>{const{dataType:r,dims:w,download:T,dispose:L}=m;return new cr({location:"ml-tensor",type:r??"float32",mlTensor:ae,dims:w,download:T,dispose:L})},Zp=(ae,m,r)=>new cr({location:"cpu-pinned",type:ae,data:m,dims:r??[m.length]}),ti=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Iu=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let Ap=!1;const eh=()=>{if(!Ap){Ap=!0;const ae=typeof BigInt64Array<"u"&&BigInt64Array.from,m=typeof BigUint64Array<"u"&&BigUint64Array.from,r=globalThis.Float16Array,w=typeof r<"u"&&r.from;ae&&(ti.set("int64",BigInt64Array),Iu.set(BigInt64Array,"int64")),m&&(ti.set("uint64",BigUint64Array),Iu.set(BigUint64Array,"uint64")),w?(ti.set("float16",r),Iu.set(r,"float16")):ti.set("float16",Uint16Array)}},th=ae=>{let m=1;for(let r=0;r{switch(ae.location){case"cpu":return new cr(ae.type,ae.data,m);case"cpu-pinned":return new cr({location:"cpu-pinned",data:ae.data,type:ae.type,dims:m});case"texture":return new cr({location:"texture",texture:ae.texture,type:ae.type,dims:m});case"gpu-buffer":return new cr({location:"gpu-buffer",gpuBuffer:ae.gpuBuffer,type:ae.type,dims:m});case"ml-tensor":return new cr({location:"ml-tensor",mlTensor:ae.mlTensor,type:ae.type,dims:m});default:throw new Error(`tensorReshape: tensor location ${ae.location} is not supported`)}};let cr=class{constructor(m,r,w){eh();let T,L;if(typeof m=="object"&&"location"in m)switch(this.dataLocation=m.location,T=m.type,L=m.dims,m.location){case"cpu-pinned":{const $=ti.get(T);if(!$)throw new TypeError(`unsupported type "${T}" to create tensor from pinned buffer`);if(!(m.data instanceof $))throw new TypeError(`buffer should be of type ${$.name}`);this.cpuData=m.data;break}case"texture":{if(T!=="float32")throw new TypeError(`unsupported type "${T}" to create tensor from texture`);this.gpuTextureData=m.texture,this.downloader=m.download,this.disposer=m.dispose;break}case"gpu-buffer":{if(T!=="float32"&&T!=="float16"&&T!=="int32"&&T!=="int64"&&T!=="uint32"&&T!=="uint8"&&T!=="bool"&&T!=="uint4"&&T!=="int4")throw new TypeError(`unsupported type "${T}" to create tensor from gpu buffer`);this.gpuBufferData=m.gpuBuffer,this.downloader=m.download,this.disposer=m.dispose;break}case"ml-tensor":{if(T!=="float32"&&T!=="float16"&&T!=="int32"&&T!=="int64"&&T!=="uint32"&&T!=="uint64"&&T!=="int8"&&T!=="uint8"&&T!=="bool"&&T!=="uint4"&&T!=="int4")throw new TypeError(`unsupported type "${T}" to create tensor from MLTensor`);this.mlTensorData=m.mlTensor,this.downloader=m.download,this.disposer=m.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let $,_;if(typeof m=="string")if(T=m,_=w,m==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");$=r}else{const I=ti.get(m);if(I===void 0)throw new TypeError(`Unsupported tensor type: ${m}.`);if(Array.isArray(r)){if(m==="float16"&&I===Uint16Array||m==="uint4"||m==="int4")throw new TypeError(`Creating a ${m} tensor from number array is not supported. Please use ${I.name} as data.`);m==="uint64"||m==="int64"?$=I.from(r,BigInt):$=I.from(r)}else if(r instanceof I)$=r;else if(r instanceof Uint8ClampedArray)if(m==="uint8")$=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(m==="float16"&&r instanceof Uint16Array&&I!==Uint16Array)$=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${T} tensor's data must be type of ${I}`)}else if(_=r,Array.isArray(m)){if(m.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const I=typeof m[0];if(I==="string")T="string",$=m;else if(I==="boolean")T="bool",$=Uint8Array.from(m);else throw new TypeError(`Invalid element type of data array: ${I}.`)}else if(m instanceof Uint8ClampedArray)T="uint8",$=Uint8Array.from(m);else{const I=Iu.get(m.constructor);if(I===void 0)throw new TypeError(`Unsupported type for tensor data: ${m.constructor}.`);T=I,$=m}if(_===void 0)_=[$.length];else if(!Array.isArray(_))throw new TypeError("A tensor's dims must be a number array");L=_,this.cpuData=$,this.dataLocation="cpu"}const H=th(L);if(this.cpuData&&H!==this.cpuData.length&&!((T==="uint4"||T==="int4")&&Math.ceil(H/2)===this.cpuData.length))throw new Error(`Tensor's size(${H}) does not match data length(${this.cpuData.length}).`);this.type=T,this.dims=L,this.size=H}static async fromImage(m,r){return Qp(m,r)}static fromTexture(m,r){return Xp(m,r)}static fromGpuBuffer(m,r){return Jp(m,r)}static fromMLTensor(m,r){return Yp(m,r)}static fromPinnedBuffer(m,r,w){return Zp(m,r,w)}toDataURL(m){return Hp(this,m)}toImageData(m){return qp(this,m)}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(m){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 r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,m&&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(m){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return sh(this,m)}};const si=cr,Fp=(ae,m)=>{(typeof gr.trace>"u"?!gr.wasm.trace:!gr.trace)||console.timeStamp(`${ae}::ORT::${m}`)},Dp=(ae,m)=>{var T;const r=((T=new Error().stack)==null?void 0:T.split(/\r\n|\r|\n/g))||[];let w=!1;for(let L=0;L{(typeof gr.trace>"u"?!gr.wasm.trace:!gr.trace)||Dp("BEGIN",ae)},$p=ae=>{(typeof gr.trace>"u"?!gr.wasm.trace:!gr.trace)||Dp("END",ae)};var rh=Object.freeze({__proto__:null,InferenceSession:class Rp{constructor(m){this.handler=m}async run(m,r,w){Cp();const T={};let L={};if(typeof m!="object"||m===null||m instanceof si||Array.isArray(m))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let H=!0;if(typeof r=="object"){if(r===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(r instanceof si)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(r)){if(r.length===0)throw new TypeError("'fetches' cannot be an empty array.");H=!1;for(const I of r){if(typeof I!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(I)===-1)throw new RangeError(`'fetches' contains invalid output name: ${I}.`);T[I]=null}if(typeof w=="object"&&w!==null)L=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else{let I=!1;const D=Object.getOwnPropertyNames(r);for(const b of this.outputNames)if(D.indexOf(b)!==-1){const h=r[b];(h===null||h instanceof si)&&(I=!0,H=!1,T[b]=h)}if(I){if(typeof w=="object"&&w!==null)L=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else L=r}}else if(typeof r<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const I of this.inputNames)if(typeof m[I]>"u")throw new Error(`input '${I}' is missing in 'feeds'.`);if(H)for(const I of this.outputNames)T[I]=null;const $=await this.handler.run(m,T,L),_={};for(const I in $)if(Object.hasOwnProperty.call($,I)){const D=$[I];D instanceof si?_[I]=D:_[I]=new si(D.type,D.data,D.dims)}return $p(),_}async release(){return this.handler.dispose()}static async create(m,r,w,T){Cp();let L,H={};if(typeof m=="string"){if(L=m,typeof r=="object"&&r!==null)H=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(m instanceof Uint8Array){if(L=m,typeof r=="object"&&r!==null)H=r;else if(typeof r<"u")throw new TypeError("'options' must be an object.")}else if(m instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&m instanceof SharedArrayBuffer){const D=m;let b=0,h=m.byteLength;if(typeof r=="object"&&r!==null)H=r;else if(typeof r=="number"){if(b=r,!Number.isSafeInteger(b))throw new RangeError("'byteOffset' must be an integer.");if(b<0||b>=D.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${D.byteLength}).`);if(h=m.byteLength-b,typeof w=="number"){if(h=w,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||b+h>D.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${D.byteLength-b}].`);if(typeof T=="object"&&T!==null)H=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else if(typeof w<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof r<"u")throw new TypeError("'options' must be an object.");L=new Uint8Array(D,b,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[$,_]=await Wp(H),I=await $.createInferenceSessionHandler(L,_);return $p(),new Rp(I)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}},TRACE:Fp,TRACE_FUNC_BEGIN:Cp,TRACE_FUNC_END:$p,Tensor:si,env:Kp,registerBackend:Vp});function nh(ae){return ae&&ae.__esModule&&Object.prototype.hasOwnProperty.call(ae,"default")?ae.default:ae}function ri(ae){throw new Error('Could not dynamically require "'+ae+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Op={exports:{}};/*! + * ONNX Runtime Web v1.22.0-dev.20250409-89f8206ba4 + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */(function(ae,m){var r=(()=>{var w=Object.defineProperty,T=Object.getOwnPropertyDescriptor,L=Object.getOwnPropertyNames,H=Object.prototype.hasOwnProperty,$=(e=>typeof ri<"u"?ri:typeof Proxy<"u"?new Proxy(e,{get:(t,s)=>(typeof ri<"u"?ri:t)[s]}):e)(function(e){if(typeof ri<"u")return ri.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),_=(e,t)=>()=>(e&&(t=e(e=0)),t),I=(e,t)=>{for(var s in t)w(e,s,{get:t[s],enumerable:!0})},D=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of L(t))!H.call(e,i)&&i!==s&&w(e,i,{get:()=>t[i],enumerable:!(n=T(t,i))||n.enumerable});return e},b=e=>D(w({},"__esModule",{value:!0}),e),h,U,z,Q,ge,j=_(()=>{h=new Map,U=[],z=(e,t,s)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let n=h.get(e);if(n===void 0)h.set(e,{backend:t,priority:s});else{if(n.priority>s)return;if(n.priority===s&&n.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${s}`)}if(s>=0){let i=U.indexOf(e);i!==-1&&U.splice(i,1);for(let o=0;o{let t=h.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let s=!!t.initPromise;try{return s||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(n){return s||(t.error=`${n}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},ge=async e=>{let t=e.executionProviders||[],s=t.map(d=>typeof d=="string"?d:d.name),n=s.length===0?U:s,i,o=[],a=new Set;for(let d of n){let u=await Q(d);typeof u=="string"?o.push({name:d,err:u}):(i||(i=u),i===u&&a.add(d))}if(!i)throw new Error(`no available backend found. ERR: ${o.map(d=>`[${d.name}] ${d.err}`).join(", ")}`);for(let{name:d,err:u}of o)s.includes(d)&&console.warn(`removing requested execution provider "${d}" from session options because it is not available: ${u}`);let c=t.filter(d=>a.has(typeof d=="string"?d:d.name));return[i,new Proxy(e,{get:(d,u)=>u==="executionProviders"?c:Reflect.get(d,u)})]}}),G=_(()=>{j()}),Y,O=_(()=>{Y="1.22.0-dev.20250409-89f8206ba4"}),S,E,x=_(()=>{O(),S="warning",E={wasm:{},webgl:{},webgpu:{},versions:{common:Y},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}`);S=e}},get logLevel(){return S}},Object.defineProperty(E,"logLevel",{enumerable:!0})}),C,re=_(()=>{x(),C=E}),q,pe,me=_(()=>{q=(e,t)=>{let s=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);s.width=e.dims[3],s.height=e.dims[2];let n=s.getContext("2d");if(n!=null){let i,o;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],o=e.dims[3]):(i=e.dims[3],o=e.dims[2]);let a=(t==null?void 0:t.format)!==void 0?t.format:"RGB",c=t==null?void 0:t.norm,d,u;c===void 0||c.mean===void 0?d=[255,255,255,255]:typeof c.mean=="number"?d=[c.mean,c.mean,c.mean,c.mean]:(d=[c.mean[0],c.mean[1],c.mean[2],0],c.mean[3]!==void 0&&(d[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias=="number"?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let f=o*i,M=0,v=f,k=f*2,A=-1;a==="RGBA"?(M=0,v=f,k=f*2,A=f*3):a==="RGB"?(M=0,v=f,k=f*2):a==="RBG"&&(M=0,k=f,v=f*2);for(let R=0;R{let s=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),n;if(s!=null){let i,o,a;(t==null?void 0:t.tensorLayout)!==void 0&&t.tensorLayout==="NHWC"?(i=e.dims[2],o=e.dims[1],a=e.dims[3]):(i=e.dims[3],o=e.dims[2],a=e.dims[1]);let c=t!==void 0&&t.format!==void 0?t.format:"RGB",d=t==null?void 0:t.norm,u,f;d===void 0||d.mean===void 0?u=[255,255,255,255]:typeof d.mean=="number"?u=[d.mean,d.mean,d.mean,d.mean]:(u=[d.mean[0],d.mean[1],d.mean[2],255],d.mean[3]!==void 0&&(u[3]=d.mean[3])),d===void 0||d.bias===void 0?f=[0,0,0,0]:typeof d.bias=="number"?f=[d.bias,d.bias,d.bias,d.bias]:(f=[d.bias[0],d.bias[1],d.bias[2],0],d.bias[3]!==void 0&&(f[3]=d.bias[3]));let M=o*i;if(t!==void 0&&(t.format!==void 0&&a===4&&t.format!=="RGBA"||a===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let v=4,k=0,A=1,R=2,ee=3,W=0,V=M,se=M*2,oe=-1;c==="RGBA"?(W=0,V=M,se=M*2,oe=M*3):c==="RGB"?(W=0,V=M,se=M*2):c==="RBG"&&(W=0,se=M,V=M*2),n=s.createImageData(i,o);for(let Me=0;Me{wt(),J=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:s,width:n}=t,i=t.norm??{mean:255,bias:0},o,a;typeof i.mean=="number"?o=[i.mean,i.mean,i.mean,i.mean]:o=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?a=[i.bias,i.bias,i.bias,i.bias]:a=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let c=t.format!==void 0?t.format:"RGBA",d=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",u=s*n,f=d==="RGBA"?new Float32Array(u*4):new Float32Array(u*3),M=4,v=0,k=1,A=2,R=3,ee=0,W=u,V=u*2,se=-1;c==="RGB"&&(M=3,v=0,k=1,A=2,R=-1),d==="RGBA"?se=u*3:d==="RBG"?(ee=0,V=u,W=u*2):d==="BGR"&&(V=0,W=u,ee=u*2);for(let oe=0;oe{let s=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,n=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,o=typeof e=="string",a,c=t??{},d=()=>{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=f=>typeof HTMLCanvasElement<"u"&&f instanceof HTMLCanvasElement||f instanceof OffscreenCanvas?f.getContext("2d"):null;if(s){let f=d();f.width=e.width,f.height=e.height;let M=u(f);if(M!=null){let v=e.height,k=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(v=t.resizedHeight,k=t.resizedWidth),t!==void 0){if(c=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=v,c.width=k}else c.tensorFormat="RGBA",c.height=v,c.width=k;M.drawImage(e,0,0),a=M.getImageData(0,0,k,v).data}else throw new Error("Can not access image data")}else if(n){let f,M;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(f=t.resizedHeight,M=t.resizedWidth):(f=e.height,M=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=f,c.width=M,t!==void 0){let v=d();v.width=M,v.height=f;let k=u(v);if(k!=null)k.putImageData(e,0,0),a=k.getImageData(0,0,M,f).data;else throw new Error("Can not access image data")}else a=e.data}else if(i){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let f=d();f.width=e.width,f.height=e.height;let M=u(f);if(M!=null){let v=e.height,k=e.width;return M.drawImage(e,0,0,k,v),a=M.getImageData(0,0,k,v).data,c.height=v,c.width=k,J(a,c)}else throw new Error("Can not access image data")}else{if(o)return new Promise((f,M)=>{let v=d(),k=u(v);if(!e||!k)return M();let A=new Image;A.crossOrigin="Anonymous",A.src=e,A.onload=()=>{v.width=A.width,v.height=A.height,k.drawImage(A,0,0,v.width,v.height);let R=k.getImageData(0,0,v.width,v.height);c.height=v.height,c.width=v.width,f(J(R.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(a!==void 0)return J(a,c);throw new Error("Input data provided is not supported - aborted tensor creation")},de=(e,t)=>{let{width:s,height:n,download:i,dispose:o}=t,a=[1,n,s,4];return new Ye({location:"texture",type:"float32",texture:e,dims:a,download:i,dispose:o})},Te=(e,t)=>{let{dataType:s,dims:n,download:i,dispose:o}=t;return new Ye({location:"gpu-buffer",type:s??"float32",gpuBuffer:e,dims:n,download:i,dispose:o})},Pe=(e,t)=>{let{dataType:s,dims:n,download:i,dispose:o}=t;return new Ye({location:"ml-tensor",type:s??"float32",mlTensor:e,dims:n,download:i,dispose:o})},be=(e,t,s)=>new Ye({location:"cpu-pinned",type:e,data:t,dims:s??[t.length]})}),Oe,he,K,ce,ye=_(()=>{Oe=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),he=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),K=!1,ce=()=>{if(!K){K=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,s=globalThis.Float16Array,n=typeof s<"u"&&s.from;e&&(Oe.set("int64",BigInt64Array),he.set(BigInt64Array,"int64")),t&&(Oe.set("uint64",BigUint64Array),he.set(BigUint64Array,"uint64")),n?(Oe.set("float16",s),he.set(s,"float16")):Oe.set("float16",Uint16Array)}}}),Fe,Xe,Qe=_(()=>{wt(),Fe=e=>{let t=1;for(let s=0;s{switch(e.location){case"cpu":return new Ye(e.type,e.data,t);case"cpu-pinned":return new Ye({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new Ye({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new Ye({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new Ye({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Ye,wt=_(()=>{me(),He(),ye(),Qe(),Ye=class{constructor(e,t,s){ce();let n,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,n=e.type,i=e.dims,e.location){case"cpu-pinned":{let a=Oe.get(n);if(!a)throw new TypeError(`unsupported type "${n}" to create tensor from pinned buffer`);if(!(e.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=e.data;break}case"texture":{if(n!=="float32")throw new TypeError(`unsupported type "${n}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(n!=="float32"&&n!=="float16"&&n!=="int32"&&n!=="int64"&&n!=="uint32"&&n!=="uint64"&&n!=="int8"&&n!=="uint8"&&n!=="bool"&&n!=="uint4"&&n!=="int4")throw new TypeError(`unsupported type "${n}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,c;if(typeof e=="string")if(n=e,c=s,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{let d=Oe.get(e);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&d===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${d.name} as data.`);e==="uint64"||e==="int64"?a=d.from(t,BigInt):a=d.from(t)}else if(t instanceof d)a=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")a=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&d!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${n} tensor's data must be type of ${d}`)}else if(c=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let d=typeof e[0];if(d==="string")n="string",a=e;else if(d==="boolean")n="bool",a=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else if(e instanceof Uint8ClampedArray)n="uint8",a=Uint8Array.from(e);else{let d=he.get(e.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);n=d,a=e}if(c===void 0)c=[a.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");i=c,this.cpuData=a,this.dataLocation="cpu"}let o=Fe(i);if(this.cpuData&&o!==this.cpuData.length&&!((n==="uint4"||n==="int4")&&Math.ceil(o/2)===this.cpuData.length))throw new Error(`Tensor's size(${o}) does not match data length(${this.cpuData.length}).`);this.type=n,this.dims=i,this.size=o}static async fromImage(e,t){return fe(e,t)}static fromTexture(e,t){return de(e,t)}static fromGpuBuffer(e,t){return Te(e,t)}static fromMLTensor(e,t){return Pe(e,t)}static fromPinnedBuffer(e,t,s){return be(e,t,s)}toDataURL(e){return q(this,e)}toImageData(e){return pe(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 t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&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(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Xe(this,e)}}}),We,le=_(()=>{wt(),We=Ye}),Ee,X,ke,Ne,Ve=_(()=>{x(),Ee=(e,t)=>{(typeof E.trace>"u"?!E.wasm.trace:!E.trace)||console.timeStamp(`${e}::ORT::${t}`)},X=(e,t)=>{var i;let s=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[],n=!1;for(let o=0;o{(typeof E.trace>"u"?!E.wasm.trace:!E.trace)||X("BEGIN",e)},Ne=e=>{(typeof E.trace>"u"?!E.wasm.trace:!E.trace)||X("END",e)}}),De,Ke=_(()=>{j(),le(),Ve(),De=class jp{constructor(t){this.handler=t}async run(t,s,n){ke();let i={},o={};if(typeof t!="object"||t===null||t instanceof We||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let a=!0;if(typeof s=="object"){if(s===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(s instanceof We)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(s)){if(s.length===0)throw new TypeError("'fetches' cannot be an empty array.");a=!1;for(let u of s){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}.`);i[u]=null}if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let u=!1,f=Object.getOwnPropertyNames(s);for(let M of this.outputNames)if(f.indexOf(M)!==-1){let v=s[M];(v===null||v instanceof We)&&(u=!0,a=!1,i[M]=v)}if(u){if(typeof n=="object"&&n!==null)o=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else o=s}}else if(typeof s<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let u of this.inputNames)if(typeof t[u]>"u")throw new Error(`input '${u}' is missing in 'feeds'.`);if(a)for(let u of this.outputNames)i[u]=null;let c=await this.handler.run(t,i,o),d={};for(let u in c)if(Object.hasOwnProperty.call(c,u)){let f=c[u];f instanceof We?d[u]=f:d[u]=new We(f.type,f.data,f.dims)}return Ne(),d}async release(){return this.handler.dispose()}static async create(t,s,n,i){ke();let o,a={};if(typeof t=="string"){if(o=t,typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(o=t,typeof s=="object"&&s!==null)a=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let f=t,M=0,v=t.byteLength;if(typeof s=="object"&&s!==null)a=s;else if(typeof s=="number"){if(M=s,!Number.isSafeInteger(M))throw new RangeError("'byteOffset' must be an integer.");if(M<0||M>=f.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${f.byteLength}).`);if(v=t.byteLength-M,typeof n=="number"){if(v=n,!Number.isSafeInteger(v))throw new RangeError("'byteLength' must be an integer.");if(v<=0||M+v>f.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${f.byteLength-M}].`);if(typeof i=="object"&&i!==null)a=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof n<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof s<"u")throw new TypeError("'options' must be an object.");o=new Uint8Array(f,M,v)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[c,d]=await ge(a),u=await c.createInferenceSessionHandler(o,d);return Ne(),new jp(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}}}),Ae,qe=_(()=>{Ke(),Ae=De}),et=_(()=>{}),ut=_(()=>{}),Re=_(()=>{}),Mt=_(()=>{}),lt={};I(lt,{InferenceSession:()=>Ae,TRACE:()=>Ee,TRACE_FUNC_BEGIN:()=>ke,TRACE_FUNC_END:()=>Ne,Tensor:()=>We,env:()=>C,registerBackend:()=>z});var pt=_(()=>{G(),re(),qe(),le(),et(),ut(),Ve(),Re(),Mt()}),yt=_(()=>{}),ct={};I(ct,{default:()=>Wt});var ht,vt,Wt,Qt=_(()=>{var e;bu(),_t(),wr(),ht="ort-wasm-proxy-worker",vt=((e=globalThis.self)==null?void 0:e.name)===ht,vt&&(self.onmessage=t=>{let{type:s,in:n}=t.data;try{switch(s){case"init-wasm":Se(n.wasm).then(()=>{qo(n).then(()=>{postMessage({type:s})},i=>{postMessage({type:s,err:i})})},i=>{postMessage({type:s,err:i})});break;case"init-ep":{let{epName:i,env:o}=n;Qo(o,i).then(()=>{postMessage({type:s})},a=>{postMessage({type:s,err:a})});break}case"copy-from":{let{buffer:i}=n,o=Jn(i);postMessage({type:s,out:o});break}case"create":{let{model:i,options:o}=n;Jo(i,o).then(a=>{postMessage({type:s,out:a})},a=>{postMessage({type:s,err:a})});break}case"release":Yo(n),postMessage({type:s});break;case"run":{let{sessionId:i,inputIndices:o,inputs:a,outputIndices:c,options:d}=n;ea(i,o,a,c,new Array(c.length).fill(null),d).then(u=>{u.some(f=>f[3]!=="cpu")?postMessage({type:s,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:s,out:u},sa([...a,...u]))},u=>{postMessage({type:s,err:u})});break}case"end-profiling":ta(n),postMessage({type:s});break;default:}}catch(i){postMessage({type:s,err:i})}}),Wt=vt?null:t=>new Worker(t??ds,{type:"classic",name:ht})}),jt,bs,ds,Ls,Js,is,Ts,Sr,Gr,kr,Kr,At,Ir,wr=_(()=>{yt(),jt=typeof location>"u"?void 0:location.origin,bs=()=>{var e,t;return typeof document<"u"?(e=document.currentScript)==null?void 0:e.src:typeof self<"u"?(t=self.location)==null?void 0:t.href:void 0},ds=bs(),Ls=()=>{if(ds&&!ds.startsWith("blob:"))return ds.substring(0,ds.lastIndexOf("/")+1)},Js=(e,t)=>{try{let s=t??ds;return(s?new URL(e,s):new URL(e)).origin===jt}catch{return!1}},is=(e,t)=>{let s=t??ds;try{return(s?new URL(e,s):new URL(e)).href}catch{return}},Ts=(e,t)=>`${t??"./"}${e}`,Sr=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Gr=async e=>(await import(e)).default,kr=(Qt(),b(ct)).default,Kr=async()=>{if(!ds)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Js(ds))return[void 0,kr()];let e=await Sr(ds);return[e,kr(e)]},At=void 0,Ir=async(e,t,s)=>{if(!e&&!t&&At&&ds&&Js(ds))return[void 0,At];{let n="ort-wasm-simd-threaded.jsep.mjs",i=e??is(n,t),o=s&&i&&!Js(i,t),a=o?await Sr(i):i??Ts(n,t);return[o?a:void 0,await Gr(a)]}}}),Vt,dr,y,te,N,Z,ue,Se,ze,_t=_(()=>{wr(),dr=!1,y=!1,te=!1,N=()=>{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}},Z=()=>{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}},ue=()=>{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}},Se=async e=>{if(dr)return Promise.resolve();if(y)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(te)throw new Error("previous call to 'initializeWebAssembly()' failed.");y=!0;let t=e.initTimeout,s=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!ue())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Z())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let n=N();s>1&&!n&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+s+", 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=s=1);let i=e.wasmPaths,o=typeof i=="string"?i:void 0,a=i==null?void 0:i.mjs,c=(a==null?void 0:a.href)??a,d=i==null?void 0:i.wasm,u=(d==null?void 0:d.href)??d,f=e.wasmBinary,[M,v]=await Ir(c,o,s>1),k=!1,A=[];if(t>0&&A.push(new Promise(R=>{setTimeout(()=>{k=!0,R()},t)})),A.push(new Promise((R,ee)=>{let W={numThreads:s};if(f)W.wasmBinary=f;else if(u||o)W.locateFile=V=>u??o+V;else if(c&&c.indexOf("blob:")!==0)W.locateFile=V=>new URL(V,c).href;else if(M){let V=Ls();V&&(W.locateFile=se=>V+se)}v(W).then(V=>{y=!1,dr=!0,Vt=V,R(),M&&URL.revokeObjectURL(M)},V=>{y=!1,te=!0,ee(V)})})),await Promise.race(A),k)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},ze=()=>{if(dr&&Vt)return Vt;throw new Error("WebAssembly is not initialized yet.")}}),$t,kt,mt,bt=_(()=>{_t(),$t=(e,t)=>{let s=ze(),n=s.lengthBytesUTF8(e)+1,i=s._malloc(n);return s.stringToUTF8(e,i,n),t.push(i),i},kt=(e,t,s,n)=>{if(typeof e=="object"&&e!==null){if(s.has(e))throw new Error("Circular reference in options");s.add(e)}Object.entries(e).forEach(([i,o])=>{let a=t?t+i:i;if(typeof o=="object")kt(o,a+".",s,n);else if(typeof o=="string"||typeof o=="number")n(a,o.toString());else if(typeof o=="boolean")n(a,o?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof o}`)})},mt=e=>{let t=ze(),s=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetLastError(i,i+n);let o=Number(t.getValue(i,n===4?"i32":"i64")),a=t.getValue(i+n,"*"),c=a?t.UTF8ToString(a):"";throw new Error(`${e} ERROR_CODE: ${o}, ERROR_MESSAGE: ${c}`)}finally{t.stackRestore(s)}}}),Yt,ss=_(()=>{_t(),bt(),Yt=e=>{let t=ze(),s=0,n=[],i=e||{};try{if((e==null?void 0:e.logSeverityLevel)===void 0)i.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)i.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&&(i.terminate=!1);let o=0;return(e==null?void 0:e.tag)!==void 0&&(o=$t(e.tag,n)),s=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,o),s===0&&mt("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&kt(e.extra,"",new WeakSet,(a,c)=>{let d=$t(a,n),u=$t(c,n);t._OrtAddRunConfigEntry(s,d,u)!==0&&mt(`Can't set a run config entry: ${a} - ${c}.`)}),[s,n]}catch(o){throw s!==0&&t._OrtReleaseRunOptions(s),n.forEach(a=>t._free(a)),o}}}),Ns,Hs,Es,ms,Mr,qs,Ar=_(()=>{_t(),bt(),Ns=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}`)}},Hs=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Es=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(s=>(typeof s=="string"?s:s.name)==="webgpu")&&(e.enableMemPattern=!1)},ms=(e,t,s,n)=>{let i=$t(t,n),o=$t(s,n);ze()._OrtAddSessionConfigEntry(e,i,o)!==0&&mt(`Can't set a session config entry: ${t} - ${s}.`)},Mr=async(e,t,s)=>{for(let n of t){let i=typeof n=="string"?n:n.name,o=[];switch(i){case"webnn":if(i="WEBNN",typeof n!="string"){let f=n==null?void 0:n.deviceType;f&&ms(e,"deviceType",f,s)}break;case"webgpu":if(i="JS",typeof n!="string"){let f=n;if(f!=null&&f.preferredLayout){if(f.preferredLayout!=="NCHW"&&f.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${f.preferredLayout}`);ms(e,"preferredLayout",f.preferredLayout,s)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let a=$t(i,s),c=o.length,d=0,u=0;if(c>0){d=ze()._malloc(c*ze().PTR_SIZE),s.push(d),u=ze()._malloc(c*ze().PTR_SIZE),s.push(u);for(let f=0;f{let t=ze(),s=0,n=[],i=e||{};Es(i);try{let o=Ns(i.graphOptimizationLevel??"all"),a=Hs(i.executionMode??"sequential"),c=typeof i.logId=="string"?$t(i.logId,n):0,d=i.logSeverityLevel??2;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log serverity level is not valid: ${d}`);let u=i.logVerbosityLevel??0;if(!Number.isInteger(u)||u<0||u>4)throw new Error(`log verbosity level is not valid: ${u}`);let f=typeof i.optimizedModelFilePath=="string"?$t(i.optimizedModelFilePath,n):0;if(s=t._OrtCreateSessionOptions(o,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,c,d,u,f),s===0&&mt("Can't create session options."),i.executionProviders&&await Mr(s,i.executionProviders,n),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);ms(s,"enableGraphCapture",i.enableGraphCapture.toString(),n)}if(i.freeDimensionOverrides)for(let[M,v]of Object.entries(i.freeDimensionOverrides)){if(typeof M!="string")throw new Error(`free dimension override name must be a string: ${M}`);if(typeof v!="number"||!Number.isInteger(v)||v<0)throw new Error(`free dimension override value must be a non-negative integer: ${v}`);let k=$t(M,n);t._OrtAddFreeDimensionOverride(s,k,v)!==0&&mt(`Can't set a free dimension override: ${M} - ${v}.`)}return i.extra!==void 0&&kt(i.extra,"",new WeakSet,(M,v)=>{ms(s,M,v,n)}),[s,n]}catch(o){throw s!==0&&t._OrtReleaseSessionOptions(s)!==0&&mt("Can't release session options."),n.forEach(a=>t._free(a)),o}}}),Vs,zs,Us,yr,Ps,Ys,ur,br,It=_(()=>{Vs=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}`)}},zs=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}`)}},Us=(e,t)=>{let s=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],n=typeof t=="number"?t:t.reduce((i,o)=>i*o,1);return s>0?Math.ceil(n*s):void 0},yr=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}`)}},Ps=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}`)}},Ys=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",ur=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",br=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}`)}}}),pr,Zs=_(()=>{yt(),pr=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let s=t.headers.get("Content-Length"),n=s?parseInt(s,10):0;if(n<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let i=t.body.getReader(),o;try{o=new ArrayBuffer(n)}catch(c){if(c instanceof RangeError){let d=Math.ceil(n/65536);o=new WebAssembly.Memory({initial:d,maximum:d}).buffer}else throw c}let a=0;for(;;){let{done:c,value:d}=await i.read();if(c)break;let u=d.byteLength;new Uint8Array(o,a,u).set(d),a+=u}return new Uint8Array(o,0,n)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Fr,Bs,Ze,tt,ft,ns,Ut,ks=_(()=>{It(),Fr=["V","I","W","E","F"],Bs=(e,t)=>{console.log(`[${Fr[e]},${new Date().toISOString()}]${t}`)},ft=(e,t)=>{Ze=e,tt=t},ns=(e,t)=>{let s=Ps(e),n=Ps(Ze);s>=n&&Bs(s,typeof t=="function"?t():t)},Ut=(...e)=>{tt&&ns(...e)}}),Dr,Ws,Le,Or,rn,xe,P,B=_(()=>{Dr=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Ws=class{static calcShape(e,t,s=!1){let n=e.length,i=t.length;if(n===0)return t;if(i===0)return e;let o=Math.max(e.length,t.length),a=new Array(o);if(s){if(n<2||i<2)return;let c=Dr.calcMatMulShape([e[n-2],e[n-1]],[t[i-2],t[i-1]]);if(c===void 0)return;[a[o-2],a[o-1]]=c}for(let c=s?3:1;c<=o;c++){let d=n-c<0?1:e[n-c],u=i-c<0?1:t[i-c];if(d!==u&&d>1&&u>1)return;let f=Math.max(d,u);if(d&&u)a[o-c]=Math.max(d,u);else{if(f>1)return;a[o-c]=0}}return a}static isValidBroadcast(e,t){let s=e.length,n=t.length;if(s>n)return!1;for(let i=1;i<=s;i++)if(e[s-i]!==1&&e[s-i]!==t[n-i])return!1;return!0}},Le=class Ep{static size(t){return Ep.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,s=4){let n=t.length;if(n===0)return[];let i=new Array(n),o=n-1;for(;o>=0;){if(t[o]%s===0){i[o]=t[o]/s;break}if(s%t[o]!==0)throw new Error("cannot convert shape");i[o]=1,s/=t[o],o--}for(o--;o>=0;o--)i[o]=t[o];return i}static sizeFromDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Ep.getSizeFromDimensionRange(t,s,t.length)}static sizeToDimension(t,s){if(s<0||s>t.length)throw new Error(`invalid dimension of ${s} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Ep.getSizeFromDimensionRange(t,0,s)}static getSizeFromDimensionRange(t,s,n){let i=1;for(let o=s;o=0;--i)n[i]=n[i+1]*t[i+1];return n}static normalizeAxis(t,s){if(t<-s&&t>=s)throw new Error("unsupported axis for this operation.");return t<0?t+s:t}static normalizeAxes(t,s){return t.map(n=>this.normalizeAxis(n,s??t.length))}static sortBasedOnPerm(t,s){return s?s.map(n=>t[n]):t.slice().reverse()}static padShape(t,s){let n=t.length;return t.map((i,o)=>i+s[o]+s[o+n])}static areEqual(t,s){return t.length!==s.length?!1:t.every((n,i)=>n===s[i])}},Or=class ku{static adjustPoolAttributes(t,s,n,i,o,a){if(!t&&n.length!==s.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let c=0;c=n.length?n.push(s[c+2]):n[c]=s[c+2];for(let c=0;c=n[c]||a[c+n.length]>=n[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,s,n,i,o,a,c){if(c){if(o.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(s.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let d=0;d{It(),ne=(e,t)=>new(yr(t))(e)}),ve,je,st,dt,nt,gt,Ot,Kt,es,us,rs=_(()=>{ks(),ve=(e,t=!0)=>{if(e.byteLength%8!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 8 (BigInt).");let s=e.byteLength/8,n=new BigInt64Array(e.buffer,e.byteOffset,s),i=new Int32Array(s);for(let o=0;o2147483647n||a<-2147483648n)throw new Error(`Overflow occurred when converting BigInt to Int32 at index ${o}: ${a}`);i[o]=Number(a)}return t?new Uint8Array(i.buffer):i},je=(e,t=!0)=>{if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (Int32).");let s=e.byteLength/4,n=new Int32Array(e.buffer,e.byteOffset,s),i=BigInt64Array.from(n,BigInt);return t?new Uint8Array(i.buffer):i},st=1,dt=()=>st++,nt=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),gt=(e,t)=>{let s=nt.get(e);if(!s)throw new Error("Unsupported data type.");return t.length>0?Math.ceil(t.reduce((n,i)=>n*i)*s/8):0},Ot=class{constructor(e){this.shouldConvertInt64toInt32=!1,this.isInt64ToInt32Converted=!1;let{sessionId:t,context:s,tensor:n,dataType:i,shape:o,shouldConvertInt64toInt32:a=!1}=e;this.sessionId=t,this.mlContext=s,this.mlTensor=n,this.dataType=i,this.tensorShape=o,this.shouldConvertInt64toInt32=a}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return gt(this.dataType,this.tensorShape)}destroy(){Ut("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e,t){if(e){let s=await this.mlContext.readTensor(this.mlTensor),n=je(new Uint8Array(s));if(t){(t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)).set(n);return}else return n.buffer}else return t?this.mlContext.readTensor(this.mlTensor,t):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,s){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===s.length&&this.tensorShape.every((n,i)=>n===s[i])}setIsInt64ToInt32Converted(e){this.isInt64ToInt32Converted=e}},Kt=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,s,n){let i=t,o=this.tensorManager.getMLContext(e),a=i==="int64"&&!o.opSupportLimits().input.dataTypes.includes("int64");if(a&&(i="int32",Ut("verbose",()=>"[WebNN] TensorIdTracker.ensureTensor: convert dataType from int64 to int32")),this.wrapper){if(this.wrapper.canReuseTensor(o,i,s))return this.wrapper.tensor;if(n){if(this.wrapper.byteLength!==gt(i,s))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 c=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,i,s,c,!0,!0,a),n&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper)if(this.wrapper.shouldConvertInt64toInt32&&(t=ve(e,!0),this.wrapper.setIsInt64ToInt32Converted(!0)),t.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else Ut("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){var t,s,n;if(this.activeUpload){let i=(t=this.wrapper)!=null&&t.isInt64ToInt32Converted?je(this.activeUpload):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(i):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(i);return}else return i.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read((s=this.wrapper)==null?void 0:s.shouldConvertInt64toInt32,e):this.wrapper.read((n=this.wrapper)==null?void 0:n.shouldConvertInt64toInt32)}},es=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}reserveTensorId(){let e=dt();return this.tensorTrackersById.set(e,new Kt(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,s,n,i){Ut("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${s}, shape: ${n}, copyOld: ${i}}`);let o=this.tensorTrackersById.get(t);if(!o)throw new Error("Tensor not found.");return o.ensureTensor(e,s,n,i)}upload(e,t){let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");s.upload(t)}async download(e,t){Ut("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t==null?void 0:t.byteLength}}`);let s=this.tensorTrackersById.get(e);if(!s)throw new Error("Tensor not found.");return s.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,s,n){let i=this.getMLContext(e),o=dt(),a=new Ot({sessionId:e,context:i,tensor:t,dataType:s,shape:n});return this.tensorTrackersById.set(o,new Kt(this,a)),this.externalTensors.add(a),o}async getCachedTensor(e,t,s,n,i,o,a=!1){let c=this.getMLContext(e);for(let[u,f]of this.freeTensors.entries())if(f.canReuseTensor(c,t,s)){Ut("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, shape: ${s}}`);let M=this.freeTensors.splice(u,1)[0];return M.sessionId=e,M}Ut("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, shape: ${s}}`);let d=await c.createTensor({dataType:t,shape:s,dimensions:s,usage:n,writable:i,readable:o});return new Ot({sessionId:e,context:c,tensor:d,dataType:t,shape:s,shouldConvertInt64toInt32:a})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},us=(...e)=>new es(...e)}),ps,Is,As,hr=_(()=>{It(),_t(),we(),rs(),ks(),ps=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Is=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let s=Object.keys(e).sort(),n=Object.keys(t).sort();return s.length===n.length&&s.every((i,o)=>i===n[o]&&e[i]===t[i])},As=class{constructor(e){this.tensorManager=us(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,ft(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Ut("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Ut("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let s of t)Ut("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${s}}`),this.tensorManager.releaseTensorId(s);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let s=this.mlContextCache.findIndex(n=>n.gpuDevice===e);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:n}),n}}else if(e===void 0){let s=this.mlContextCache.findIndex(n=>n.options===void 0&&n.gpuDevice===void 0);if(s!==-1)return this.mlContextCache[s].mlContext;{let n=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:n}),n}}let t=this.mlContextCache.findIndex(s=>Is(s.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:s}),s}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let s=this.sessionIdsByMLContext.get(t);s||(s=new Set,this.sessionIdsByMLContext.set(t,s)),s.add(e),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let s=this.sessionIdsByMLContext.get(t);if(s.delete(e),s.size===0){this.sessionIdsByMLContext.delete(t);let n=this.mlContextCache.findIndex(i=>i.mlContext===t);n!==-1&&this.mlContextCache.splice(n,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Ut("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,s,n,i){let o=ps.get(s);if(!o)throw new Error(`Unsupported ONNX data type: ${s}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,o,n,i)}async createTemporaryTensor(e,t,s){Ut("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${s}}`);let n=ps.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,n,s,!1);let o=this.temporarySessionTensorIds.get(e);return o?o.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!ze().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Ut("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let s=await this.tensorManager.download(e);return ne(s,t)}}registerMLTensor(e,t,s,n){let i=ps.get(s);if(!i)throw new Error(`Unsupported ONNX data type: ${s}`);let o=this.tensorManager.registerTensor(e,t,i,n);return Ut("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${n}} -> {tensorId: ${o}}`),o}registerMLConstant(e,t,s,n,i,o,a=!1){if(!o)throw new Error("External mounted files are not available.");let c=e;e.startsWith("./")&&(c=e.substring(2));let d=o.get(c);if(!d)throw new Error(`File with name ${c} not found in preloaded files.`);if(t+s>d.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let u=d.slice(t,t+s).buffer,f;switch(i.dataType){case"float32":f=new Float32Array(u);break;case"float16":f=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(u):new Uint16Array(u);break;case"int32":f=new Int32Array(u);break;case"uint32":f=new Uint32Array(u);break;case"int64":a?(f=ve(new Uint8Array(u),!1),i.dataType="int32"):f=new BigInt64Array(u);break;case"uint64":f=new BigUint64Array(u);break;case"int8":f=new Int8Array(u);break;case"int4":case"uint4":case"uint8":f=new Uint8Array(u);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return Ut("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}} ${a?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),n.constant(i,f)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,t){let s=this.sessionGraphInputs.get(e);return s?s.includes(t):!1}isInt64Supported(e){var t;return!!((t=this.mlContextBySessionId.get(e))!=null&&t.opSupportLimits().input.dataTypes.includes("int64"))}flush(){}}}),Cs=_(()=>{}),er,os,fs,Rs,Gs,or,vs,ar,ys,hs=_(()=>{ks(),Cs(),er=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]]),os=[],fs=e=>Math.ceil(Number(e)/16)*16,Rs=e=>{for(let t=0;tGs++,vs=async(e,t,s,n)=>{let i=fs(s),o=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let a=e.getCommandEncoder();e.endComputePass(),a.copyBufferToBuffer(t,0,o,0,i),e.flush(),await o.mapAsync(GPUMapMode.READ);let c=o.getMappedRange();if(n){let d=n();return d.set(new Uint8Array(c,0,s)),d}else return new Uint8Array(c.slice(0,s))}finally{o.destroy()}},ar=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[t]of er)os.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let s=t.buffer,n=t.byteOffset,i=t.byteLength,o=fs(i),a=this.storageCache.get(e);if(!a)throw new Error("gpu data for uploading does not exist");if(Number(a.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${a.originalSize}, data size=${i}`);let c=this.backend.device.createBuffer({mappedAtCreation:!0,size:o,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),d=c.getMappedRange();new Uint8Array(d).set(new Uint8Array(s,n,i)),c.unmap();let u=this.backend.device.createCommandEncoder();u.copyBufferToBuffer(c,0,a.gpuData.buffer,0,o),this.backend.device.queue.submit([u.finish()]),c.destroy(),Ut("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let s=this.storageCache.get(e);if(!s)throw new Error("source gpu data for memcpy does not exist");let n=this.storageCache.get(t);if(!n)throw new Error("destination gpu data for memcpy does not exist");if(s.originalSize!==n.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=fs(s.originalSize),o=this.backend.getCommandEncoder();this.backend.endComputePass(),o.copyBufferToBuffer(s.gpuData.buffer,0,n.gpuData.buffer,0,i)}registerExternalBuffer(e,t,s){let n;if(s){if(n=s[0],e===s[1])return Ut("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, buffer is the same, skip.`),n;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 n=or();return this.storageCache.set(n,{gpuData:{id:n,type:0,buffer:e},originalSize:t}),Ut("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${n}, registered.`),n}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Ut("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let s=Rs(e),n,i=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,o=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||o){let c=(i?this.freeBuffers:this.freeUniformBuffers).get(s);c?c.length>0?n=c.pop():n=this.backend.device.createBuffer({size:s,usage:t}):n=this.backend.device.createBuffer({size:s,usage:t})}else n=this.backend.device.createBuffer({size:s,usage:t});let a={id:or(),type:0,buffer:n};return this.storageCache.set(a.id,{gpuData:a,originalSize:Number(e)}),Ut("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${a.id}`),a}get(e){var t;return(t=this.storageCache.get(e))==null?void 0:t.gpuData}release(e){let t=typeof e=="bigint"?Number(e):e,s=this.storageCache.get(t);if(!s){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return Ut("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${s.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(s.gpuData.buffer),s.originalSize}async download(e,t){let s=this.storageCache.get(Number(e));if(!s)throw new Error("data does not exist");await vs(this.backend,s.gpuData.buffer,s.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=er.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let s=this.freeBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let s=this.freeUniformBuffers.get(e.size)||[];t===void 0||s.length>=t?e.destroy():s.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 t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(s=>{s.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(Ut("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(s=>{s.gpuData.buffer.destroy()}),this.storageCache=new Map)}},ys=(...e)=>new ar(...e)}),gs,Lt,Ht=_(()=>{gs=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}},Lt=e=>new gs(e)}),lr,Hr,cs,$s,Ct,as,ni,qr,Qs,Et,nn,Ue,xt,aa,Lr,la,ca,Nt=_(()=>{It(),B(),lr=64,Hr=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==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}`)}},cs=(e,t=1)=>{let s=Hr(e,t);return typeof s=="string"?s:s[0]},$s=(e,t=1)=>{let s=Hr(e,t);return typeof s=="string"?s:s[1]},Ct=(...e)=>{let t=[];return e.forEach(s=>{s.length!==0&&t.push({type:12,data:s},{type:12,data:Le.computeStrides(s)})}),t},as=e=>e%4===0?4:e%2===0?2:1,ni=(e="f32",t,s="0")=>!t||t===1?`${e}(${s})`:`vec${t}<${e}>(${s})`,qr=(e,t,s)=>e==="f32"?s:t===1?`f32(${s})`:`vec${t}(${s})`,Qs=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,Et=(e,t,s,n)=>e.startsWith("uniforms.")&&s>4?typeof t=="string"?n==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:n==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:s>1?`${e}[${t}]`:e,nn=(e,t,s,n,i)=>{let o=typeof s=="number",a=o?s:s.length,c=[...new Array(a).keys()],d=a<2?"u32":a<=4?`vec${a}`:`array`,u=Hr(t,i),f=typeof u=="string"?u:u[1],M=typeof u=="string"?u:u[0],v={indices:d,value:f,storage:M,tensor:t},k=Je=>typeof Je=="string"?Je:`${Je}u`,A={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},R=o?"uniforms.":"",ee=`${R}${e}_shape`,W=`${R}${e}_strides`,V="";for(let Je=0;Je ${v.indices} { + var indices: ${v.indices}; + var current = offset; + ${V} + return indices; + }`,oe=Je=>(A.offsetToIndices=!0,a<2?Je:`o2i_${e}(${Je})`),Me=[];if(a>=2)for(let Je=a-1;Je>=0;Je--)Me.push(`${Et(W,Je,a)} * (indices[${Je}])`);let Ie=a<2?"":` + fn i2o_${e}(indices: ${v.indices}) -> u32 { + return ${Me.join("+")}; + }`,Ce=Je=>(A.indicesToOffset=!0,a<2?Je:`i2o_${e}(${Je})`),Be=(...Je)=>a===0?"0u":`${v.indices}(${Je.map(k).join(",")})`,Ge=(Je,it)=>a<2?`${Je}`:`${Et(Je,it,a)}`,rt=(Je,it,Ft)=>a<2?`${Je}=${Ft};`:`${Et(Je,it,a)}=${Ft};`,St={},Tt=(Je,it)=>{A.broadcastedIndicesToOffset=!0;let Ft=`${it.name}broadcastedIndicesTo${e}Offset`;if(Ft in St)return`${Ft}(${Je})`;let qt=[];for(let Ds=a-1;Ds>=0;Ds--){let ei=it.indicesGet("outputIndices",Ds+it.rank-a);qt.push(`${Ge(W,Ds)} * (${ei} % ${Ge(ee,Ds)})`)}return St[Ft]=`fn ${Ft}(outputIndices: ${it.type.indices}) -> u32 { + return ${qt.length>0?qt.join("+"):"0u"}; + }`,`${Ft}(${Je})`},ot=(Je,it)=>(()=>{if(v.storage===v.value)return`${e}[${Je}]=${it};`;if(v.storage==="vec2"&&v.value==="i32")return`${e}[${Je}]=vec2(u32(${it}), select(0u, 0xFFFFFFFFu, ${it} < 0));`;if(v.storage==="vec2"&&v.value==="u32")return`${e}[${Je}]=vec2(u32(${it}), 0u);`;if(v.storage==="u32"&&v.value==="vec4")return`${e}[${Je}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${it}));`;throw new Error(`not supported combination of storage type ${v.storage} and value type ${v.value} yet`)})(),Dt=Je=>(()=>{if(v.storage===v.value)return`${e}[${Je}]`;if(v.storage==="vec2"&&v.value==="i32")return`i32(${e}[${Je}].x)`;if(v.storage==="vec2"&&v.value==="u32")return`u32(${e}[${Je}].x)`;if(v.storage==="u32"&&v.value==="vec4")return`vec4(bool(${e}[${Je}] & 0xFFu), bool(${e}[${Je}] & 0xFF00u), bool(${e}[${Je}] & 0xFF0000u), bool(${e}[${Je}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${v.storage} and value type ${v.value} yet`)})(),zt=a<2?"":` + fn get_${e}ByIndices(indices: ${v.indices}) -> ${f} { + return ${Dt(`i2o_${e}(indices)`)}; + }`,Pt=a<2?"":(()=>{let Je=c.map(Ft=>`d${Ft}: u32`).join(", "),it=c.map(Ft=>`d${Ft}`).join(", ");return` + fn get_${e}(${Je}) -> ${f} { + return get_${e}ByIndices(${Be(it)}); + }`})(),at=(...Je)=>{if(Je.length!==a)throw new Error(`indices length must be ${a}`);let it=Je.map(k).join(",");return a===0?Dt("0u"):a===1?Dt(it[0]):(A.get=!0,A.getByIndices=!0,A.indicesToOffset=!0,`get_${e}(${it})`)},Zt=Je=>a<2?Dt(Je):(A.getByIndices=!0,A.indicesToOffset=!0,`get_${e}ByIndices(${Je})`),Rt=a<2?"":` + fn set_${e}ByIndices(indices: ${v.indices}, value: ${f}) { + ${ot(`i2o_${e}(indices)`,"value")} + }`,Gt=a<2?"":(()=>{let Je=c.map(Ft=>`d${Ft}: u32`).join(", "),it=c.map(Ft=>`d${Ft}`).join(", ");return` + fn set_${e}(${Je}, value: ${f}) { + set_${e}ByIndices(${Be(it)}, value); + }`})();return{impl:()=>{let Je=[],it=!1;return A.offsetToIndices&&(Je.push(se),it=!0),A.indicesToOffset&&(Je.push(Ie),it=!0),A.broadcastedIndicesToOffset&&(Object.values(St).forEach(Ft=>Je.push(Ft)),it=!0),A.set&&(Je.push(Gt),it=!0),A.setByIndices&&(Je.push(Rt),it=!0),A.get&&(Je.push(Pt),it=!0),A.getByIndices&&(Je.push(zt),it=!0),!o&&it&&Je.unshift(`const ${ee} = ${v.indices}(${s.join(",")});`,`const ${W} = ${v.indices}(${Le.computeStrides(s).join(",")});`),Je.join(` +`)},type:v,offsetToIndices:oe,indicesToOffset:Ce,broadcastedIndicesToOffset:Tt,indices:Be,indicesGet:Ge,indicesSet:rt,set:(...Je)=>{if(Je.length!==a+1)throw new Error(`indices length must be ${a}`);let it=Je[a];if(typeof it!="string")throw new Error("value must be string");let Ft=Je.slice(0,a).map(k).join(",");return a===0?ot("0u",it):a===1?ot(Ft[0],it):(A.set=!0,A.setByIndices=!0,A.indicesToOffset=!0,`set_${e}(${Ft}, ${it})`)},setByOffset:ot,setByIndices:(Je,it)=>a<2?ot(Je,it):(A.setByIndices=!0,A.indicesToOffset=!0,`set_${e}ByIndices(${Je}, ${it});`),get:at,getByOffset:Dt,getByIndices:Zt,usage:n,name:e,strides:W,shape:ee,rank:a}},Ue=(e,t,s,n=1)=>nn(e,t,s,"input",n),xt=(e,t,s,n=1)=>nn(e,t,s,"output",n),aa=(e,t,s)=>nn(e,t,s,"atomicOutput",1),Lr=(e,t,s,n=1)=>nn(e,t,s,"internal",n),la=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=lr){let t=typeof e=="number"?e:e[0],s=typeof e=="number"?1:e[1],n=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||s>this.limits.maxComputeWorkgroupSizeY||n>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*s*n>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${s}, ${n}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,o=i?`@builtin(global_invocation_id) global_id : vec3, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, + @builtin(local_invocation_id) local_id : vec3, + @builtin(local_invocation_index) local_idx : u32, + @builtin(workgroup_id) workgroup_id : vec3, + @builtin(num_workgroups) num_workgroups : vec3`,a=i?`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 * ${t*s*n}u + local_idx;`;return`@compute @workgroup_size(${t}, ${s}, ${n}) + fn main(${o}) { + ${a} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,t){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let s=e.usage==="input"?"read":"read_write",n=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${t}) var ${e.name}: array<${n}>;`}declareVariables(...e){return e.map(t=>this.declareVariable(t,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(t=>this.registerInternalVariable(t)),this}registerUniform(e,t,s=1){return this.uniforms.push({name:e,type:t,length:s}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:t,type:s,length:n}of this.uniforms)if(n&&n>4)s==="f16"?e.push(`@align(16) ${t}:array, ${Math.ceil(n/8)}>`):e.push(`${t}:array, ${Math.ceil(n/4)}>`);else{let i=n==null||n===1?s:`vec${n}<${s}>`;e.push(`${t}:${i}`)}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=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},ca=(e,t)=>new la(e,t)}),da,ii,oi,ua,pa,ai,Ks,li,ha,_r=_(()=>{It(),B(),Ht(),Nt(),da=(e,t)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(t.length!==0&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},ii=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),oi=(e,t)=>Le.sortBasedOnPerm(e,ii(e.length,t)),ua=(e,t,s,n)=>{let i=`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`;for(let o=0;o{let s=[],n=[];for(let i=0;i{let s=0;for(let n=0;n{let s=e.dataType,n=e.dims.length,i=ii(n,t),o=oi(e.dims,i),a=e.dims,c=o,d=n<2||ai(i,e.dims),u;if(d)return u=A=>{let R=Ue("input",s,a,4),ee=xt("output",s,c,4);return` + ${A.registerUniform("output_size","u32").declareVariables(R,ee)} + ${A.mainStart()} + ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let A=Le.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(A/64/4)},programUniforms:[{type:12,data:Math.ceil(A/4)}]}},getShaderSource:u};let{newShape:f,newPerm:M}=pa(e.dims,i),v=Le.areEqual(M,[2,3,1]),k=Le.areEqual(M,[3,1,2]);if(f.length===2||v||k){a=v?[f[0],f[1]*f[2]]:k?[f[0]*f[1],f[2]]:f,c=[a[1],a[0]];let A=16;return u=R=>{let ee=Ue("a",s,a.length),W=xt("output",s,c.length);return` + ${R.registerUniform("output_size","u32").declareVariables(ee,W)} + var tile : array, ${A}>; + ${R.mainStart([A,A,1])} + let stride = (uniforms.output_shape[1] - 1) / ${A} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${A}u + local_id.x; + let input_row = workgroup_id_x * ${A}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${ee.getByIndices(`${ee.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${A}u + local_id.x; + let output_row = workgroup_id_y * ${A}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 R=Le.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(c[1]/A),y:Math.ceil(c[0]/A)},programUniforms:[{type:12,data:R},...Ct(a,c)]}},getShaderSource:u}}return u=A=>{let R=Ue("a",s,a.length),ee=xt("output",s,c.length);return` + ${A.registerUniform("output_size","u32").declareVariables(R,ee)} + + ${ua(i,n,R,ee)} + + ${A.mainStart()} + ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${ee.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${ee.setByOffset("global_idx",R.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let A=Le.size(o);return{outputs:[{dims:o,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(A/64)},programUniforms:[{type:12,data:A},...Ct(a,c)]}},getShaderSource:u}},li=(e,t)=>{da(e.inputs,t.perm),e.compute(Ks(e.inputs[0],t.perm))},ha=e=>Lt({perm:e.perm})}),Au,_a,ci,di,gn,ma,fa,ga,wa,Ma,tr,ya,ba,ui,va,wn,pi,xa,hi,zr,Ta,Sp=_(()=>{It(),B(),Nt(),Mi(),_r(),Au={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"},_a={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"},ci={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},di={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},gn=(e,t)=>{let s=[];for(let n=t-e;n{let s=[],n=e.length;for(let o=0;oe[o]);return[s,i]},fa=(e,t)=>{let s=e.length+t.length,n=[],i=0;for(let o=0;o{for(let s=0;s{let s=[];if(!ga(e,t)){for(let n=0;ns.push(n))}return s},Ma=(e,t,s,n,i,o,a)=>{let c=s[0].dims,d=Le.size(o),u=Le.size(a),f=Ue("_A",s[0].dataType,c),M=xt("output",i,o),v=64;d===1&&(v=256);let k=` + var aBestValues : array; + `,A=R=>` + ${R.registerUniform("reduceSize","u32").declareVariables(f,M)} + ${k} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${R.mainStart(v)} + + let outputIndex = global_idx / ${v}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${ci[n]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${v}) { + let candidate = f32(${f.getByOffset("offset + k")}); + bestValue = ${Au[n]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${v}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 = ${_a[n]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${M.setByOffset("outputIndex",`${n==="mean"?`${M.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${M.type.storage}(${di[n]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${t};${v}`,inputDependencies:["type"]},getShaderSource:A,getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:d},programUniforms:[{type:12,data:u}]})}},tr=(e,t,s,n)=>{let i=e.inputs.length===1?s:yn(e.inputs,s),o=i.axes;o.length===0&&!i.noopWithEmptyAxes&&(o=e.inputs[0].dims.map((k,A)=>A));let a=Le.normalizeAxes(o,e.inputs[0].dims.length),c=a,d=e.inputs[0],u=wa(c,e.inputs[0].dims.length);u.length>0&&(d=e.compute(Ks(e.inputs[0],u),{inputs:[0],outputs:[-1]})[0],c=gn(c.length,d.dims.length));let[f,M]=ma(d.dims,c),v=f;i.keepDims&&(v=fa(f,a)),e.compute(Ma(t,i.cacheKey,[d],n,e.inputs[0].dataType,v,M),{inputs:[d]})},ya=(e,t)=>{tr(e,"ReduceMeanShared",t,"mean")},ba=(e,t)=>{tr(e,"ReduceL1Shared",t,"l1")},ui=(e,t)=>{tr(e,"ReduceL2Shared",t,"l2")},va=(e,t)=>{tr(e,"ReduceLogSumExpShared",t,"logSumExp")},wn=(e,t)=>{tr(e,"ReduceMaxShared",t,"max")},pi=(e,t)=>{tr(e,"ReduceMinShared",t,"min")},xa=(e,t)=>{tr(e,"ReduceProdShared",t,"prod")},hi=(e,t)=>{tr(e,"ReduceSumShared",t,"sum")},zr=(e,t)=>{tr(e,"ReduceSumSquareShared",t,"sumSquare")},Ta=(e,t)=>{tr(e,"ReduceLogSumShared",t,"logSum")}}),sr,Fu,Mn,yn,rr,Ea,Pa,Ca,$a,bn,Sa,ka,Ia,_i,Aa,nr,mi,Fa,Da,fi,Oa,La,gi,za,Ba,wi,Mi=_(()=>{It(),B(),Ht(),Nt(),Sp(),sr=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.")},Fu=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Mn=(e,t,s,n,i,o,a=!1,c=!1)=>{let d=[],u=s[0].dims,f=u.length,M=Le.normalizeAxes(i,f),v=!c&&M.length===0;u.forEach((R,ee)=>{v||M.indexOf(ee)>=0?a&&d.push(1):d.push(R)});let k=d.length,A=Le.size(d);return{name:e,shaderCache:t,getShaderSource:R=>{let ee=[],W=Ue("_A",s[0].dataType,f),V=xt("output",o,k),se=n(W,V,M),oe=se[2];for(let Me=0,Ie=0;Me=0?(a&&Ie++,oe=`for(var j${Me}: u32 = 0; j${Me} < ${u[Me]}; j${Me}++) { + ${se[2].includes("last_index")?`let last_index = j${Me};`:""} + ${W.indicesSet("input_indices",Me,`j${Me}`)} + ${oe} + }`):(ee.push(`${W.indicesSet("input_indices",Me,V.indicesGet("output_indices",Ie))};`),Ie++);return` + + ${R.registerUniform("output_size","u32").declareVariables(W,V)} + + ${R.mainStart()} + ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${W.type.indices}; + let output_indices = ${V.offsetToIndices("global_idx")}; + + ${ee.join(` +`)} + ${se[0]} // init ops for reduce max/min + ${se[1]} + ${oe} + ${se[3]} + ${se.length===4?V.setByOffset("global_idx","value"):se.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:d,dataType:o}],dispatchGroup:{x:Math.ceil(A/64)},programUniforms:[{type:12,data:A},...Ct(u,d)]})}},yn=(e,t)=>{let s=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(n=>s.push(Number(n))),Lt({axes:s,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},rr=(e,t,s,n)=>{let i=e.inputs,o=i.length===1?s:yn(i,s);e.compute(Mn(t,{hint:o.cacheKey,inputDependencies:["rank"]},[i[0]],o.noopWithEmptyAxes&&o.axes.length===0?Fu:n,o.axes,i[0].dataType,o.keepDims,o.noopWithEmptyAxes),{inputs:[0]})},Ea=(e,t)=>{sr(e.inputs),rr(e,"ReduceLogSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,"value = log(value);"])},Pa=(e,t)=>{sr(e.inputs),rr(e,"ReduceL1",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += abs(${s.getByIndices("input_indices")});`,""])},Ca=(e,t)=>{sr(e.inputs),rr(e,"ReduceL2",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},$a=(e,t)=>{sr(e.inputs),rr(e,"ReduceLogSumExp",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += exp(${s.getByIndices("input_indices")});`,"value = log(value);"])},bn=(e,t)=>{sr(e.inputs),rr(e,"ReduceMax",t,(s,n,i)=>{let o=[];for(let a=0;a=0||i.length===0)&&o.push(s.indicesSet("input_indices",a,0));return[`${o.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = max(value, ${s.getByIndices("input_indices")});`,""]})},Sa=(e,t)=>{sr(e.inputs),rr(e,"ReduceMean",t,(s,n,i)=>{let o=1;for(let a=0;a=0||i.length===0)&&(o*=e.inputs[0].dims[a]);return["var sum = f32(0);","",`sum += f32(${s.getByIndices("input_indices")});`,`let value = ${n.type.value}(sum / ${o});`]})},ka=(e,t)=>{sr(e.inputs),rr(e,"ReduceMin",t,(s,n,i)=>{let o=[];for(let a=0;a=0||i.length===0)&&o.push(`input_indices[${a}] = 0;`);return[`${o.join(` +`)}`,`var value = ${s.getByIndices("input_indices")};`,`value = min(value, ${s.getByIndices("input_indices")});`,""]})},Ia=(e,t)=>{sr(e.inputs),rr(e,"ReduceProd",t,(s,n)=>[`var value = ${n.type.storage}(1);`,"",`value *= ${s.getByIndices("input_indices")};`,""])},_i=(e,t)=>{sr(e.inputs),rr(e,"ReduceSum",t,(s,n)=>[`var value = ${n.type.storage}(0);`,"",`value += ${s.getByIndices("input_indices")};`,""])},Aa=(e,t)=>{sr(e.inputs),rr(e,"ReduceSumSquare",t,(s,n)=>[`var t = ${n.type.value}(0); var value = ${n.type.value}(0);`,"",`t = ${s.getByIndices("input_indices")}; value += t * t;`,""])},nr=(e,t,s)=>{if(t.length===0)return s;let n=1,i=1;for(let o=0;o1024},mi=(e,t)=>{nr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Sa(e,t):ya(e,t)},Fa=(e,t)=>{nr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Pa(e,t):ba(e,t)},Da=(e,t)=>{nr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ca(e,t):ui(e,t)},fi=(e,t)=>{nr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$a(e,t):va(e,t)},Oa=(e,t)=>{nr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?bn(e,t):wn(e,t)},La=(e,t)=>{nr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?ka(e,t):pi(e,t)},gi=(e,t)=>{nr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ia(e,t):xa(e,t)},za=(e,t)=>{nr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?_i(e,t):hi(e,t)},Ba=(e,t)=>{nr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Aa(e,t):zr(e,t)},wi=(e,t)=>{nr(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ea(e,t):Ta(e,t)}}),yi,bi,Ra,vi,ja=_(()=>{It(),Ht(),Mi(),yi=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.")},bi=(e,t)=>{yi(e.inputs);let s=(n,i,o)=>{let a=[];for(let c=0;c=0||o.length===0)&&a.push(`input_indices[${c}] = 0;`);return[`${a.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Mn("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},Ra=(e,t)=>{yi(e.inputs);let s=(n,i,o)=>{let a=[];for(let c=0;c=0||o.length===0)&&a.push(`input_indices[${c}] = 0;`);return[`${a.join(` +`)}`,`var value = ${n.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${n.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { + value = ${n.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(Mn("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],s,[t.axis],7,t.keepDims),{inputs:[0]})},vi=e=>Lt(e)}),Na,vn,xi,Va,Ua,Qr,Wa,Ga,xn=_(()=>{It(),B(),Cs(),Nt(),Na=(e,t)=>{let s=e[0],n=e[1],i=e[2],o=e[3],a=e[4],c=e[5];if(a&&c)throw new Error("Attention cannot have both past and attention_bias");if(s.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let d=s.dims[0],u=s.dims[1],f=s.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(n.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(n.dims[0]!==f)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==n.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let M=i.dims[0]/3,v=M,k=v;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let se of t.qkvHiddenSizes)if(se%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");M=t.qkvHiddenSizes[0],v=t.qkvHiddenSizes[1],k=t.qkvHiddenSizes[2]}let A=u;if(M!==v)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==M+v+k)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let R=0;if(a){if(v!==k)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(a.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(a.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(a.dims[1]!==d)throw new Error('Input "past" second dimension must be batch_size');if(a.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(a.dims[4]!==v/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(R=a.dims[3])}let ee=A+R,W=-1,V=0;if(o)throw new Error("Mask not supported");if(a)throw new Error("past is not supported");if(c){if(c.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(c.dims[0]!==d||c.dims[1]!==t.numHeads||c.dims[2]!==u||c.dims[3]!==ee)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:d,sequenceLength:u,pastSequenceLength:R,kvSequenceLength:A,totalSequenceLength:ee,maxSequenceLength:W,inputHiddenSize:f,hiddenSize:M,vHiddenSize:k,headSize:Math.floor(M/t.numHeads),vHeadSize:Math.floor(k/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:V,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},vn=(e,t,s)=>t&&e?` + let total_sequence_length_input = u32(${t.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; + } + `:` + ${s?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,xi=(e,t,s,n,i,o,a,c)=>{let d=as(a?1:o),u=64,f=o/d;f{let V=xt("x",e.dataType,e.dims,d),se=[V],oe=a?Ue("seq_lens",a.dataType,a.dims):void 0;oe&&se.push(oe);let Me=c?Ue("total_sequence_length_input",c.dataType,c.dims):void 0;Me&&se.push(Me);let Ie=$s(e.dataType),Ce=[{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(Ce).declareVariables(...se)} + ${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; + ${vn(oe,Me,!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 = ${a?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + var thread_max_vector = ${A}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${A}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(d){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: ${d}`)}})()}; + 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 = ${A}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${A}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(d){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: ${d}`)}})()}; + 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] = ${V.type.value}(${Ie}(1.0) / ${Ie}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${A}(x[offset + i]); + x[offset + i] = ${V.type.value}(exp(f32input - max_value) / sum); + } + } + ${a?` + for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { + x[offset + total_seq_id] = ${V.type.value}(${Ie}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${u};${k};${d}`,inputDependencies:R},getShaderSource:ee,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:i,z:t*s},programUniforms:v})}},Va=(e,t,s,n,i,o,a,c,d)=>{let u=a+o.kvSequenceLength,f=[o.batchSize,o.numHeads,o.sequenceLength,u],M=e>1&&n,v=o.kvNumHeads?o.kvNumHeads:o.numHeads,k=M?[o.batchSize,v,u,o.headSize]:void 0,A=o.nReps?o.nReps:1,R=o.scale===0?1/Math.sqrt(o.headSize):o.scale,ee=as(o.headSize),W=o.headSize/ee,V=12,se={x:Math.ceil(u/V),y:Math.ceil(o.sequenceLength/V),z:o.batchSize*o.numHeads},oe=[{type:12,data:o.sequenceLength},{type:12,data:W},{type:12,data:u},{type:12,data:o.numHeads},{type:12,data:o.headSize},{type:1,data:R},{type:12,data:a},{type:12,data:o.kvSequenceLength},{type:12,data:A}],Me=M&&n&&Le.size(n.dims)>0,Ie=["type","type"];Me&&Ie.push("type"),i&&Ie.push("type"),c&&Ie.push("type"),d&&Ie.push("type");let Ce=[{dims:f,dataType:t.dataType,gpuDataType:0}];M&&Ce.push({dims:k,dataType:t.dataType,gpuDataType:0});let Be=Ge=>{let rt=Ue("q",t.dataType,t.dims,ee),St=Ue("key",s.dataType,s.dims,ee),Tt=[rt,St];if(Me){let Rt=Ue("past_key",n.dataType,n.dims,ee);Tt.push(Rt)}i&&Tt.push(Ue("attention_bias",i.dataType,i.dims));let ot=c?Ue("seq_lens",c.dataType,c.dims):void 0;ot&&Tt.push(ot);let Dt=d?Ue("total_sequence_length_input",d.dataType,d.dims):void 0;Dt&&Tt.push(Dt);let zt=xt("output",t.dataType,f),Pt=[zt];M&&Pt.push(xt("present_key",t.dataType,k,ee));let at=$s(1,ee),Zt=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${V}u; + + var tileQ: array<${rt.type.storage}, ${V*V}>; + var tileK: array<${rt.type.storage}, ${V*V}>; + ${Ge.registerUniforms(Zt).declareVariables(...Tt,...Pt)} + ${Ge.mainStart([V,V,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${A===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${A===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; + ${vn(ot,Dt,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${Me&&M?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${M?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${at}(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; + ${Me&&M?` + 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]; + }`} + ${M?`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 += ${at}(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(ee){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: ${ee}`)}})()}; + output[outputIdx] = ${zt.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${ee};${i!==void 0};${n!==void 0};${e}`,inputDependencies:Ie},getRunData:()=>({outputs:Ce,dispatchGroup:se,programUniforms:oe}),getShaderSource:Be}},Ua=(e,t,s,n,i,o,a=void 0,c=void 0)=>{let d=o+i.kvSequenceLength,u=i.nReps?i.nReps:1,f=i.vHiddenSize*u,M=e>1&&n,v=i.kvNumHeads?i.kvNumHeads:i.numHeads,k=M?[i.batchSize,v,d,i.headSize]:void 0,A=[i.batchSize,i.sequenceLength,f],R=12,ee={x:Math.ceil(i.vHeadSize/R),y:Math.ceil(i.sequenceLength/R),z:i.batchSize*i.numHeads},W=[{type:12,data:i.sequenceLength},{type:12,data:d},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:f},{type:12,data:o},{type:12,data:i.kvSequenceLength},{type:12,data:u}],V=M&&n&&Le.size(n.dims)>0,se=["type","type"];V&&se.push("type"),a&&se.push("type"),c&&se.push("type");let oe=[{dims:A,dataType:t.dataType,gpuDataType:0}];M&&oe.push({dims:k,dataType:t.dataType,gpuDataType:0});let Me=Ie=>{let Ce=Ue("probs",t.dataType,t.dims),Be=Ue("v",s.dataType,s.dims),Ge=[Ce,Be];V&&Ge.push(Ue("past_value",n.dataType,n.dims));let rt=a?Ue("seq_lens",a.dataType,a.dims):void 0;a&&Ge.push(rt);let St=c?Ue("total_sequence_length_input",c.dataType,c.dims):void 0;c&&Ge.push(St);let Tt=[xt("output",t.dataType,A)];M&&Tt.push(xt("present_value",t.dataType,k));let ot=[{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 = ${R}u; + var tileQ: array<${Ce.type.value}, ${R*R}>; + var tileV: array<${Ce.type.value}, ${R*R}>; + ${Ie.registerUniforms(ot).declareVariables(...Ge,...Tt)} + ${Ie.mainStart([R,R,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; + ${vn(rt,St,!0)} + let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch + ${V&&M?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${M?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${Ce.type.storage}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileQ[TILE_SIZE * local_id.y + local_id.x] = probs[offsetA + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + var idx = TILE_SIZE * local_id.y + local_id.x; + ${V&&M?` + 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]; + }`} + ${M?` + 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:`${n!==void 0};${e}`,inputDependencies:se},getRunData:()=>({outputs:oe,dispatchGroup:ee,programUniforms:W}),getShaderSource:Me}},Qr=(e,t,s,n,i,o,a,c,d,u,f=void 0,M=void 0)=>{let v=Math.min(e.outputCount,1+(a?1:0)+(c?1:0)),k=v>1?u.pastSequenceLength:0,A=k+u.kvSequenceLength,R=d&&Le.size(d.dims)>0?d:void 0,ee=[t,s];v>1&&a&&Le.size(a.dims)>0&&ee.push(a),R&&ee.push(R),f&&ee.push(f),M&&ee.push(M);let W=e.compute(Va(v,t,s,a,R,u,k,f,M),{inputs:ee,outputs:v>1?[-1,1]:[-1]})[0];e.compute(xi(W,u.batchSize,u.numHeads,k,u.sequenceLength,A,f,M),{inputs:f&&M?[W,f,M]:[W],outputs:[]});let V=[W,n];v>1&&c&&Le.size(c.dims)>0&&V.push(c),f&&V.push(f),M&&V.push(M),e.compute(Ua(v,W,n,c,u,k,f,M),{inputs:V,outputs:v>1?[0,2]:[0]})},Wa=(e,t)=>{let s=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],n=t.sequenceLength,i=t.inputHiddenSize,o=t.headSize,a=12,c={x:Math.ceil(t.headSize/a),y:Math.ceil(t.sequenceLength/a),z:t.batchSize*t.numHeads},d=[e.inputs[0],e.inputs[1],e.inputs[2]],u=[{type:12,data:n},{type:12,data:i},{type:12,data:o},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],f=M=>{let v=xt("output_q",d[0].dataType,s),k=xt("output_k",d[0].dataType,s),A=xt("output_v",d[0].dataType,s),R=Ue("input",d[0].dataType,d[0].dims),ee=Ue("weight",d[1].dataType,d[1].dims),W=Ue("bias",d[2].dataType,d[2].dims),V=R.type.storage,se=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${a}u; + var tileInput: array<${V}, ${a*a}>; + var tileWeightQ: array<${V}, ${a*a}>; + var tileWeightK: array<${V}, ${a*a}>; + var tileWeightV: array<${V}, ${a*a}>; + ${M.registerUniforms(se).declareVariables(R,ee,W,v,k,A)} + ${M.mainStart([a,a,1])} + let batchIndex = workgroup_id.z / uniforms.num_heads; + let headNumber = workgroup_id.z % uniforms.num_heads; + let m = global_id.y; + let n = global_id.x; + + let inputOffset = batchIndex * (uniforms.M * uniforms.K) + m * uniforms.K; + let biasOffsetQ = headNumber * uniforms.head_size; + let biasOffsetK = uniforms.hidden_size + biasOffsetQ; + let biasOffsetV = uniforms.hidden_size + biasOffsetK; + + var valueQ = ${V}(0); + var valueK = ${V}(0); + var valueV = ${V}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:s,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:c,programUniforms:u}),getShaderSource:f},{inputs:d,outputs:[-1,-1,-1]})},Ga=(e,t)=>{let s=Na(e.inputs,t),[n,i,o]=Wa(e,s);return Qr(e,n,i,o,e.inputs[4],void 0,void 0,void 0,e.inputs[5],s)}}),Ka,Ha,Ti,qa,Du=_(()=>{pt(),It(),B(),Ht(),Nt(),Ka=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let s=(n,i,o)=>{let a=i.length;if(a!==n.length)throw new Error(`${o}: num dimensions != ${a}`);i.forEach((c,d)=>{if(c!==n[d])throw new Error(`${o}: dim[${d}] do not match`)})};if(e[0].dims.length>1){let n=t.format==="NHWC"?t.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,t.spatial?2:void 0);s(e[1].dims,n,"Invalid input scale"),s(e[2].dims,n,"Invalid input B"),s(e[3].dims,n,"Invalid input mean"),s(e[4].dims,n,"Invalid input var")}else s(e[1].dims,[1],"Invalid input scale"),s(e[2].dims,[1],"Invalid input B"),s(e[3].dims,[1],"Invalid input mean"),s(e[4].dims,[1],"Invalid input var")},Ha=(e,t)=>{let{epsilon:s,spatial:n,format:i}=t,o=e[0].dims,a=n?as(o[o.length-1]):1,c=i==="NHWC"&&o.length>1?a:1,d=Le.size(o)/a,u=n,f=u?o.length:o,M=Ue("x",e[0].dataType,e[0].dims,a),v=Ue("scale",e[1].dataType,e[1].dims,c),k=Ue("bias",e[2].dataType,e[2].dims,c),A=Ue("inputMean",e[3].dataType,e[3].dims,c),R=Ue("inputVar",e[4].dataType,e[4].dims,c),ee=xt("y",e[0].dataType,f,a),W=()=>{let se="";if(n)se=`let cOffset = ${o.length===1?"0u":i==="NHWC"?`outputIndices[${o.length-1}] / ${a}`:"outputIndices[1]"};`;else if(i==="NCHW")se=` + ${ee.indicesSet("outputIndices","0","0")} + let cOffset = ${ee.indicesToOffset("outputIndices")};`;else{se=`var cIndices = ${v.type.indices}(0); + cIndices[0] = outputIndices[${o.length-1}];`;for(let oe=1;oe` + const epsilon = ${s}; + ${se.registerUniform("outputSize","u32").declareVariables(M,v,k,A,R,ee)} + ${se.mainStart()} + ${se.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${ee.offsetToIndices(`global_idx * ${a}`)}; + ${W()} + let scale = ${v.getByOffset("cOffset")}; + let bias = ${k.getByOffset("cOffset")}; + let inputMean = ${A.getByOffset("cOffset")}; + let inputVar = ${R.getByOffset("cOffset")}; + let x = ${M.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${ee.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${n}_${a}`,inputDependencies:u?["rank","type","type","type","type"]:void 0},getShaderSource:V,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:u?[{type:12,data:d},...Ct(o)]:[{type:12,data:d}]})}},Ti=e=>Lt(e),qa=(e,t)=>{let{inputs:s,outputCount:n}=e,i=Ti({...t,outputCount:n});if(C.webgpu.validateInputContent&&Ka(s,i),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Ha(s,i))}}),Ei,Qa,Xa,Ja=_(()=>{B(),Nt(),Ei=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")},Qa=e=>{let t=e[0].dims,s=e[0].dims[2],n=Le.size(t)/4,i=e[0].dataType,o=Ue("input",i,t,4),a=Ue("bias",i,[s],4),c=Ue("residual",i,t,4),d=xt("output",i,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:u=>` + const channels = ${s}u / 4; + ${u.declareVariables(o,a,c,d)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let value = ${o.getByOffset("global_idx")} + + ${a.getByOffset("global_idx % channels")} + ${c.getByOffset("global_idx")}; + ${d.setByOffset("global_idx","value")} + }`}},Xa=e=>{Ei(e.inputs),e.compute(Qa(e.inputs))}}),Ya,Xt,Pi,Za,el,Ci,tl,sl,$i,rl,nl,Si,il,ol,ki,al,on,Ii,Tn,ll,Ai,cl,dl,Fi,ul,pl,Di,hl,_l,Oi,ml,fl,Li,gl,wl,En,Ml,zi,Pn,yl,bl,vl,xl,Bi,Tl,Ri=_(()=>{It(),B(),Ht(),Nt(),Ya=(e,t,s,n,i,o,a)=>{let c=Math.ceil(t/4),d="";typeof i=="string"?d=`${i}(a)`:d=i("a");let u=Ue("inputData",s,[c],4),f=xt("outputData",n,[c],4),M=[{name:"vec_size",type:"u32"}];return a&&M.push(...a),` + ${e.registerUniforms(M).declareVariables(u,f)} + + ${o??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${u.getByOffset("global_idx")}; + ${f.setByOffset("global_idx",d)} + }`},Xt=(e,t,s,n,i,o=e.dataType,a,c)=>{let d=[{type:12,data:Math.ceil(Le.size(e.dims)/4)}];return a&&d.push(...a),{name:t,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:u=>Ya(u,Le.size(e.dims),e.dataType,o,s,n,c),getRunData:u=>({outputs:[{dims:e.dims,dataType:o}],dispatchGroup:{x:Math.ceil(Le.size(u[0].dims)/64/4)},programUniforms:d})}},Pi=e=>{e.compute(Xt(e.inputs[0],"Abs","abs"))},Za=e=>{e.compute(Xt(e.inputs[0],"Acos","acos"))},el=e=>{e.compute(Xt(e.inputs[0],"Acosh","acosh"))},Ci=e=>{e.compute(Xt(e.inputs[0],"Asin","asin"))},tl=e=>{e.compute(Xt(e.inputs[0],"Asinh","asinh"))},sl=e=>{e.compute(Xt(e.inputs[0],"Atan","atan"))},$i=e=>{e.compute(Xt(e.inputs[0],"Atanh","atanh"))},rl=e=>Lt(e),nl=(e,t)=>{let s;switch(t.to){case 10:s="vec4";break;case 1:s="vec4";break;case 12:s="vec4";break;case 6:s="vec4";break;case 9:s="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(Xt(e.inputs[0],"Cast",s,void 0,t.cacheKey,t.to))},Si=e=>{let t,s,n=e.length>=2&&e[1].data!==0,i=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=n?e[1].getFloat32Array()[0]:-34028234663852886e22,s=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=n?e[1].getUint16Array()[0]:64511,s=i?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Lt({min:t,max:s})},il=(e,t)=>{let s=t||Si(e.inputs),n=$s(e.inputs[0].dataType);e.compute(Xt(e.inputs[0],"Clip",i=>`clamp(${i}, vec4<${n}>(uniforms.min), vec4<${n}>(uniforms.max))`,void 0,s.cacheKey,void 0,[{type:e.inputs[0].dataType,data:s.min},{type:e.inputs[0].dataType,data:s.max}],[{name:"min",type:n},{name:"max",type:n}]),{inputs:[0]})},ol=e=>{e.compute(Xt(e.inputs[0],"Ceil","ceil"))},ki=e=>{e.compute(Xt(e.inputs[0],"Cos","cos"))},al=e=>{e.compute(Xt(e.inputs[0],"Cosh","cosh"))},on=e=>Lt(e),Ii=(e,t)=>{let s=$s(e.inputs[0].dataType);e.compute(Xt(e.inputs[0],"Elu",n=>`elu_vf32(${n})`,` + const elu_alpha_ = ${s}(${t.alpha}); + + fn elu_f32(a: ${s}) -> ${s} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${s}>) -> vec4<${s}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,t.cacheKey))},Tn=(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)); +}`,ll=e=>{let t=$s(e.inputs[0].dataType);e.compute(Xt(e.inputs[0],"Erf",s=>`erf_vf32(${s})`,Tn(t)))},Ai=e=>{e.compute(Xt(e.inputs[0],"Exp","exp"))},cl=e=>{e.compute(Xt(e.inputs[0],"Floor","floor"))},dl=e=>{let t=$s(e.inputs[0].dataType);e.compute(Xt(e.inputs[0],"Gelu",s=>`0.5 * ${s} * (1.0 + erf_vf32(${s} * 0.7071067811865475))`,Tn(t)))},Fi=(e,t)=>{let s=$s(e.inputs[0].dataType);e.compute(Xt(e.inputs[0],"LeakyRelu",n=>`select(leaky_relu_alpha_ * ${n}, ${n}, ${n} >= vec4<${s}>(0.0))`,`const leaky_relu_alpha_ = ${s}(${t.alpha});`,t.cacheKey))},ul=e=>{e.compute(Xt(e.inputs[0],"Not",t=>`!${t}`))},pl=e=>{e.compute(Xt(e.inputs[0],"Neg",t=>`-${t}`))},Di=e=>{e.compute(Xt(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},hl=e=>{let t=$s(e.inputs[0].dataType);e.compute(Xt(e.inputs[0],"Relu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > vec4<${t}>(0.0))`))},_l=e=>{e.compute(Xt(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},Oi=e=>Lt(e),ml=(e,t)=>{let s=$s(e.inputs[0].dataType);e.compute(Xt(e.inputs[0],"HardSigmoid",n=>`max(vec4<${s}>(0.0), min(vec4<${s}>(1.0), ${t.alpha} * ${n} + vec4<${s}>(${t.beta})))`,void 0,t.cacheKey))},fl=e=>{e.compute(Xt(e.inputs[0],"Sin","sin"))},Li=e=>{e.compute(Xt(e.inputs[0],"Sinh","sinh"))},gl=e=>{e.compute(Xt(e.inputs[0],"Sqrt","sqrt"))},wl=e=>{e.compute(Xt(e.inputs[0],"Tan","tan"))},En=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,Ml=e=>{e.compute(Xt(e.inputs[0],"Tanh",En))},zi=(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 ${En("v")}; +} +`,Pn=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,yl=e=>{let t=$s(e.inputs[0].dataType);e.compute(Xt(e.inputs[0],"FastGelu",Pn,zi(t),void 0,e.inputs[0].dataType))},bl=(e,t)=>{let s=$s(e.inputs[0].dataType);return e.compute(Xt(e.inputs[0],"ThresholdedRelu",n=>`select(vec4<${s}>(0.0), ${n}, ${n} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${s}>(${t.alpha});`,t.cacheKey)),0},vl=e=>{e.compute(Xt(e.inputs[0],"Log","log"))},xl=(e,t)=>` +const alpha = vec4<${e}>(${t}); +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; +} +`,Bi=e=>`quick_gelu_impl(${e})`,Tl=(e,t)=>{let s=$s(e.inputs[0].dataType);e.compute(Xt(e.inputs[0],"QuickGelu",Bi,xl(s,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),ji,El,Pl,Cl=_(()=>{B(),Nt(),Ri(),ji=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")},El=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let s=Ue("input",e[0].dataType,e[0].dims,4),n=Ue("bias",e[0].dataType,[e[0].dims[2]],4),i=xt("output",e[0].dataType,t,4),o=Le.size(t)/4,a=cs(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)}}),getShaderSource:c=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${c.declareVariables(s,n,i)} + + ${Tn(a)} + + ${c.mainStart()} + ${c.guardAgainstOutOfBoundsWorkgroupSizes(o)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${i.setByOffset("global_idx","valueLeft * geluRight")} + }`}},Pl=e=>{ji(e.inputs),e.compute(El(e.inputs))}}),$l,Sl,Xs,kl,Il,Ni,Al,Fl,Vi,Dl,Ol,Ui,Ll,Ou=_(()=>{It(),B(),Nt(),$l=(e,t,s,n,i,o,a,c,d,u,f,M)=>{let v,k;typeof c=="string"?v=k=(V,se)=>`${c}((${V}),(${se}))`:typeof c=="function"?v=k=c:(v=c.scalar,k=c.vector);let A=xt("outputData",f,n.length,4),R=Ue("aData",d,t.length,4),ee=Ue("bData",u,s.length,4),W;if(i)if(o){let V=Le.size(t)===1,se=Le.size(s)===1,oe=t.length>0&&t[t.length-1]%4===0,Me=s.length>0&&s[s.length-1]%4===0;V||se?W=A.setByOffset("global_idx",k(V?`${R.type.value}(${R.getByOffset("0")}.x)`:R.getByOffset("global_idx"),se?`${ee.type.value}(${ee.getByOffset("0")}.x)`:ee.getByOffset("global_idx"))):W=` + let outputIndices = ${A.offsetToIndices("global_idx * 4u")}; + let offsetA = ${R.broadcastedIndicesToOffset("outputIndices",A)}; + let offsetB = ${ee.broadcastedIndicesToOffset("outputIndices",A)}; + ${A.setByOffset("global_idx",k(a||oe?R.getByOffset("offsetA / 4u"):`${R.type.value}(${R.getByOffset("offsetA / 4u")}[offsetA % 4u])`,a||Me?ee.getByOffset("offsetB / 4u"):`${ee.type.value}(${ee.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else W=A.setByOffset("global_idx",k(R.getByOffset("global_idx"),ee.getByOffset("global_idx")));else{if(!o)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let V=(se,oe,Me="")=>{let Ie=`aData[indexA${oe}][componentA${oe}]`,Ce=`bData[indexB${oe}][componentB${oe}]`;return` + let outputIndices${oe} = ${A.offsetToIndices(`global_idx * 4u + ${oe}u`)}; + let offsetA${oe} = ${R.broadcastedIndicesToOffset(`outputIndices${oe}`,A)}; + let offsetB${oe} = ${ee.broadcastedIndicesToOffset(`outputIndices${oe}`,A)}; + let indexA${oe} = offsetA${oe} / 4u; + let indexB${oe} = offsetB${oe} / 4u; + let componentA${oe} = offsetA${oe} % 4u; + let componentB${oe} = offsetB${oe} % 4u; + ${se}[${oe}] = ${Me}(${v(Ie,Ce)}); + `};f===9?W=` + var data = vec4(0); + ${V("data",0,"u32")} + ${V("data",1,"u32")} + ${V("data",2,"u32")} + ${V("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:W=` + ${V("outputData[global_idx]",0)} + ${V("outputData[global_idx]",1)} + ${V("outputData[global_idx]",2)} + ${V("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(R,ee,A)} + + ${M??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${W} + }`},Sl=(e,t,s,n,i,o,a=s.dataType)=>{let c=s.dims.map(R=>Number(R)??1),d=n.dims.map(R=>Number(R)??1),u=!Le.areEqual(c,d),f=c,M=Le.size(c),v=!1,k=!1,A=[u];if(u){let R=Ws.calcShape(c,d,!1);if(!R)throw new Error("Can't perform binary op on the given tensors");f=R.slice(),M=Le.size(f);let ee=Le.size(c)===1,W=Le.size(d)===1,V=c.length>0&&c[c.length-1]%4===0,se=d.length>0&&d[d.length-1]%4===0;A.push(ee),A.push(W),A.push(V),A.push(se);let oe=1;for(let Me=1;MeR.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:R=>$l(R,c,d,f,v,u,k,i,s.dataType,n.dataType,a,o),getRunData:()=>({outputs:[{dims:f,dataType:a}],dispatchGroup:{x:Math.ceil(M/64/4)},programUniforms:[{type:12,data:Math.ceil(Le.size(f)/4)},...Ct(c,d,f)]})}},Xs=(e,t,s,n,i,o)=>{e.compute(Sl(t,i??"",e.inputs[0],e.inputs[1],s,n,o))},kl=e=>{Xs(e,"Add",(t,s)=>`${t}+${s}`)},Il=e=>{Xs(e,"Div",(t,s)=>`${t}/${s}`)},Ni=e=>{Xs(e,"Equal",{scalar:(t,s)=>`u32(${t}==${s})`,vector:(t,s)=>`vec4(${t}==${s})`},void 0,void 0,9)},Al=e=>{Xs(e,"Mul",(t,s)=>`${t}*${s}`)},Fl=e=>{let t=Ue("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Xs(e,"Pow",{scalar:(s,n)=>`pow_custom(${s},${n})`,vector:(s,n)=>`pow_vector_custom(${s},${n})`},` + fn pow_custom(a : ${t}, b : ${t}) -> ${t} { + if (b == ${t}(0.0)) { + return ${t}(1.0); + } else if (a < ${t}(0.0) && f32(b) != floor(f32(b))) { + return ${t}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${t}(1.0), round(f32(abs(b) % ${t}(2.0))) != 1.0) * ${t}(${t==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${t}>, b : vec4<${t}>) -> vec4<${t}> { + // TODO: implement vectorized pow + return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},Vi=e=>{Xs(e,"Sub",(t,s)=>`${t}-${s}`)},Dl=e=>{Xs(e,"Greater",{scalar:(t,s)=>`u32(${t}>${s})`,vector:(t,s)=>`vec4(${t}>${s})`},void 0,void 0,9)},Ol=e=>{Xs(e,"Less",{scalar:(t,s)=>`u32(${t}<${s})`,vector:(t,s)=>`vec4(${t}<${s})`},void 0,void 0,9)},Ui=e=>{Xs(e,"GreaterOrEqual",{scalar:(t,s)=>`u32(${t}>=${s})`,vector:(t,s)=>`vec4(${t}>=${s})`},void 0,void 0,9)},Ll=e=>{Xs(e,"LessOrEqual",{scalar:(t,s)=>`u32(${t}<=${s})`,vector:(t,s)=>`vec4(${t}<=${s})`},void 0,void 0,9)}}),zl,Bl,Wi,Rl,jl,Nl,Lu=_(()=>{It(),B(),Ht(),Nt(),zl=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let s=0,n=e[s],i=n.dataType,o=n.dims.length;e.forEach((a,c)=>{if(c!==s){if(a.dataType!==i)throw new Error("input tensors should be one type");if(a.dims.length!==o)throw new Error("input tensors should have the same shape");a.dims.forEach((d,u)=>{if(u!==t&&d!==n.dims[u])throw new Error("non concat dimensions must match")})}})},Bl=(e,t)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${t}); + for (var i: u32 = 0u; i < ${e}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${e}u; + }`,Wi=(e,t)=>{let s=e.length,n=[];for(let i=0;i{let i=Le.size(s),o=new Array(e.length),a=new Array(e.length),c=0,d=[],u=[],f=[{type:12,data:i}];for(let R=0;R`uniforms.sizeInConcatAxis${R}`).join(","),A=R=>` + + ${(()=>{R.registerUniform("outputSize","u32");for(let ee=0;ee(${k}); + ${v} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${Wi(a,M)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:s,dataType:n}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:f}),getShaderSource:A}},jl=(e,t)=>{let s=e.inputs,n=s[0].dims,i=Le.normalizeAxis(t.axis,n.length);zl(s,i);let o=n.slice();o[i]=s.reduce((c,d)=>c+(d.dims.length>i?d.dims[i]:0),0);let a=s.filter(c=>Le.size(c.dims)>0);e.compute(Rl(a,i,o,s[0].dataType),{inputs:a})},Nl=e=>Lt({axis:e.axis})}),vr,Br,Rr,Gi,jr=_(()=>{It(),B(),vr=(e,t,s="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${s}(uniforms.clip_min)), ${t}(${s}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${s}(uniforms.alpha) * value + ${s}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${s}(uniforms.alpha) * value, value, value >= ${t}(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}`)}},Br=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},Rr=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},Gi=e=>{let t=(e==null?void 0:e.activation)||"";if(t==="HardSigmoid"){let[s,n]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:t,alpha:s,beta:n}}else if(t==="Clip"){let[s,n]=(e==null?void 0:e.activation_params)||[xe,P];return{activation:t,clipMax:n,clipMin:s}}else if(t==="LeakyRelu"){let[s]=(e==null?void 0:e.activation_params)||[.01];return{activation:t,alpha:s}}return{activation:t}}}),ws,Vl,Ki=_(()=>{ws=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Vl=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),Ul,zu=_(()=>{Ul=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)); +} +`}),Xr,Hi,qi=_(()=>{It(),B(),Nt(),jr(),Xr=(e,t,s,n,i)=>{let o=n-s;return` + ${Array.from({length:s}).map((a,c)=>` + if (${Et(t.shape,c,t.rank)} != 1) { + ${t.indicesSet(e,c,Et(i,c+o,n))} + } else { + ${t.indicesSet(e,c,0)} + }`).join("")} +`},Hi=(e,t,s,n,i=!1,o)=>{let a=e[0].dims,c=e[1].dims,d=a[a.length-2],u=c[c.length-1],f=a[a.length-1],M=as(u),v=as(f),k=as(d),A=Le.size(s)/M/k,R=e.length>2,ee=n?n.slice(0,-2):s.slice(0,-2),W=[Le.size(ee),d,u],V=[{type:12,data:A},{type:12,data:d},{type:12,data:u},{type:12,data:f}];Br(t,V),V.push(...Ct(ee,a,c)),R&&V.push(...Ct(e[2].dims)),V.push(...Ct(W));let se=oe=>{let Me=Lr("batch_dims",e[0].dataType,ee.length),Ie=Ue("a",e[0].dataType,a.length,v),Ce=Ue("b",e[1].dataType,c.length,M),Be=xt("output",e[0].dataType,W.length,M),Ge=cs(Be.type.tensor),rt=vr(t,Be.type.value,Ge),St=[Ie,Ce],Tt="";if(R){let zt=i?M:1;St.push(Ue("bias",e[2].dataType,e[2].dims.length,zt)),Tt=`${i?`value += bias[col / ${zt}];`:`value += ${Be.type.value}(bias[row + i]);`}`}let ot=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Rr(t,ot);let Dt=()=>{let zt=`var a_data: ${Ie.type.value};`;for(let Pt=0;Pt; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${v}) { + ${Dt()} + } + for (var i = 0u; i < ${k}u; i++) { + var value = values[i]; + ${Tt} + ${rt} + let cur_indices = ${Be.type.indices}(batch, row + i, col); + let offset = ${Be.indicesToOffset("cur_indices")}; + ${Be.setByOffset(`offset / ${M}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${M};${v};${k};${i}`,inputDependencies:R?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:o?o(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(A/64)},programUniforms:V}),getShaderSource:se}}}),Qi,Wl,Xi,Cn,Gl,Ji,Yi,$n,Zi=_(()=>{It(),B(),Nt(),jr(),qi(),Ki(),Qi=(e,t)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${t?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${t?", batchIndices":""}); + `,Wl=(e,t)=>e?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${t===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]; + ${t===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]; + ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,Xi=(e,t,s="f32",n,i=!1,o=32,a=!1,c=32)=>{let d=t[1]*e[1],u=t[0]*e[0],f=i?d:o,M=i?o:d,v=f/t[0],k=o/t[1];if(!((i&&v===4&&e[1]===4||!i&&(v===3||v===4))&&f%t[0]===0&&o%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${v} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${v} must be 3 or 4. + tileAWidth ${f} must be divisible by workgroupSize[0]${t[0]}. tileInner ${o} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${f/v}>, ${M}>; +var mm_Bsub: array, ${u/e[0]}>, ${o}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${v}; +const tileInner = ${o}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${a?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${d}; + + let num_tiles = ${a?`${Math.ceil(c/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${a?`i32(globalId.z) * ${c}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${k}; + 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; + ${Qi(i,n)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${k}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${n?", 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]; + ${v===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${Wl(i,v)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},Cn=(e,t)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${t?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${t?", batchIndices":""}); + `,Gl=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Ji=(e,t,s="f32",n,i=!1,o=32,a=!1,c=32,d=!1)=>{let u=e[1]*t[1],f=e[0]*t[0],M=i?u:o,v=i?o:u;if(!(v%t[1]===0&&M%t[0]===0&&o%t[1]===0))throw new Error(`tileAHight ${v} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${M} must be divisible by workgroupSize[0]${t[0]}, tileInner ${o} must be divisible by workgroupSize[1]${t[1]}`);let k=v/t[1],A=M/t[0],R=o/t[1],ee=d?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${u}; + let globalColStart = i32(workgroupId.x) * ${f}; + + // 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 < ${v}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${M}; inputCol = inputCol + ${t[0]}) { + ${Cn(i,n)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${o}; inputRow = inputRow + ${t[1]}) { + for (var inputCol = localCol; inputCol < ${f}; inputCol = inputCol + ${t[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${s}, 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 * ${t[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${t[1]}];`:`mm_Asub[localRow + innerRow * ${t[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 * ${t[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${t[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) * ${k}; +let tileColA = i32(localId.x) * ${A}; +let tileRowB = i32(localId.y) * ${R}; +// 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 < ${k}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${A}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${Cn(i,n)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${R}; 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${n?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${s}, 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) { + ${Gl(i)} + 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, ${v}>; + var mm_Bsub : array, ${o}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${o}; + +@compute @workgroup_size(${t[0]}, ${t[1]}, ${t[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${a?"0":"i32(globalId.z)"}; + ${n?`let batchIndices = ${n.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${a?`${Math.ceil(c/o)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${a?`i32(globalId.z) * ${c}`:"0"}; + + var acc : array, rowPerThread>; + ${ee} + } +`},Yi=(e,t,s,n,i=!1)=>{let[o,a,c,d]=n,u=cs(n[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${o.type.indices}) -> ${ws(e,u)} { + var value = ${ws(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${a.type.indices}; + ${Xr("aIndices",a,a.rank-2,o.rank,"batchIndices")} + ${a.indicesSet("aIndices",a.rank-2,"u32(row)")} + ${a.indicesSet("aIndices",a.rank-1,"u32(colIn)")} + value = ${a.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${o.type.indices}) -> ${ws(e,u)} { + var value = ${ws(e,u)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${c.type.indices}; + ${Xr("bIndices",c,c.rank-2,o.rank,"batchIndices")} + ${c.indicesSet("bIndices",c.rank-2,"u32(row)")} + ${c.indicesSet("bIndices",c.rank-1,"u32(colIn)")} + value = ${c.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${ws(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); + ${t?`value = value + ${i?"bias[colIn]":`${ws(e,u)}(bias[row])`};`:""} + ${s} + ${d.setByIndices("vec3(coords)","value")} + } + } + `},$n=(e,t,s,n,i=!1,o)=>{let a=e[0].dims,c=e[1].dims,d=a.slice(0,-2),u=c.slice(0,-2),f=n?n.slice(0,-2):s.slice(0,-2),M=Le.size(f),v=a[a.length-2],k=a[a.length-1],A=c[c.length-1],R=k%4===0&&A%4===0,ee=v<=8?[4,1,1]:[4,4,1],W=[8,8,1],V=[Math.ceil(A/W[0]/ee[0]),Math.ceil(v/W[1]/ee[1]),Math.ceil(M/W[2]/ee[2])],se=R?4:1,oe=[...d,v,k/se],Me=oe.length,Ie=[...u,k,A/se],Ce=Ie.length,Be=[M,v,A/se],Ge=[{type:6,data:v},{type:6,data:A},{type:6,data:k}];Br(t,Ge),Ge.push(...Ct(f,oe,Ie));let rt=["rank","rank"],St=e.length>2;St&&(Ge.push(...Ct(e[2].dims)),rt.push("rank")),Ge.push(...Ct(Be));let Tt=ot=>{let Dt=f.length,zt=Lr("batchDims",e[0].dataType,Dt,1),Pt=cs(e[0].dataType),at=Ue("a",e[0].dataType,Me,se),Zt=Ue("b",e[1].dataType,Ce,se),Rt=xt("result",e[0].dataType,Be.length,se),Gt=[at,Zt];if(St){let Ds=i?se:1;Gt.push(Ue("bias",e[2].dataType,e[2].dims.length,Ds))}let Je=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Rr(t,Je);let it=cs(Rt.type.tensor),Ft=vr(t,Rt.type.value,it),qt=Yi(se,St,Ft,[zt,at,Zt,Rt],i);return` + ${ot.registerUniforms(Je).registerInternalVariables(zt).declareVariables(...Gt,Rt)} + ${qt} + ${R?Xi(ee,W,Pt,zt):Ji(ee,W,Pt,zt)} + `};return{name:"MatMul",shaderCache:{hint:`${ee};${t.activation};${R};${i}`,inputDependencies:rt},getRunData:()=>({outputs:[{dims:o?o(s):s,dataType:e[0].dataType}],dispatchGroup:{x:V[0],y:V[1],z:V[2]},programUniforms:Ge}),getShaderSource:Tt}}}),eo,Kl,Bu=_(()=>{It(),ks(),Nt(),jr(),Ki(),zu(),Zi(),eo=(e,t,s,n,i=!1,o,a=4,c=4,d=4,u="f32")=>{let f=Ge=>{switch(Ge){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 ${Ge} is not supported.`)}},M=Ge=>{switch(Ge){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 ${Ge} is not supported.`)}},v=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,k=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,A=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",R=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",ee=e?"row":"col",W=e?"col":"row",V=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${ee} / outWidth; + let outCol = ${ee} % 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 = ${ws(a,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 < ${A} && xCol >= 0 && xCol < ${R}) { + ${v} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${f(a)} + } + return resData;`,se=e?t&&n?` + let col = colIn * ${a}; + ${V}`:` + let col = colIn * ${a}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${V} + } + return ${ws(a,u)}(0.0);`:n&&s?` + let col = colIn * ${a}; + ${V}`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${V} + } + return ${ws(a,u)}(0.0);`,oe=e?n&&s?M(c):` + let col = colIn * ${c}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${M(c)} + } + return ${ws(c,u)}(0.0);`:` + let col = colIn * ${c}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${M(c)} + } + return ${ws(c,u)}(0.0);`,Me=ws(d,u),Ie=ws(e?a:c,u),Ce=ws(e?c:a,u),Be=vr(o,Me,u);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${Ie} { + ${e?se:oe} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${Ce} { + ${e?oe:se} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${Me}) { + let col = colIn * ${d}; + 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])"}; + ${k} + ${Vl(i)} + ${Be} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},Kl=(e,t,s,n,i,o,a,c,d)=>{let u=t.format==="NHWC",f=u?e[0].dims[3]:e[0].dims[1],M=s[0],v=u?s[2]:s[3],k=u?s[1]:s[2],A=u?s[3]:s[1],R=u&&(f%4===0||f%3===0)&&A%4===0,ee=u?A:v*k,W=u?v*k:A,V=[8,8,1],se=n<=8?[4,1,1]:[4,4,1],oe=[Math.ceil(ee/V[0]/se[0]),Math.ceil(W/V[1]/se[1]),Math.ceil(M/V[2]/se[2])];Ut("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${oe}`);let Me=R?u&&f%4!==0?3:4:1,Ie=V[1]*se[1],Ce=V[0]*se[0],Be=Math.max(V[0]*Me,V[1]),Ge=n%Ie===0,rt=i%Ce===0,St=o%Be===0,Tt=R?[Me,4,4]:[1,1,1],ot=[{type:6,data:n},{type:6,data:i},{type:6,data:o},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];Br(t,ot),ot.push(...Ct(e[0].dims,e[1].dims));let Dt=["rank","rank"];a&&(ot.push(...Ct(e[2].dims)),Dt.push("rank")),ot.push(...Ct(s));let zt=Pt=>{let at=[{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}];Rr(t,at);let Zt=R?4:1,Rt=cs(e[0].dataType),Gt=` + fn setOutputAtIndex(flatIndex : i32, value : ${R?`vec4<${Rt}>`:Rt}) { + result[flatIndex] = ${R?`vec4<${Rt}>`:Rt}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${R?`vec4<${Rt}>`:Rt}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${R?"/ 4":""}, value); + }`,Je=Ue("x",e[0].dataType,e[0].dims.length,Me===3?1:Me),it=Ue("w",e[1].dataType,e[1].dims.length,Zt),Ft=[Je,it],qt=xt("result",e[0].dataType,s.length,Zt);if(a){let Ds=Ue("bias",e[2].dataType,e[2].dims.length,Zt);Ft.push(Ds),Gt+=` + fn getBiasByOutputCoords(coords : vec4) -> ${R?`vec4<${Rt}>`:Rt} { + return bias[coords.${u?"w":"y"}${R?"/ 4":""}]; + }`}return` + ${Ul("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 }; + ${Pt.registerUniforms(at).declareVariables(...Ft,qt)} + ${Gt} + ${eo(u,Ge,rt,St,a,t,Tt[0],Tt[1],Tt[2],Rt)} + ${R?Xi(se,V,Rt,void 0,!u,Be):Ji(se,V,Rt,void 0,!u,Be,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${Me};${R};${Ge};${rt};${St};${Ie};${Ce};${Be}`,inputDependencies:Dt},getRunData:()=>({outputs:[{dims:d?d(s):s,dataType:e[0].dataType}],dispatchGroup:{x:oe[0],y:oe[1],z:oe[2]},programUniforms:ot}),getShaderSource:zt}}}),Sn,to,an,so,kn,Hl,ro,ql,Ru=_(()=>{It(),ks(),B(),Nt(),jr(),Ki(),Sn=e=>{let t=1;for(let s=0;stypeof e=="number"?[e,e,e]:e,an=(e,t)=>t<=1?e:e+(e-1)*(t-1),so=(e,t,s,n=1)=>{let i=an(t,n);return Math.floor((e[0]*(s-1)-s+i)/2)},kn=(e,t,s,n,i)=>{i==null&&(i=so(e,t[0],n[0]));let o=[0,0,0,s];for(let a=0;a<3;a++)e[a]+2*i>=t[a]&&(o[a]=Math.trunc((e[a]-t[a]+2*i)/n[a]+1));return o},Hl=(e,t,s,n,i,o,a,c,d,u)=>{let f,M,v,k;if(e==="VALID"&&(e=0),typeof e=="number"){f={top:e,bottom:e,left:e,right:e,front:e,back:e};let A=kn([t,s,n,1],[c,d,u],1,[i,o,a],e);M=A[0],v=A[1],k=A[2]}else if(Array.isArray(e)){if(!e.every((R,ee,W)=>R===W[0]))throw Error(`Unsupported padding parameter: ${e}`);f={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let A=kn([t,s,n,1],[c,d,u],1,[i,o,a],e[0]);M=A[0],v=A[1],k=A[2]}else if(e==="SAME_UPPER"){M=Math.ceil(t/i),v=Math.ceil(s/o),k=Math.ceil(n/a);let A=(M-1)*i+c-t,R=(v-1)*o+d-s,ee=(k-1)*a+u-n,W=Math.floor(A/2),V=A-W,se=Math.floor(R/2),oe=R-se,Me=Math.floor(ee/2),Ie=ee-Me;f={top:se,bottom:oe,left:Me,right:Ie,front:W,back:V}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:f,outDepth:M,outHeight:v,outWidth:k}},ro=(e,t,s,n,i,o=!1,a="channelsLast")=>{let c,d,u,f,M;if(a==="channelsLast")[c,d,u,f,M]=e;else if(a==="channelsFirst")[c,M,d,u,f]=e;else throw new Error(`Unknown dataFormat ${a}`);let[v,,k,A,R]=t,[ee,W,V]=to(s),[se,oe,Me]=to(n),Ie=an(k,se),Ce=an(A,oe),Be=an(R,Me),{padInfo:Ge,outDepth:rt,outHeight:St,outWidth:Tt}=Hl(i,d,u,f,ee,W,V,Ie,Ce,Be),ot=o?v*M:v,Dt=[0,0,0,0,0];return a==="channelsFirst"?Dt=[c,ot,rt,St,Tt]:a==="channelsLast"&&(Dt=[c,rt,St,Tt,ot]),{batchSize:c,dataFormat:a,inDepth:d,inHeight:u,inWidth:f,inChannels:M,outDepth:rt,outHeight:St,outWidth:Tt,outChannels:ot,padInfo:Ge,strideDepth:ee,strideHeight:W,strideWidth:V,filterDepth:k,filterHeight:A,filterWidth:R,effectiveFilterDepth:Ie,effectiveFilterHeight:Ce,effectiveFilterWidth:Be,dilationDepth:se,dilationHeight:oe,dilationWidth:Me,inShape:e,outShape:Dt,filterShape:t}},ql=(e,t,s,n,i,o)=>{let a=o==="channelsLast";a?e[0].dims[3]:e[0].dims[1];let c=[64,1,1],d={x:s.map((ee,W)=>W)},u=[Math.ceil(Sn(d.x.map(ee=>s[ee]))/c[0]),1,1];Ut("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${u}`);let f=1,M=Le.size(s),v=[{type:12,data:M},{type:12,data:n},{type:12,data:i},{type:12,data:t.strides},{type:12,data:t.dilations}];Br(t,v),v.push(...Ct(e[0].dims,e[1].dims));let k=["rank","rank"],A=e.length===3;A&&(v.push(...Ct(e[2].dims)),k.push("rank")),v.push(...Ct(s));let R=ee=>{let W=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:n.length},{name:"pads",type:"u32",length:i.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];Rr(t,W);let V=1,se=cs(e[0].dataType),oe=Ue("x",e[0].dataType,e[0].dims.length,f),Me=Ue("W",e[1].dataType,e[1].dims.length,V),Ie=[oe,Me],Ce=xt("result",e[0].dataType,s.length,V),Be="";if(A){let St=Ue("bias",e[2].dataType,e[2].dims.length,V);Ie.push(St),Be+=` + fn getBiasByOutputCoords(coords : array) -> ${se} { + return bias[${a?Et("coords",4,5):Et("coords",1,5)}]; + }`}let Ge=ws(f,se),rt=vr(t,Ge,se);return` + ${Be} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${oe.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${Me.getByIndices("aIndices")}; + } + ${ee.registerUniforms(W).declareVariables(...Ie,Ce)} + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${Ce.offsetToIndices("global_idx")}; + let batch = ${Et("coords",0,oe.rank)}; + let d2 = ${a?Et("coords",oe.rank-1,oe.rank):Et("coords",1,oe.rank)}; + let xFRCCorner = vec3(${a?Et("coords",1,oe.rank):Et("coords",2,oe.rank)}, + ${a?Et("coords",2,oe.rank):Et("coords",3,oe.rank)}, + ${a?Et("coords",3,oe.rank):Et("coords",4,oe.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${a?Et("uniforms.x_shape",1,oe.rank):Et("uniforms.x_shape",2,oe.rank)}; + let xShapeZ = ${a?Et("uniforms.x_shape",2,oe.rank):Et("uniforms.x_shape",3,oe.rank)}; + let xShapeW = ${a?Et("uniforms.x_shape",3,oe.rank):Et("uniforms.x_shape",4,oe.rank)}; + let xShapeU = ${a?Et("uniforms.x_shape",4,oe.rank):Et("uniforms.x_shape",1,oe.rank)}; + let inputDepthNearestVec4 = (xShapeU / 4) * 4; + let inputDepthVec4Remainder = xShapeU % 4; + + var value = 0.0; + for (var wF = 0u; wF < uniforms.filter_dims[0]; wF++) { + let xF = xFCorner + wF * uniforms.dilations[0]; + if (xF < 0 || xF >= xShapeY) { + continue; + } + + for (var wR = 0u; wR < uniforms.filter_dims[1]; wR++) { + let xR = xRCorner + wR * uniforms.dilations[1]; + if (xR < 0 || xR >= xShapeZ) { + continue; + } + + for (var wC = 0u; wC < uniforms.filter_dims[2]; wC++) { + let xC = xCCorner + wC * uniforms.dilations[2]; + if (xC < 0 || xC >= xShapeW) { + continue; + } + + for (var d1 = 0u; d1 < inputDepthNearestVec4; d1 += 4) { + ${a?`let xValues = vec4( + getX(batch, xF, xR, xC, d1), + getX(batch, xF, xR, xC, d1 + 1), + getX(batch, xF, xR, xC, d1 + 2), + getX(batch, xF, xR, xC, d1 + 3)); + `:`let xValues = vec4( + getX(batch, d1, xF, xR, xC), + getX(batch, d1 + 1, xF, xR, xC), + getX(batch, d1 + 2, xF, xR, xC), + getX(batch, d1 + 3, xF, xR, xC)); + `} + let wValues = vec4( + getW(d2, d1, wF, wR, wC), + getW(d2, d1 + 1, wF, wR, wC), + getW(d2, d1 + 2, wF, wR, wC), + getW(d2, d1 + 3, wF, wR, wC)); + value += dot(xValues, wValues); + } + if (inputDepthVec4Remainder == 1) { + ${a?`value += getX(batch, xF, xR, xC, inputDepthNearestVec4) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`:`value += getX(batch, inputDepthNearestVec4, xF, xR, xC) + * getW(d2, inputDepthNearestVec4, wF, wR, wC);`} + } else if (inputDepthVec4Remainder == 2) { + ${a?`let xValues = vec2( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1)); + `:`let xValues = vec2( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC)); + `} + let wValues = vec2( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC)); + value += dot(xValues, wValues); + } else if (inputDepthVec4Remainder == 3) { + ${a?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${A?"value = value + getBiasByOutputCoords(coords)":""}; + ${rt} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${a};${f};${A}`,inputDependencies:k},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:u[0],y:u[1],z:u[2]},programUniforms:v}),getShaderSource:R}}}),ln,no,ju=_(()=>{It(),B(),Nt(),jr(),ln=(e,t,s,n)=>{let i=e.length>2,o=i?"value += b[output_channel];":"",a=e[0].dims,c=e[1].dims,d=t.format==="NHWC",u=d?s[3]:s[1],f=u/t.group,M=d&&f>=4?as(u):1,v=Le.size(s)/M,k=[{type:12,data:v},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:f}];Br(t,k),k.push(...Ct(a,[c[0],c[1],c[2],c[3]/M]));let A=i?["rank","rank","rank"]:["rank","rank"];k.push(...Ct([s[0],s[1],s[2],s[3]/M]));let R=ee=>{let W=xt("output",e[0].dataType,s.length,M),V=cs(W.type.tensor),se=vr(t,W.type.value,V),oe=Ue("x",e[0].dataType,a.length),Me=Ue("w",e[1].dataType,c.length,M),Ie=[oe,Me];i&&Ie.push(Ue("b",e[2].dataType,e[2].dims,M));let Ce=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];Rr(t,Ce);let Be=d?` + 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 = ${oe.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${Me.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 = ${oe.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${Me.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${ee.registerUniforms(Ce).declareVariables(...Ie,W)} + + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${W.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${d?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${d?1:2}], outputIndices[${d?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${M} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${d?2:1}]; + + var value: ${W.type.value} = ${W.type.value}(0); + ${Be} + ${o} + ${se} + ${W.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${M}`,inputDependencies:A},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:k}),getShaderSource:R}},no=(e,t,s,n)=>{let i=e.length>2,o=as(s[3]),a=as(s[2]),c=Le.size(s)/o/a,d=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/o],u=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/o],f=[s[0],s[1],s[2],s[3]/o],M=[{type:12,data:c},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];Br(t,M),M.push(...Ct(d,u,f));let v=(a-1)*t.strides[1]+u[1],k=A=>{let R=xt("output",e[0].dataType,f.length,o),ee=cs(R.type.tensor),W=vr(t,R.type.value,ee),V=Ue("x",e[0].dataType,d.length,o),se=Ue("w",e[1].dataType,u.length,o),oe=[V,se];i&&oe.push(Ue("b",e[2].dataType,e[2].dims,o));let Me=i?"value += b[output_channel];":"",Ie=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Rr(t,Ie),` + ${A.registerUniforms(Ie).declareVariables(...oe,R)} + ${A.mainStart()} + ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${a}u; + let col = (index1 % width1) * ${a}u; + index1 = index1 / width1; + let row = index1 % uniforms.output_shape[1]; + let batch = index1 / uniforms.output_shape[1]; + + let x_corner = vec2(i32(row), i32(col)) * uniforms.strides - uniforms.pads; + + var x_vals: array<${V.type.value}, ${v}>; + var values: array<${R.type.value}, ${a}>; + let input_channel = output_channel; + // Use constant instead of uniform can give better performance for w's height/width. + for (var w_height: u32 = 0u; w_height < ${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 < ${v}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${V.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${V.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${u[1]}; w_width++) { + let w_val = ${se.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${a}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${a}u; i++) { + var value = values[i]; + ${Me} + ${W} + ${R.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${o};${a};${v};${u[0]};${u[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(s):s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:M}),getShaderSource:k}}}),Ql,In,io,An,oo,ao,lo,Xl,co,Jl=_(()=>{B(),Bu(),Ru(),Zi(),ju(),jr(),qi(),_r(),Ql=(e,t,s,n,i,o)=>{let a=e[0],c=e.slice(o?1:2,o?3:4),d=c.length,u=t[0],f=t.slice(2).map((v,k)=>v+(v-1)*(s[k]-1)),M=c.map((v,k)=>v+n[k]+n[k+d]).map((v,k)=>Math.floor((v-f[k]+i[k])/i[k]));return M.splice(0,0,a),M.splice(o?3:1,0,u),M},In=[2,3,1,0],io=(e,t)=>{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 s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[1]*t.group;if(s!==n)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 i=e[0].dims.length-2;if(t.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(t.strides.length!==i)throw new Error(`strides should be ${i}D`);if(t.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},An=(e,t)=>{let s=e.kernelShape.slice();s.length{let t=Gi(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,o=e.group,a=e.kernel_shape,c=e.pads,d=e.strides,u=e.w_is_const();return{autoPad:n,format:s,dilations:i,group:o,kernelShape:a,pads:c,strides:d,wIsConst:u,...t,cacheKey:`${e.format};${t.activation};`}},ao=(e,t,s,n)=>{let i=s.format==="NHWC",o=Ql(t[0].dims,t[1].dims,s.dilations,s.pads,s.strides,i);if(s.group!==1){let Ie=[t[0]];if(i){let Ce=e.kernelCustomData.wT??e.compute(Ks(t[1],In),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=Ce),Ie.push(Ce)}else Ie.push(t[1]);t.length===3&&Ie.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&i&&t[1].dims[0]===s.group&&t[1].dims[1]===1&&s.dilations[0]===1&&s.dilations[1]===1?e.compute(no(Ie,s,o,n),{inputs:Ie}):e.compute(ln(Ie,s,o,n),{inputs:Ie});return}let a=t.length===3,c=t[0].dims[i?1:2],d=t[0].dims[i?2:3],u=t[0].dims[i?3:1],f=t[1].dims[2],M=t[1].dims[3],v=o[i?1:2],k=o[i?2:3],A=o[i?3:1],R=i&&f===c&&M===d&&s.pads[0]===0&&s.pads[1]===0;if(R||f===1&&M===1&&s.dilations[0]===1&&s.dilations[1]===1&&s.strides[0]===1&&s.strides[1]===1&&s.pads[0]===0&&s.pads[1]===0){let Ie=o[0],Ce,Be,Ge,rt=[];if(i){let ot=e.kernelCustomData.wT??e.compute(Ks(t[1],In),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];if(s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=ot),R){let Dt=c*d*u;Ce=t[0].reshape([1,Ie,Dt]),Be=ot.reshape([1,Dt,A]),Ge=[1,Ie,A]}else Ce=t[0].reshape([Ie,c*d,u]),Be=ot.reshape([1,u,A]),Ge=[Ie,v*k,A];rt.push(Ce),rt.push(Be)}else Ce=t[0].reshape([Ie,u,c*d]),Be=t[1].reshape([1,A,u]),Ge=[Ie,A,v*k],rt.push(Be),rt.push(Ce);a&&rt.push(t[2]);let St=Ge[2],Tt=rt[0].dims[rt[0].dims.length-1];St<8&&Tt<8?e.compute(Hi(rt,s,o,Ge,i,n),{inputs:rt}):e.compute($n(rt,s,o,Ge,i,n),{inputs:rt});return}let ee=!0,W=e.kernelCustomData.wT??e.compute(Ks(t[1],In),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=W);let V=[t[0],W];a&&V.push(t[2]);let se=i?v*k:A,oe=i?A:v*k,Me=f*M*u;e.compute(Kl(V,s,o,se,oe,Me,a,ee,n),{inputs:V})},lo=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[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&&n.push(e.inputs[2]);let i=[0,t.pads[0],0,t.pads[1]],o=[1].concat(t.strides),a=[1].concat(t.dilations),c=[1].concat(t.kernelShape),d=An({...t,pads:i,strides:o,dilations:a,kernelShape:c},n);ao(e,n,d,u=>s?[u[0],u[2],u[3]]:[u[0],u[1],u[3]])},Xl=(e,t,s)=>{let n=s.format==="NHWC"?"channelsLast":"channelsFirst",i=An(s,t),o=s.autoPad==="NOTSET"?s.pads:s.autoPad,a=ro(t[0].dims,t[1].dims,s.strides,s.dilations,o,!1,n);e.compute(ql(t,i,a.outShape,[a.filterDepth,a.filterHeight,a.filterWidth],[a.padInfo.front,a.padInfo.top,a.padInfo.left],n))},co=(e,t)=>{if(io(e.inputs,t),e.inputs[0].dims.length===3)lo(e,t);else if(e.inputs[0].dims.length===5)Xl(e,e.inputs,t);else{let s=An(t,e.inputs);ao(e,e.inputs,s)}}}),Yl,Nu=_(()=>{It(),ks(),B(),Nt(),Yl=(e,t,s)=>{let n=e.length>2,i=t.outputShape,o=t.format==="NHWC",a=t.group,c=e[1].dims,d=c[2]/a,u=c[3],f=o?as(d):1,M=o&&u===1&&d>=4,v=M?Math.floor(d/4)*4:Math.floor(d/f)*f,k=d-v,A=o?as(u):1,R=o?u===1?f:A:1,ee=Le.size(i)/A,W=[Math.ceil(ee/64),1,1];Ut("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${W}`);let V=["rank","rank"],se=[t.strides[0],t.strides[1]],oe=[t.kernelShape[o?1:2],t.kernelShape[o?2:3]],Me=[t.dilations[0],t.dilations[1]],Ie=[oe[0]+(t.dilations[0]<=1?0:(t.kernelShape[o?1:2]-1)*(t.dilations[0]-1)),oe[1]+(t.dilations[1]<=1?0:(t.kernelShape[o?2:3]-1)*(t.dilations[1]-1))],Ce=[Ie[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),Ie[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],Be=[{type:12,data:ee},{type:12,data:se},{type:12,data:oe},{type:12,data:Me},{type:12,data:Ie},{type:6,data:Ce},{type:12,data:v},{type:12,data:d},{type:12,data:u},...Ct(e[0].dims,e[1].dims)];n&&(Be.push(...Ct(e[2].dims)),V.push("rank")),Be.push(...Ct(i));let Ge=rt=>{let St=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:se.length},{name:"filter_dims",type:"u32",length:oe.length},{name:"dilations",type:"u32",length:oe.length},{name:"effective_filter_dims",type:"u32",length:Ie.length},{name:"pads",type:"i32",length:Ce.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],Tt=cs(e[0].dataType),ot=o?1:2,Dt=o?2:3,zt=o?3:1,Pt=Ue("W",e[1].dataType,e[1].dims.length,R),at=Ue("Dy",e[0].dataType,e[0].dims.length,f),Zt=[at,Pt];n&&Zt.push(Ue("bias",e[2].dataType,[i[zt]].length,A));let Rt=xt("result",e[0].dataType,i.length,A),Gt=()=>{let Ft="";if(M)f===4?Ft+=` + let xValue = ${at.getByOffset("x_offset")}; + let wValue = ${Pt.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue); + x_offset += 1u; + w_offset += 1u;`:f===2?Ft+=` + dotProd = dotProd + dot(vec4<${Tt}>(${at.getByOffset("x_offset")}, ${at.getByOffset("x_offset + 1u")}), vec4<${Tt}>(${Pt.getByOffset("w_offset")}, ${Pt.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;`:f===1&&(Ft+=` + dotProd = dotProd + dot(vec4<${Tt}>(${at.getByOffset("x_offset")}, ${at.getByOffset("x_offset + 1u")}, ${at.getByOffset("x_offset + 2u")}, ${at.getByOffset("x_offset + 3u")}), vec4<${Tt}>(${Pt.getByOffset("w_offset")}, ${Pt.getByOffset("w_offset + 1u")}, ${Pt.getByOffset("w_offset + 2u")}, ${Pt.getByOffset("w_offset + 3u")})); + x_offset += 4u; + w_offset += 4u;`);else if(Ft+=` + let xValue = ${o?at.getByOffset(`${at.indicesToOffset(`${at.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${f}`):at.get("batch","inputChannel","idyR","idyC")}; + `,f===1)Ft+=` + let w_offset = ${Pt.indicesToOffset(`${Pt.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${Pt.getByOffset(`w_offset / ${R}`)}; + dotProd = dotProd + xValue * wValue;`;else for(let qt=0;qt{if(k===0)return"";if(!M)throw new Error(`packInputAs4 ${M} is not true.`);let Ft="";if(f===1){Ft+="dotProd = dotProd";for(let qt=0;qt(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 = ${Rt.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 = (${Tt}(dyRCorner) + ${Tt}(wR)) / ${Tt}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${Tt}(uniforms.Dy_shape[${ot}]) || 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 = (${Tt}(dyCCorner) + ${Tt}(wC)) / ${Tt}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${Tt}(uniforms.Dy_shape[${Dt}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + ${M?` + var x_offset = ${at.indicesToOffset(`${at.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${f}; + var w_offset = ${Pt.indicesToOffset(`${Pt.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${R}; + `:""} + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${M?4:f}) { + ${Gt()} + inputChannel = inputChannel + ${M?4:f}; + } + ${Je()} + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${n?` + bias[d1 / ${A}]`:""}; + ${Rt.setByOffset("global_idx","value")}; + `;return` + ${rt.registerUniforms(St).declareVariables(...Zt,Rt)} + ${rt.mainStart()} + ${rt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${it}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${f}${R}${A}${M}${k}`,inputDependencies:V},getRunData:()=>({dispatchGroup:{x:W[0],y:W[1],z:W[2]},outputs:[{dims:s?s(i):i,dataType:e[0].dataType}],programUniforms:Be}),getShaderSource:Ge}}}),Zl,uo,ec,po,ho,tc,_o,mo,sc,Vu=_(()=>{Nu(),jr(),_r(),Zl=(e,t,s,n,i,o)=>(e-1)*t+s+(n-1)*i+1-o,uo=(e,t,s,n,i)=>{let o=Math.floor(e/2);t==="SAME_UPPER"?(s[n]=o,s[i]=e-o):t==="SAME_LOWER"&&(s[n]=e-o,s[i]=o)},ec=(e,t,s,n,i,o,a,c,d,u)=>{let f=e.length-2,M=u.length===0;d.length{let s=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((M,v)=>M*v,1)===0){s.length=0;for(let M=2;MM+v,0)===0){let M=t[0].dims.length-2;d=new Array(M).fill(1)}let u=e.strides.slice();if(u.reduce((M,v)=>M+v,0)===0){let M=t[0].dims.length-2;u=new Array(M).fill(1)}ec(c,s,d,e.autoPad,e.group,i,u,n,a,o);let f=Object.assign({},e);return Object.assign(f,{kernelShape:s,pads:i,outputPadding:a,outputShape:o,dilations:d,strides:u}),f},ho=e=>{let t=Gi(e),s=e.format,n=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,o=e.group,a=e.kernelShape,c=e.pads,d=e.strides,u=e.wIsConst(),f=e.outputPadding,M=e.outputShape;return{autoPad:n,format:s,dilations:i,group:o,kernelShape:a,outputPadding:f,outputShape:M,pads:c,strides:d,wIsConst:u,...t,cacheKey:`${e.format};${t.activation};`}},tc=(e,t)=>{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 s=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],n=e[1].dims[0];if(s!==n)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let o=e[0].dims.length-2;if(t.dilations.reduce((a,c)=>a+c,0)>0&&t.dilations.length!==o)throw new Error(`dilations should be ${o}D`);if(t.strides.reduce((a,c)=>a+c,0)>0&&t.strides.length!==o)throw new Error(`strides should be ${o}D`);if(t.pads.reduce((a,c)=>a+c,0)>0&&t.pads.length!==o*2)throw new Error(`pads should be ${o*2}D`);if(t.outputPadding.length!==o&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${o}D`);if(t.kernelShape.reduce((a,c)=>a+c,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},_o=(e,t,s,n)=>{let i=e.kernelCustomData.wT??e.compute(Ks(t[1],[2,3,0,1]),{inputs:[1],outputs:[s.wIsConst?-2:-1]})[0];s.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i);let o=[t[0],i];t.length===3&&o.push(t[2]),e.compute(Yl(o,s,n),{inputs:o})},mo=(e,t)=>{let s=t.format==="NHWC",n=[e.inputs[0].reshape(s?[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&&n.push(e.inputs[2]);let i=t.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let o=t.dilations;(o.length===0||o[0]===0)&&(o=[1]);let a=t.strides;(a.length===0||a[0]===0)&&(a=[1]);let c=t.pads;c.length===0&&(c=[0,0]),c=[0,c[0],0,c[1]],a=[1].concat(a),o=[1].concat(o),i=[1].concat(i);let d=t.outputPadding;d=[0].concat(d);let u=po({...t,pads:c,strides:a,dilations:o,kernelShape:i,outputPadding:d},n);_o(e,n,u,f=>s?[f[0],f[2],f[3]]:[f[0],f[1],f[3]])},sc=(e,t)=>{if(tc(e.inputs,t),e.inputs[0].dims.length===3)mo(e,t);else{let s=po(t,e.inputs);_o(e,e.inputs,s)}}}),Fn,rc,nc,Uu=_(()=>{It(),B(),Ht(),Nt(),Fn=(e,t,s,n)=>{let i=Le.size(t),o=t.length,a=Ue("input",e,o),c=xt("output",e,o),d=s.dataType===6?s.getInt32Array()[0]:Number(s.getBigInt64Array()[0]),u=Le.normalizeAxis(d,o),f=M=>{let v=` i32(${a.indicesGet("inputIndices","uniforms.axis")}) `,k=Et("uniforms.input_shape","uniforms.axis",o),A=n.reverse?v+(n.exclusive?" + 1":""):"0",R=n.reverse?k:v+(n.exclusive?"":" + 1");return` + ${M.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(a,c)} + ${M.mainStart()} + ${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${c.offsetToIndices("global_idx")}; + var sum = ${c.type.value}(0); + let first : i32 = ${A}; + let last : i32 = ${R}; + for (var i : i32 = first; i < last; i++) { + ${a.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${a.getByIndices("inputIndices")}; + } + ${c.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:n.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:u},...Ct(t,t)]}),getShaderSource:f}},rc=(e,t)=>{let s=e.inputs[0].dims,n=e.inputs[0].dataType,i=e.inputs[1];e.compute(Fn(n,s,i,t),{inputs:[0]})},nc=e=>{let t=e.exclusive===1,s=e.reverse===1;return Lt({exclusive:t,reverse:s})}}),fo,ic,oc,go,ac,Wu=_(()=>{It(),B(),Ht(),Nt(),fo=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.")},ic=(e,t,s,n)=>{let i=[];i.push(`fn perm(i: ${n.type.indices}) -> ${s.type.indices} { + var a: ${s.type.indices};`);for(let o=0;o{let s,n,i,o,a,c,d=t.format==="NHWC",u=t.blocksize,f=t.mode==="DCR";d?([s,n,i,o]=e.dims,a=f?[s,n,i,u,u,o/u**2]:[s,n,i,o/u**2,u,u],c=f?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([s,n,i,o]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],a=f?[s,u,u,o/u**2,n,i]:[s,o/u**2,u,u,n,i],c=f?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let M=e.reshape(a),v=M.dims.length,k=e.dataType,A=Ue("a",k,v),R=xt("output",k,v),ee=W=>` + ${W.registerUniform("output_size","u32").declareVariables(A,R)} + + ${ic(c,v,A,R)} + + ${W.mainStart()} + ${W.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${R.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${R.setByOffset("global_idx",A.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:W=>{let V=d?[s,n*u,i*u,o/u**2]:[s,o/u**2,n*u,i*u],se=Le.size(V),oe=M.dims,Me=Le.sortBasedOnPerm(oe,c);return{outputs:[{dims:V,dataType:W[0].dataType}],dispatchGroup:{x:Math.ceil(se/64)},programUniforms:[{type:12,data:se},...Ct(oe,Me)]}},getShaderSource:ee}},go=(e,t)=>{fo(e.inputs),e.compute(oc(e.inputs[0],t))},ac=e=>Lt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Dn,cn,dn,lc,cc,dc,uc,wo,pc,hc,_c,Gu=_(()=>{It(),B(),Ht(),Nt(),Dn="[a-zA-Z]|\\.\\.\\.",cn="("+Dn+")+",dn="^"+cn+"$",lc="("+cn+",)*"+cn,cc="^"+lc+"$",dc=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let s=this.symbolToIndices.get(e);s===void 0?s=[t]:s.push(t),this.symbolToIndices.set(e,s)}},uc=class{constructor(e,t){var i;this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[s,n]=t.includes("->")?t.split("->",2):[t,""];if(!s.match(RegExp(cc)))throw new Error("Invalid LHS term");if(s.split(",").forEach((o,a)=>{let c=e[a].dims.slice();if(!o.match(RegExp(dn)))throw new Error("Invalid LHS term");let d=this.processTerm(o,!0,c,a);this.lhs.push(d)}),n==="")n+=[...this.symbolToInfo.entries()].filter(([o,a])=>a.count===1||o==="...").map(([o])=>o).join("");else if(!n.match(RegExp(cn)))throw new Error("Invalid RHS");(i=n.match(RegExp(Dn,"g")))==null||i.forEach(o=>{if(o==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let a=this.symbolToInfo.get(o);if(a===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(a.dimValue)}}),this.rhs=this.processTerm(n,!1,this.outputDims)}addSymbol(e,t,s){let n=this.symbolToInfo.get(e);if(n!==void 0){if(n.dimValue!==t&&n.count!==1)throw new Error("Dimension mismatch");n.count++,n.inputIndices.push(s)}else n={count:1,dimValue:t,inputIndices:[s]};this.symbolToInfo.set(e,n)}processTerm(e,t,s,n=-1){let i=s.length,o=!1,a=[],c=0;if(!e.match(RegExp(dn))&&!t&&e!=="")throw new Error("Invalid LHS term");let d=e.match(RegExp(Dn,"g")),u=new dc(n);return d==null||d.forEach((f,M)=>{if(f==="..."){if(o)throw new Error("Only one ellipsis is allowed per input term");o=!0;let v=i-d.length+1;if(v<0)throw new Error("Ellipsis out of bounds");if(a=s.slice(c,c+v),this.hasEllipsis){if(this.ellipsisDims.length!==a.length||this.ellipsisDims.toString()!==a.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=a;else throw new Error("Ellipsis must be specified in the LHS");for(let k=0;ke+"_max",pc=(e,t,s,n)=>{let i=e.map(u=>u.length).map((u,f)=>Ue(`input${f}`,t,u)),o=Le.size(n),a=xt("output",t,n.length),c=[...s.symbolToInfo.keys()].filter(u=>!s.rhs.symbolToIndices.has(u)),d=u=>{let f=[],M="var prod = 1.0;",v="var sum = 0.0;",k="sum += prod;",A=[],R=[],ee=[],W=[],V=s.symbolToInfo.size===s.rhs.symbolToIndices.size;s.symbolToInfo.forEach((oe,Me)=>{var Ie;if(s.rhs.symbolToIndices.has(Me)){let Ce=(Ie=s.rhs.symbolToIndices.get(Me))==null?void 0:Ie[0];Ce!==void 0&&s.lhs.forEach((Be,Ge)=>{if(oe.inputIndices.includes(Ge)){let rt=Be.symbolToIndices.get(Me);if(rt===void 0)throw new Error("Invalid symbol error");rt.forEach(St=>{f.push(`${i[Ge].indicesSet(`input${Ge}Indices`,St,a.indicesGet("outputIndices",Ce))}`)})}})}else s.lhs.forEach((Ce,Be)=>{if(oe.inputIndices.includes(Be)){let Ge=Ce.symbolToIndices.get(Me);if(Ge===void 0)throw new Error("Invalid symbol error");Ge.forEach(rt=>{A.push(`${i[Be].indicesSet(`input${Be}Indices`,rt,`${Me}`)}`)}),W.push(`prod *= ${i[Be].getByIndices(`input${Be}Indices`)};`)}}),R.push(`for(var ${Me}: u32 = 0; ${Me} < uniforms.${wo(Me)}; ${Me}++) {`),ee.push("}")});let se=V?[...f,`let sum = ${i.map((oe,Me)=>oe.getByIndices(`input${Me}Indices`)).join(" * ")};`]:[...f,v,...R,...A,M,...W,k,...ee];return` + ${u.registerUniforms(c.map(oe=>({name:`${wo(oe)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,a)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${a.offsetToIndices("global_idx")}; + ${i.map((oe,Me)=>`var input${Me}Indices: ${i[Me].type.indices};`).join(` +`)} + ${se.join(` +`)}; + ${a.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:s.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let u=c.filter(M=>s.symbolToInfo.has(M)).map(M=>{var v;return{type:12,data:((v=s.symbolToInfo.get(M))==null?void 0:v.dimValue)||0}});u.push({type:12,data:o});let f=e.map((M,v)=>[...Ct(M)]).reduce((M,v)=>M.concat(v),u);return f.push(...Ct(n)),{outputs:[{dims:n,dataType:t}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:f}},getShaderSource:d}},hc=(e,t)=>{let s=new uc(e.inputs,t.equation),n=s.outputDims,i=e.inputs.map((o,a)=>o.dims);e.compute(pc(i,e.inputs[0].dataType,s,n))},_c=e=>{let t=e.equation.replace(/\s+/g,"");return Lt({equation:t})}}),Mo,yo,mc,bo,fc,Ku=_(()=>{It(),B(),Nt(),Mo=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=s.length{let s=e.length-t.length,n=[];for(let i=0;ie.length>t.length?yo(e,t):yo(t,e),bo=e=>{let t=e[0].dims,s=Array.from(e[1].getBigInt64Array(),Number),n=mc(t,s),i=e[0].dataType,o=i===9||Le.size(t)===1,a=i===9||t.length>0&&t[t.length-1]%4===0?4:1,c=o||n.length>0&&n[n.length-1]%4===0?4:1,d=Math.ceil(Le.size(n)/c),u=M=>{let v=Ue("input",i,t.length,a),k=xt("output",i,n.length,c),A;if(i===9){let R=(ee,W,V="")=>` + let outputIndices${W} = ${k.offsetToIndices(`outputOffset + ${W}u`)}; + let offset${W} = ${v.broadcastedIndicesToOffset(`outputIndices${W}`,k)}; + let index${W} = offset${W} / 4u; + let component${W} = offset${W} % 4u; + ${ee}[${W}] = ${V}(${v.getByOffset(`index${W}`)}[component${W}]); + `;A=` + let outputOffset = global_idx * ${c}; + var data = vec4(0); + ${R("data",0,"u32")} + ${R("data",1,"u32")} + ${R("data",2,"u32")} + ${R("data",3,"u32")} + ${k.setByOffset("global_idx","data")} + }`}else A=` + let outputIndices = ${k.offsetToIndices(`global_idx * ${c}`)}; + let inputOffset = ${v.broadcastedIndicesToOffset("outputIndices",k)}; + let data = ${k.type.value}(${v.getByOffset(`inputOffset / ${a}`)}); + ${k.setByOffset("global_idx","data")} + }`;return` + ${M.registerUniform("vec_size","u32").declareVariables(v,k)} + ${M.mainStart()} + ${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${A}`},f=[{type:12,data:d},...Ct(t,n)];return{name:"Expand",shaderCache:{hint:`${n.length};${a}${c}`,inputDependencies:["rank"]},getShaderSource:u,getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:f})}},fc=e=>{Mo(e.inputs),e.compute(bo(e.inputs),{inputs:[0]})}}),gc,wc,Mc=_(()=>{It(),B(),Nt(),Ri(),gc=e=>{let t=e[0].dataType,s=Le.size(e[0].dims),n=Le.size(e[1].dims),i=n%4===0,o=a=>{let c=Ue("x",t,[1],4),d=Ue("bias",t,[1],4),u=xt("y",t,[1],4),f=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],M=k=>` + let bias${k}_offset: u32 = (global_idx * 4 + ${k}) % uniforms.bias_size; + let bias${k} = ${d.getByOffset(`bias${k}_offset / 4`)}[bias${k}_offset % 4];`,v=i?` + let bias = ${d.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${M(0)}${M(1)}${M(2)}${M(3)} + let bias = ${c.type.value}(bias0, bias1, bias2, bias3);`;return`${a.registerUniforms(f).declareVariables(c,d,u)} + + ${zi($s(t))} + + ${a.mainStart(lr)} + ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${c.getByOffset("global_idx")}; + ${v} + let x_in = x + bias; + ${u.setByOffset("global_idx",Pn("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:o,getRunData:a=>({outputs:[{dims:a[0].dims,dataType:a[0].dataType}],programUniforms:[{type:12,data:Math.ceil(s/4)},{type:12,data:n}],dispatchGroup:{x:Math.ceil(s/lr/4)}})}},wc=e=>{e.inputs.length<2||Le.size(e.inputs[1].dims)===0?yl(e):e.compute(gc(e.inputs))}}),yc,bc,vo,vc,Hu=_(()=>{It(),B(),Ht(),Nt(),yc=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},bc=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s.length,o=Le.normalizeAxis(t.axis,i),a=s.slice(0);a.splice(o,1,...n);let c=s[o],d=e[0].dataType===9?4:1,u=Math.ceil(Le.size(a)/d),f=[{type:12,data:u},{type:6,data:c},{type:12,data:o},...Ct(e[0].dims,e[1].dims,a)],M=v=>{let k=Ue("data",e[0].dataType,e[0].dims.length,d),A=Ue("inputIndices",e[1].dataType,e[1].dims.length),R=xt("output",e[0].dataType,a.length,d),ee=V=>{let se=n.length,oe=`var indicesIndices${V} = ${A.type.indices}(0);`;for(let Me=0;Me1?`indicesIndices${V}[${Me}]`:`indicesIndices${V}`} = ${a.length>1?`outputIndices${V}[uniforms.axis + ${Me}]`:`outputIndices${V}`};`;oe+=` + var idx${V} = ${A.getByIndices(`indicesIndices${V}`)}; + if (idx${V} < 0) { + idx${V} = idx${V} + uniforms.axisDimLimit; + } + var dataIndices${V} : ${k.type.indices}; + `;for(let Me=0,Ie=0;Me1?`dataIndices${V}[${Me}]`:`dataIndices${V}`} = u32(idx${V});`,Ie+=se):(oe+=`${i>1?`dataIndices${V}[${Me}]`:`dataIndices${V}`} = ${a.length>1?`outputIndices${V}[${Ie}]`:`outputIndices${V}`};`,Ie++);return oe},W;if(e[0].dataType===9){let V=(se,oe,Me="")=>` + let outputIndices${oe} = ${R.offsetToIndices(`outputOffset + ${oe}u`)}; + ${ee(oe)}; + let offset${oe} = ${k.indicesToOffset(`dataIndices${oe}`)}; + let index${oe} = offset${oe} / 4u; + let component${oe} = offset${oe} % 4u; + ${se}[${oe}] = ${Me}(${k.getByOffset(`index${oe}`)}[component${oe}]); + `;W=` + let outputOffset = global_idx * ${d}; + var value = vec4(0); + ${V("value",0,"u32")} + ${V("value",1,"u32")} + ${V("value",2,"u32")} + ${V("value",3,"u32")} + ${R.setByOffset("global_idx","value")} + `}else W=` + let outputIndices = ${R.offsetToIndices("global_idx")}; + ${ee("")}; + let value = ${k.getByIndices("dataIndices")}; + ${R.setByOffset("global_idx","value")}; + `;return` + ${v.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(k,A,R)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${W} + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:M}},vo=e=>Lt({axis:e.axis}),vc=(e,t)=>{let s=e.inputs;yc(s),e.compute(bc(e.inputs,t))}}),xo,xc,Tc,Ec=_(()=>{It(),B(),Nt(),xo=(e,t,s,n,i,o,a,c,d)=>{let u=[{type:12,data:o},{type:12,data:n},{type:12,data:i},{type:12,data:s},{type:12,data:a},{type:12,data:c},{type:12,data:d}],f=[o];u.push(...Ct(t.dims,f));let M=v=>{let k=Ue("indices_data",t.dataType,t.dims.length),A=xt("input_slice_offsets_data",12,1,1),R=[k,A],ee=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:i.length},{name:"sizes_from_slice_dims_data",type:"u32",length:s.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${v.registerUniforms(ee).declareVariables(...R)} + ${v.mainStart()} + ${v.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) { + ${i.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"} + } + ${s.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:`${i.length}_${s.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:f,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:u}),getShaderSource:M},{inputs:[t],outputs:[-1]})[0]},xc=(e,t)=>{let s=e.inputs,n=s[0].dims,i=s[0].dataType,o=s[1].dims,a=o[o.length-1],c=Le.sizeToDimension(o,o.length-1),d=Le.sizeFromDimension(n,t.batchDims+a),u=Le.sizeToDimension(n,t.batchDims),f=Le.sizeFromDimension(n,t.batchDims),M=c/u,v=new Array(a),k=d;for(let oe=0;oen.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let ee=o.slice(0,-1).concat(n.slice(R)),W=Le.size(ee),V=[{type:12,data:W},{type:12,data:d},...Ct(s[0].dims,A.dims,ee)],se=oe=>{let Me=Ue("data",s[0].dataType,s[0].dims.length),Ie=Ue("slice_offsets",12,A.dims.length),Ce=xt("output",s[0].dataType,ee.length);return` + ${oe.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(Me,Ie,Ce)} + ${oe.mainStart()} + ${oe.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:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:ee,dataType:i}],dispatchGroup:{x:Math.ceil(W/64)},programUniforms:V}),getShaderSource:se},{inputs:[s[0],A]})},Tc=e=>({batchDims:e.batch_dims,cacheKey:""})}),Pc,Cc,$c,Sc,qu=_(()=>{It(),B(),Ht(),Nt(),Pc=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let s=Le.normalizeAxis(t.quantizeAxis,e[0].dims.length),n=t.blockSize,i=e[0],o=e[2],a=e.length===4?e[3]:void 0;if(o.dims.length!==i.dims.length||!i.dims.map((c,d)=>d===s?Math.ceil(c/n)===o.dims[d]:c===o.dims[d]).reduce((c,d)=>c&&d,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(a){if(a.dataType!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(a.dims.length!==o.dims.length||!a.dims.map((c,d)=>c===o.dims[d]).reduce((c,d)=>c&&d,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Cc=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s.length,o=Le.normalizeAxis(t.gatherAxis,i),a=Le.normalizeAxis(t.quantizeAxis,i),c=s.slice(0);c.splice(o,1,...n);let d=Le.size(c),u=e[2].dataType,f=e[0].dataType===22,M=[{type:12,data:d},{type:12,data:a},{type:12,data:o},{type:12,data:t.blockSize},...Ct(...e.map((k,A)=>k.dims),c)],v=k=>{let A=Ue("data",e[0].dataType,e[0].dims.length),R=Ue("inputIndices",e[1].dataType,e[1].dims.length),ee=Ue("scales",e[2].dataType,e[2].dims.length),W=e.length>3?Ue("zeroPoint",e[3].dataType,e[3].dims.length):void 0,V=xt("output",u,c.length),se=[A,R,ee];W&&se.push(W);let oe=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${k.registerUniforms(oe).declareVariables(...se,V)} + ${k.mainStart()} + let output_indices = ${V.offsetToIndices("global_idx")}; + var indices_indices = ${R.type.indices}(0); + ${n.length>1?` + for (var i: u32 = 0; i < ${n.length}; i++) { + let index = ${V.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${R.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${V.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${A.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${V.indicesGet("output_indices","i")}; + ${A.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${R.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${s[o]}; + } + ${A.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${c.length}; i++) { + let index = ${V.indicesGet("output_indices",`i + ${n.length} - 1`)}; + ${A.indicesSet("data_indices","i","index")}; + } + let data_offset = ${A.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${A.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${f?"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 = ${ee.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${ee.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${ee.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 = ${f?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${$s(u)}(quantized_data - zero_point) * scale; + ${V.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((k,A)=>A!==1).map(k=>k.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(k,A)=>"rank")},getRunData:()=>({outputs:[{dims:c,dataType:u}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:M}),getShaderSource:v}},$c=(e,t)=>{let s=e.inputs;Pc(s,t),e.compute(Cc(e.inputs,t))},Sc=e=>Lt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),kc,Ic,Ac,To,Qu=_(()=>{It(),B(),Ht(),Nt(),kc=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.`)},Ic=(e,t)=>{let s=e[0].dims,n=e[0].dataType,i=s.length,o=e[1].dims,a=e[1].dataType,c=Le.normalizeAxis(t.axis,i),d=s[c],u=o.slice(0),f=Le.size(u),M=Ue("input",n,i),v=Ue("indicesInput",a,o.length),k=xt("output",n,u.length),A=[{type:12,data:f},{type:6,data:d},{type:12,data:c}];return A.push(...Ct(s,o,u)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:A}),getShaderSource:R=>` + ${R.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(M,v,k)} + ${R.mainStart()} + ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${k.offsetToIndices("global_idx")}; + + var idx = ${v.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${M.type.indices}(outputIndices); + ${M.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${M.getByIndices("inputIndices")}; + + ${k.setByOffset("global_idx","value")}; + }`}},Ac=e=>Lt({axis:e.axis}),To=(e,t)=>{let s=e.inputs;kc(s),e.compute(Ic(e.inputs,t))}}),Fc,Dc,Oc,Lc,Xu=_(()=>{It(),B(),Nt(),Fc=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")},Dc=(e,t)=>{let s=e[0].dims.slice(),n=e[1].dims.slice(),[i,o,a]=rn.getShapeOfGemmResult(s,t.transA,n,t.transB,e.length===3?e[2].dims:void 0),c=[i,o];if(!c)throw new Error("Can't use gemm on the given tensors");let d=16,u=Math.ceil(o/d),f=Math.ceil(i/d),M=!0,v=Le.size(c),k=[{type:12,data:M?u:v},{type:12,data:i},{type:12,data:o},{type:12,data:a},{type:1,data:t.alpha},{type:1,data:t.beta}],A=["type","type"];e.length===3&&(k.push(...Ct(e[2].dims)),A.push("rank")),k.push(...Ct(c));let R=W=>{let V="";t.transA&&t.transB?V="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?V="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?V="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(V="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let se=t.alpha===1?"":"value *= uniforms.alpha;",oe=Ue("a",e[0].dataType,e[0].dims),Me=Ue("b",e[1].dataType,e[1].dims),Ie=oe.type.value,Ce=null,Be=[oe,Me];e.length===3&&(Ce=Ue("c",e[2].dataType,e[2].dims.length),Be.push(Ce));let Ge=xt("output",e[0].dataType,c.length);Be.push(Ge);let rt=[{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(rt).declareVariables(...Be)} + + ${W.mainStart()} + ${W.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${Ie}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${V} + } + + ${se} + ${Ce!=null?`let cOffset = ${Ce.broadcastedIndicesToOffset("vec2(m, n)",Ge)}; value += ${Ie}(uniforms.beta) * ${Ce.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},ee=W=>{let V=Ue("a",e[0].dataType,e[0].dims),se=Ue("b",e[1].dataType,e[1].dims),oe=null,Me=[V,se];e.length===3&&(oe=Ue("c",e[2].dataType,e[2].dims.length),Me.push(oe));let Ie=xt("output",e[0].dataType,c.length);Me.push(Ie);let Ce=[{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"}],Be="",Ge="";t.transA&&t.transB?(Ge=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${V.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${se.type.value}(0); + } + `,Be="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):t.transA&&!t.transB?(Ge=` + var col = tile_row_start + local_id.x; + var row = k_start + local_id.y; + if (col < uniforms.M && row < uniforms.K) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col]; + } else { + tile_a[local_id.y][local_id.x] = ${V.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${se.type.value}(0); + } + `,Be="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!t.transA&&t.transB?(Ge=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${V.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${se.type.value}(0); + } + `,Be="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!t.transA&&!t.transB&&(Ge=` + var col = k_start + local_id.x; + var row = tile_row_start + local_id.y; + if (col < uniforms.K && row < uniforms.M) { + tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col]; + } else { + tile_a[local_id.y][local_id.x] = ${V.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${se.type.value}(0); + } + `,Be="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let rt=t.alpha===1?"":"value *= uniforms.alpha;";return` + ${W.registerUniforms(Ce).declareVariables(...Me)} + var tile_a: array, ${d}>; + var tile_b: array, ${d}>; + ${W.mainStart([d,d,1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${d}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${d}; + let num_tiles = (uniforms.K - 1) / ${d} + 1; + var k_start = 0u; + var value = ${Ie.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${Ge} + k_start = k_start + ${d}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${d}; k++) { + ${Be} + } + workgroupBarrier(); + } + + ${rt} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${oe!=null?`let cOffset = ${oe.broadcastedIndicesToOffset("vec2(m, n)",Ie)}; value += ${Ie.type.value}(uniforms.beta) * ${oe.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return M?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:A},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:u*f},programUniforms:k}),getShaderSource:ee}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:A},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:k}),getShaderSource:R}},Oc=e=>{let t=e.transA,s=e.transB,n=e.alpha,i=e.beta;return{transA:t,transB:s,alpha:n,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},Lc=(e,t)=>{Fc(e.inputs),e.compute(Dc(e.inputs,t))}}),ir,mr,Nr,xr,zc,Bc,Tr,Rc,jc,Nc,Vc,Eo,Uc,Wc,Ju=_(()=>{It(),B(),Ht(),Nt(),[ir,mr,Nr,xr]=[0,1,2,3],zc=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")},Bc=` + 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; + } +`,Tr=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; + } +`,Rc=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)); + `} + } +`,jc=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); + }`:""} +`,Nc=(e,t,s)=>` + fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { + var pixel = ${t}(0); + var indices = vec4(0); + indices[${ir}] = batch; + indices[${mr}] = channel;`+(()=>{switch(s.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${Nr}] = u32(r); + indices[${xr}] = u32(c); + } else { + return ${t}(0); + } + `;case"border":return` + indices[${Nr}] = u32(clamp(r, 0, H - 1)); + indices[${xr}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${Nr}] = gs_reflect(r, border[1], border[3]); + indices[${xr}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${s.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,Vc=(e,t,s)=>(()=>{switch(s.mode){case"nearest":return` + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${ir}], indices[${mr}], 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[${ir}], indices[${mr}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${ir}], indices[${mr}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${ir}], indices[${mr}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${ir}], indices[${mr}], border); + + let dx2 = ${t}(f32(x2) - x); + let dx1 = ${t}(x - f32(x1)); + let dy2 = ${t}(f32(y2) - y); + let dy1 = ${t}(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<${t}>; + 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[${ir}], indices[${mr}], 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 ${s.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Eo=(e,t)=>{let s=Ue("x",e[0].dataType,e[0].dims.length),n=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=Ue("grid",e[1].dataType,n.length,2),o=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(o=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[ir,mr,Nr,xr]=[0,3,1,2]);let a=xt("output",e[0].dataType,o.length),c=s.type.value,d=Le.size(o),u=[{type:12,data:d},...Ct(e[0].dims,n,o)],f=M=>` + ${M.registerUniform("output_size","u32").declareVariables(s,i,a)} + ${Bc} + ${Tr(c)} + ${Rc(t)} + ${jc(t)} + ${Nc(s,c,t)} + + ${M.mainStart()} + ${M.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${Nr}]); + let W_in = i32(uniforms.x_shape[${xr}]); + + ${t.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${a.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${ir}], indices[${Nr}], indices[${xr}]); + let nxy = ${i.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${Vc(a,c,t)} + }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:M=>{let v=Le.size(o);return{outputs:[{dims:o,dataType:M[0].dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:u}},getShaderSource:f}},Uc=(e,t)=>{zc(e.inputs),e.compute(Eo(e.inputs,t))},Wc=e=>Lt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Fs,On,Gc,Po,Kc,Er,Hc,qc=_(()=>{It(),B(),Ht(),Cs(),xn(),Nt(),_r(),Fs=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,On=(e,t)=>{let s=e[0],n=Fs(e,1),i=Fs(e,2),o=Fs(e,3),a=Fs(e,4),c=Fs(e,5),d=Fs(e,6),u=Fs(e,7);if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let f=s.dims[0],M=s.dims[1],v=s.dims.length===3?s.dims[2]:t.numHeads*s.dims[4],k=M,A=0,R=0,ee=Math.floor(v/t.numHeads);if(d&&u&&Le.size(d.dims)&&Le.size(u.dims)){if(d.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(d.dims[0]!==f||d.dims[1]!==t.numHeads||d.dims[3]!==ee)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(u.dims[0]!==f||u.dims[1]!==t.numHeads||u.dims[3]!==ee)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.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');A=d.dims[2],R=d.dims[2]}else if(d&&Le.size(d.dims)||u&&Le.size(u.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let W;if(n&&Le.size(n.dims)>0){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(n.dims[2]!==s.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');W=2,k=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==ee)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');W=5,k=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==ee)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');W=0,k=n.dims[2]}}else{if(s.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(s.dims[2]!==t.numHeads||s.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');W=3}if(o&&Le.size(o.dims)>0){if(o.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(n&&n.dims.length===5&&n.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let V=A+k,se=0;if(a&&Le.size(a.dims)>0){se=8;let Ce=a.dims;throw Ce.length===1?Ce[0]===f?se=1:Ce[0]===3*f+2&&(se=3):Ce.length===2&&Ce[0]===f&&Ce[1]===V&&(se=5),se===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let oe=!1,Me=v;if(i&&Le.size(i.dims)>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(k!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Me=i.dims[2]}else{if(k!==i.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');Me=i.dims[1]*i.dims[3],oe=!0}}let Ie=!1;if(a&&Le.size(a.dims)>0)throw new Error("Key padding mask is not supported");if(c&&Le.size(c.dims)>0){if(c.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(c.dims[0]!==f||c.dims[1]!==t.numHeads||c.dims[2]!==M||c.dims[3]!==V)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:f,sequenceLength:M,pastSequenceLength:A,kvSequenceLength:k,totalSequenceLength:V,maxSequenceLength:R,inputHiddenSize:0,hiddenSize:v,vHiddenSize:Me,headSize:ee,vHeadSize:Math.floor(Me/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:se,scale:t.scale,broadcastResPosBias:Ie,passPastInKv:oe,qkvFormat:W}},Gc=e=>Lt({...e}),Po=Lt({perm:[0,2,1,3]}),Kc=(e,t,s,n,i,o,a)=>{let c=[n,i,o],d=Le.size(c),u=[{type:12,data:d},{type:12,data:a},{type:12,data:o}],f=M=>{let v=xt("qkv_with_bias",t.dataType,c),k=Ue("qkv",t.dataType,c),A=Ue("bias",s.dataType,c),R=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${M.registerUniforms(R).declareVariables(k,A,v)} + ${M.mainStart()} + ${M.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:c,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:u}),getShaderSource:f},{inputs:[t,s],outputs:[-1]})[0]},Er=(e,t,s,n,i,o,a,c)=>{let d=o;if(a&&Le.size(a.dims)>0){if(n===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return d=Kc(e,o,a,t,n,s*i,c),d=d.reshape([t,n,s,i]),s===1||n===1?d:e.compute(Ks(d,Po.perm),{inputs:[d],outputs:[-1]})[0]}else return o.dims.length===3&&(d=o.reshape([t,n,s,i])),s===1||n===1?d:e.compute(Ks(d,Po.perm),{inputs:[d],outputs:[-1]})[0]},Hc=(e,t)=>{let s=On(e.inputs,t),n=e.inputs[0],i=Fs(e.inputs,1),o=Fs(e.inputs,2),a=Fs(e.inputs,3),c=Fs(e.inputs,4),d=Fs(e.inputs,5),u=Fs(e.inputs,6),f=Fs(e.inputs,7);if(n.dims.length===5)throw new Error("Packed QKV is not implemented");if((i==null?void 0:i.dims.length)===5)throw new Error("Packed KV is not implemented");let M=i&&o&&i.dims.length===4&&o.dims.length===4,v=Er(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,n,a,0);if(M)return Qr(e,v,i,o,c,void 0,u,f,d,s);if(!i||!o)throw new Error("key and value must be provided");let k=Er(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.headSize,i,a,s.hiddenSize),A=Er(e,s.batchSize,s.numHeads,s.kvSequenceLength,s.vHeadSize,o,a,2*s.hiddenSize);Qr(e,v,k,A,c,void 0,u,f,d,s)}}),Qc,Xc,Ln,Jc,Co,Yc,Yu,Zc=_(()=>{It(),B(),Ht(),Nt(),Qc=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Xc=(e,t)=>{let s=[],n=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>s.push(Number(i))),n=s.length),Lt({numOutputs:n,axis:t.axis,splitSizes:s})},Ln=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${Et("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,Jc=e=>{let t=e.length,s=[];for(let n=0;n{let s=e[0].dims,n=Le.size(s),i=e[0].dataType,o=Le.normalizeAxis(t.axis,s.length),a=new Array(t.numOutputs),c=Ue("input",i,s.length),d=new Array(t.numOutputs),u=[],f=[],M=0,v=[{type:12,data:n}];for(let A=0;A` + ${A.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",d.length).declareVariables(c,...a)} + ${Ln(d.length)} + ${Jc(a)} + + ${A.mainStart()} + ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${c.offsetToIndices("global_idx")}; + var index = ${c.indicesGet("indices",o)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${Et("uniforms.size_in_split_axis","output_number - 1u",d.length)}; + ${c.indicesSet("indices",o,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:k,getRunData:()=>({outputs:u,dispatchGroup:{x:Math.ceil(n/64)},programUniforms:v})}},Yc=(e,t)=>{Qc(e.inputs);let s=e.inputs.length===1?t:Xc(e.inputs,t);e.compute(Co(e.inputs,s),{inputs:[0]})},Yu=e=>{let t=e.axis,s=e.splitSizes,n=e.numOutputs<0?s.length:e.numOutputs;if(n!==s.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Lt({axis:t,numOutputs:n,splitSizes:s})}}),ed,zn,Jr,td=_(()=>{It(),B(),Ht(),Nt(),ed=(e,t)=>{let[s,n,i,o]=e,{numHeads:a,rotaryEmbeddingDim:c}=t;if(s.dims.length!==3&&s.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${s.dims.length}`);if(!Le.areEqual(n.dims,[])&&!Le.areEqual(n.dims,[1])&&n.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${n.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(o.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${o.dims.length}`);if(!Le.areEqual(i.dims,o.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(c>0&&a===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let d=s.dims[0],u=s.dims[s.dims.length-2],f=i.dims[0],M=Le.sizeFromDimension(s.dims,1)/u,v=c===0?i.dims[1]*2:M/a;if(c>v)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(n.dims.length===2){if(d!==n.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${n.dims[0]}`);if(u!==n.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${n.dims[1]}`)}if(v/2!==i.dims[1]&&c/2!==i.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${i.dims[1]}`);if(u>f)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},zn=(e,t)=>{let{interleaved:s,numHeads:n,rotaryEmbeddingDim:i,scale:o}=t,a=e[0].dims[0],c=Le.sizeFromDimension(e[0].dims,1),d=e[0].dims[e[0].dims.length-2],u=c/d,f=e[2].dims[1],M=i===0?f*2:u/n,v=new Array(a,d,u/M,M-f),k=Le.computeStrides(v),A=[{type:1,data:o},{type:12,data:v},{type:12,data:k},...e[0].dims.length===3?new Array({type:12,data:[c,u,M,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[c,M,d*M,1]}):[],...Ct(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],R=ee=>{let W=Ue("input",e[0].dataType,e[0].dims.length),V=Ue("position_ids",e[1].dataType,e[1].dims.length),se=Ue("cos_cache",e[2].dataType,e[2].dims.length),oe=Ue("sin_cache",e[3].dataType,e[3].dims.length),Me=xt("output",e[0].dataType,e[0].dims.length);return ee.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:v.length},{name:"global_strides",type:"u32",length:k.length},{name:"input_output_strides",type:"u32",length:k.length}]),` + ${ee.declareVariables(W,V,se,oe,Me)} + + ${ee.mainStart(lr)} + let half_rotary_emb_dim = uniforms.${se.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${V.broadcastedIndicesToOffset("bsnh.xy",xt("",V.type.tensor,2))}; + let position_id = + u32(${V.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${s}); + let j = i + select(half_rotary_emb_dim, 1, ${s}); + let re = ${W.getByOffset("i")} * ${se.get("position_id","bsnh[3]")} - + ${W.getByOffset("j")} * ${oe.get("position_id","bsnh[3]")}; + ${Me.setByOffset("i","re")} + let im = ${W.getByOffset("i")} * ${oe.get("position_id","bsnh[3]")} + + ${W.getByOffset("j")} * ${se.get("position_id","bsnh[3]")}; + ${Me.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${Me.setByOffset("k",W.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Lt({interleaved:s}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:R,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Le.size(v)/lr)},programUniforms:A})}},Jr=(e,t)=>{ed(e.inputs,t),e.compute(zn(e.inputs,t))}}),sd,rd,$o,nd,id,Zu=_(()=>{Ht(),It(),xn(),qc(),Zc(),_r(),td(),Nt(),sd=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let s=e[0],n=e[1],i=e[2],o=e[3],a=e[4];if(t.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(s.dims.length!==3&&s.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let c=!1,d=s.dims[0],u=s.dims[1],f=s.dims.length===3?c?s.dims[2]/3:s.dims[2]:t.numHeads*s.dims[4],M=u,v=0,k=!n||n.dims.length===0,A=Math.floor(k?f/(t.numHeads+2*t.kvNumHeads):f/t.numHeads);k&&(f=A*t.numHeads);let R=o&&o.dims.length!==0,ee=a&&a.dims.length!==0;if(R&&o.dims.length===4&&o.dims[0]===d&&o.dims[1]!==t.kvNumHeads&&o.dims[2]===t.kvNumHeads&&o.dims[3]===A)throw new Error("BSNH pastKey/pastValue is not supported");if(R&&ee){if(o.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(a.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');v=o.dims[2]}else if(R||ee)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let W=1;if(n&&n.dims.length>0){if(s.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(n.dims.length<3||n.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(s.dims[0]!==n.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(n.dims.length===3){if(s.dims[2]%n.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');M=n.dims[1]}else if(n.dims.length===5){if(n.dims[2]!==t.numHeads||n.dims[3]!==2||n.dims[4]!==A)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');M=n.dims[1]}else{if(n.dims[1]!==t.numHeads||n.dims[3]!==A)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');M=n.dims[2]}}else{if(s.dims.length!==3&&s.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(s.dims.length===5&&(s.dims[2]!==t.numHeads||s.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');W=3}let V=0,se=!1,oe=t.kvNumHeads?A*t.kvNumHeads:f;if(i&&i.dims.length>0){if(i.dims.length!==3&&i.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(s.dims[0]!==i.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(i.dims.length===3){if(M!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');oe=i.dims[2]}else{if(M!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');oe=i.dims[1]*i.dims[3],se=!0}}let Me=e.length>4?e[5]:void 0;if(Me&&Me.dims.length!==1&&Me.dims[0]!==d)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:d,sequenceLength:u,pastSequenceLength:v,kvSequenceLength:M,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:f,vHiddenSize:oe,headSize:A,vHeadSize:Math.floor(oe/t.kvNumHeads),numHeads:t.numHeads,kvNumHeads:t.kvNumHeads,nReps:t.numHeads/t.kvNumHeads,pastPresentShareBuffer:!1,maskType:V,scale:t.scale,broadcastResPosBias:!1,passPastInKv:se,qkvFormat:W}},rd=Lt({perm:[0,2,1,3]}),$o=(e,t,s)=>{let n=t,i=s.kvNumHeads;return t.dims.length===3&&s.kvSequenceLength!==0&&(n=t.reshape([s.batchSize,s.kvSequenceLength,i,s.headSize]),n=e.compute(Ks(n,rd.perm),{inputs:[n],outputs:[-1]})[0]),n},nd=(e,t,s,n)=>{let i=7,o=["type","type"],a=[e*t],c=e*t,d=[{type:12,data:c},{type:12,data:t},{type:12,data:e}],u=f=>{let M=Ue("seq_lens",s.dataType,s.dims),v=Ue("total_seq_lens",n.dataType,n.dims),k=xt("pos_ids",i,a),A=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` + ${f.registerUniforms(A).declareVariables(M,v,k)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let total_sequence_length = u32(${v.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 = ${M.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; + } + ${k.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; + } + ${k.setByOffset("global_idx","pos_id")} + } else if (global_idx < uniforms.batch_size) { + ${k.setByOffset("global_idx","seqlen")} + }; + } + `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${t}`,inputDependencies:o},getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:d}),getShaderSource:u}},id=(e,t)=>{var oe;let s=sd(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((oe=e.inputs[1])==null?void 0:oe.dims.length)===5)throw new Error("Packed KV is not implemented");let n=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,o=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,a=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,c=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,d=e.inputs.length>4?e.inputs[5]:void 0,u=e.inputs.length>5?e.inputs[6]:void 0,f=s.kvNumHeads?s.kvNumHeads:s.numHeads,M=Lt({axis:2,numOutputs:3,splitSizes:[s.numHeads*s.headSize,f*s.headSize,f*s.headSize]}),[v,k,A]=!i&&!o?e.compute(Co([n],M),{inputs:[n],outputs:[-1,-1,-1]}):[n,i,o],R,ee;if(t.doRotary){let Me=e.compute(nd(s.batchSize,s.sequenceLength,d,u),{inputs:[d,u],outputs:[-1]})[0],Ie=e.inputs[7],Ce=e.inputs[8],Be=Lt({interleaved:t.rotaryInterleaved!==0,numHeads:s.numHeads,rotaryEmbeddingDim:0,scale:t.scale}),Ge=[v,Me,Ie,Ce],rt=[-1];R=e.compute(zn(Ge,Be),{inputs:Ge,outputs:rt})[0],Ge.splice(0,1,k);let St=Lt({interleaved:t.rotaryInterleaved!==0,numHeads:s.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});ee=e.compute(zn(Ge,St),{inputs:Ge,outputs:rt})[0]}let W=Er(e,s.batchSize,s.numHeads,s.sequenceLength,s.headSize,t.doRotary?R:v,void 0,0),V=$o(e,t.doRotary?ee:k,s),se=$o(e,A,s);Qr(e,W,V,se,void 0,void 0,a,c,void 0,s,d,u)}}),un,ep,od,ad,tp=_(()=>{It(),B(),_r(),Nt(),un=(e,t,s,n,i,o,a,c)=>{let d=as(o),u=d===1?"f32":`vec${d}f`,f=d===1?"vec2f":`mat2x${d}f`,M=i*a,v=64;M===1&&(v=256);let k=[i,a,o/d],A=[i,a,2],R=["rank","type","type"],ee=[];ee.push(...Ct(k,A));let W=V=>{let se=Ue("x",t.dataType,3,d),oe=Ue("scale",s.dataType,s.dims),Me=Ue("bias",n.dataType,n.dims),Ie=xt("output",1,3,2),Ce=[se,oe,Me,Ie];return` + var workgroup_shared : array<${f}, ${v}>; + const workgroup_size = ${v}u; + ${V.declareVariables(...Ce)} + ${V.mainStart(v)} + 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}(${se.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${f}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${Qs("workgroup_shared[0][0]",d)} / f32(hight * ${d}); + let squared_sum_final = ${Qs("workgroup_shared[0][1]",d)} / f32(hight * ${d}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${c})); + 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:`${d};${c};${v}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:A,dataType:1}],dispatchGroup:{x:M},programUniforms:ee}),getShaderSource:W},{inputs:[t,s,n],outputs:[-1]})[0]},ep=(e,t,s)=>{let n=t[0].dims,i=n,o=2,a=n[0],c=n[1],d=Le.sizeFromDimension(n,o),u=as(d),f=Le.size(i)/u,M=un(e,t[0],t[1],t[2],a,d,c,s.epsilon),v=[a,c,d/u],k=[a,c],A=["type","none"],R=ee=>{let W=Ue("x",t[0].dataType,v.length,u),V=Ue("scale_shift",1,k.length,2),se=xt("output",t[0].dataType,v.length,u),oe=[W,V,se];return` + ${ee.registerUniform("output_size","u32").declareVariables(...oe)} + ${ee.mainStart()} + ${ee.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${se.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${V.getByIndices("vec2(batch, channel)")}; + let value = ${W.getByOffset("global_idx")} * ${se.type.value}(scale_shift.x) + ${se.type.value}(scale_shift.y); + ${se.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${u}`,inputDependencies:A},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(f/64)},programUniforms:[{type:12,data:f},...Ct(v,k,v)]}),getShaderSource:R},{inputs:[t[0],M]})},od=(e,t,s)=>{let n=t[0].dims,i=n,o=n[0],a=n[n.length-1],c=Le.sizeFromDimension(n,1)/a,d=as(a),u=Le.size(i)/d,f=[{type:12,data:c},{type:12,data:Math.floor(a/d)}],M=["type","type"],v=!1,k=[0,n.length-1];for(let W=0;Wn[k[V]])),R=un(e,A,t[1],t[2],o,c,a,s.epsilon),ee=W=>{let V=cs(t[0].dataType),se=d===1?"vec2f":`mat${d}x2f`,oe=Ce=>{let Be=Ce===0?"x":"y",Ge=d===1?"f32":`vec${d}f`;switch(d){case 1:return`${V}(${Ge}(scale.${Be}))`;case 2:return`vec2<${V}>(${Ge}(scale[0].${Be}, scale[1].${Be}))`;case 4:return`vec4<${V}>(${Ge}(scale[0].${Be}, scale[1].${Be}, scale[2].${Be}, scale[3].${Be}))`;default:throw new Error(`Not supported compoents ${d}`)}},Me=Ue("input",t[0].dataType,t[0].dims,d),Ie=xt("output",t[0].dataType,i,d);return` + @group(0) @binding(0) var input : array<${Me.type.storage}>; + @group(0) @binding(1) var scale_input : array<${se}>; + @group(0) @binding(2) var output : array<${Ie.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], ${oe(0)}, ${oe(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${d}`,inputDependencies:M},getRunData:()=>({outputs:[{dims:i,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:f}),getShaderSource:ee},{inputs:[t[0],R]})},ad=(e,t)=>{t.format==="NHWC"?od(e,e.inputs,t):ep(e,e.inputs,t)}}),ld,cd,So,sp=_(()=>{It(),B(),Nt(),ld=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},cd=(e,t,s)=>{let n=t.simplified,i=e[0].dims,o=e[1],a=!n&&e[2],c=i,d=Le.normalizeAxis(t.axis,i.length),u=Le.sizeToDimension(i,d),f=Le.sizeFromDimension(i,d),M=Le.size(o.dims),v=a?Le.size(a.dims):0;if(M!==f||a&&v!==f)throw new Error(`Size of X.shape()[axis:] == ${f}. + Size of scale and bias (if provided) must match this. + Got scale size of ${M} and bias size of ${v}`);let k=[];for(let Me=0;Me1,V=s>2,se=Me=>{let Ie=cs(e[0].dataType),Ce=[Ue("x",e[0].dataType,e[0].dims,A),Ue("scale",o.dataType,o.dims,A)];a&&Ce.push(Ue("bias",a.dataType,a.dims,A)),Ce.push(xt("output",e[0].dataType,c,A)),W&&Ce.push(xt("mean_data_output",1,k)),V&&Ce.push(xt("inv_std_output",1,k));let Be=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${Me.registerUniforms(Be).declareVariables(...Ce)} + ${Me.mainStart()} + ${Me.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${ni("f32",A)}; + var mean_square_vector = ${ni("f32",A)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${qr(Ie,A,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${Qs("mean_vector",A)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${Qs("mean_square_vector",A)} / uniforms.norm_size ${n?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${qr(Ie,A,"x[j + offset]")}; + let f32scale = ${qr(Ie,A,"scale[j]")}; + output[j + offset] = ${Ce[0].type.value}((f32input ${n?"":"- mean"}) * inv_std_dev * f32scale + ${a?`+ ${qr(Ie,A,"bias[j]")}`:""} + ); + } + + ${W?"mean_data_output[global_idx] = mean":""}; + ${V?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},oe=[{dims:c,dataType:e[0].dataType}];return W&&oe.push({dims:k,dataType:1}),V&&oe.push({dims:k,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${A};${s};${n}`,inputDependencies:R},getRunData:()=>({outputs:oe,dispatchGroup:{x:Math.ceil(u/64)},programUniforms:ee}),getShaderSource:se}},So=(e,t)=>{ld(e.inputs),e.compute(cd(e.inputs,t,e.outputCount))}}),dd,ko,rp=_(()=>{B(),qi(),Zi(),dd=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.")},ko=e=>{dd(e.inputs);let t=Ws.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let s=t[t.length-1],n=e.inputs[0].dims[e.inputs[0].dims.length-1];if(s<8&&n<8)e.compute(Hi(e.inputs,{activation:""},t));else{let i=t[t.length-2],o=Le.size(e.inputs[0].dims.slice(0,-2)),a=Le.size(e.inputs[1].dims.slice(0,-2));if(o!==1&&i===1&&a===1){let c=e.inputs[0].reshape([1,o,n]),d=e.inputs[1].reshape([1,n,s]),u=[1,o,s],f=[c,d];e.compute($n(f,{activation:""},t,u),{inputs:f})}else e.compute($n(e.inputs,{activation:""},t))}}}),ud,Io,pd,hd,Ao,np=_(()=>{It(),B(),Ht(),Nt(),ud=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let s=e[0],n=s.dims.length;if(s.dims[n-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((t.k+t.blockSize-1)/t.blockSize),o=t.blockSize/8*t.bits,a=e[1];if(!Le.areEqual(a.dims,[t.n,i,o]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let c=e[2].dims;if(Le.size(c)!==t.n*i)throw new Error("scales input size error.");if(e.length===4){let d=e[3].dims,u=t.bits>4?t.n*i:t.n*Math.floor((i+1)/2);if(Le.size(d)!==u)throw new Error("zeroPoints input size error.")}},Io=(e,t)=>{let s=e[0].dims,n=s.length,i=s[n-2],o=t.k,a=t.n,c=s.slice(0,n-2),d=Le.size(c),u=e[1].dims[2]/4,f=e[0].dataType,M=as(t.k),v=as(u),k=as(a),A=c.concat([i,a]),R=i>1&&a/k%2===0?2:1,ee=Le.size(A)/k/R,W=64,V=[],se=[d,i,o/M],oe=Le.convertShape(e[1].dims).slice();oe.splice(-1,1,u/v),V.push(...Ct(se)),V.push(...Ct(oe)),V.push(...Ct(e[2].dims)),e.length===4&&V.push(...Ct(Le.convertShape(e[3].dims)));let Me=[d,i,a/k];V.push(...Ct(Me));let Ie=Ce=>{let Be=se.length,Ge=Ue("a",e[0].dataType,Be,M),rt=Ue("b",12,oe.length,v),St=Ue("scales",e[2].dataType,e[2].dims.length),Tt=[Ge,rt,St],ot=e.length===4?Ue("zero_points",12,e[3].dims.length):void 0;ot&&Tt.push(ot);let Dt=Me.length,zt=xt("output",e[0].dataType,Dt,k),Pt=cs(e[0].dataType),at=(()=>{switch(M){case 1:return`array<${Pt}, 8>`;case 2:return`mat4x2<${Pt}>`;case 4:return`mat2x4<${Pt}>`;default:throw new Error(`${M}-component is not supported.`)}})(),Zt=()=>{let Je=` + // reuse a data + var input_offset = ${Ge.indicesToOffset(`${Ge.type.indices}(batch, row, word_offset)`)}; + var a_data: ${at}; + for (var j: u32 = 0; j < ${8/M}; j++) { + a_data[j] = ${Ge.getByOffset("input_offset")}; + input_offset++; + } + `;for(let it=0;it> 4) & b_mask); + b_quantized_values = ${at}(${Array.from({length:4},(Ft,qt)=>`${Pt}(b_value_lower[${qt}]), ${Pt}(b_value_upper[${qt}])`).join(", ")}); + b_dequantized_values = ${M===1?`${at}(${Array.from({length:8},(Ft,qt)=>`(b_quantized_values[${qt}] - ${ot?`zero_point${it}`:"zero_point"}) * scale${it}`).join(", ")});`:`(b_quantized_values - ${at}(${Array(8).fill(`${ot?`zero_point${it}`:"zero_point"}`).join(",")})) * scale${it};`}; + workgroup_shared[local_id.x * ${R} + ${Math.floor(it/k)}]${k>1?`[${it%k}]`:""} += ${Array.from({length:8/M},(Ft,qt)=>`${M===1?`a_data[${qt}] * b_dequantized_values[${qt}]`:`dot(a_data[${qt}], b_dequantized_values[${qt}])`}`).join(" + ")}; + `;return Je},Rt=()=>{let Je=` + var col_index = col * ${k}; + ${ot?` + 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 = ${Pt}(8);`} + `;for(let it=0;it> 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 = ${ot.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${it} = ${Pt}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return Je},Gt=()=>{let Je=`col_index = col * ${k};`;for(let it=0;it; + var b_value_upper: vec4; + var b_quantized_values: ${at}; + var b_dequantized_values: ${at};`,Je};return` + var workgroup_shared: array<${zt.type.value}, ${R*W}>; + ${Ce.declareVariables(...Tt,zt)} + ${Ce.mainStart([W,1,1])} + let output_indices = ${zt.offsetToIndices(`(global_idx / ${W}) * ${R}`)}; + 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 * ${t.blockSize/M}; + ${Rt()} + for (var word: u32 = 0; word < ${u}; word += ${v}) { + ${Gt()} + for (var i: u32 = 0; i < ${v}; i++) { + ${Zt()} + word_offset += ${8/M}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${R}) { + var output_value: ${zt.type.value} = ${zt.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 += ${R}; + } + ${zt.setByIndices(`${zt.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${M};${v};${k};${R};${W}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:A,dataType:f}],dispatchGroup:{x:ee},programUniforms:V}),getShaderSource:Ie}},pd=(e,t)=>{let s=e[0].dims,n=s.length,i=s[n-2],o=t.k,a=t.n,c=s.slice(0,n-2),d=Le.size(c),u=e[1].dims[2]/4,f=e[0].dataType,M=as(t.k),v=as(u),k=c.concat([i,a]),A=128,R=a%8===0?8:a%4===0?4:1,ee=A/R,W=ee*v*8,V=W/M,se=W/t.blockSize,oe=Le.size(k)/R,Me=[],Ie=[d,i,o/M],Ce=Le.convertShape(e[1].dims).slice();Ce.splice(-1,1,u/v),Me.push(...Ct(Ie)),Me.push(...Ct(Ce)),Me.push(...Ct(e[2].dims)),e.length===4&&Me.push(...Ct(Le.convertShape(e[3].dims)));let Be=[d,i,a];Me.push(...Ct(Be));let Ge=rt=>{let St=Ie.length,Tt=Ue("a",e[0].dataType,St,M),ot=Ue("b",12,Ce.length,v),Dt=Ue("scales",e[2].dataType,e[2].dims.length),zt=[Tt,ot,Dt],Pt=e.length===4?Ue("zero_points",12,e[3].dims.length):void 0;Pt&&zt.push(Pt);let at=Be.length,Zt=xt("output",e[0].dataType,at),Rt=cs(e[0].dataType),Gt=()=>{switch(M){case 1:return` + let a_data0 = vec4<${Rt}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${Rt}>(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<${Rt}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${Rt}>(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(`${M}-component is not supported.`)}};return` + var sub_a: array<${Tt.type.value}, ${V}>; + var inter_results: array, ${R}>; + ${rt.declareVariables(...zt,Zt)} + ${rt.mainStart([ee,R,1])} + let output_indices = ${Zt.offsetToIndices(`workgroup_index * ${R}`)}; + 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) / ${se} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${V}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${V}; a_offset += ${A}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${Tt.getByIndices(`${Tt.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${Tt.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${se} + local_id.x; + ${Pt?` + 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 = ${Pt.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${Rt}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${Rt}(8);`} + let scale = ${Dt.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${ot.getByIndices(`${ot.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${t.blockSize/M}; + for (var i: u32 = 0; i < ${v}; i++) { + ${Gt()} + let b_value = ${v===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<${Rt}>(${Array.from({length:4},(Je,it)=>`${Rt}(b_value_lower[${it}]), ${Rt}(b_value_upper[${it}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${Rt}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(Je,it)=>`${`dot(a_data${it}, b_dequantized_values[${it}])`}`).join(" + ")}; + word_offset += ${8/M}; + } + workgroupBarrier(); + } + + if (local_idx < ${R}) { + var output_value: ${Zt.type.value} = ${Zt.type.value}(0); + for (var b = 0u; b < ${ee}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${Zt.setByIndices(`${Zt.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${M};${v};${ee};${R}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:k,dataType:f}],dispatchGroup:{x:oe},programUniforms:Me}),getShaderSource:Ge}},hd=(e,t)=>{ud(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(pd(e.inputs,t)):e.compute(Io(e.inputs,t))},Ao=e=>Lt(e)}),_d,Bn,md,fd,gd,wd,Fo,Rn,ip,op=_(()=>{It(),B(),Nt(),_d=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 t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Bn=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${Et("uniforms.pads",i,s)}; + if (k < 0) { + break; + } + if (k >= i32(${Et("uniforms.x_shape",i,t)})) { + break; + } + offset += k * i32(${Et("uniforms.x_strides",i,t)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + } + `},md=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${Et("uniforms.pads",i,s)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${Et("uniforms.x_shape",i,t)}) - 1); + k = k % _2n_1; + if(k >= i32(${Et("uniforms.x_shape",i,t)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${Et("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},fd=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${Et("uniforms.pads",i,s)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${Et("uniforms.x_shape",i,t)})) { + k = i32(${Et("uniforms.x_shape",i,t)}) - 1; + } + offset += k * i32(${Et("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},gd=(e,t,s)=>{let n="";for(let i=t-1;i>=0;--i)n+=` + k = i32(${e.indicesGet("indices",i)}) - ${Et("uniforms.pads",i,s)}; + if (k < 0) { + k += i32(${Et("uniforms.x_shape",i,t)}]); + } + if (k >= i32(${Et("uniforms.x_shape",i,t)})) { + k -= i32(${Et("uniforms.x_shape",i,t)}); + } + offset += k * i32(${Et("uniforms.x_strides",i,t)}); + `;return` + var offset = 0; + var k = 0; + ${n} + value = x[offset]; + `},wd=(e,t,s)=>{switch(s.mode){case 0:return Bn(e,t,s.pads.length);case 1:return md(e,t,s.pads.length);case 2:return fd(e,t,s.pads.length);case 3:return gd(e,t,s.pads.length);default:throw new Error("Invalid mode")}},Fo=(e,t)=>{let s=Le.padShape(e[0].dims.slice(),t.pads),n=e[0].dims,i=Le.size(s),o=[{type:12,data:i},{type:6,data:t.pads}],a=e.length>=3&&e[2].data;t.mode===0&&o.push({type:a?e[2].dataType:1,data:t.value}),o.push(...Ct(e[0].dims,s));let c=["rank"],d=u=>{let f=xt("output",e[0].dataType,s.length),M=Ue("x",e[0].dataType,n.length),v=M.type.value,k=wd(f,n.length,t),A=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&A.push({name:"constant_value",type:a?v:"f32"}),` + ${u.registerUniforms(A).declareVariables(M,f)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${f.offsetToIndices("global_idx")}; + + var value = ${v}(0); + ${k} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${a}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(Le.size(s)/64)},programUniforms:o}),getShaderSource:d}},Rn=(e,t)=>{if(e.length>1){let s=e[1].getBigInt64Array(),n=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,o=new Int32Array(2*i).fill(0);if(e.length>=4){let c=e[3].getBigInt64Array();for(let d=0;do[Number(d)]=Number(c));let a=[];return o.forEach(c=>a.push(c)),{mode:t.mode,value:n,pads:a}}else return t},ip=(e,t)=>{_d(e.inputs);let s=Rn(e.inputs,t);e.compute(Fo(e.inputs,s),{inputs:[0]})}}),pn,jn,Do,Oo,Nn,Md,yd,Vn,bd,ap,Lo,hn,vd,xd,zo,Un,Td,Ed,Pd,Bo=_(()=>{pt(),It(),B(),Nt(),pn=e=>{if(C.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},jn=(e,t,s)=>{let n=t.format==="NHWC",i=e.dims.slice();n&&i.splice(1,0,i.pop());let o=Object.hasOwnProperty.call(t,"dilations"),a=t.kernelShape.slice(),c=t.strides.slice(),d=o?t.dilations.slice():[],u=t.pads.slice();Or.adjustPoolAttributes(s,i,a,c,d,u);let f=Or.computePoolOutputShape(s,i,c,d,a,u,t.autoPad),M=Object.assign({},t);o?Object.assign(M,{kernelShape:a,strides:c,pads:u,dilations:d,cacheKey:t.cacheKey}):Object.assign(M,{kernelShape:a,strides:c,pads:u,cacheKey:t.cacheKey});let v=f.slice();return v.push(v.splice(1,1)[0]),[M,n?v:f]},Do=(e,t)=>{let s=t.format==="NHWC",n=Le.size(e),i=Le.size(t.kernelShape),o=[{type:12,data:n},{type:12,data:i}],a=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let c=t.kernelShape[t.kernelShape.length-1],d=t.strides[t.strides.length-1],u=t.pads[t.pads.length/2-1],f=t.pads[t.pads.length-1],M=!!(u+f);o.push({type:12,data:c},{type:12,data:d},{type:12,data:u},{type:12,data:f}),a.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let v=!1;if(t.kernelShape.length===2){let k=t.kernelShape[t.kernelShape.length-2],A=t.strides[t.strides.length-2],R=t.pads[t.pads.length/2-2],ee=t.pads[t.pads.length-2];v=!!(R+ee),o.push({type:12,data:k},{type:12,data:A},{type:12,data:R},{type:12,data:ee}),a.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[o,a,!0,M,v]}else{if(s)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let c=Le.computeStrides(t.kernelShape);o.push({type:12,data:c},{type:12,data:t.pads},{type:12,data:t.strides}),a.push({name:"kernelStrides",type:"u32",length:c.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let d=t.pads.reduce((u,f)=>u+f);return[o,a,!!d,!1,!1]}},Oo=(e,t,s,n,i,o,a,c,d,u,f,M)=>{let v=i.format==="NHWC",k=t.type.value,A=xt("output",t.type.tensor,n);if(i.kernelShape.length<=2){let R="",ee="",W="",V=s-(v?2:1);if(f?R=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${V}] = indices[${V}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${V}] < 0 || xIndices[${V}] + >= uniforms.x_shape[${V}]) { + pad++; + continue; + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${o} + }`:R=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${V}] = indices[${V}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${o} + }`,i.kernelShape.length===2){let se=s-(v?3:2);M?ee=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${se}] = indices[${se}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${se}] < 0 || xIndices[${se}] >= uniforms.x_shape[${se}]) { + pad += i32(uniforms.kw); + continue; + } + `:ee=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${se}] = indices[${se}] * uniforms.sh - uniforms.phStart + j; + `,W=` + } + `}return` + ${e.registerUniforms(d).declareVariables(t,A)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${A.offsetToIndices("global_idx")}; + var xIndices = ${A.offsetToIndices("global_idx")}; + + var value = ${k}(${c}); + var pad = 0; + ${ee} + ${R} + ${W} + ${a} + + output[global_idx] = value; + }`}else{if(v)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let R=i.kernelShape.length,ee=i.pads.length,W="";return u?W=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${o} + }`:W=` + } + let x_val = x[${t.indicesToOffset("xIndices")}]; + ${o} + `,` + ${e.registerUniforms(d).declareVariables(t,A)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${A.offsetToIndices("global_idx")}; + var xIndices = ${A.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${k}(${c}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${R-1}u; j++) { + offsets[j] = offset / ${Et("uniforms.kernelStrides","j",R)}; + offset -= offsets[j] * ${Et("uniforms.kernelStrides","j",R)}; + } + offsets[${R-1}] = offset; + + isPad = false; + for (var j = ${s-R}u; j < ${s}u; j++) { + xIndices[j] = indices[j] * ${Et("uniforms.strides",`j - ${s-R}u`,R)} + + offsets[j - ${s-R}u] - ${Et("uniforms.pads","j - 2u",ee)}; + ${W} + } + ${a} + + output[global_idx] = value; + }`}},Nn=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Md=e=>`${Nn(e)};${e.countIncludePad}`,yd=e=>`${Nn(e)};${e.storageOrder};${e.dilations}`,Vn=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}),bd=(e,t,s,n)=>{let[i,o]=jn(t,n,s),a=Ue("x",t.dataType,t.dims.length),c=a.type.value,d="value += x_val;",u="";i.countIncludePad?u+=`value /= ${c}(uniforms.kernelSize);`:u+=`value /= ${c}(i32(uniforms.kernelSize) - pad);`;let[f,M,v,k,A]=Do(o,i);f.push(...Ct(t.dims,o));let R=["rank"];return{name:e,shaderCache:{hint:`${n.cacheKey};${v};${k};${A}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Le.size(o)/64)},programUniforms:f}),getShaderSource:ee=>Oo(ee,a,t.dims.length,o.length,i,d,u,0,M,v,k,A)}},ap=e=>{let t=e.count_include_pad!==0,s=Vn(e);if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let n={countIncludePad:t,...s,cacheKey:""};return{...n,cacheKey:Md(n)}},Lo=(e,t)=>{pn(e.inputs),e.compute(bd("AveragePool",e.inputs[0],!1,t))},hn={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},vd=e=>{let t=e.format;return{format:t,...hn,cacheKey:t}},xd=(e,t)=>{pn(e.inputs),e.compute(bd("GlobalAveragePool",e.inputs[0],!0,t))},zo=(e,t,s,n)=>{let[i,o]=jn(t,n,s),a=` + value = max(x_val, value); + `,c="",d=Ue("x",t.dataType,t.dims.length),u=["rank"],[f,M,v,k,A]=Do(o,i);return f.push(...Ct(t.dims,o)),{name:e,shaderCache:{hint:`${n.cacheKey};${v};${k};${A}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:o,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(Le.size(o)/64)},programUniforms:f}),getShaderSource:R=>Oo(R,d,t.dims.length,o.length,i,a,c,t.dataType===10?-65504:-1e5,M,v,k,A)}},Un=(e,t)=>{pn(e.inputs),e.compute(zo("MaxPool",e.inputs[0],!1,t))},Td=e=>{let t=e.storage_order,s=e.dilations,n=Vn(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:t,dilations:s,...n,cacheKey:""};return{...i,cacheKey:yd(i)}},Ed=e=>{let t=e.format;return{format:t,...hn,cacheKey:t}},Pd=(e,t)=>{pn(e.inputs),e.compute(zo("GlobalMaxPool",e.inputs[0],!0,t))}}),Cd,$d,Sd,Wn,lp=_(()=>{It(),B(),Ht(),Nt(),Cd=(e,t)=>{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((s,n)=>s===e[2].dims[n]).reduce((s,n)=>s&&n,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.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((i,o)=>o===t.axis||i===e[0].dims[o]).reduce((i,o)=>i&&o,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let s=e[0].dims[t.axis],n=e[1].dims[t.axis];if(t.blockSizeMath.ceil(s/(n-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},$d=(e,t)=>{let s=Le.normalizeAxis(t.axis,e[0].dims.length),n=e[0].dataType,i=n===3,o=e[0].dims,a=e[1].dataType,c=Le.size(o),d=n===3||n===2,u=d?[Math.ceil(Le.size(e[0].dims)/4)]:e[0].dims,f=e[1].dims,M=e.length>2?e[2]:void 0,v=M?d?[Math.ceil(Le.size(M.dims)/4)]:M.dims:void 0,k=f.length===0||f.length===1&&f[0]===1,A=k===!1&&f.length===1,R=as(c),ee=k&&(!d||R===4),W=ee?R:1,V=ee&&!d?R:1,se=Ue("input",d?12:n,u.length,V),oe=Ue("scale",a,f.length),Me=M?Ue("zero_point",d?12:n,v.length):void 0,Ie=xt("output",a,o.length,W),Ce=[se,oe];Me&&Ce.push(Me);let Be=[u,f];M&&Be.push(v);let Ge=[{type:12,data:c/W},{type:12,data:s},{type:12,data:t.blockSize},...Ct(...Be,o)],rt=St=>{let Tt=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${St.registerUniforms(Tt).declareVariables(...Ce,Ie)} + ${St.mainStart()} + ${St.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${Ie.offsetToIndices("global_idx")}; + + // Set input x + ${d?` + let input = ${se.getByOffset("global_idx / 4")}; + let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${W===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${se.getByOffset("global_idx")};`}; + + // Set scale input + ${k?`let scale_value= ${oe.getByOffset("0")}`:A?` + let scale_index = ${Ie.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${oe.getByOffset("scale_index")};`:` + var scale_indices: ${oe.type.indices} = output_indices; + let index = ${oe.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${oe.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${oe.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${Me?k?d?` + let zero_point_input = ${Me.getByOffset("0")}; + let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${Me.getByOffset("0")}`:A?d?` + let zero_point_index = ${Ie.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${Me.getByOffset("zero_point_index / 4")}; + let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_index % 4]`:` + let zero_point_index = ${Ie.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${Me.getByOffset("zero_point_index")};`:d?` + let zero_point_offset = ${oe.indicesToOffset("scale_indices")}; + let zero_point_input = ${Me.getByOffset("zero_point_offset / 4")}; + let zero_point_vec = ${i?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"}; + let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${Me.getByIndices("scale_indices")};`:`let zero_point_value = ${d?i?"i32":"u32":se.type.value}(0);`}; + // Compute and write output + ${Ie.setByOffset("global_idx",`${Ie.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:Me?["rank","rank","rank"]:["rank","rank"]},getShaderSource:rt,getRunData:()=>({outputs:[{dims:o,dataType:a}],dispatchGroup:{x:Math.ceil(c/W/64),y:1,z:1},programUniforms:Ge})}},Sd=(e,t)=>{Cd(e.inputs,t),e.compute($d(e.inputs,t))},Wn=e=>Lt({axis:e.axis,blockSize:e.blockSize})}),kd,Id,Ad,cp=_(()=>{pt(),It(),Nt(),kd=(e,t,s)=>{let n=e===t,i=et&&s>0;if(n||i||o)throw new Error("Range these inputs' contents are invalid.")},Id=(e,t,s,n)=>{let i=Math.abs(Math.ceil((t-e)/s)),o=[i],a=i,c=[{type:12,data:a},{type:n,data:e},{type:n,data:s},...Ct(o)],d=u=>{let f=xt("output",n,o.length),M=f.type.value,v=[{name:"outputSize",type:"u32"},{name:"start",type:M},{name:"delta",type:M}];return` + ${u.registerUniforms(v).declareVariables(f)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${M}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${n}`},getShaderSource:d,getRunData:()=>({outputs:[{dims:o,dataType:n}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:c})}},Ad=e=>{let t=0,s=0,n=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],s=e.inputs[1].getInt32Array()[0],n=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],s=e.inputs[1].getFloat32Array()[0],n=e.inputs[2].getFloat32Array()[0]),C.webgpu.validateInputContent&&kd(t,s,n),e.compute(Id(t,s,n,e.inputs[0].dataType),{inputs:[]})}}),Fd,Ro,jo,Dd,Od,No,dp=_(()=>{It(),B(),Ht(),Nt(),Fd=(e,t,s,n)=>{if(e!=="none"&&n!=="i32"&&n!=="u32"&&n!=="f32")throw new Error(`Input ${n} is not supported with reduction ${e}.`);let i=`{ + var oldValue = 0; + loop { + let newValueF32 =`,o=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${t}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${t}=${s};`;case"add":return n==="i32"||n==="u32"?`atomicAdd(&${t}, bitcast<${n}>(${s}));`:` + ${i}bitcast<${n}>(oldValue) + (${s})${o}`;case"max":return n==="i32"||n==="u32"?`atomicMax(&${t}, bitcast<${n}>(${s}));`:` + ${i}max(bitcast(oldValue), (${s}))${o}`;case"min":return n==="i32"||n==="u32"?`atomicMin(&${t}, bitcast<${n}>(${s}));`:`${i}min(bitcast<${n}>(oldValue), (${s}))${o}`;case"mul":return`${i}(bitcast<${n}>(oldValue) * (${s}))${o}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Ro=(e,t)=>`${e===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[${t?"i - indices_start":"i"}]; + let dim_value = uniforms.output_shape[${t?"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));`,jo=(e,t,s)=>`for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * ${s?"global_idx":"idx"} + i]; + ${Fd(e.reduction,"output[data_offset + i]","value",t)} + }`,Dd=(e,t)=>{let s=e[0].dims,n=e[1].dims,i=s,o=1,a=Math.ceil(Le.size(n)/o),c=n[n.length-1],d=Le.sizeFromDimension(s,c),u=Le.sizeFromDimension(n,0)/c,f=[{type:12,data:a},{type:12,data:c},{type:12,data:d},...Ct(e[1].dims,e[2].dims,i)],M=v=>{let k=Ue("indices",e[1].dataType,e[1].dims.length),A=Ue("updates",e[2].dataType,e[2].dims.length,o),R=t.reduction!=="none"&&t.reduction!==""?aa("output",e[0].dataType,i.length):xt("output",e[0].dataType,i.length,o);return` + ${v.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(k,A,R)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var hasDuplicates = false; + if (${t.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 (${t.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); + ${Ro(s.length,!1)} + } + ${jo(t,R.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); + ${Ro(s.length,!0)} + } + ${jo(t,R.type.value,!0)} + }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:f}),getShaderSource:M}},Od=e=>Lt({reduction:e.reduction}),No=(e,t)=>{e.compute(Dd(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Ld,Vo,zd,Uo,Bd,Wo,Rd,Gn,jd,Nd,Vd,Ud,Go,Kn,Wd,Gd,Kd,Hd,qd,Hn,up=_(()=>{It(),B(),Ht(),Nt(),Ld=(e,t)=>{if(e.every(s=>s>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.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(t.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")}},Vo=(e,t,s)=>{t.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let n=new Array(s).fill(1);return t.forEach((i,o)=>n[i]=e[o]),n},zd=(e,t,s,n,i,o)=>{let[a,c,d]=s>10?[1,2,3]:[-1,e.length>1?1:-1,-1],u=e[0].dims.length;if(a>0&&e.length>a&&e[a].dims.length>0)e[a].getFloat32Array().forEach(f=>o.push(f));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(c>0&&e.length>c&&e[c].dims.length===1&&e[c].dims[0]>0){if(e[c].getFloat32Array().forEach(f=>n.push(f)),n.length!==0&&n.length!==u&&s>=18&&n.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Ld(n,t),t.axes.length>0&&Vo(n,t.axes,u).forEach((f,M)=>n[M]=f)}if(d>0&&e.length>d&&e[d].dims.length===1&&e[d].dims[0]>0&&(e[d].getBigInt64Array().forEach(f=>i.push(Number(f))),i.length!==0&&i.length!==u&&s>=18&&i.length!==t.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(t.axes.length>0){if(n.length!==0&&n.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(i.length!==0&&i.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof n<"u"&&typeof i<"u"&&n.length>0&&i.length>u)throw new Error("Resize requires only of scales or sizes to be specified")},Uo=(e,t,s,n)=>` + // 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}) * (${t}); + let whole = ${n}(big / (${s})); + let fract = ${n}(big % (${s})) / ${n}(${s}); + return whole + fract; +`,Bd=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return` + if (xScale < 1.0 || floor(xScale) != xScale) { + return ${t}(xResized) / ${t}(xScale); + } else { + ${Uo("xResized","lengthOriginal","lengthResized",t)} + } + `;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) { + return 0.0; + } else { + ${Uo("xResized","lengthOriginal - 1","lengthResized - 1",t)} + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${t}(roiStart) * ${t}(lengthOriginal - 1) + + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / + ${t}(lengthResized - 1); + } else { + return 0.5 * ${t}(roiStart + roiEnd) * ${t}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${t}xScale * ${t}(lengthResized); + const adjustment = ${t}(lengthResized) / outputWidth; + const center = ${t}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Wo=(e,t,s)=>`fn getNearestPixelFromOriginal(xOriginal: ${s}, isDownSample: bool) -> ${s} {`+(()=>{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(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Rd=(e,t,s)=>{let n=new Array(s).fill(0).concat(new Array(s).fill(1)),i=e.length===0?n:e.slice();return t.length>0?(t.forEach((o,a)=>{n[o]=i[a],n[a+s]=i[t.length+a]}),n):i},Gn=(e,t,s,n)=>{let i=[];if(s.length>0)if(n.length>0){if(e.forEach(o=>i.push(o)),Math.max(...n)>e.length)throw new Error("axes is out of bound");n.forEach((o,a)=>i[o]=s[a])}else s.forEach(o=>i.push(o));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((o,a)=>Math.round(o*t[a]))}return i},jd=(e,t,s)=>{let n=(()=>{switch(s.keepAspectRatioPolicy){case"not_larger":return s.axes.length>0?Math.min(...s.axes.map(o=>t[o]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return s.axes.length>0?Math.max(...s.axes.map(o=>t[o]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${s.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let i=e.slice();return s.axes.length>0?(s.axes.forEach(o=>t[o]=n),s.axes.forEach(o=>i[o]=Math.round(e[o]*t[o]))):(t.fill(n,0,t.length),i.forEach((o,a)=>i[a]=Math.round(o*t[a]))),i},Nd=(e,t,s,n,i)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${s.length}> { + var original_indices: array<${e.type.value}, ${s.length}>; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${Et("uniforms.scales","i",n)}; + var roi_low = ${Et("uniforms.roi","i",i)}; + var roi_hi = ${Et("uniforms.roi",`i + ${t.length}`,i)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${Et("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${Et("uniforms.output_shape","i",s.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,Vd=(e,t,s,n,i,o,a)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${n.length}; i++) { + var output_index = ${t.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${Et("uniforms.scales","i",i)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${Et("uniforms.roi","i",o)}; + var roi_hi = ${Et("uniforms.roi",`i + ${s.length}`,o)}; + var input_shape_i = ${Et("uniforms.input_shape","i",s.length)}; + var output_shape_i = ${Et("uniforms.output_shape","i",n.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${a} || (original_idx >= 0 && original_idx < ${t.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${t.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; + }`,Ud=(e,t)=>` + fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { + for (var i:u32 = 0; i < ${t.length}; i++) { + var input_index = ${e.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${Et("uniforms.input_shape","i",t.length)}) { + return false; + } + } + return true; + }`,Go=(e,t,s,n)=>e.rank>n?` + ${e.indicesSet("input_indices",t,"channel")}; + ${e.indicesSet("input_indices",s,"batch")}; +`:"",Kn=(e,t,s,n,i)=>{let[o,a,c,d]=s.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",a,`max(0, min(row, ${s[a]} - 1))`)}; + ${e.indicesSet("input_indices",c,`max(0, min(col, ${s[c]} - 1))`)}; + ${Go(e,d,o,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${t.type.indices}) -> ${u} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${u} = originalIndices[${a}]; + var col:${u} = originalIndices[${c}]; + ${n?`if (row < 0 || row > (${s[a]} - 1) || col < 0 || col > (${s[c]} - 1)) { + return ${i}; + }`:""}; + row = max(0, min(row, ${s[a]} - 1)); + col = max(0, min(col, ${s[c]} - 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 = ${s.length>2?`u32(originalIndices[${d}])`:"0"}; + var batch: u32 = ${s.length>2?`u32(originalIndices[${o}])`:"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); + }`},Wd=(e,t,s,n,i,o,a,c,d,u)=>{let f=s.length===2,[M,v]=f?[0,1]:[2,3],k=e.type.value,A=R=>{let ee=R===M?"row":"col";return` + fn ${ee}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${k} { + var output_index = ${t.indicesGet("output_indices",R)}; + var originalIdx: ${k} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[R]}, + ${n[R]}, ${s[R]}, ${o[R]}, ${o[R]} + ${s.length}); + var fractOriginalIdx: ${k} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${c} && (originalIdx < 0 || originalIdx > (${s[R]} - 1))) { + return ${d}; + } + var data: array<${k}, 4> = array<${k}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${ee}: ${k} = originalIdx + ${k}(i); + if (${ee} < 0 || ${ee} >= ${s[R]}) { + ${u?`coefs[i + 1] = 0.0; + continue;`:c?`return ${d};`:`${ee} = max(0, min(${ee}, ${s[R]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",R,`u32(${ee})`)}; + data[i + 1] = ${R===M?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${A(M)}; + ${A(v)}; + fn getCubicInterpolationCoefs(s: ${k}) -> array<${k}, 4> { + var absS = abs(s); + var coeffs: array<${k}, 4> = array<${k}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${k} = 1.0 - absS; + var twoMinusAbsS: ${k} = 2.0 - absS; + var onePlusAbsS: ${k} = 1.0 + absS; + coeffs[0] = ((${a} * onePlusAbsS - 5 * ${a}) * onePlusAbsS + 8 * ${a}) * onePlusAbsS - 4 * ${a}; + coeffs[1] = ((${a} + 2) * absS - (${a} + 3)) * absS * absS + 1; + coeffs[2] = ((${a} + 2) * oneMinusAbsS - (${a} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${a} * twoMinusAbsS - 5 * ${a}) * twoMinusAbsS + 8 * ${a}) * twoMinusAbsS - 4 * ${a}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${k}, 4>, coefs: array<${k}, 4>) -> ${k} { + var coefsSum: ${k} = 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: ${t.type.indices}) -> ${k} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},Gd=(e,t,s,n,i)=>{let[o,a,c,d,u]=s.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],f=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${f} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",a,`max(0, min(depth, ${s[a]} - 1))`)}; + ${e.indicesSet("input_indices",c,`max(0, min(height, ${s[c]} - 1))`)}; + ${e.indicesSet("input_indices",d,`max(0, min(width, ${s[d]} - 1))`)}; + ${Go(e,u,o,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${t.type.indices}) -> ${f} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${f} = originalIndices[${a}]; + var height:${f} = originalIndices[${c}]; + var width:${f} = originalIndices[${d}]; + ${n?`if (depth < 0 || depth > (${s[a]} - 1) || height < 0 || height > (${s[c]} - 1) || width < 0 || (width > ${s[d]} - 1)) { + return ${i}; + }`:""}; + + depth = max(0, min(depth, ${s[a]} - 1)); + height = max(0, min(height, ${s[c]} - 1)); + width = max(0, min(width, ${s[d]} - 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 = ${s.length>3?`u32(originalIndices[${u}])`:"0"}; + var batch: u32 = ${s.length>3?`u32(originalIndices[${o}])`:"0"}; + + var x111: ${f} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${f} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${f} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${f} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${f} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${f} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${f} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${f} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${f} = abs(depth - ${f}(depth1)); + var dx2: ${f} = abs(${f}(depth2) - depth); + var dy1: ${f} = abs(height - ${f}(height1)); + var dy2: ${f} = abs(${f}(height2) - height); + var dz1: ${f} = abs(width - ${f}(width1)); + var dz2: ${f} = abs(${f}(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); + }`},Kd=(e,t,s,n,i,o)=>{let a=e.dims,c=Rd(o,t.axes,a.length),d=Gn(a,n,i,t.axes),u=n.slice();n.length===0&&(u=a.map((V,se)=>V===0?1:d[se]/V),t.keepAspectRatioPolicy!=="stretch"&&(d=jd(a,u,t)));let f=xt("output",e.dataType,d.length),M=Ue("input",e.dataType,a.length),v=Le.size(d),k=a.length===d.length&&a.every((V,se)=>V===d[se]),A=t.coordinateTransformMode==="tf_crop_and_resize",R=t.extrapolationValue,ee=M.type.value,W=V=>` + ${k?"":` + ${Bd(t.coordinateTransformMode,ee)}; + ${(()=>{switch(t.mode){case"nearest":return` + ${Ud(M,a)}; + ${Wo(t.nearestMode,s,ee)}; + ${Vd(M,f,a,d,u.length,c.length,A)}; + `;case"linear":return` + ${Nd(f,a,d,u.length,c.length)}; + ${(()=>{if(a.length===2||a.length===4)return`${Kn(M,f,a,A,R)}`;if(a.length===3||a.length===5)return`${Gd(M,f,a,A,R)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(a.length===2||a.length===4)return`${Wd(M,f,a,d,u,c,t.cubicCoeffA,A,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${V.registerUniform("output_size","u32").registerUniform("scales","f32",u.length).registerUniform("roi","f32",c.length).declareVariables(M,f)} + ${V.mainStart()} + ${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${k?"output[global_idx] = input[global_idx];":` + let output_indices = ${f.offsetToIndices("global_idx")}; + var input_indices: ${M.type.indices}; + ${(()=>{switch(t.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${M.getByIndices("input_indices")}; + } else { + output[global_idx] = ${t.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${a.length===2||a.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${t.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${s}|${u.length>0?t.mode==="cubic"?u:u.length:""}|${i.length>0?i:""}|${c.length>0?c:""}|${k}|${t.mode==="nearest"?a.length:a}`,inputDependencies:["rank"]},getShaderSource:W,getRunData:()=>({outputs:[{dims:d,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:[{type:12,data:v},{type:1,data:u},{type:1,data:c},...Ct(a,d)]})}},Hd=e=>{let t=e.customDataBuffer;return new Uint32Array(t,t.byteOffset,1)[0]},qd=(e,t)=>{let s=[],n=[],i=[],o=Hd(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");zd(e.inputs,t,o,s,n,i),e.compute(Kd(e.inputs[0],t,o,s,n,i),{inputs:[0]})},Hn=e=>{let t=e.antialias,s=e.axes,n=e.coordinateTransformMode,i=e.cubicCoeffA,o=e.excludeOutside!==0,a=e.extrapolationValue,c=e.keepAspectRatioPolicy,d=e.mode,u=e.nearestMode===""?"simple":e.nearestMode;return Lt({antialias:t,axes:s,coordinateTransformMode:n,cubicCoeffA:i,excludeOutside:o,extrapolationValue:a,keepAspectRatioPolicy:c,mode:d,nearestMode:u})}}),Qd,Xd,Jt,kp=_(()=>{It(),B(),Nt(),Qd=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],s=e[1],n=e[2];if(t.dataType!==s.dataType||t.dataType!==n.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(s.dims.length!==3&&s.dims.length!==2)throw new Error("Skip must be 2D or 3D");let i=t.dims[t.dims.length-1],o=t.dims[t.dims.length-2];if(s.dims[s.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(s.dims[s.dims.length-2]!==o)throw new Error("Skip must have the same sequence length as input");if(n.dims.length!==1)throw new Error("Gamma must be 1D");if(n.dims[n.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let a=e[3];if(a.dims.length!==1)throw new Error("Beta must be 1D");if(a.dims[a.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let a=e[4];if(a.dims.length!==1)throw new Error("Bias must be 1D");if(a.dims[a.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},Xd=(e,t,s,n)=>{let i=t.simplified,o=e[0].dims,a=Le.size(o),c=o,d=a,u=o.slice(-1)[0],f=n?o.slice(0,-1).concat(1):[],M=!i&&e.length>3,v=e.length>4,k=n&&s>1,A=n&&s>2,R=s>3,ee=64,W=as(u),V=[{type:12,data:d},{type:12,data:W},{type:12,data:u},{type:1,data:t.epsilon}],se=Me=>{let Ie=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],Ce=[Ue("x",e[0].dataType,e[0].dims,W),Ue("skip",e[1].dataType,e[1].dims,W),Ue("gamma",e[2].dataType,e[2].dims,W)];M&&Ce.push(Ue("beta",e[3].dataType,e[3].dims,W)),v&&Ce.push(Ue("bias",e[4].dataType,e[4].dims,W)),Ce.push(xt("output",e[0].dataType,c,W)),k&&Ce.push(xt("mean_output",1,f)),A&&Ce.push(xt("inv_std_output",1,f)),R&&Ce.push(xt("input_skip_bias_sum",e[0].dataType,c,W));let Be=cs(e[0].dataType),Ge=cs(1,W);return` + + ${Me.registerUniforms(Ie).declareVariables(...Ce)} + var sum_shared : array<${Ge}, ${ee}>; + var sum_squared_shared : array<${Ge}, ${ee}>; + + ${Me.mainStart([ee,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${ee}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${ee}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${ee-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${v?"bias[offset1d + i]":Be+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${R?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${qr(Be,W,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${ee}; + for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) { + reduce_size = curr_size + (reduce_size & 1); + if (ix < curr_size) { + sum_shared[ix] += sum_shared[ix + reduce_size]; + sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size]; + } + workgroupBarrier(); + } + + let sum = sum_shared[0]; + let square_sum = sum_squared_shared[0]; + let mean = ${Qs("sum",W)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${Qs("square_sum",W)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); + ${k?"mean_output[global_idx] = mean;":""} + ${A?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${i?"":`- ${Be}(mean)`}) * + ${Be}(inv_std_dev) * gamma[offset1d + i] + ${M?"+ beta[offset1d + i]":""}; + } + }`},oe=[{dims:c,dataType:e[0].dataType}];return s>1&&oe.push({dims:f,dataType:1}),s>2&&oe.push({dims:f,dataType:1}),s>3&&oe.push({dims:o,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${W};${k};${A};${R}`,inputDependencies:e.map((Me,Ie)=>"type")},getShaderSource:se,getRunData:()=>({outputs:oe,dispatchGroup:{x:Math.ceil(d/u)},programUniforms:V})}},Jt=(e,t)=>{Qd(e.inputs);let s=[0];e.outputCount>1&&s.push(-3),e.outputCount>2&&s.push(-3),e.outputCount>3&&s.push(3),e.compute(Xd(e.inputs,t,e.outputCount,!1),{outputs:s})}}),pp,qn,hp,Qn,Jd,Yd,Zd,eu,tu=_(()=>{It(),B(),Ht(),Nt(),pp=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((s,n)=>{if(e[n+1].dataType!==6&&e[n+1].dataType!==7)throw new Error(`Input ${n} must be an array of int32 or int64`)})},qn=(e,t)=>{let s=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(n=>s.push(Number(n)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(n=>s.push(Number(n)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return s},hp=(e,t)=>{if(e.length>1){let s=qn(e,1),n=qn(e,2),i=qn(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),Lt({starts:s,ends:n,axes:i})}else return t},Qn=(e,t,s,n,i)=>{let o=e;return e<0&&(o+=s[n[t]]),i[t]<0?Math.max(0,Math.min(o,s[n[t]]-1)):Math.max(0,Math.min(o,s[n[t]]))},Jd=(e,t,s)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${s.length}; i >= 0; i--) { + let input_shape_i = ${Et("uniforms.input_shape","i",s.length)}; + let steps_i = ${Et("uniforms.steps","i",s.length)}; + let signs_i = ${Et("uniforms.signs","i",s.length)}; + let starts_i = ${Et("uniforms.starts","i",s.length)}; + var output_index = ${t.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; + }`,Yd=(e,t)=>{let s=e[0].dims,n=Le.size(s),i=t.axes.length>0?Le.normalizeAxes(t.axes,s.length):[...Array(s.length).keys()],o=qn(e,4);o.forEach(W=>W!==0||(()=>{throw new Error("step cannot be 0")})),o.length===0&&(o=Array(i.length).fill(1));let a=t.starts.map((W,V)=>Qn(W,V,s,i,o)),c=t.ends.map((W,V)=>Qn(W,V,s,i,o));if(i.length!==a.length||i.length!==c.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==s.length)for(let W=0;WMath.sign(W));o.forEach((W,V,se)=>{if(W<0){let oe=(c[V]-a[V])/W,Me=a[V],Ie=Me+oe*o[V];a[V]=Ie,c[V]=Me,se[V]=-W}});let u=s.slice(0);i.forEach((W,V)=>{u[W]=Math.ceil((c[W]-a[W])/o[W])});let f={dims:u,dataType:e[0].dataType},M=xt("output",e[0].dataType,u.length),v=Ue("input",e[0].dataType,e[0].dims.length),k=Le.size(u),A=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:a.length},{name:"signs",type:"i32",length:d.length},{name:"steps",type:"u32",length:o.length}],R=[{type:12,data:k},{type:12,data:a},{type:6,data:d},{type:12,data:o},...Ct(e[0].dims,u)],ee=W=>` + ${W.registerUniforms(A).declareVariables(v,M)} + ${Jd(v,M,s)} + ${W.mainStart()} + ${W.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${M.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${M.setByOffset("global_idx",v.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${d.length}_${a.length}_${o.length}`,inputDependencies:["rank"]},getShaderSource:ee,getRunData:()=>({outputs:[f],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:R})}},Zd=(e,t)=>{pp(e.inputs,t);let s=hp(e.inputs,t);e.compute(Yd(e.inputs,s),{inputs:[0]})},eu=e=>{let t=e.starts,s=e.ends,n=e.axes;return Lt({starts:t,ends:s,axes:n})}}),Ko,_p,su,ru,nu=_(()=>{It(),B(),Ht(),_r(),Nt(),Ko=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},_p=(e,t)=>{let s=e.inputs[0],n=s.dims,i=Le.size(n),o=n.length,a=Le.normalizeAxis(t.axis,o),c=aBe),u[a]=o-1,u[o-1]=a,d=e.compute(Ks(s,u),{inputs:[s],outputs:[-1]})[0]):d=s;let f=d.dims,M=f[o-1],v=i/M,k=as(M),A=M/k,R=64;v===1&&(R=256);let ee=(Ce,Be)=>Be===4?`max(max(${Ce}.x, ${Ce}.y), max(${Ce}.z, ${Ce}.w))`:Be===2?`max(${Ce}.x, ${Ce}.y)`:Be===3?`max(max(${Ce}.x, ${Ce}.y), ${Ce}.z)`:Ce,W=Ue("x",d.dataType,d.dims,k),V=xt("result",d.dataType,d.dims,k),se=W.type.value,oe=cs(d.dataType)==="f32"?`var threadMax = ${se}(-3.402823e+38f);`:`var threadMax = ${se}(-65504.0h);`,Me=Ce=>` + var rowMaxShared : ${se}; + var rowSumShared : ${se}; + var threadShared : array<${se}, ${R}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${se} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${se}) { + let index = row * row_stride + col; + result[index] = value; + } + ${Ce.registerUniform("packedCols","i32").declareVariables(W,V)} + ${Ce.mainStart(R)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${R}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${oe} + 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 = ${se}(${ee("threadShared[0]",k)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${se}(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 = ${se}(${Qs("threadShared[0]",k)}); + } + 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); + } + }`,Ie=e.compute({name:"Softmax",shaderCache:{hint:`${k};${R}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:f,dataType:d.dataType}],dispatchGroup:{x:v},programUniforms:[{type:6,data:A}]}),getShaderSource:Me},{inputs:[d],outputs:[c?-1:0]})[0];c&&e.compute(Ks(Ie,u),{inputs:[Ie]})},su=(e,t)=>{Ko(e.inputs),_p(e,t)},ru=e=>Lt({axis:e.axis})}),Ho,iu,mp,ou,au,fp=_(()=>{It(),B(),Nt(),Ho=e=>Array.from(e.getBigInt64Array(),Number),iu=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(Ho(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")},mp=(e,t)=>{let s=[];for(let n=0;n{let s=e[0].dims,n=t??Ho(e[1]),i=mp(s,n),o=Le.size(i),a=e[0].dataType,c=Ue("input",a,s.length),d=xt("output",a,i.length),u=f=>` + const inputShape = ${c.indices(...s)}; + ${f.registerUniform("output_size","u32").declareVariables(c,d)} + ${f.mainStart()} + ${f.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${d.offsetToIndices("global_idx")}; + var input_indices: ${c.type.indices}; + for (var i = 0; i < ${s.length}; i++) { + let input_dim_i = ${c.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${d.indicesGet("output_indices","i")} % input_dim_i; + + ${c.indicesSet("input_indices","i","input_dim_value")} + } + ${d.setByOffset("global_idx",c.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${n}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},...Ct(e[0].dims,i)]}),getShaderSource:u}},au=e=>{iu(e.inputs),e.compute(ou(e.inputs),{inputs:[0]})}}),Yr,lu,cu,gp=_(()=>{It(),B(),Nt(),Yr=(e,t,s,n,i)=>{let o=xt("output_data",i,s.length,4),a=Ue("a_data",t[1].dataType,t[1].dims.length,4),c=Ue("b_data",t[2].dataType,t[2].dims.length,4),d=Ue("c_data",t[0].dataType,t[0].dims.length,4),u,f=(M,v,k)=>`select(${v}, ${M}, ${k})`;if(!n)u=o.setByOffset("global_idx",f(a.getByOffset("global_idx"),c.getByOffset("global_idx"),d.getByOffset("global_idx")));else{let M=(v,k,A="")=>{let R=`a_data[index_a${k}][component_a${k}]`,ee=`b_data[index_b${k}][component_b${k}]`,W=`bool(c_data[index_c${k}] & (0xffu << (component_c${k} * 8)))`;return` + let output_indices${k} = ${o.offsetToIndices(`global_idx * 4u + ${k}u`)}; + let offset_a${k} = ${a.broadcastedIndicesToOffset(`output_indices${k}`,o)}; + let offset_b${k} = ${c.broadcastedIndicesToOffset(`output_indices${k}`,o)}; + let offset_c${k} = ${d.broadcastedIndicesToOffset(`output_indices${k}`,o)}; + let index_a${k} = offset_a${k} / 4u; + let index_b${k} = offset_b${k} / 4u; + let index_c${k} = offset_c${k} / 4u; + let component_a${k} = offset_a${k} % 4u; + let component_b${k} = offset_b${k} % 4u; + let component_c${k} = offset_c${k} % 4u; + ${v}[${k}] = ${A}(${f(R,ee,W)}); + `};i===9?u=` + var data = vec4(0); + ${M("data",0,"u32")} + ${M("data",1,"u32")} + ${M("data",2,"u32")} + ${M("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:u=` + ${M("output_data[global_idx]",0)} + ${M("output_data[global_idx]",1)} + ${M("output_data[global_idx]",2)} + ${M("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(d,a,c,o)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${u} + }`},lu=e=>{let t=e[1].dims,s=e[2].dims,n=e[0].dims,i=e[1].dataType,o=!(Le.areEqual(t,s)&&Le.areEqual(s,n)),a=t,c=Le.size(t);if(o){let u=Ws.calcShape(Ws.calcShape(t,s,!1),n,!1);if(!u)throw new Error("Can't perform where op on the given tensors");a=u,c=Le.size(a)}let d=Math.ceil(c/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:u=>Yr(u,e,a,o,i),getRunData:()=>({outputs:[{dims:a,dataType:i}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:d},...Ct(n,t,s,a)]})}},cu=e=>{e.compute(lu(e.inputs))}}),du,wp=_(()=>{ja(),xn(),Du(),Ja(),Cl(),Ou(),Lu(),Jl(),Vu(),Uu(),Wu(),Gu(),Ku(),Mc(),Hu(),Ec(),qu(),Qu(),Xu(),Ju(),Zu(),tp(),sp(),rp(),np(),qc(),op(),Bo(),lp(),cp(),dp(),Mi(),up(),td(),kp(),tu(),nu(),Zc(),fp(),_r(),Ri(),gp(),du=new Map([["Abs",[Pi]],["Acos",[Za]],["Acosh",[el]],["Add",[kl]],["ArgMax",[Ra,vi]],["ArgMin",[bi,vi]],["Asin",[Ci]],["Asinh",[tl]],["Atan",[sl]],["Atanh",[$i]],["Attention",[Ga]],["AveragePool",[Lo,ap]],["BatchNormalization",[qa]],["BiasAdd",[Xa]],["BiasSplitGelu",[Pl]],["Cast",[nl,rl]],["Ceil",[ol]],["Clip",[il]],["Concat",[jl,Nl]],["Conv",[co,oo]],["ConvTranspose",[sc,ho]],["Cos",[ki]],["Cosh",[al]],["CumSum",[rc,nc]],["DepthToSpace",[go,ac]],["DequantizeLinear",[Sd,Wn]],["Div",[Il]],["Einsum",[hc,_c]],["Elu",[Ii,on]],["Equal",[Ni]],["Erf",[ll]],["Exp",[Ai]],["Expand",[fc]],["FastGelu",[wc]],["Floor",[cl]],["FusedConv",[co,oo]],["Gather",[vc,vo]],["GatherElements",[To,Ac]],["GatherBlockQuantized",[$c,Sc]],["GatherND",[xc,Tc]],["Gelu",[dl]],["Gemm",[Lc,Oc]],["GlobalAveragePool",[xd,vd]],["GlobalMaxPool",[Pd,Ed]],["Greater",[Dl]],["GreaterOrEqual",[Ui]],["GridSample",[Uc,Wc]],["GroupQueryAttention",[id]],["HardSigmoid",[ml,Oi]],["InstanceNormalization",[ad]],["LayerNormalization",[So]],["LeakyRelu",[Fi,on]],["Less",[Ol]],["LessOrEqual",[Ll]],["Log",[vl]],["MatMul",[ko]],["MatMulNBits",[hd,Ao]],["MaxPool",[Un,Td]],["Mul",[Al]],["MultiHeadAttention",[Hc,Gc]],["Neg",[pl]],["Not",[ul]],["Pad",[ip]],["Pow",[Fl]],["QuickGelu",[Tl,on]],["Range",[Ad]],["Reciprocal",[Di]],["ReduceMin",[La]],["ReduceMean",[mi]],["ReduceMax",[Oa]],["ReduceSum",[za]],["ReduceProd",[gi]],["ReduceL1",[Fa]],["ReduceL2",[Da]],["ReduceLogSum",[wi]],["ReduceLogSumExp",[fi]],["ReduceSumSquare",[Ba]],["Relu",[hl]],["Resize",[qd,Hn]],["RotaryEmbedding",[Jr]],["ScatterND",[No,Od]],["Sigmoid",[_l]],["Sin",[fl]],["Sinh",[Li]],["Slice",[Zd,eu]],["SkipLayerNormalization",[Jt]],["Split",[Yc,Yu]],["Sqrt",[gl]],["Softmax",[su,ru]],["Sub",[Vi]],["Tan",[wl]],["Tanh",[Ml]],["ThresholdedRelu",[bl,on]],["Tile",[au]],["Transpose",[li,ha]],["Where",[cu]]])}),uu,Mp=_(()=>{pt(),ks(),Nt(),uu=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,s,n,i){ke(e.programInfo.name);let o=this.backend.device,a=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let c=[];for(let u of t)c.push({binding:c.length,resource:{buffer:u.buffer}});for(let u of s)c.push({binding:c.length,resource:{buffer:u.buffer}});i&&c.push({binding:c.length,resource:i});let d=o.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:c,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let u={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:d,dispatchGroup:n};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(u)}a.setPipeline(e.computePipeline),a.setBindGroup(0,d),a.dispatchWorkgroups(...n),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(),Ne(e.programInfo.name)}dispose(){}build(e,t){ke(e.name);let s=this.backend.device,n=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(u=>{s.features.has(u.feature)&&n.push(`enable ${u.extension};`)});let i=ca(t,this.backend.device.limits),o=e.getShaderSource(i),a=`${n.join(` +`)} +${i.additionalImplementations} +${o}`,c=s.createShaderModule({code:a,label:e.name});Ut("verbose",()=>`[WebGPU] ${e.name} shader code: ${a}`);let d=s.createComputePipeline({compute:{module:c,entryPoint:"main"},layout:"auto",label:e.name});return Ne(e.name),{programInfo:e,computePipeline:d,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,s=typeof e=="number"?1:e.y||1,n=typeof e=="number"?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=i&&s<=i&&n<=i)return[t,s,n];let o=t*s*n,a=Math.ceil(Math.sqrt(o));if(a>i){if(a=Math.ceil(Math.cbrt(o)),a>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[a,a,a]}else return[a,a,1]}}}),pu={};I(pu,{WebGpuBackend:()=>mu});var yp,hu,_u,mu,bp=_(()=>{pt(),It(),ks(),we(),hs(),wp(),Mp(),yp=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let s=[];for(let n=0;n{var i,o;let n=e.name;return(i=e.shaderCache)!=null&&i.hint&&(n+="["+e.shaderCache.hint+"]"),n+=":"+s+`:${yp(t,((o=e.shaderCache)==null?void 0:o.inputDependencies)??new Array(t.length).fill("dims"))}`,n},_u=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},mu=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,t){this.env=e;let s=[],n={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:s},i=o=>t.features.has(o)&&s.push(o)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups"),this.device=await t.requestDevice(n),this.adapterInfo=new _u(t.info||await t.requestAdapterInfo()),this.gpuDataManager=ys(this),this.programManager=new uu(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ft(e.logLevel,!!e.debug),this.device.onuncapturederror=o=>{o.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${o.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,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(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;ke(),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 n;let t=new BigUint64Array(e.getMappedRange()),s=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=k);let R=Number(k-this.queryTimeBase),ee=Number(A-this.queryTimeBase);if(!Number.isSafeInteger(R)||!Number.isSafeInteger(ee))throw new RangeError("incorrect timestamp range");if((n=this.env.webgpu.profiling)!=null&&n.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:M.map(W=>({dims:W.dims,dataType:zs(W.dataType)})),outputsMetadata:v.map(W=>({dims:W.dims,dataType:zs(W.dataType)})),kernelId:a,kernelType:d,kernelName:u,programName:f,startTime:R,endTime:ee});else{let W="";M.forEach((se,oe)=>{W+=`input[${oe}]: [${se.dims}] | ${zs(se.dataType)}, `});let V="";v.forEach((se,oe)=>{V+=`output[${oe}]: [${se.dims}] | ${zs(se.dataType)}, `}),console.log(`[profiling] kernel "${a}|${d}|${u}|${f}" ${W}${V}execution time: ${ee-R} ns`)}Ee("GPU",`${f}::${k}::${A}`)}e.unmap(),this.pendingQueries.delete(e)}),Ne()}run(e,t,s,n,i,o){ke(e.name);let a=[];for(let V=0;Vse):s;if(f.length!==c.length)throw new Error(`Output size ${f.length} must be equal to ${c.length}.`);let M=[],v=[];for(let V=0;V=o)throw new Error(`Invalid output index: ${f[V]}`);if(f[V]===-3)continue;let se=f[V]===-1,oe=f[V]===-2,Me=se||oe?i(c[V].dataType,c[V].dims):n(f[V],c[V].dataType,c[V].dims);if(M.push(Me),Me.data===0)continue;let Ie=this.gpuDataManager.get(Me.data);if(!Ie)throw new Error(`no GPU data for output: ${Me.data}`);if(se&&this.temporaryData.push(Ie),oe){let Ce=this.kernelPersistentData.get(this.currentKernelId);Ce||(Ce=[],this.kernelPersistentData.set(this.currentKernelId,Ce)),Ce.push(Ie)}v.push(Ie)}if(a.length!==t.length||v.length!==M.length){if(v.length===0)return Ne(e.name),M;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let k;if(u){let V=0,se=[];u.forEach(Ce=>{let Be=typeof Ce.data=="number"?[Ce.data]:Ce.data;if(Be.length===0)return;let Ge=Ce.type===10?2:4,rt,St;Ce.type===10?(St=Be.length>4?16:Be.length>2?8:Be.length*Ge,rt=Be.length>4?16:Ge*Be.length):(St=Be.length<=2?Be.length*Ge:16,rt=16),V=Math.ceil(V/St)*St,se.push(V);let Tt=Ce.type===10?8:4;V+=Be.length>4?Math.ceil(Be.length/Tt)*rt:Be.length*Ge});let oe=16;V=Math.ceil(V/oe)*oe;let Me=new ArrayBuffer(V);u.forEach((Ce,Be)=>{let Ge=se[Be],rt=typeof Ce.data=="number"?[Ce.data]:Ce.data;if(Ce.type===6)new Int32Array(Me,Ge,rt.length).set(rt);else if(Ce.type===12)new Uint32Array(Me,Ge,rt.length).set(rt);else if(Ce.type===10)new Uint16Array(Me,Ge,rt.length).set(rt);else if(Ce.type===1)new Float32Array(Me,Ge,rt.length).set(rt);else throw new Error(`Unsupported uniform type: ${zs(Ce.type)}`)});let Ie=this.gpuDataManager.create(V,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ie.buffer,0,Me,0,V),this.gpuDataManager.release(Ie.id),k={offset:0,size:V,buffer:Ie.buffer}}let A=this.programManager.normalizeDispatchGroupSize(d),R=A[1]===1&&A[2]===1,ee=hu(e,t,R),W=this.programManager.getArtifact(ee);if(W||(W=this.programManager.build(e,A),this.programManager.setArtifact(ee,W),Ut("info",()=>`[artifact] key: ${ee}, 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 V=0;V`[ProgramManager] run "${e.name}" (key=${ee}) with ${A[0]}x${A[1]}x${A[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let V={kernelId:this.currentKernelId,programName:W.programInfo.name,inputTensorViews:t,outputTensorViews:M};this.pendingKernels.push(V),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(V)}return this.programManager.run(W,a,v,A,k),Ne(e.name),M}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,s,n){let i=du.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let o={kernelType:e,kernelName:n,kernelEntry:i[0],attributes:[i[1],s]};this.kernels.set(t,o)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let s of t)this.gpuDataManager.release(s.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,s){let n=this.kernels.get(e);if(!n)throw new Error(`kernel not created: ${e}`);let i=n.kernelType,o=n.kernelName,a=n.kernelEntry,c=n.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${o}" is not allowed to be called recursively`);this.currentKernelId=e,c[0]&&(c[1]=c[0](c[1]),c[0]=void 0),Ut("info",()=>`[WebGPU] Start to run kernel "[${i}] ${o}"...`);let d=this.env.debug;this.temporaryData=[];try{return d&&this.device.pushErrorScope("validation"),a(t,c[1]),0}catch(u){return s.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${o}" failed. ${u}`)),1}finally{d&&s.push(this.device.popErrorScope().then(u=>u?`GPU validation error for kernel "[${i}] ${o}": ${u.message}`:null));for(let u of this.temporaryData)this.gpuDataManager.release(u.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,s,n){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let o=i.get(t),a=this.gpuDataManager.registerExternalBuffer(s,n,o);return i.set(t,[a,s]),a}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(s=>this.gpuDataManager.unregisterExternalBuffer(s[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,s){return async()=>{let n=await vs(this,e,t);return ne(n.buffer,s)}}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(){Ut("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(){Ut("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Ut("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),s=e.length;this.pendingKernels=[];for(let n=0;n=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()}}}),fu={};I(fu,{init:()=>gu});var Xn,vp,gu,wu=_(()=>{It(),ks(),B(),hr(),Xn=class Np{constructor(t,s,n,i){this.module=t,this.dataType=s,this.data=n,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=Le.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=Le.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=Le.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=Le.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(Le.size(t)!==Le.size(this.dims))throw new Error("Invalid new shape");return new Np(this.module,this.dataType,this.data,t)}},vp=class{constructor(e,t,s){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let n=e.PTR_SIZE,i=s/e.PTR_SIZE,o=n===4?"i32":"i64";this.opKernelContext=Number(e.getValue(n*i++,o));let a=Number(e.getValue(n*i++,o));this.outputCount=Number(e.getValue(n*i++,o)),this.customDataOffset=Number(e.getValue(n*i++,"*")),this.customDataSize=Number(e.getValue(n*i++,o));let c=[];for(let d=0;dtypeof c=="number"?this.inputs[c]:c))??this.inputs,n=(t==null?void 0:t.outputs)??[],i=(c,d,u)=>new Xn(this.module,d,this.output(c,u),u),o=(c,d)=>{let u=Us(c,d);if(!u)throw new Error(`Unsupported data type: ${c}`);let f=u>0?this.backend.gpuDataManager.create(u).id:0;return new Xn(this.module,c,f,d)};return this.backend.run(e,s,n,i,o,this.outputCount)}output(e,t){let s=this.module.stackSave();try{let n=this.module.PTR_SIZE,i=n===4?"i32":"i64",o=this.module.stackAlloc((1+t.length)*n);this.module.setValue(o,t.length,i);for(let a=0;a{let i=t.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let o=(bp(),b(pu)).WebGpuBackend,a=new o;await a.initialize(s,n),i("webgpu",[a,c=>a.alloc(Number(c)),c=>a.free(c),(c,d,u,f=!1)=>{if(f)Ut("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(c)}, dst=${Number(d)}, size=${Number(u)}`),a.memcpy(Number(c),Number(d));else{Ut("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(c)}, gpuDataId=${Number(d)}, size=${Number(u)}`);let M=t.HEAPU8.subarray(Number(c>>>0),Number(c>>>0)+Number(u));a.upload(Number(d),M)}},async(c,d,u)=>{Ut("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${c}, dataOffset=${d}, size=${u}`),await a.download(Number(c),()=>t.HEAPU8.subarray(Number(d)>>>0,Number(d+u)>>>0))},(c,d,u)=>a.createKernel(c,Number(d),u,t.UTF8ToString(t._JsepGetNodeName(Number(d)))),c=>a.releaseKernel(c),(c,d,u,f)=>{Ut("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${u}, kernel=${c}, contextDataOffset=${d}`);let M=new vp(t,a,Number(d));return a.computeKernel(Number(c),M,f)},()=>a.captureBegin(),()=>a.captureEnd(),()=>a.replay()])}else{let o=new As(s);i("webnn",[o,()=>o.reserveTensorId(),a=>o.releaseTensorId(a),async(a,c,d,u,f)=>o.ensureTensor(a,c,d,u,f),(a,c)=>{o.uploadTensor(a,c)},async(a,c)=>o.downloadTensor(a,c)])}}}),Mu,qo,Qo,Pr,yu,Xo,Jn,Jo,Yo,Zo,ea,ta,sa,bu=_(()=>{ss(),Ar(),It(),_t(),bt(),Zs(),Mu=(e,t)=>{ze()._OrtInit(e,t)!==0&&mt("Can't initialize onnxruntime.")},qo=async e=>{Mu(e.wasm.numThreads,Ps(e.logLevel))},Qo=async(e,t)=>{var s,n;(n=(s=ze()).asyncInit)==null||n.call(s);{let i=(wu(),b(fu)).init;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let o=e.webgpu.adapter;if(o){if(typeof o.limits!="object"||typeof o.features!="object"||typeof o.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let a=e.webgpu.powerPreference;if(a!==void 0&&a!=="low-power"&&a!=="high-performance")throw new Error(`Invalid powerPreference setting: "${a}"`);let c=e.webgpu.forceFallbackAdapter;if(c!==void 0&&typeof c!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${c}"`);if(o=await navigator.gpu.requestAdapter({powerPreference:a,forceFallbackAdapter:c}),!o)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await i("webgpu",ze(),e,o)}if(t==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await i("webnn",ze(),e)}}},Pr=new Map,yu=e=>{let t=ze(),s=t.stackSave();try{let n=t.PTR_SIZE,i=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,i,i+n)!==0&&mt("Can't get session input/output count.");let o=n===4?"i32":"i64";return[Number(t.getValue(i,o)),Number(t.getValue(i+n,o))]}finally{t.stackRestore(s)}},Xo=(e,t)=>{let s=ze(),n=s.stackSave(),i=0;try{let o=s.PTR_SIZE,a=s.stackAlloc(2*o);s._OrtGetInputOutputMetadata(e,t,a,a+o)!==0&&mt("Can't get session input/output metadata.");let c=Number(s.getValue(a,"*"));i=Number(s.getValue(a+o,"*"));let d=s.HEAP32[i/4];if(d===0)return[c,0];let u=s.HEAPU32[i/4+1],f=[];for(let M=0;M{let t=ze(),s=t._malloc(e.byteLength);if(s===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,s),[s,e.byteLength]},Jo=async(e,t)=>{var M,v,k,A;let s,n,i=ze();Array.isArray(e)?[s,n]=e:e.buffer===i.HEAPU8.buffer?[s,n]=[e.byteOffset,e.byteLength]:[s,n]=Jn(e);let o=0,a=0,c=0,d=[],u=[],f=[];try{if([a,d]=await qs(t),(t==null?void 0:t.externalData)&&i.mountExternalData){let Be=[];for(let Ge of t.externalData){let rt=typeof Ge=="string"?Ge:Ge.path;Be.push(pr(typeof Ge=="string"?Ge:Ge.data).then(St=>{i.mountExternalData(rt,St)}))}await Promise.all(Be)}for(let Be of(t==null?void 0:t.executionProviders)??[])if((typeof Be=="string"?Be:Be.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof Be!="string"){let Ge=Be,rt=Ge==null?void 0:Ge.context,St=Ge==null?void 0:Ge.gpuDevice,Tt=Ge==null?void 0:Ge.deviceType,ot=Ge==null?void 0:Ge.powerPreference;rt?i.currentContext=rt:St?i.currentContext=await i.webnnCreateMLContext(St):i.currentContext=await i.webnnCreateMLContext({deviceType:Tt,powerPreference:ot})}else i.currentContext=await i.webnnCreateMLContext();break}o=await i._OrtCreateSession(s,n,a),(M=i.webgpuOnCreateSession)==null||M.call(i,o),o===0&&mt("Can't create a session."),(v=i.jsepOnCreateSession)==null||v.call(i),i.currentContext&&(i.webnnRegisterMLContext(o,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[R,ee]=yu(o),W=!!(t!=null&&t.enableGraphCapture),V=[],se=[],oe=[],Me=[],Ie=[];for(let Be=0;BeBe==="gpu-buffer"||Be==="ml-tensor")&&(c=i._OrtCreateBinding(o),c===0&&mt("Can't create IO binding."),Ce={handle:c,outputPreferredLocations:Ie,outputPreferredLocationsEncoded:Ie.map(Be=>br(Be))}),Pr.set(o,[o,u,f,Ce,W,!1]),[o,V,se,oe,Me]}catch(R){throw u.forEach(ee=>i._OrtFree(ee)),f.forEach(ee=>i._OrtFree(ee)),c!==0&&i._OrtReleaseBinding(c)!==0&&mt("Can't release IO binding."),o!==0&&i._OrtReleaseSession(o)!==0&&mt("Can't release session."),R}finally{i._free(s),a!==0&&i._OrtReleaseSessionOptions(a)!==0&&mt("Can't release session options."),d.forEach(R=>i._free(R)),(A=i.unmountExternalData)==null||A.call(i)}},Yo=e=>{var d,u,f;let t=ze(),s=Pr.get(e);if(!s)throw new Error(`cannot release session. invalid session id: ${e}`);let[n,i,o,a,c]=s;a&&(c&&t._OrtClearBoundOutputs(a.handle)!==0&&mt("Can't clear bound outputs."),t._OrtReleaseBinding(a.handle)!==0&&mt("Can't release IO binding.")),(d=t.jsepOnReleaseSession)==null||d.call(t,e),(u=t.webnnOnReleaseSession)==null||u.call(t,e),(f=t.webgpuOnReleaseSession)==null||f.call(t,e),i.forEach(M=>t._OrtFree(M)),o.forEach(M=>t._OrtFree(M)),t._OrtReleaseSession(n)!==0&&mt("Can't release session."),Pr.delete(e)},Zo=async(e,t,s,n,i,o,a=!1)=>{if(!e){t.push(0);return}let c=ze(),d=c.PTR_SIZE,u=e[0],f=e[1],M=e[3],v=M,k,A;if(u==="string"&&(M==="gpu-buffer"||M==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(a&&M!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${o} when enableGraphCapture is true.`);if(M==="gpu-buffer"){let W=e[2].gpuBuffer;A=Us(Vs(u),f);{let V=c.jsepRegisterBuffer;if(!V)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');k=V(n,o,W,A)}}else if(M==="ml-tensor"){let W=e[2].mlTensor;A=Us(Vs(u),f);let V=c.webnnRegisterMLTensor;if(!V)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');k=V(n,W,Vs(u),f)}else{let W=e[2];if(Array.isArray(W)){A=d*W.length,k=c._malloc(A),s.push(k);for(let V=0;Vc.setValue(ee+se*d,V,d===4?"i32":"i64"));let W=c._OrtCreateTensor(Vs(u),k,A,ee,f.length,br(v));W===0&&mt(`Can't create tensor for input/output. session=${n}, index=${o}.`),t.push(W)}finally{c.stackRestore(R)}},ea=async(e,t,s,n,i,o)=>{var St,Tt,ot,Dt;let a=ze(),c=a.PTR_SIZE,d=Pr.get(e);if(!d)throw new Error(`cannot run inference. invalid session id: ${e}`);let u=d[0],f=d[1],M=d[2],v=d[3],k=d[4],A=d[5],R=t.length,ee=n.length,W=0,V=[],se=[],oe=[],Me=[],Ie=a.stackSave(),Ce=a.stackAlloc(R*c),Be=a.stackAlloc(R*c),Ge=a.stackAlloc(ee*c),rt=a.stackAlloc(ee*c);try{[W,V]=Yt(o);for(let at=0;atOs*ls,1);it=zs(Ds);let oa=v==null?void 0:v.outputPreferredLocations[n[at]];if(it==="string"){if(oa==="gpu-buffer"||oa==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Os=[];for(let ls=0;ls0){let Os=a.jsepGetBuffer;if(!Os)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let ls=Os(Ft),Ss=Us(Ds,tn);if(Ss===void 0||!Ys(it))throw new Error(`Unsupported data type: ${it}`);Je=!0,Pt.push([it,fr,{gpuBuffer:ls,download:a.jsepCreateDownloader(ls,Ss,it),dispose:()=>{a._OrtReleaseTensor(Zt)!==0&&mt("Can't release tensor.")}},"gpu-buffer"])}else if(oa==="ml-tensor"&&tn>0){let Os=a.webnnEnsureTensor,ls=a.webnnIsInt64Supported;if(!Os||!ls)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Us(Ds,tn)===void 0||!ur(it))throw new Error(`Unsupported data type: ${it}`);if(it==="int64"&&!ls(e))throw new Error('preferredLocation "ml-tensor" for int64 output is not supported by current WebNN Context.');let Ss=await Os(e,Ft,Ds,fr,!1);Je=!0,Pt.push([it,fr,{mlTensor:Ss,download:a.webnnCreateMLTensorDownloader(Ft,it),dispose:()=>{a.webnnReleaseTensorId(Ft),a._OrtReleaseTensor(Zt)}},"ml-tensor"])}else{let Os=yr(it),ls=new Os(tn);new Uint8Array(ls.buffer,ls.byteOffset,ls.byteLength).set(a.HEAPU8.subarray(Ft,Ft+ls.byteLength)),Pt.push([it,fr,ls,"cpu"])}}finally{a.stackRestore(Rt),it==="string"&&Ft&&a._free(Ft),Je||a._OrtReleaseTensor(Zt),(Dt=a.webnnOnRunEnd)==null||Dt.call(a,u)}}return v&&!k&&(a._OrtClearBoundOutputs(v.handle)!==0&&mt("Can't clear bound outputs."),Pr.set(e,[u,f,M,v,k,!1])),Pt}finally{a.stackRestore(Ie),se.forEach(zt=>a._OrtReleaseTensor(zt)),oe.forEach(zt=>a._OrtReleaseTensor(zt)),Me.forEach(zt=>a._free(zt)),W!==0&&a._OrtReleaseRunOptions(W),V.forEach(zt=>a._free(zt))}},ta=e=>{let t=ze(),s=Pr.get(e);if(!s)throw new Error("invalid session id");let n=s[0],i=t._OrtEndProfiling(n);i===0&&mt("Can't get an profile file name."),t._OrtFree(i)},sa=e=>{let t=[];for(let s of e){let n=s[2];!Array.isArray(n)&&"buffer"in n&&t.push(n.buffer)}return t}}),Cr,js,Zr,_n,mn,Yn,ra,Zn,Vr,Ur,vu,xu,Tu,Eu,Pu,Cu,xp,Bt,$u=_(()=>{pt(),bu(),_t(),wr(),Cr=()=>!!C.wasm.proxy&&typeof document<"u",Zr=!1,_n=!1,mn=!1,Zn=new Map,Vr=(e,t)=>{let s=Zn.get(e);s?s.push(t):Zn.set(e,[t])},Ur=()=>{if(Zr||!_n||mn||!js)throw new Error("worker not ready")},vu=e=>{switch(e.data.type){case"init-wasm":Zr=!1,e.data.err?(mn=!0,ra[1](e.data.err)):(_n=!0,ra[0]()),Yn&&(URL.revokeObjectURL(Yn),Yn=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Zn.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}}},xu=async()=>{if(!_n){if(Zr)throw new Error("multiple calls to 'initWasm()' detected.");if(mn)throw new Error("previous call to 'initWasm()' failed.");if(Zr=!0,Cr())return new Promise((e,t)=>{js==null||js.terminate(),Kr().then(([s,n])=>{try{js=n,js.onerror=o=>t(o),js.onmessage=vu,ra=[e,t];let i={type:"init-wasm",in:C};if(!i.in.wasm.wasmPaths&&s){let o=Ls();o&&(i.in.wasm.wasmPaths=o)}js.postMessage(i),Yn=s}catch(i){t(i)}},t)});try{await Se(C.wasm),await qo(C),_n=!0}catch(e){throw mn=!0,e}finally{Zr=!1}}},Tu=async e=>{if(Cr())return Ur(),new Promise((t,s)=>{Vr("init-ep",[t,s]);let n={type:"init-ep",in:{epName:e,env:C}};js.postMessage(n)});await Qo(C,e)},Eu=async e=>Cr()?(Ur(),new Promise((t,s)=>{Vr("copy-from",[t,s]);let n={type:"copy-from",in:{buffer:e}};js.postMessage(n,[e.buffer])})):Jn(e),Pu=async(e,t)=>{if(Cr()){if(t!=null&&t.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ur(),new Promise((s,n)=>{Vr("create",[s,n]);let i={type:"create",in:{model:e,options:{...t}}},o=[];e instanceof Uint8Array&&o.push(e.buffer),js.postMessage(i,o)})}else return Jo(e,t)},Cu=async e=>{if(Cr())return Ur(),new Promise((t,s)=>{Vr("release",[t,s]);let n={type:"release",in:e};js.postMessage(n)});Yo(e)},xp=async(e,t,s,n,i,o)=>{if(Cr()){if(s.some(a=>a[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(a=>a))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ur(),new Promise((a,c)=>{Vr("run",[a,c]);let d=s,u={type:"run",in:{sessionId:e,inputIndices:t,inputs:d,outputIndices:n,options:o}};js.postMessage(u,sa(d))})}else return ea(e,t,s,n,i,o)},Bt=async e=>{if(Cr())return Ur(),new Promise((t,s)=>{Vr("end-profiling",[t,s]);let n={type:"end-profiling",in:e};js.postMessage(n)});ta(e)}}),_s,Ms,xs,en=_(()=>{pt(),$u(),It(),yt(),Zs(),_s=(e,t)=>{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 ${t()}`)}},Ms=e=>{switch(e[3]){case"cpu":return new We(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!Ys(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:s,download:n,dispose:i}=e[2];return We.fromGpuBuffer(s,{dataType:t,dims:e[1],download:n,dispose:i})}case"ml-tensor":{let t=e[0];if(!ur(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:s,download:n,dispose:i}=e[2];return We.fromMLTensor(s,{dataType:t,dims:e[1],download:n,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},xs=class{async fetchModelAndCopyToWasmMemory(e){return Eu(await pr(e))}async loadModel(e,t){ke();let s;typeof e=="string"?s=await this.fetchModelAndCopyToWasmMemory(e):s=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Pu(s,t),Ne()}async dispose(){return Cu(this.sessionId)}async run(e,t,s){ke();let n=[],i=[];Object.entries(e).forEach(M=>{let v=M[0],k=M[1],A=this.inputNames.indexOf(v);if(A===-1)throw new Error(`invalid input '${v}'`);n.push(k),i.push(A)});let o=[],a=[];Object.entries(t).forEach(M=>{let v=M[0],k=M[1],A=this.outputNames.indexOf(v);if(A===-1)throw new Error(`invalid output '${v}'`);o.push(k),a.push(A)});let c=n.map((M,v)=>_s(M,()=>`input "${this.inputNames[i[v]]}"`)),d=o.map((M,v)=>M?_s(M,()=>`output "${this.outputNames[a[v]]}"`):null),u=await xp(this.sessionId,i,c,a,d,s),f={};for(let M=0;Mia,initializeFlags:()=>na,wasmBackend:()=>p});var na,ia,p,g=_(()=>{pt(),$u(),en(),na=()=>{(typeof C.wasm.initTimeout!="number"||C.wasm.initTimeout<0)&&(C.wasm.initTimeout=0);let e=C.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.`),C.wasm.simd=!1),typeof C.wasm.proxy!="boolean"&&(C.wasm.proxy=!1),typeof C.wasm.trace!="boolean"&&(C.wasm.trace=!1),typeof C.wasm.numThreads!="number"||!Number.isInteger(C.wasm.numThreads)||C.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)C.wasm.numThreads=1;else{let t=typeof navigator>"u"?$("node:os").cpus().length:navigator.hardwareConcurrency;C.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},ia=class{async init(e){na(),await xu(),await Tu(e)}async createInferenceSessionHandler(e,t){let s=new xs;return await s.loadModel(e,t),s}},p=new ia}),F={};I(F,{InferenceSession:()=>Ae,TRACE:()=>Ee,TRACE_FUNC_BEGIN:()=>ke,TRACE_FUNC_END:()=>Ne,Tensor:()=>We,default:()=>$e,env:()=>C,registerBackend:()=>z}),pt(),pt(),pt();var _e="1.22.0-dev.20250409-89f8206ba4",$e=lt;{let e=(g(),b(Tp)).wasmBackend;z("webgpu",e,5),z("webnn",e,5),z("cpu",e,10),z("wasm",e,10)}return Object.defineProperty(C.versions,"web",{value:_e,enumerable:!0}),b(F)})();/** + * @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. + * ============================================================================= + */ae.exports=r})(Op);var Lp=Op.exports,ih=nh(Lp),oh=Wr({__proto__:null,default:ih},[Lp]),ah={"onnxruntime-common":ae=>{ae.exports=rh},"onnxruntime-web":ae=>{ae.exports=oh},"?2ce3":()=>{},"?7992":()=>{},"?5af5":()=>{},"?2b25":()=>{},"?db59":()=>{},"?383f":()=>{},"?fa4b":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(ae,m,r)=>{r.r(m),r.d(m,{Environment:()=>ct,Interpreter:()=>vt,Template:()=>dr,parse:()=>Xe,tokenize:()=>D});var w=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Comment:"Comment"}),T=class{constructor(y,te){this.value=y,this.type=te}};function L(y){return/\w/.test(y)}function H(y){return/[0-9]/.test(y)}var $=[["{%",w.OpenStatement],["%}",w.CloseStatement],["{{",w.OpenExpression],["}}",w.CloseExpression],["(",w.OpenParen],[")",w.CloseParen],["{",w.OpenCurlyBracket],["}",w.CloseCurlyBracket],["[",w.OpenSquareBracket],["]",w.CloseSquareBracket],[",",w.Comma],[".",w.Dot],[":",w.Colon],["|",w.Pipe],["<=",w.ComparisonBinaryOperator],[">=",w.ComparisonBinaryOperator],["==",w.ComparisonBinaryOperator],["!=",w.ComparisonBinaryOperator],["<",w.ComparisonBinaryOperator],[">",w.ComparisonBinaryOperator],["+",w.AdditiveBinaryOperator],["-",w.AdditiveBinaryOperator],["~",w.AdditiveBinaryOperator],["*",w.MultiplicativeBinaryOperator],["/",w.MultiplicativeBinaryOperator],["%",w.MultiplicativeBinaryOperator],["=",w.Equals]],_=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function I(y,te={}){return y.endsWith(` +`)&&(y=y.slice(0,-1)),te.lstrip_blocks&&(y=y.replace(/^[ \t]*({[#%-])/gm,"$1")),te.trim_blocks&&(y=y.replace(/([#%-]})\n/g,"$1")),y.replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{").replace(/-#}\s*/g,"#}").replace(/\s*{#-/g,"{#").replace(/{%\s*(end)?generation\s*%}/gs,"")}function D(y,te={}){var _t,$t;const N=[],Z=I(y,te);let ue=0,Se=0;const ze=kt=>{let mt="";for(;kt(Z[ue]);){if(Z[ue]==="\\"){if(++ue,ue>=Z.length)throw new SyntaxError("Unexpected end of input");const bt=Z[ue++],Yt=_.get(bt);if(Yt===void 0)throw new SyntaxError(`Unexpected escaped character: ${bt}`);mt+=Yt;continue}if(mt+=Z[ue++],ue>=Z.length)throw new SyntaxError("Unexpected end of input")}return mt};e:for(;ue0){N.push(new T(bt,w.Text));continue}}if(Z[ue]==="{"&&Z[ue+1]==="#"){ue+=2;let bt="";for(;Z[ue]!=="#"||Z[ue+1]!=="}";){if(ue+2>=Z.length)throw new SyntaxError("Missing end of comment tag");bt+=Z[ue++]}N.push(new T(bt,w.Comment)),ue+=2;continue}ze(bt=>/\s/.test(bt));const mt=Z[ue];if(mt==="-"||mt==="+"){const bt=($t=N.at(-1))==null?void 0:$t.type;if(bt===w.Text||bt===void 0)throw new SyntaxError(`Unexpected character: ${mt}`);switch(bt){case w.Identifier:case w.NumericLiteral:case w.StringLiteral:case w.CloseParen:case w.CloseSquareBracket:break;default:{++ue;const Yt=ze(H);N.push(new T(`${mt}${Yt}`,Yt.length>0?w.NumericLiteral:w.UnaryOperator));continue}}}for(const[bt,Yt]of $){if(bt==="}}"&&Se>0)continue;if(Z.slice(ue,ue+bt.length)===bt){N.push(new T(bt,Yt)),Yt===w.OpenExpression?Se=0:Yt===w.OpenCurlyBracket?++Se:Yt===w.CloseCurlyBracket&&--Se,ue+=bt.length;continue e}}if(mt==="'"||mt==='"'){++ue;const bt=ze(Yt=>Yt!==mt);N.push(new T(bt,w.StringLiteral)),++ue;continue}if(H(mt)){let bt=ze(H);if(Z[ue]==="."&&H(Z[ue+1])){++ue;const Yt=ze(H);bt=`${bt}.${Yt}`}N.push(new T(bt,w.NumericLiteral));continue}if(L(mt)){const bt=ze(L);N.push(new T(bt,w.Identifier));continue}throw new SyntaxError(`Unexpected character: ${mt}`)}return N}var b=class{constructor(){ie(this,"type","Statement")}},h=class extends b{constructor(te){super();ie(this,"type","Program");this.body=te}},U=class extends b{constructor(te,N,Z){super();ie(this,"type","If");this.test=te,this.body=N,this.alternate=Z}},z=class extends b{constructor(te,N,Z,ue){super();ie(this,"type","For");this.loopvar=te,this.iterable=N,this.body=Z,this.defaultBlock=ue}},Q=class extends b{constructor(){super(...arguments);ie(this,"type","Break")}},ge=class extends b{constructor(){super(...arguments);ie(this,"type","Continue")}},j=class extends b{constructor(te,N,Z){super();ie(this,"type","Set");this.assignee=te,this.value=N,this.body=Z}},G=class extends b{constructor(te,N,Z){super();ie(this,"type","Macro");this.name=te,this.args=N,this.body=Z}},Y=class extends b{constructor(te){super();ie(this,"type","Comment");this.value=te}},O=class extends b{constructor(){super(...arguments);ie(this,"type","Expression")}},S=class extends O{constructor(te,N,Z){super();ie(this,"type","MemberExpression");this.object=te,this.property=N,this.computed=Z}},E=class extends O{constructor(te,N){super();ie(this,"type","CallExpression");this.callee=te,this.args=N}},x=class extends O{constructor(te){super();ie(this,"type","Identifier");this.value=te}},C=class extends O{constructor(te){super();ie(this,"type","Literal");this.value=te}},re=class extends C{constructor(){super(...arguments);ie(this,"type","IntegerLiteral")}},q=class extends C{constructor(){super(...arguments);ie(this,"type","FloatLiteral")}},pe=class extends C{constructor(){super(...arguments);ie(this,"type","StringLiteral")}},me=class extends C{constructor(){super(...arguments);ie(this,"type","ArrayLiteral")}},J=class extends C{constructor(){super(...arguments);ie(this,"type","TupleLiteral")}},fe=class extends C{constructor(){super(...arguments);ie(this,"type","ObjectLiteral")}},de=class extends O{constructor(te,N,Z){super();ie(this,"type","BinaryExpression");this.operator=te,this.left=N,this.right=Z}},Te=class extends O{constructor(te,N){super();ie(this,"type","FilterExpression");this.operand=te,this.filter=N}},Pe=class extends b{constructor(te,N){super();ie(this,"type","FilterStatement");this.filter=te,this.body=N}},be=class extends O{constructor(te,N){super();ie(this,"type","SelectExpression");this.lhs=te,this.test=N}},He=class extends O{constructor(te,N,Z){super();ie(this,"type","TestExpression");this.operand=te,this.negate=N,this.test=Z}},Oe=class extends O{constructor(te,N){super();ie(this,"type","UnaryExpression");this.operator=te,this.argument=N}},he=class extends O{constructor(te=void 0,N=void 0,Z=void 0){super();ie(this,"type","SliceExpression");this.start=te,this.stop=N,this.step=Z}},K=class extends O{constructor(te,N){super();ie(this,"type","KeywordArgumentExpression");this.key=te,this.value=N}},ce=class extends O{constructor(te){super();ie(this,"type","SpreadExpression");this.argument=te}},ye=class extends b{constructor(te,N,Z){super();ie(this,"type","CallStatement");this.call=te,this.callerArgs=N,this.body=Z}},Fe=class extends O{constructor(te,N,Z){super();ie(this,"type","Ternary");this.condition=te,this.trueExpr=N,this.falseExpr=Z}};function Xe(y){const te=new h([]);let N=0;function Z(Ze,tt){const ft=y[N++];if(!ft||ft.type!==Ze)throw new Error(`Parser Error: ${tt}. ${ft.type} !== ${Ze}.`);return ft}function ue(Ze){if(!$t(Ze))throw new SyntaxError(`Expected ${Ze}`);++N}function Se(){switch(y[N].type){case w.Comment:return new Y(y[N++].value);case w.Text:return kt();case w.OpenStatement:return mt();case w.OpenExpression:return bt();default:throw new SyntaxError(`Unexpected token type: ${y[N].type}`)}}function ze(...Ze){return N+Ze.length<=y.length&&Ze.every((tt,ft)=>tt===y[N+ft].type)}function _t(...Ze){var tt,ft,ns;return((tt=y[N])==null?void 0:tt.type)===w.OpenStatement&&((ft=y[N+1])==null?void 0:ft.type)===w.Identifier&&Ze.includes((ns=y[N+1])==null?void 0:ns.value)}function $t(...Ze){return N+Ze.length<=y.length&&Ze.every((tt,ft)=>y[N+ft].type==="Identifier"&&tt===y[N+ft].value)}function kt(){return new pe(Z(w.Text,"Expected text token").value)}function mt(){if(Z(w.OpenStatement,"Expected opening statement token"),y[N].type!==w.Identifier)throw new SyntaxError(`Unknown statement, got ${y[N].type}`);const Ze=y[N].value;let tt;switch(Ze){case"set":++N,tt=Yt();break;case"if":++N,tt=ss(),Z(w.OpenStatement,"Expected {% token"),ue("endif"),Z(w.CloseStatement,"Expected %} token");break;case"macro":++N,tt=Ns(),Z(w.OpenStatement,"Expected {% token"),ue("endmacro"),Z(w.CloseStatement,"Expected %} token");break;case"for":++N,tt=Es(),Z(w.OpenStatement,"Expected {% token"),ue("endfor"),Z(w.CloseStatement,"Expected %} token");break;case"call":{++N;let ft=null;ze(w.OpenParen)&&(ft=Ys());const ns=Bs();if(ns.type!=="Identifier")throw new SyntaxError("Expected identifier following call statement");const Ut=Ys();Z(w.CloseStatement,"Expected closing statement token");const ks=[];for(;!_t("endcall");)ks.push(Se());Z(w.OpenStatement,"Expected '{%'"),ue("endcall"),Z(w.CloseStatement,"Expected closing statement token");const Dr=new E(ns,Ut);tt=new ye(Dr,ft,ks);break}case"break":++N,Z(w.CloseStatement,"Expected closing statement token"),tt=new Q;break;case"continue":++N,Z(w.CloseStatement,"Expected closing statement token"),tt=new ge;break;case"filter":{++N;let ft=Bs();ft instanceof x&&ze(w.OpenParen)&&(ft=Ps(ft)),Z(w.CloseStatement,"Expected closing statement token");const ns=[];for(;!_t("endfilter");)ns.push(Se());Z(w.OpenStatement,"Expected '{%'"),ue("endfilter"),Z(w.CloseStatement,"Expected '%}'"),tt=new Pe(ft,ns);break}default:throw new SyntaxError(`Unknown statement type: ${Ze}`)}return tt}function bt(){Z(w.OpenExpression,"Expected opening expression token");const Ze=ms();return Z(w.CloseExpression,"Expected closing expression token"),Ze}function Yt(){const Ze=Hs();let tt=null;const ft=[];if(ze(w.Equals))++N,tt=Hs();else{for(Z(w.CloseStatement,"Expected %} token");!_t("endset");)ft.push(Se());Z(w.OpenStatement,"Expected {% token"),ue("endset")}return Z(w.CloseStatement,"Expected closing statement token"),new j(Ze,tt,ft)}function ss(){const Ze=ms();Z(w.CloseStatement,"Expected closing statement token");const tt=[],ft=[];for(;!_t("elif","else","endif");)tt.push(Se());if(_t("elif")){++N,++N;const ns=ss();ft.push(ns)}else if(_t("else"))for(++N,++N,Z(w.CloseStatement,"Expected closing statement token");!_t("endif");)ft.push(Se());return new U(Ze,tt,ft)}function Ns(){const Ze=Bs();if(Ze.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const tt=Ys();Z(w.CloseStatement,"Expected closing statement token");const ft=[];for(;!_t("endmacro");)ft.push(Se());return new G(Ze,tt,ft)}function Hs(Ze=!1){const tt=Ze?Bs:ms,ft=[tt()],ns=ze(w.Comma);for(;ns&&(++N,ft.push(tt()),!!ze(w.Comma)););return ns?new J(ft):ft[0]}function Es(){const Ze=Hs(!0);if(!(Ze instanceof x||Ze instanceof J))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Ze.type} instead`);if(!$t("in"))throw new SyntaxError("Expected `in` keyword following loop variable");++N;const tt=ms();Z(w.CloseStatement,"Expected closing statement token");const ft=[];for(;!_t("endfor","else");)ft.push(Se());const ns=[];if(_t("else"))for(++N,++N,Z(w.CloseStatement,"Expected closing statement token");!_t("endfor");)ns.push(Se());return new z(Ze,tt,ft,ns)}function ms(){return Mr()}function Mr(){const Ze=qs();if($t("if")){++N;const tt=qs();if($t("else")){++N;const ft=Mr();return new Fe(tt,Ze,ft)}else return new be(Ze,tt)}return Ze}function qs(){let Ze=Ar();for(;$t("or");){const tt=y[N];++N;const ft=Ar();Ze=new de(tt,Ze,ft)}return Ze}function Ar(){let Ze=Vs();for(;$t("and");){const tt=y[N];++N;const ft=Vs();Ze=new de(tt,Ze,ft)}return Ze}function Vs(){let Ze;for(;$t("not");){const tt=y[N];++N;const ft=Vs();Ze=new Oe(tt,ft)}return Ze??zs()}function zs(){let Ze=Us();for(;;){let tt;if($t("not","in"))tt=new T("not in",w.Identifier),N+=2;else if($t("in"))tt=y[N++];else if(ze(w.ComparisonBinaryOperator))tt=y[N++];else break;const ft=Us();Ze=new de(tt,Ze,ft)}return Ze}function Us(){let Ze=pr();for(;ze(w.AdditiveBinaryOperator);){const tt=y[N];++N;const ft=pr();Ze=new de(tt,Ze,ft)}return Ze}function yr(){const Ze=It(Bs());return ze(w.OpenParen)?Ps(Ze):Ze}function Ps(Ze){let tt=new E(Ze,Ys());return tt=It(tt),ze(w.OpenParen)&&(tt=Ps(tt)),tt}function Ys(){Z(w.OpenParen,"Expected opening parenthesis for arguments list");const Ze=ur();return Z(w.CloseParen,"Expected closing parenthesis for arguments list"),Ze}function ur(){const Ze=[];for(;!ze(w.CloseParen);){let tt;if(y[N].type===w.MultiplicativeBinaryOperator&&y[N].value==="*"){++N;const ft=ms();tt=new ce(ft)}else if(tt=ms(),ze(w.Equals)){if(++N,!(tt instanceof x))throw new SyntaxError("Expected identifier for keyword argument");const ft=ms();tt=new K(tt,ft)}Ze.push(tt),ze(w.Comma)&&++N}return Ze}function br(){const Ze=[];let tt=!1;for(;!ze(w.CloseSquareBracket);)ze(w.Colon)?(Ze.push(void 0),++N,tt=!0):(Ze.push(ms()),ze(w.Colon)&&(++N,tt=!0));if(Ze.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(tt){if(Ze.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new he(...Ze)}return Ze[0]}function It(Ze){for(;ze(w.Dot)||ze(w.OpenSquareBracket);){const tt=y[N];++N;let ft;const ns=tt.type===w.OpenSquareBracket;if(ns)ft=br(),Z(w.CloseSquareBracket,"Expected closing square bracket");else if(ft=Bs(),ft.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Ze=new S(Ze,ft,ns)}return Ze}function pr(){let Ze=Zs();for(;ze(w.MultiplicativeBinaryOperator);){const tt=y[N++],ft=Zs();Ze=new de(tt,Ze,ft)}return Ze}function Zs(){let Ze=Fr();for(;$t("is");){++N;const tt=$t("not");tt&&++N;const ft=Bs();if(!(ft instanceof x))throw new SyntaxError("Expected identifier for the test");Ze=new He(Ze,tt,ft)}return Ze}function Fr(){let Ze=yr();for(;ze(w.Pipe);){++N;let tt=Bs();if(!(tt instanceof x))throw new SyntaxError("Expected identifier for the filter");ze(w.OpenParen)&&(tt=Ps(tt)),Ze=new Te(Ze,tt)}return Ze}function Bs(){const Ze=y[N++];switch(Ze.type){case w.NumericLiteral:{const tt=Ze.value;return tt.includes(".")?new q(Number(tt)):new re(Number(tt))}case w.StringLiteral:{let tt=Ze.value;for(;ze(w.StringLiteral);)tt+=y[N++].value;return new pe(tt)}case w.Identifier:return new x(Ze.value);case w.OpenParen:{const tt=Hs();return Z(w.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),tt}case w.OpenSquareBracket:{const tt=[];for(;!ze(w.CloseSquareBracket);)tt.push(ms()),ze(w.Comma)&&++N;return++N,new me(tt)}case w.OpenCurlyBracket:{const tt=new Map;for(;!ze(w.CloseCurlyBracket);){const ft=ms();Z(w.Colon,"Expected colon between key and value in object literal");const ns=ms();tt.set(ft,ns),ze(w.Comma)&&++N}return++N,new fe(tt)}default:throw new SyntaxError(`Unexpected token: ${Ze.type}`)}}for(;N=0?(te=(te??(te=0))<0?Math.max(y.length+te,0):Math.min(te,y.length),N=(N??(N=y.length))<0?Math.max(y.length+N,0):Math.min(N,y.length)):(te=(te??(te=y.length-1))<0?Math.max(y.length+te,-1):Math.min(te,y.length-1),N=(N??(N=-1))<-1?Math.max(y.length+N,-1):Math.min(N,y.length-1));const Se=[];for(let ze=te;ue*zete.toUpperCase())}function We(y){return le(new Date,y)}function le(y,te){const N=new Intl.DateTimeFormat(void 0,{month:"long"}),Z=new Intl.DateTimeFormat(void 0,{month:"short"}),ue=Se=>Se<10?"0"+Se:Se.toString();return te.replace(/%[YmdbBHM%]/g,Se=>{switch(Se){case"%Y":return y.getFullYear().toString();case"%m":return ue(y.getMonth()+1);case"%d":return ue(y.getDate());case"%b":return Z.format(y);case"%B":return N.format(y);case"%H":return ue(y.getHours());case"%M":return ue(y.getMinutes());case"%%":return"%";default:return Se}})}function Ee(y){return y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function X(y,te,N,Z){if(Z===0)return y;let ue=Z==null||Z<0?1/0:Z;const Se=te.length===0?new RegExp("(?=)","gu"):new RegExp(Ee(te),"gu");return y.replaceAll(Se,ze=>ue>0?(--ue,N):ze)}var ke=class extends Error{},Ne=class extends Error{},Ve=class{constructor(y=void 0){ie(this,"type","RuntimeValue");ie(this,"value");ie(this,"builtins",new Map);this.value=y}__bool__(){return new qe(!!this.value)}toString(){return String(this.value)}},De=class extends Ve{constructor(){super(...arguments);ie(this,"type","IntegerValue")}},Ke=class extends Ve{constructor(){super(...arguments);ie(this,"type","FloatValue")}toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},Ae=class extends Ve{constructor(){super(...arguments);ie(this,"type","StringValue");ie(this,"builtins",new Map([["upper",new lt(()=>new Ae(this.value.toUpperCase()))],["lower",new lt(()=>new Ae(this.value.toLowerCase()))],["strip",new lt(()=>new Ae(this.value.trim()))],["title",new lt(()=>new Ae(wt(this.value)))],["capitalize",new lt(()=>new Ae(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],["length",new De(this.value.length)],["rstrip",new lt(()=>new Ae(this.value.trimEnd()))],["lstrip",new lt(()=>new Ae(this.value.trimStart()))],["startswith",new lt(te=>{if(te.length===0)throw new Error("startswith() requires at least one argument");const N=te[0];if(N instanceof Ae)return new qe(this.value.startsWith(N.value));if(N instanceof Re){for(const Z of N.value){if(!(Z instanceof Ae))throw new Error("startswith() tuple elements must be strings");if(this.value.startsWith(Z.value))return new qe(!0)}return new qe(!1)}throw new Error("startswith() argument must be a string or tuple of strings")})],["endswith",new lt(te=>{if(te.length===0)throw new Error("endswith() requires at least one argument");const N=te[0];if(N instanceof Ae)return new qe(this.value.endsWith(N.value));if(N instanceof Re){for(const Z of N.value){if(!(Z instanceof Ae))throw new Error("endswith() tuple elements must be strings");if(this.value.endsWith(Z.value))return new qe(!0)}return new qe(!1)}throw new Error("endswith() argument must be a string or tuple of strings")})],["split",new lt(te=>{const N=te[0]??new pt;if(!(N instanceof Ae||N instanceof pt))throw new Error("sep argument must be a string or null");const Z=te[1]??new De(-1);if(!(Z instanceof De))throw new Error("maxsplit argument must be a number");let ue=[];if(N instanceof pt){const Se=this.value.trimStart();for(const{0:ze,index:_t}of Se.matchAll(/\S+/g)){if(Z.value!==-1&&ue.length>=Z.value&&_t!==void 0){ue.push(ze+Se.slice(_t+ze.length));break}ue.push(ze)}}else{if(N.value==="")throw new Error("empty separator");ue=this.value.split(N.value),Z.value!==-1&&ue.length>Z.value&&ue.push(ue.splice(Z.value).join(N.value))}return new Re(ue.map(Se=>new Ae(Se)))})],["replace",new lt(te=>{if(te.length<2)throw new Error("replace() requires at least two arguments");const N=te[0],Z=te[1];if(!(N instanceof Ae&&Z instanceof Ae))throw new Error("replace() arguments must be strings");let ue;if(te.length>2?te[2].type==="KeywordArgumentsValue"?ue=te[2].value.get("count")??new pt:ue=te[2]:ue=new pt,!(ue instanceof De||ue instanceof pt))throw new Error("replace() count argument must be a number or null");return new Ae(X(this.value,N.value,Z.value,ue.value))})]]))}},qe=class extends Ve{constructor(){super(...arguments);ie(this,"type","BooleanValue")}},et=class extends Ve{constructor(){super(...arguments);ie(this,"type","ObjectValue");ie(this,"builtins",new Map([["get",new lt(([te,N])=>{if(!(te instanceof Ae))throw new Error(`Object key must be a string: got ${te.type}`);return this.value.get(te.value)??N??new pt})],["items",new lt(()=>this.items())],["keys",new lt(()=>this.keys())],["values",new lt(()=>this.values())]]))}__bool__(){return new qe(this.value.size>0)}items(){return new Re(Array.from(this.value.entries()).map(([te,N])=>new Re([new Ae(te),N])))}keys(){return new Re(Array.from(this.value.keys()).map(te=>new Ae(te)))}values(){return new Re(Array.from(this.value.values()))}},ut=class extends et{constructor(){super(...arguments);ie(this,"type","KeywordArgumentsValue")}},Re=class extends Ve{constructor(){super(...arguments);ie(this,"type","ArrayValue");ie(this,"builtins",new Map([["length",new De(this.value.length)]]))}__bool__(){return new qe(this.value.length>0)}},Mt=class extends Re{constructor(){super(...arguments);ie(this,"type","TupleValue")}},lt=class extends Ve{constructor(){super(...arguments);ie(this,"type","FunctionValue")}},pt=class extends Ve{constructor(){super(...arguments);ie(this,"type","NullValue")}},yt=class extends Ve{constructor(){super(...arguments);ie(this,"type","UndefinedValue")}},ct=class{constructor(y){ie(this,"variables",new Map([["namespace",new lt(y=>{if(y.length===0)return new et(new Map);if(y.length!==1||!(y[0]instanceof et))throw new Error("`namespace` expects either zero arguments or a single object argument");return y[0]})]]));ie(this,"tests",new Map([["boolean",y=>y.type==="BooleanValue"],["callable",y=>y instanceof lt],["odd",y=>{if(!(y instanceof De))throw new Error(`cannot odd on ${y.type}`);return y.value%2!==0}],["even",y=>{if(!(y instanceof De))throw new Error(`cannot even on ${y.type}`);return y.value%2===0}],["false",y=>y.type==="BooleanValue"&&!y.value],["true",y=>y.type==="BooleanValue"&&y.value],["none",y=>y.type==="NullValue"],["string",y=>y.type==="StringValue"],["number",y=>y instanceof De||y instanceof Ke],["integer",y=>y instanceof De],["iterable",y=>y.type==="ArrayValue"||y.type==="StringValue"],["mapping",y=>y.type==="ObjectValue"],["lower",y=>{const te=y.value;return y.type==="StringValue"&&te===te.toLowerCase()}],["upper",y=>{const te=y.value;return y.type==="StringValue"&&te===te.toUpperCase()}],["none",y=>y.type==="NullValue"],["defined",y=>y.type!=="UndefinedValue"],["undefined",y=>y.type==="UndefinedValue"],["equalto",(y,te)=>y.value===te.value],["eq",(y,te)=>y.value===te.value]]));this.parent=y}set(y,te){return this.declareVariable(y,Wt(te))}declareVariable(y,te){if(this.variables.has(y))throw new SyntaxError(`Variable already declared: ${y}`);return this.variables.set(y,te),te}setVariable(y,te){return this.variables.set(y,te),te}resolve(y){if(this.variables.has(y))return this;if(this.parent)return this.parent.resolve(y);throw new Error(`Unknown variable: ${y}`)}lookupVariable(y){try{return this.resolve(y).variables.get(y)??new yt}catch{return new yt}}};function ht(y){y.set("false",!1),y.set("true",!0),y.set("none",null),y.set("raise_exception",te=>{throw new Error(te)}),y.set("range",Qe),y.set("strftime_now",We),y.set("True",!0),y.set("False",!1),y.set("None",null)}var vt=class{constructor(y){ie(this,"global");this.global=y??new ct}run(y){return this.evaluate(y,this.global)}evaluateBinaryExpression(y,te){const N=this.evaluate(y.left,te);switch(y.operator.value){case"and":return N.__bool__().value?this.evaluate(y.right,te):N;case"or":return N.__bool__().value?N:this.evaluate(y.right,te)}const Z=this.evaluate(y.right,te);switch(y.operator.value){case"==":return new qe(N.value==Z.value);case"!=":return new qe(N.value!=Z.value)}if(N instanceof yt||Z instanceof yt){if(Z instanceof yt&&["in","not in"].includes(y.operator.value))return new qe(y.operator.value==="not in");throw new Error(`Cannot perform operation ${y.operator.value} on undefined values`)}else{if(N instanceof pt||Z instanceof pt)throw new Error("Cannot perform operation on null values");if(y.operator.value==="~")return new Ae(N.value.toString()+Z.value.toString());if((N instanceof De||N instanceof Ke)&&(Z instanceof De||Z instanceof Ke)){const ue=N.value,Se=Z.value;switch(y.operator.value){case"+":case"-":case"*":{const ze=y.operator.value==="+"?ue+Se:y.operator.value==="-"?ue-Se:ue*Se;return N instanceof Ke||Z instanceof Ke?new Ke(ze):new De(ze)}case"/":return new Ke(ue/Se);case"%":{const ze=ue%Se;return N instanceof Ke||Z instanceof Ke?new Ke(ze):new De(ze)}case"<":return new qe(ue":return new qe(ue>Se);case">=":return new qe(ue>=Se);case"<=":return new qe(ue<=Se)}}else if(N instanceof Re&&Z instanceof Re)switch(y.operator.value){case"+":return new Re(N.value.concat(Z.value))}else if(Z instanceof Re){const ue=Z.value.find(Se=>Se.value===N.value)!==void 0;switch(y.operator.value){case"in":return new qe(ue);case"not in":return new qe(!ue)}}}if(N instanceof Ae||Z instanceof Ae)switch(y.operator.value){case"+":return new Ae(N.value.toString()+Z.value.toString())}if(N instanceof Ae&&Z instanceof Ae)switch(y.operator.value){case"in":return new qe(Z.value.includes(N.value));case"not in":return new qe(!Z.value.includes(N.value))}if(N instanceof Ae&&Z instanceof et)switch(y.operator.value){case"in":return new qe(Z.value.has(N.value));case"not in":return new qe(!Z.value.has(N.value))}throw new SyntaxError(`Unknown operator "${y.operator.value}" between ${N.type} and ${Z.type}`)}evaluateArguments(y,te){const N=[],Z=new Map;for(const ue of y)if(ue.type==="SpreadExpression"){const Se=ue,ze=this.evaluate(Se.argument,te);if(!(ze instanceof Re))throw new Error(`Cannot unpack non-iterable type: ${ze.type}`);for(const _t of ze.value)N.push(_t)}else if(ue.type==="KeywordArgumentExpression"){const Se=ue;Z.set(Se.key.value,this.evaluate(Se.value,te))}else{if(Z.size>0)throw new Error("Positional arguments must come before keyword arguments");N.push(this.evaluate(ue,te))}return[N,Z]}applyFilter(y,te,N){if(te.type==="Identifier"){const Z=te;if(Z.value==="tojson")return new Ae(Qt(y));if(y instanceof Re)switch(Z.value){case"list":return y;case"first":return y.value[0];case"last":return y.value[y.value.length-1];case"length":return new De(y.value.length);case"reverse":return new Re(y.value.reverse());case"sort":return new Re(y.value.sort((ue,Se)=>{if(ue.type!==Se.type)throw new Error(`Cannot compare different types: ${ue.type} and ${Se.type}`);switch(ue.type){case"IntegerValue":case"FloatValue":return ue.value-Se.value;case"StringValue":return ue.value.localeCompare(Se.value);default:throw new Error(`Cannot compare type: ${ue.type}`)}}));case"join":return new Ae(y.value.map(ue=>ue.value).join(""));case"string":return new Ae(Qt(y));case"unique":{const ue=new Set,Se=[];for(const ze of y.value)ue.has(ze.value)||(ue.add(ze.value),Se.push(ze));return new Re(Se)}default:throw new Error(`Unknown ArrayValue filter: ${Z.value}`)}else if(y instanceof Ae)switch(Z.value){case"length":case"upper":case"lower":case"title":case"capitalize":{const ue=y.builtins.get(Z.value);if(ue instanceof lt)return ue.value([],N);if(ue instanceof De)return ue;throw new Error(`Unknown StringValue filter: ${Z.value}`)}case"trim":return new Ae(y.value.trim());case"indent":return new Ae(y.value.split(` +`).map((ue,Se)=>Se===0||ue.length===0?ue:" "+ue).join(` +`));case"join":case"string":return y;case"int":{const ue=parseInt(y.value,10);return new De(isNaN(ue)?0:ue)}case"float":{const ue=parseFloat(y.value);return new Ke(isNaN(ue)?0:ue)}default:throw new Error(`Unknown StringValue filter: ${Z.value}`)}else if(y instanceof De||y instanceof Ke)switch(Z.value){case"abs":return y instanceof De?new De(Math.abs(y.value)):new Ke(Math.abs(y.value));case"int":return new De(Math.floor(y.value));case"float":return new Ke(y.value);default:throw new Error(`Unknown NumericValue filter: ${Z.value}`)}else if(y instanceof et)switch(Z.value){case"items":return new Re(Array.from(y.value.entries()).map(([ue,Se])=>new Re([new Ae(ue),Se])));case"length":return new De(y.value.size);default:throw new Error(`Unknown ObjectValue filter: ${Z.value}`)}else if(y instanceof qe)switch(Z.value){case"bool":return new qe(y.value);case"int":return new De(y.value?1:0);case"float":return new Ke(y.value?1:0);case"string":return new Ae(y.value?"true":"false");default:throw new Error(`Unknown BooleanValue filter: ${Z.value}`)}throw new Error(`Cannot apply filter "${Z.value}" to type: ${y.type}`)}else if(te.type==="CallExpression"){const Z=te;if(Z.callee.type!=="Identifier")throw new Error(`Unknown filter: ${Z.callee.type}`);const ue=Z.callee.value;if(ue==="tojson"){const[,Se]=this.evaluateArguments(Z.args,N),ze=Se.get("indent")??new pt;if(!(ze instanceof De||ze instanceof pt))throw new Error("If set, indent must be a number");return new Ae(Qt(y,ze.value))}else if(ue==="join"){let Se;if(y instanceof Ae)Se=Array.from(y.value);else if(y instanceof Re)Se=y.value.map(kt=>kt.value);else throw new Error(`Cannot apply filter "${ue}" to type: ${y.type}`);const[ze,_t]=this.evaluateArguments(Z.args,N),$t=ze.at(0)??_t.get("separator")??new Ae("");if(!($t instanceof Ae))throw new Error("separator must be a string");return new Ae(Se.join($t.value))}else if(ue==="int"||ue==="float"){const[Se,ze]=this.evaluateArguments(Z.args,N),_t=Se.at(0)??ze.get("default")??(ue==="int"?new De(0):new Ke(0));if(y instanceof Ae){const $t=ue==="int"?parseInt(y.value,10):parseFloat(y.value);return isNaN($t)?_t:ue==="int"?new De($t):new Ke($t)}else{if(y instanceof De||y instanceof Ke)return y;if(y instanceof qe)return ue==="int"?new De(y.value?1:0):new Ke(y.value?1:0);throw new Error(`Cannot apply filter "${ue}" to type: ${y.type}`)}}else if(ue==="default"){const[Se,ze]=this.evaluateArguments(Z.args,N),_t=Se[0]??new Ae(""),$t=Se[1]??ze.get("boolean")??new qe(!1);if(!($t instanceof qe))throw new Error("`default` filter flag must be a boolean");return y instanceof yt||$t.value&&!y.__bool__().value?_t:y}if(y instanceof Re){switch(ue){case"selectattr":case"rejectattr":{const Se=ue==="selectattr";if(y.value.some(bt=>!(bt instanceof et)))throw new Error(`\`${ue}\` can only be applied to array of objects`);if(Z.args.some(bt=>bt.type!=="StringLiteral"))throw new Error(`arguments of \`${ue}\` must be strings`);const[ze,_t,$t]=Z.args.map(bt=>this.evaluate(bt,N));let kt;if(_t){const bt=N.tests.get(_t.value);if(!bt)throw new Error(`Unknown test: ${_t.value}`);kt=bt}else kt=(...bt)=>bt[0].__bool__().value;const mt=y.value.filter(bt=>{const Yt=bt.value.get(ze.value),ss=Yt?kt(Yt,$t):!1;return Se?ss:!ss});return new Re(mt)}case"map":{const[,Se]=this.evaluateArguments(Z.args,N);if(Se.has("attribute")){const ze=Se.get("attribute");if(!(ze instanceof Ae))throw new Error("attribute must be a string");const _t=Se.get("default"),$t=y.value.map(kt=>{if(!(kt instanceof et))throw new Error("items in map must be an object");return kt.value.get(ze.value)??_t??new yt});return new Re($t)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${ue}`)}else if(y instanceof Ae){switch(ue){case"indent":{const[Se,ze]=this.evaluateArguments(Z.args,N),_t=Se.at(0)??ze.get("width")??new De(4);if(!(_t instanceof De))throw new Error("width must be a number");const $t=Se.at(1)??ze.get("first")??new qe(!1),kt=Se.at(2)??ze.get("blank")??new qe(!1),mt=y.value.split(` +`),bt=" ".repeat(_t.value),Yt=mt.map((ss,Ns)=>!$t.value&&Ns===0||!kt.value&&ss.length===0?ss:bt+ss);return new Ae(Yt.join(` +`))}case"replace":{const Se=y.builtins.get("replace");if(!(Se instanceof lt))throw new Error("replace filter not available");const[ze,_t]=this.evaluateArguments(Z.args,N);return Se.value([...ze,new ut(_t)],N)}}throw new Error(`Unknown StringValue filter: ${ue}`)}else throw new Error(`Cannot apply filter "${ue}" to type: ${y.type}`)}throw new Error(`Unknown filter: ${te.type}`)}evaluateFilterExpression(y,te){const N=this.evaluate(y.operand,te);return this.applyFilter(N,y.filter,te)}evaluateTestExpression(y,te){const N=this.evaluate(y.operand,te),Z=te.tests.get(y.test.value);if(!Z)throw new Error(`Unknown test: ${y.test.value}`);const ue=Z(N);return new qe(y.negate?!ue:ue)}evaluateSelectExpression(y,te){return this.evaluate(y.test,te).__bool__().value?this.evaluate(y.lhs,te):new yt}evaluateUnaryExpression(y,te){const N=this.evaluate(y.argument,te);switch(y.operator.value){case"not":return new qe(!N.value);default:throw new SyntaxError(`Unknown operator: ${y.operator.value}`)}}evaluateTernaryExpression(y,te){return this.evaluate(y.condition,te).__bool__().value?this.evaluate(y.trueExpr,te):this.evaluate(y.falseExpr,te)}evalProgram(y,te){return this.evaluateBlock(y.body,te)}evaluateBlock(y,te){let N="";for(const Z of y){const ue=this.evaluate(Z,te);ue.type!=="NullValue"&&ue.type!=="UndefinedValue"&&(N+=ue.toString())}return new Ae(N)}evaluateIdentifier(y,te){return te.lookupVariable(y.value)}evaluateCallExpression(y,te){const[N,Z]=this.evaluateArguments(y.args,te);Z.size>0&&N.push(new ut(Z));const ue=this.evaluate(y.callee,te);if(ue.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${ue.type}`);return ue.value(N,te)}evaluateSliceExpression(y,te,N){if(!(y instanceof Re||y instanceof Ae))throw new Error("Slice object must be an array or string");const Z=this.evaluate(te.start,N),ue=this.evaluate(te.stop,N),Se=this.evaluate(te.step,N);if(!(Z instanceof De||Z instanceof yt))throw new Error("Slice start must be numeric or undefined");if(!(ue instanceof De||ue instanceof yt))throw new Error("Slice stop must be numeric or undefined");if(!(Se instanceof De||Se instanceof yt))throw new Error("Slice step must be numeric or undefined");return y instanceof Re?new Re(Ye(y.value,Z.value,ue.value,Se.value)):new Ae(Ye(Array.from(y.value),Z.value,ue.value,Se.value).join(""))}evaluateMemberExpression(y,te){const N=this.evaluate(y.object,te);let Z;if(y.computed){if(y.property.type==="SliceExpression")return this.evaluateSliceExpression(N,y.property,te);Z=this.evaluate(y.property,te)}else Z=new Ae(y.property.value);let ue;if(N instanceof et){if(!(Z instanceof Ae))throw new Error(`Cannot access property with non-string: got ${Z.type}`);ue=N.value.get(Z.value)??N.builtins.get(Z.value)}else if(N instanceof Re||N instanceof Ae)if(Z instanceof De)ue=N.value.at(Z.value),N instanceof Ae&&(ue=new Ae(N.value.at(Z.value)));else if(Z instanceof Ae)ue=N.builtins.get(Z.value);else throw new Error(`Cannot access property with non-string/non-number: got ${Z.type}`);else{if(!(Z instanceof Ae))throw new Error(`Cannot access property with non-string: got ${Z.type}`);ue=N.builtins.get(Z.value)}return ue instanceof Ve?ue:new yt}evaluateSet(y,te){const N=y.value?this.evaluate(y.value,te):this.evaluateBlock(y.body,te);if(y.assignee.type==="Identifier"){const Z=y.assignee.value;te.setVariable(Z,N)}else if(y.assignee.type==="TupleLiteral"){const Z=y.assignee;if(!(N instanceof Re))throw new Error(`Cannot unpack non-iterable type in set: ${N.type}`);const ue=N.value;if(ue.length!==Z.value.length)throw new Error(`Too ${Z.value.length>ue.length?"few":"many"} items to unpack in set`);for(let Se=0;Sess.setVariable(y.loopvar.value,bt);else if(y.loopvar.type==="TupleLiteral"){const ss=y.loopvar;if(bt.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${bt.type}`);const Ns=bt;if(ss.value.length!==Ns.value.length)throw new Error(`Too ${ss.value.length>Ns.value.length?"few":"many"} items to unpack`);Yt=Hs=>{for(let Es=0;Es0?Se[kt-1]:new yt],["nextitem",kt{var ze;const ue=new ct(Z);N=N.slice();let Se;((ze=N.at(-1))==null?void 0:ze.type)==="KeywordArgumentsValue"&&(Se=N.pop());for(let _t=0;_t{const kt=new ct($t);if(y.callerArgs)for(let mt=0;mtthis.evaluate(N,te)));case"TupleLiteral":return new Mt(y.value.map(N=>this.evaluate(N,te)));case"ObjectLiteral":{const N=new Map;for(const[Z,ue]of y.value){const Se=this.evaluate(Z,te);if(!(Se instanceof Ae))throw new Error(`Object keys must be strings: got ${Se.type}`);N.set(Se.value,this.evaluate(ue,te))}return new et(N)}case"Identifier":return this.evaluateIdentifier(y,te);case"CallExpression":return this.evaluateCallExpression(y,te);case"MemberExpression":return this.evaluateMemberExpression(y,te);case"UnaryExpression":return this.evaluateUnaryExpression(y,te);case"BinaryExpression":return this.evaluateBinaryExpression(y,te);case"FilterExpression":return this.evaluateFilterExpression(y,te);case"FilterStatement":return this.evaluateFilterStatement(y,te);case"TestExpression":return this.evaluateTestExpression(y,te);case"SelectExpression":return this.evaluateSelectExpression(y,te);case"Ternary":return this.evaluateTernaryExpression(y,te);case"Comment":return new pt;default:throw new SyntaxError(`Unknown node type: ${y.type}`)}}};function Wt(y){switch(typeof y){case"number":return Number.isInteger(y)?new De(y):new Ke(y);case"string":return new Ae(y);case"boolean":return new qe(y);case"undefined":return new yt;case"object":return y===null?new pt:Array.isArray(y)?new Re(y.map(Wt)):new et(new Map(Object.entries(y).map(([te,N])=>[te,Wt(N)])));case"function":return new lt((te,N)=>{const Z=y(...te.map(ue=>ue.value))??null;return Wt(Z)});default:throw new Error(`Cannot convert to runtime value: ${y}`)}}function Qt(y,te,N){const Z=N??0;switch(y.type){case"NullValue":case"UndefinedValue":return"null";case"IntegerValue":case"FloatValue":case"StringValue":case"BooleanValue":return JSON.stringify(y.value);case"ArrayValue":case"ObjectValue":{const ue=te?" ".repeat(te):"",Se=` +`+ue.repeat(Z),ze=Se+ue;if(y.type==="ArrayValue"){const _t=y.value.map($t=>Qt($t,te,Z+1));return te?`[${ze}${_t.join(`,${ze}`)}${Se}]`:`[${_t.join(", ")}]`}else{const _t=Array.from(y.value.entries()).map(([$t,kt])=>{const mt=`"${$t}": ${Qt(kt,te,Z+1)}`;return te?`${ze}${mt}`:mt});return te?`{${_t.join(",")}${Se}}`:`{${_t.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${y.type}`)}}var jt=` +`,bs="{%- ",ds=" -%}";function Ls(y){switch(y.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":return y.operator.value==="and"?1:y.operator.value==="in"||y.operator.value==="not in"?2:0}return 0}function Js(y,te=" "){const N=typeof te=="number"?" ".repeat(te):te;return Ts(y.body,0,N).replace(/\n$/,"")}function is(...y){return bs+y.join(" ")+ds}function Ts(y,te,N){return y.map(Z=>Sr(Z,te,N)).join(jt)}function Sr(y,te,N){const Z=N.repeat(te);switch(y.type){case"Program":return Ts(y.body,te,N);case"If":return Gr(y,te,N);case"For":return kr(y,te,N);case"Set":return Kr(y,te,N);case"Macro":return At(y,te,N);case"Break":return Z+is("break");case"Continue":return Z+is("continue");case"CallStatement":return Ir(y,te,N);case"FilterStatement":return wr(y,te,N);case"Comment":return Z+"{# "+y.value+" #}";default:return Z+"{{- "+Vt(y)+" -}}"}}function Gr(y,te,N){const Z=N.repeat(te),ue=[];let Se=y;for(;Se&&(ue.push({test:Se.test,body:Se.body}),Se.alternate.length===1&&Se.alternate[0].type==="If");)Se=Se.alternate[0];let ze=Z+is("if",Vt(ue[0].test))+jt+Ts(ue[0].body,te+1,N);for(let _t=1;_t0&&(ze+=jt+Z+is("else")+jt+Ts(Se.alternate,te+1,N)),ze+=jt+Z+is("endif"),ze}function kr(y,te,N){const Z=N.repeat(te);let ue="";if(y.iterable.type==="SelectExpression"){const ze=y.iterable;ue=`${Vt(ze.lhs)} if ${Vt(ze.test)}`}else ue=Vt(y.iterable);let Se=Z+is("for",Vt(y.loopvar),"in",ue)+jt+Ts(y.body,te+1,N);return y.defaultBlock.length>0&&(Se+=jt+Z+is("else")+jt+Ts(y.defaultBlock,te+1,N)),Se+=jt+Z+is("endfor"),Se}function Kr(y,te,N){const Z=N.repeat(te),ue=Vt(y.assignee),Se=y.value?Vt(y.value):"",ze=Z+is("set",`${ue}${y.value?" = "+Se:""}`);return y.body.length===0?ze:ze+jt+Ts(y.body,te+1,N)+jt+Z+is("endset")}function At(y,te,N){const Z=N.repeat(te),ue=y.args.map(Vt).join(", ");return Z+is("macro",`${y.name.value}(${ue})`)+jt+Ts(y.body,te+1,N)+jt+Z+is("endmacro")}function Ir(y,te,N){const Z=N.repeat(te),ue=y.callerArgs&&y.callerArgs.length>0?`(${y.callerArgs.map(Vt).join(", ")})`:"",Se=Vt(y.call);let ze=Z+is(`call${ue}`,Se)+jt;return ze+=Ts(y.body,te+1,N)+jt,ze+=Z+is("endcall"),ze}function wr(y,te,N){const Z=N.repeat(te),ue=y.filter.type==="Identifier"?y.filter.value:Vt(y.filter);let Se=Z+is("filter",ue)+jt;return Se+=Ts(y.body,te+1,N)+jt,Se+=Z+is("endfilter"),Se}function Vt(y,te=-1){switch(y.type){case"SpreadExpression":return`*${Vt(y.argument)}`;case"Identifier":return y.value;case"IntegerLiteral":return`${y.value}`;case"FloatLiteral":return`${y.value}`;case"StringLiteral":return JSON.stringify(y.value);case"BinaryExpression":{const N=y,Z=Ls(N),ue=Vt(N.left,Z),Se=Vt(N.right,Z+1),ze=`${ue} ${N.operator.value} ${Se}`;return Z`${Vt(Z)}: ${Vt(ue)}`).join(", ")}}`;case"SliceExpression":{const N=y,Z=N.start?Vt(N.start):"",ue=N.stop?Vt(N.stop):"",Se=N.step?`:${Vt(N.step)}`:"";return`${Z}:${ue}${Se}`}case"KeywordArgumentExpression":{const N=y;return`${N.key.value}=${Vt(N.value)}`}case"Ternary":{const N=y,Z=`${Vt(N.trueExpr)} if ${Vt(N.condition,0)} else ${Vt(N.falseExpr)}`;return te>-1?`(${Z})`:Z}default:throw new Error(`Unknown expression type: ${y.type}`)}}var dr=class{constructor(y){ie(this,"parsed");const te=D(y,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=Xe(te)}render(y){const te=new ct;if(ht(te),y)for(const[ue,Se]of Object.entries(y))te.set(ue,Se);return new vt(te).run(this.parsed).value}format(y){return Js(this.parsed,(y==null?void 0:y.indent)||" ")}}},"./src/backends/onnx.js":(ae,m,r)=>{var w;r.r(m),r.d(m,{Tensor:()=>$.Tensor,createInferenceSession:()=>ge,deviceToExecutionProviders:()=>z,isONNXProxy:()=>Y,isONNXTensor:()=>j});var T=r("./src/env.js"),L=r("?2ce3"),H=r("onnxruntime-web"),$=r("onnxruntime-common");const _=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"}}),I=[];let D,b;const h=Symbol.for("onnxruntime");if(h in globalThis)b=globalThis[h];else if(T.apis.IS_NODE_ENV){switch(b=L??(w||(w=r.t(L,2))),process.platform){case"win32":I.push("dml");break;case"linux":process.arch==="x64"&&I.push("cuda");break}I.push("cpu"),D=["cpu"]}else b=H,T.apis.IS_WEBNN_AVAILABLE&&I.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),T.apis.IS_WEBGPU_AVAILABLE&&I.push("webgpu"),I.push("wasm"),D=["wasm"];const U=b.InferenceSession;function z(O=null){if(!O)return D;switch(O){case"auto":return I;case"gpu":return I.filter(S=>["webgpu","cuda","dml","webnn-gpu"].includes(S))}if(I.includes(O))return[_[O]??O];throw new Error(`Unsupported device: "${O}". Should be one of: ${I.join(", ")}.`)}let Q=null;async function ge(O,S,E){Q&&await Q;const x=U.create(O,S);Q??(Q=x);const C=await x;return C.config=E,C}function j(O){return O instanceof b.Tensor}const G=b==null?void 0:b.env;G!=null&&G.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!G.wasm.wasmPaths&&(G.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${T.env.version}/dist/`),G.wasm.proxy=!1),G!=null&&G.webgpu&&(G.webgpu.powerPreference="high-performance");function Y(){var O;return(O=G==null?void 0:G.wasm)==null?void 0:O.proxy}T.env.backends.onnx=G},"./src/base/feature_extraction_utils.js":(ae,m,r)=>{r.r(m),r.d(m,{FeatureExtractor:()=>H,validate_audio_inputs:()=>$});var w=r("./src/utils/constants.js"),T=r("./src/utils/generic.js"),L=r("./src/utils/hub.js");class H extends T.Callable{constructor(I){super(),this.config=I}static async from_pretrained(I,D={}){const b=await(0,L.getModelJSON)(I,w.FEATURE_EXTRACTOR_NAME,!0,D);return new this(b)}}function $(_,I){var D;if(!(_ instanceof Float32Array||_ instanceof Float64Array))throw new Error(`${I} expects input to be a Float32Array or a Float64Array, but got ${((D=_==null?void 0:_.constructor)==null?void 0:D.name)??typeof _} 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":(ae,m,r)=>{r.r(m),r.d(m,{ImageProcessor:()=>O,center_to_corners_format:()=>b,post_process_instance_segmentation:()=>Y,post_process_object_detection:()=>h,post_process_panoptic_segmentation:()=>G,post_process_semantic_segmentation:()=>U});var w=r("./src/utils/generic.js"),T=r("./src/utils/tensor.js"),L=r("./src/utils/maths.js");r("./src/utils/image.js");var H=r("./src/utils/core.js"),$=r("./src/utils/hub.js"),_=r("./src/utils/constants.js");function I(S,E,x=0,C=null){const re=S/E;let q=(0,L.bankers_round)(re)*E;return C!==null&&q>C&&(q=Math.floor(re)*E),qE&&K.push(ye)}else{let ye=(0,L.max)(he.data)[1];if(ye===J-1||(ce=(0,L.softmax)(he.data),ce[ye]Xe*Te[(Qe+1)%2])),Pe.boxes.push(Fe),Pe.classes.push(ye),Pe.scores.push(ce[ye])}}fe.push(Pe)}return fe}function U(S,E=null){const x=S.logits,C=x.dims[0];if(E!==null&&E.length!==C)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const re=[];for(let q=0;qTe[K]&&(Te[K]=he[K],Pe[K]=Oe)}const be=new Array(me.dims[0]);for(let Oe=0;OeOe!==void 0);re.push({segmentation:de,labels:He})}return re}function z(S,E,x,C){const re=[],q=[],pe=[];for(let me=0;mex&&(re.push(fe),q.push(Pe),pe.push(de))}return[re,q,pe]}function Q(S,E,x,C=.5,re=.8){const q=[];let pe=0,me=0;const J=E[x].data;for(let de=0;de=C&&++me;let fe=pe>0&&me>0;return fe&&(fe=pe/me>re),[fe,q]}function ge(S,E,x,C,re,q=null,pe=null){const[me,J]=pe??S[0].dims,fe=new T.Tensor("int32",new Int32Array(me*J),[me,J]),de=[];if(pe!==null)for(let Oe=0;OePe[ce]&&(Te[ce]=Oe,Pe[ce]=K[ce])}let be=0;const He=fe.data;for(let Oe=0;Oe200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(S,E)/Math.min(S,E)}`);let q=Math.round(S/x)*x,pe=Math.round(E/x)*x;if(q*pe>re){const me=Math.sqrt(S*E/re);q=Math.floor(S/me/x)*x,pe=Math.floor(E/me/x)*x}else if(q*peq?fe=Math.floor(q*J/re):q>re&&(J=Math.floor(re*fe/q)),await E.resize(fe,J,{resample:C}))}async crop_margin(E,x=200){const C=E.clone().grayscale(),re=(0,L.min)(C.data)[0],pe=(0,L.max)(C.data)[0]-re;if(pe===0)return E;const me=x/255;let J=C.width,fe=C.height,de=0,Te=0;const Pe=C.data;for(let be=0;bethis.preprocess(q)));return{pixel_values:(0,T.stack)(C.map(q=>q.pixel_values),0),original_sizes:C.map(q=>q.original_size),reshaped_input_sizes:C.map(q=>q.reshaped_input_size)}}static async from_pretrained(E,x={}){const C=await(0,$.getModelJSON)(E,_.IMAGE_PROCESSOR_NAME,!0,x);return new this(C)}}},"./src/base/processing_utils.js":(ae,m,r)=>{r.r(m),r.d(m,{Processor:()=>H});var w=r("./src/utils/constants.js"),T=r("./src/utils/generic.js"),L=r("./src/utils/hub.js");class H extends T.Callable{constructor(_,I,D){super(),this.config=_,this.components=I,this.chat_template=D}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(_,I={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(_,{tokenize:!1,chat_template:this.chat_template??void 0,...I})}batch_decode(..._){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(..._)}decode(..._){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(..._)}async _call(_,...I){for(const D of[this.image_processor,this.feature_extractor,this.tokenizer])if(D)return D(_,...I);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(_,I={}){const[D,b,h]=await Promise.all([this.uses_processor_config?(0,L.getModelJSON)(_,w.PROCESSOR_NAME,!0,I):{},Promise.all(this.classes.filter(U=>U in this).map(async U=>{const z=await this[U].from_pretrained(_,I);return[U.replace(/_class$/,""),z]})).then(Object.fromEntries),this.uses_chat_template_file?(0,L.getModelText)(_,w.CHAT_TEMPLATE_NAME,!0,I):null]);return new this(D,b,h)}}ie(H,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),ie(H,"uses_processor_config",!1),ie(H,"uses_chat_template_file",!1)},"./src/configs.js":(ae,m,r)=>{r.r(m),r.d(m,{AutoConfig:()=>D,PretrainedConfig:()=>I,getCacheShapes:()=>$});var w=r("./src/utils/core.js"),T=r("./src/utils/hub.js");async function L(b,h){return await(0,T.getModelJSON)(b,"config.json",!0,h)}function H(b){const h={};let U={};switch(b.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"voxtral":case"smolvlm":case"gemma3n":U=H(b.text_config);break;case"moondream1":U=H(b.phi_config);break;case"musicgen":U=H(b.decoder);break;case"multi_modality":U=H(b.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":h.num_heads="n_head",h.num_layers="n_layer",h.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":h.num_heads="num_attention_heads",h.num_layers="num_hidden_layers",h.hidden_size="hidden_size";break;case"llama":case"arcee":case"lfm2":case"smollm3":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":case"llava_qwen2":h.num_heads="num_key_value_heads",h.num_layers="num_hidden_layers",h.hidden_size="hidden_size",h.num_attention_heads="num_attention_heads",h.dim_kv="head_dim";break;case"qwen3":case"gemma":case"gemma2":case"gemma3_text":case"gemma3n_text":case"glm":case"helium":case"ernie4_5":h.num_heads="num_key_value_heads",h.num_layers="num_hidden_layers",h.dim_kv="head_dim";break;case"openelm":h.num_heads="num_kv_heads",h.num_layers="num_transformer_layers",h.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":h.num_heads="num_heads",h.num_layers="num_layers",h.hidden_size="hidden_size";break;case"bloom":h.num_heads="n_head",h.num_layers="n_layer",h.hidden_size="hidden_size";break;case"mpt":h.num_heads="n_heads",h.num_layers="n_layers",h.hidden_size="d_model";break;case"exaone":h.num_heads="num_key_value_heads",h.num_layers="num_layers",h.dim_kv="head_dim",h.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":h.num_decoder_layers="num_decoder_layers",h.num_decoder_heads="num_heads",h.decoder_dim_kv="d_kv",h.num_encoder_layers="num_layers",h.num_encoder_heads="num_heads",h.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":h.num_decoder_layers="decoder_layers",h.num_decoder_heads="decoder_attention_heads",h.decoder_hidden_size="d_model",h.num_encoder_layers="encoder_layers",h.num_encoder_heads="encoder_attention_heads",h.encoder_hidden_size="d_model";break;case"speecht5":h.num_decoder_layers="decoder_layers",h.num_decoder_heads="decoder_attention_heads",h.decoder_hidden_size="hidden_size",h.num_encoder_layers="encoder_layers",h.num_encoder_heads="encoder_attention_heads",h.encoder_hidden_size="hidden_size";break;case"trocr":h.num_encoder_layers=h.num_decoder_layers="decoder_layers",h.num_encoder_heads=h.num_decoder_heads="decoder_attention_heads",h.encoder_hidden_size=h.decoder_hidden_size="d_model";break;case"musicgen_decoder":h.num_encoder_layers=h.num_decoder_layers="num_hidden_layers",h.num_encoder_heads=h.num_decoder_heads="num_attention_heads",h.encoder_hidden_size=h.decoder_hidden_size="hidden_size";break;case"moonshine":h.num_decoder_layers="decoder_num_hidden_layers",h.num_decoder_heads="decoder_num_key_value_heads",h.num_encoder_layers="encoder_num_hidden_layers",h.num_encoder_heads="encoder_num_key_value_heads",h.encoder_hidden_size=h.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const Q=H(b.decoder),ge="num_decoder_layers"in Q,j=(0,w.pick)(b,["model_type","is_encoder_decoder"]);return ge?(j.num_decoder_layers=Q.num_decoder_layers,j.num_decoder_heads=Q.num_decoder_heads,j.decoder_hidden_size=Q.decoder_hidden_size,j.num_encoder_layers=Q.num_encoder_layers,j.num_encoder_heads=Q.num_encoder_heads,j.encoder_hidden_size=Q.encoder_hidden_size):(j.num_layers=Q.num_layers,j.num_heads=Q.num_heads,j.hidden_size=Q.hidden_size),j}const z={...U,...(0,w.pick)(b,["model_type","multi_query","is_encoder_decoder"])};for(const Q in h)z[Q]=b[h[Q]];return z}function $(b,h){if(b.model_type==="lfm2"){const U=(h==null?void 0:h.prefix)??"past_key_values",z=U==="present"?"present":"past",Q={},{layer_types:ge,num_attention_heads:j,num_key_value_heads:G,hidden_size:Y,conv_L_cache:O}=b,S=Y/j,E=(h==null?void 0:h.batch_size)??1;for(let x=0;x{var re,q;r.r(m),r.d(m,{apis:()=>j,env:()=>x});var w=r("?db59"),T=r("?383f"),L=r("?fa4b");const H="3.7.2",$=typeof window<"u"&&typeof window.document<"u",_=typeof self<"u"&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes((re=self.constructor)==null?void 0:re.name),I=typeof self<"u"&&"caches"in self,D=typeof navigator<"u"&&"gpu"in navigator,b=typeof navigator<"u"&&"ml"in navigator,h=typeof process<"u",U=h&&((q=process==null?void 0:process.release)==null?void 0:q.name)==="node",z=!C(w),Q=!C(T),ge=typeof globalThis.Deno<"u",j=Object.freeze({IS_BROWSER_ENV:$,IS_WEBWORKER_ENV:_,IS_WEB_CACHE_AVAILABLE:I,IS_WEBGPU_AVAILABLE:D,IS_WEBNN_AVAILABLE:b,IS_PROCESS_AVAILABLE:h,IS_NODE_ENV:U,IS_FS_AVAILABLE:z,IS_PATH_AVAILABLE:Q}),G=z&&Q;let Y="./";if(G){const pe=Object({url:sn&&sn.src||new URL("assets/worker-afe162b7.js",document.baseURI).href}).url;pe?Y=T.dirname(T.dirname(L.fileURLToPath(pe))):typeof __dirname<"u"&&(Y=T.dirname(__dirname))}const O=G?T.join(Y,"/.cache/"):null,S="/models/",E=G?T.join(Y,S):S,x={version:H,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!($||_),localModelPath:E,useFS:z,useBrowserCache:I&&!ge,useFSCache:z,cacheDir:O,useCustomCache:!1,customCache:null};function C(pe){return Object.keys(pe).length===0}},"./src/generation/configuration_utils.js":(ae,m,r)=>{r.r(m),r.d(m,{GenerationConfig:()=>T});var w=r("./src/utils/core.js");class T{constructor(H){ie(this,"max_length",20);ie(this,"max_new_tokens",null);ie(this,"min_length",0);ie(this,"min_new_tokens",null);ie(this,"early_stopping",!1);ie(this,"max_time",null);ie(this,"do_sample",!1);ie(this,"num_beams",1);ie(this,"num_beam_groups",1);ie(this,"penalty_alpha",null);ie(this,"use_cache",!0);ie(this,"temperature",1);ie(this,"top_k",50);ie(this,"top_p",1);ie(this,"typical_p",1);ie(this,"epsilon_cutoff",0);ie(this,"eta_cutoff",0);ie(this,"diversity_penalty",0);ie(this,"repetition_penalty",1);ie(this,"encoder_repetition_penalty",1);ie(this,"length_penalty",1);ie(this,"no_repeat_ngram_size",0);ie(this,"bad_words_ids",null);ie(this,"force_words_ids",null);ie(this,"renormalize_logits",!1);ie(this,"constraints",null);ie(this,"forced_bos_token_id",null);ie(this,"forced_eos_token_id",null);ie(this,"remove_invalid_values",!1);ie(this,"exponential_decay_length_penalty",null);ie(this,"suppress_tokens",null);ie(this,"streamer",null);ie(this,"begin_suppress_tokens",null);ie(this,"forced_decoder_ids",null);ie(this,"guidance_scale",null);ie(this,"num_return_sequences",1);ie(this,"output_attentions",!1);ie(this,"output_hidden_states",!1);ie(this,"output_scores",!1);ie(this,"return_dict_in_generate",!1);ie(this,"pad_token_id",null);ie(this,"bos_token_id",null);ie(this,"eos_token_id",null);ie(this,"encoder_no_repeat_ngram_size",0);ie(this,"decoder_start_token_id",null);ie(this,"generation_kwargs",{});Object.assign(this,(0,w.pick)(H,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(ae,m,r)=>{r.r(m),r.d(m,{ClassifierFreeGuidanceLogitsProcessor:()=>j,ForcedBOSTokenLogitsProcessor:()=>_,ForcedEOSTokenLogitsProcessor:()=>I,LogitsProcessor:()=>L,LogitsProcessorList:()=>$,LogitsWarper:()=>H,MinLengthLogitsProcessor:()=>z,MinNewTokensLengthLogitsProcessor:()=>Q,NoBadWordsLogitsProcessor:()=>ge,NoRepeatNGramLogitsProcessor:()=>h,RepetitionPenaltyLogitsProcessor:()=>U,SuppressTokensAtBeginLogitsProcessor:()=>D,TemperatureLogitsWarper:()=>G,TopKLogitsWarper:()=>O,TopPLogitsWarper:()=>Y,WhisperTimeStampLogitsProcessor:()=>b});var w=r("./src/utils/generic.js");r("./src/utils/tensor.js");var T=r("./src/utils/maths.js");class L extends w.Callable{_call(E,x){throw Error("`_call` should be implemented in a subclass")}}class H extends w.Callable{_call(E,x){throw Error("`_call` should be implemented in a subclass")}}class $ extends w.Callable{constructor(){super(),this.processors=[]}push(E){this.processors.push(E)}extend(E){this.processors.push(...E)}_call(E,x){let C=x;for(const re of this.processors)C=re(E,C);return C}[Symbol.iterator](){return this.processors.values()}}class _ extends L{constructor(E){super(),this.bos_token_id=E}_call(E,x){for(let C=0;C=1&&q[q.length-1]>=this.timestamp_begin,me=q.length<2||q[q.length-2]>=this.timestamp_begin;if(pe&&(me?re.subarray(this.timestamp_begin).fill(-1/0):re.subarray(0,this.eos_token_id).fill(-1/0)),E[C].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Te=this.timestamp_begin+this.max_initial_timestamp_index;re.subarray(Te+1).fill(-1/0)}const J=(0,T.log_softmax)(re),fe=Math.log(J.subarray(this.timestamp_begin).map(Math.exp).reduce((Te,Pe)=>Te+Pe)),de=(0,T.max)(J.subarray(0,this.timestamp_begin))[0];fe>de&&re.subarray(0,this.timestamp_begin).fill(-1/0)}return x}}class h extends L{constructor(E){super(),this.no_repeat_ngram_size=E}getNgrams(E){const x=E.length,C=[];for(let q=0;q1 to use the classifier free guidance processor, got guidance scale ${E}.`);this.guidance_scale=E}_call(E,x){if(x.dims[0]!==2*E.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${x.dims[0]} for the logits and ${E.length} for the input ids.`);const C=E.length,re=x.slice([0,C],null),q=x.slice([C,x.dims[0]],null);for(let pe=0;pe1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${E}`);if(!Number.isInteger(C)||C<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${C}`);this.top_p=E,this.filter_value=x,this.min_tokens_to_keep=C}}class O extends H{constructor(E,{filter_value:x=-1/0,min_tokens_to_keep:C=1}={}){if(super(),!Number.isInteger(E)||E<0)throw new Error(`\`top_k\` must be a positive integer, but is ${E}`);this.top_k=Math.max(E,C),this.filter_value=x}}},"./src/generation/logits_sampler.js":(ae,m,r)=>{r.r(m),r.d(m,{LogitsSampler:()=>H});var w=r("./src/utils/generic.js"),T=r("./src/utils/tensor.js"),L=r("./src/utils/maths.js");r("./src/generation/configuration_utils.js");class H extends w.Callable{constructor(b){super(),this.generation_config=b}async _call(b){return this.sample(b)}async sample(b){throw Error("sample should be implemented in subclasses.")}getLogits(b,h){let U=b.dims.at(-1),z=b.data;if(h===-1)z=z.slice(-U);else{let Q=h*U;z=z.slice(Q,Q+U)}return z}randomSelect(b){let h=0;for(let z=0;z1)return new I(b);if(b.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${b.num_return_sequences}.`);return new $(b)}}class $ extends H{async sample(b){const h=(0,L.max)(b.data)[1];return[[BigInt(h),0]]}}class _ extends H{async sample(b){let h=b.dims.at(-1);this.generation_config.top_k>0&&(h=Math.min(this.generation_config.top_k,h));const[U,z]=await(0,T.topk)(b,h),Q=(0,L.softmax)(U.data);return Array.from({length:this.generation_config.num_beams},()=>{const ge=this.randomSelect(Q);return[z.data[ge],Math.log(Q[ge])]})}}class I extends H{async sample(b){let h=b.dims.at(-1);this.generation_config.top_k>0&&(h=Math.min(this.generation_config.top_k,h));const[U,z]=await(0,T.topk)(b,h),Q=(0,L.softmax)(U.data);return Array.from({length:this.generation_config.num_beams},(ge,j)=>[z.data[j],Math.log(Q[j])])}}},"./src/generation/stopping_criteria.js":(ae,m,r)=>{r.r(m),r.d(m,{EosTokenCriteria:()=>$,InterruptableStoppingCriteria:()=>_,MaxLengthCriteria:()=>H,StoppingCriteria:()=>T,StoppingCriteriaList:()=>L});var w=r("./src/utils/generic.js");class T extends w.Callable{_call(D,b){throw Error("StoppingCriteria needs to be subclassed")}}class L extends w.Callable{constructor(){super(),this.criteria=[]}push(D){this.criteria.push(D)}extend(D){D instanceof L?D=D.criteria:D instanceof T&&(D=[D]),this.criteria.push(...D)}_call(D,b){const h=new Array(D.length).fill(!1);for(const U of this.criteria){const z=U(D,b);for(let Q=0;Qb.length>=this.max_length)}}class $ extends T{constructor(D){super(),Array.isArray(D)||(D=[D]),this.eos_token_id=D}_call(D,b){return D.map(h=>{const U=h.at(-1);return this.eos_token_id.some(z=>U==z)})}}class _ extends T{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(D,b){return new Array(D.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(ae,m,r)=>{r.r(m),r.d(m,{BaseStreamer:()=>H,TextStreamer:()=>_,WhisperTextStreamer:()=>I});var w=r("./src/utils/core.js"),T=r("./src/tokenizers.js"),L=r("./src/env.js");class H{put(b){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const $=L.apis.IS_PROCESS_AVAILABLE?D=>process.stdout.write(D):D=>console.log(D);class _ extends H{constructor(b,{skip_prompt:h=!1,callback_function:U=null,token_callback_function:z=null,skip_special_tokens:Q=!0,decode_kwargs:ge={},...j}={}){super(),this.tokenizer=b,this.skip_prompt=h,this.callback_function=U??$,this.token_callback_function=z,this.decode_kwargs={skip_special_tokens:Q,...ge,...j},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(b){var ge;if(b.length>1)throw Error("TextStreamer only supports batch size of 1");const h=this.next_tokens_are_prompt;if(h&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;const U=b[0];(ge=this.token_callback_function)==null||ge.call(this,U),this.token_cache=(0,w.mergeArrays)(this.token_cache,U);const z=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let Q;h||z.endsWith(` +`)?(Q=z.slice(this.print_len),this.token_cache=[],this.print_len=0):z.length>0&&(0,T.is_chinese_char)(z.charCodeAt(z.length-1))?(Q=z.slice(this.print_len),this.print_len+=Q.length):(Q=z.slice(this.print_len,z.lastIndexOf(" ")+1),this.print_len+=Q.length),this.on_finalized_text(Q,!1)}end(){let b;this.token_cache.length>0?(b=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):b="",this.next_tokens_are_prompt=!0,this.on_finalized_text(b,!0)}on_finalized_text(b,h){var U,z;b.length>0&&((U=this.callback_function)==null||U.call(this,b)),h&&this.callback_function===$&&L.apis.IS_PROCESS_AVAILABLE&&((z=this.callback_function)==null||z.call(this,` +`))}}class I extends _{constructor(b,{skip_prompt:h=!1,callback_function:U=null,token_callback_function:z=null,on_chunk_start:Q=null,on_chunk_end:ge=null,on_finalize:j=null,time_precision:G=.02,skip_special_tokens:Y=!0,decode_kwargs:O={}}={}){super(b,{skip_prompt:h,skip_special_tokens:Y,callback_function:U,token_callback_function:z,decode_kwargs:O}),this.timestamp_begin=b.timestamp_begin,this.on_chunk_start=Q,this.on_chunk_end=ge,this.on_finalize=j,this.time_precision=G,this.waiting_for_timestamp=!1}put(b){var U,z,Q;if(b.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const h=b[0];if(h.length===1){const ge=Number(h[0])-this.timestamp_begin;if(ge>=0){const j=ge*this.time_precision;this.waiting_for_timestamp?(U=this.on_chunk_end)==null||U.call(this,j):(z=this.on_chunk_start)==null||z.call(this,j),this.waiting_for_timestamp=!this.waiting_for_timestamp,(Q=this.token_callback_function)==null||Q.call(this,h);return}}return super.put(b)}end(){var b;super.end(),(b=this.on_finalize)==null||b.call(this)}}},"./src/models.js":(ae,m,r)=>{r.r(m),r.d(m,{ASTForAudioClassification:()=>pa,ASTModel:()=>ua,ASTPreTrainedModel:()=>oi,AlbertForMaskedLM:()=>Ot,AlbertForQuestionAnswering:()=>gt,AlbertForSequenceClassification:()=>nt,AlbertModel:()=>dt,AlbertPreTrainedModel:()=>st,ArceeForCausalLM:()=>Ha,ArceeModel:()=>Ka,ArceePreTrainedModel:()=>xn,AutoModel:()=>wu,AutoModelForAudioClassification:()=>mn,AutoModelForAudioFrameClassification:()=>ra,AutoModelForAudioTextToText:()=>Cu,AutoModelForCTC:()=>_n,AutoModelForCausalLM:()=>Jn,AutoModelForDepthEstimation:()=>vu,AutoModelForDocumentQuestionAnswering:()=>Zn,AutoModelForImageClassification:()=>ea,AutoModelForImageFeatureExtraction:()=>Eu,AutoModelForImageMatting:()=>Vr,AutoModelForImageSegmentation:()=>ta,AutoModelForImageTextToText:()=>Pu,AutoModelForImageToImage:()=>Ur,AutoModelForMaskGeneration:()=>Zr,AutoModelForMaskedLM:()=>Jo,AutoModelForNormalEstimation:()=>xu,AutoModelForObjectDetection:()=>Cr,AutoModelForPoseEstimation:()=>Tu,AutoModelForQuestionAnswering:()=>Yo,AutoModelForSemanticSegmentation:()=>sa,AutoModelForSeq2SeqLM:()=>Qo,AutoModelForSequenceClassification:()=>Mu,AutoModelForSpeechSeq2Seq:()=>Pr,AutoModelForTextToSpectrogram:()=>yu,AutoModelForTextToWaveform:()=>Xo,AutoModelForTokenClassification:()=>qo,AutoModelForUniversalSegmentation:()=>bu,AutoModelForVision2Seq:()=>Zo,AutoModelForXVector:()=>Yn,AutoModelForZeroShotObjectDetection:()=>js,BartForConditionalGeneration:()=>fs,BartForSequenceClassification:()=>Rs,BartModel:()=>os,BartPretrainedModel:()=>er,BaseModelOutput:()=>Ne,BeitForImageClassification:()=>Bu,BeitModel:()=>Kl,BeitPreTrainedModel:()=>eo,BertForMaskedLM:()=>Ke,BertForQuestionAnswering:()=>et,BertForSequenceClassification:()=>Ae,BertForTokenClassification:()=>qe,BertModel:()=>De,BertPreTrainedModel:()=>Ve,BlenderbotForConditionalGeneration:()=>Lt,BlenderbotModel:()=>gs,BlenderbotPreTrainedModel:()=>hs,BlenderbotSmallForConditionalGeneration:()=>Hr,BlenderbotSmallModel:()=>lr,BlenderbotSmallPreTrainedModel:()=>Ht,BloomForCausalLM:()=>Sl,BloomModel:()=>$l,BloomPreTrainedModel:()=>Cl,CLIPModel:()=>Ta,CLIPPreTrainedModel:()=>zr,CLIPSegForImageSegmentation:()=>nr,CLIPSegModel:()=>Aa,CLIPSegPreTrainedModel:()=>_i,CLIPTextModel:()=>Sp,CLIPTextModelWithProjection:()=>sr,CLIPVisionModel:()=>Fu,CLIPVisionModelWithProjection:()=>Mn,CamembertForMaskedLM:()=>kt,CamembertForQuestionAnswering:()=>Yt,CamembertForSequenceClassification:()=>mt,CamembertForTokenClassification:()=>bt,CamembertModel:()=>$t,CamembertPreTrainedModel:()=>_t,CausalLMOutput:()=>en,CausalLMOutputWithPast:()=>Tp,ChineseCLIPModel:()=>$a,ChineseCLIPPreTrainedModel:()=>Ca,ClapAudioModelWithProjection:()=>gd,ClapModel:()=>md,ClapPreTrainedModel:()=>Bn,ClapTextModelWithProjection:()=>fd,CodeGenForCausalLM:()=>Ua,CodeGenModel:()=>Va,CodeGenPreTrainedModel:()=>xi,CohereForCausalLM:()=>dl,CohereModel:()=>cl,CoherePreTrainedModel:()=>Ai,ConvBertForMaskedLM:()=>wr,ConvBertForQuestionAnswering:()=>y,ConvBertForSequenceClassification:()=>Vt,ConvBertForTokenClassification:()=>dr,ConvBertModel:()=>Ir,ConvBertPreTrainedModel:()=>At,ConvNextForImageClassification:()=>bc,ConvNextModel:()=>yc,ConvNextPreTrainedModel:()=>Mc,ConvNextV2ForImageClassification:()=>Hu,ConvNextV2Model:()=>vc,ConvNextV2PreTrainedModel:()=>vo,DFineForObjectDetection:()=>co,DFineModel:()=>Xl,DFinePreTrainedModel:()=>lo,DINOv3ConvNextModel:()=>kc,DINOv3ConvNextPreTrainedModel:()=>qu,DINOv3ViTModel:()=>Sc,DINOv3ViTPreTrainedModel:()=>$c,DPTForDepthEstimation:()=>Wu,DPTModel:()=>ac,DPTPreTrainedModel:()=>go,DacDecoderModel:()=>qd,DacDecoderOutput:()=>Gd,DacEncoderModel:()=>Hd,DacEncoderOutput:()=>Wd,DacModel:()=>Kd,DacPreTrainedModel:()=>Kn,DebertaForMaskedLM:()=>Hs,DebertaForQuestionAnswering:()=>Mr,DebertaForSequenceClassification:()=>Es,DebertaForTokenClassification:()=>ms,DebertaModel:()=>Ns,DebertaPreTrainedModel:()=>ss,DebertaV2ForMaskedLM:()=>Vs,DebertaV2ForQuestionAnswering:()=>yr,DebertaV2ForSequenceClassification:()=>zs,DebertaV2ForTokenClassification:()=>Us,DebertaV2Model:()=>Ar,DebertaV2PreTrainedModel:()=>qs,DecisionTransformerModel:()=>cp,DecisionTransformerPreTrainedModel:()=>Ad,DeiTForImageClassification:()=>po,DeiTModel:()=>ec,DeiTPreTrainedModel:()=>uo,DepthAnythingForDepthEstimation:()=>cn,DepthAnythingPreTrainedModel:()=>Dn,DepthProForDepthEstimation:()=>wo,DepthProPreTrainedModel:()=>uc,DetrForObjectDetection:()=>an,DetrForSegmentation:()=>so,DetrModel:()=>to,DetrObjectDetectionOutput:()=>kn,DetrPreTrainedModel:()=>Sn,DetrSegmentationOutput:()=>Hl,Dinov2ForImageClassification:()=>Tc,Dinov2Model:()=>xc,Dinov2PreTrainedModel:()=>xo,Dinov2WithRegistersForImageClassification:()=>Cc,Dinov2WithRegistersModel:()=>Pc,Dinov2WithRegistersPreTrainedModel:()=>Ec,DistilBertForMaskedLM:()=>pr,DistilBertForQuestionAnswering:()=>It,DistilBertForSequenceClassification:()=>ur,DistilBertForTokenClassification:()=>br,DistilBertModel:()=>Ys,DistilBertPreTrainedModel:()=>Ps,DonutSwinModel:()=>wc,DonutSwinPreTrainedModel:()=>gc,EfficientNetForImageClassification:()=>yd,EfficientNetModel:()=>Md,EfficientNetPreTrainedModel:()=>Nn,ElectraForMaskedLM:()=>Z,ElectraForQuestionAnswering:()=>ze,ElectraForSequenceClassification:()=>ue,ElectraForTokenClassification:()=>Se,ElectraModel:()=>N,ElectraPreTrainedModel:()=>te,Ernie4_5_ForCausalLM:()=>ud,Ernie4_5_Model:()=>rp,Ernie4_5_PretrainedModel:()=>ko,EsmForMaskedLM:()=>Bs,EsmForSequenceClassification:()=>Ze,EsmForTokenClassification:()=>tt,EsmModel:()=>Fr,EsmPreTrainedModel:()=>Zs,ExaoneForCausalLM:()=>sl,ExaoneModel:()=>tl,ExaonePreTrainedModel:()=>Ci,FalconForCausalLM:()=>_d,FalconModel:()=>np,FalconPreTrainedModel:()=>Ao,FastViTForImageClassification:()=>Ki,FastViTModel:()=>Vl,FastViTPreTrainedModel:()=>ws,Florence2ForConditionalGeneration:()=>wa,Florence2PreTrainedModel:()=>ga,GLPNForDepthEstimation:()=>Ku,GLPNModel:()=>fc,GLPNPreTrainedModel:()=>bo,GPT2LMHeadModel:()=>Da,GPT2Model:()=>Fa,GPT2PreTrainedModel:()=>mi,GPTBigCodeForCausalLM:()=>vn,GPTBigCodeModel:()=>Na,GPTBigCodePreTrainedModel:()=>ja,GPTJForCausalLM:()=>vi,GPTJModel:()=>Ra,GPTJPreTrainedModel:()=>bi,GPTNeoForCausalLM:()=>Ba,GPTNeoModel:()=>za,GPTNeoPreTrainedModel:()=>gi,GPTNeoXForCausalLM:()=>yi,GPTNeoXModel:()=>Mi,GPTNeoXPreTrainedModel:()=>wi,Gemma2ForCausalLM:()=>_l,Gemma2Model:()=>hl,Gemma2PreTrainedModel:()=>Di,Gemma3ForCausalLM:()=>fl,Gemma3Model:()=>ml,Gemma3PreTrainedModel:()=>Oi,Gemma3nForConditionalGeneration:()=>ui,Gemma3nPreTrainedModel:()=>ba,GemmaForCausalLM:()=>pl,GemmaModel:()=>ul,GemmaPreTrainedModel:()=>Fi,GlmForCausalLM:()=>el,GlmModel:()=>Za,GlmPreTrainedModel:()=>Pi,GraniteForCausalLM:()=>ll,GraniteModel:()=>Tn,GranitePreTrainedModel:()=>Ii,GroundingDinoForObjectDetection:()=>Ac,GroundingDinoPreTrainedModel:()=>Ic,GroupViTModel:()=>jr,GroupViTPreTrainedModel:()=>Gi,HeliumForCausalLM:()=>Xt,HeliumModel:()=>Ya,HeliumPreTrainedModel:()=>Ja,HieraForImageClassification:()=>_o,HieraModel:()=>tc,HieraPreTrainedModel:()=>ho,HubertForCTC:()=>ed,HubertForSequenceClassification:()=>zn,HubertModel:()=>Zc,HubertPreTrainedModel:()=>Yu,IJepaForImageClassification:()=>Ou,IJepaModel:()=>Ll,IJepaPreTrainedModel:()=>Ui,Idefics3ForConditionalGeneration:()=>wn,Idefics3PreTrainedModel:()=>va,ImageMattingOutput:()=>na,JAISLMHeadModel:()=>La,JAISModel:()=>Oa,JAISPreTrainedModel:()=>fi,JinaCLIPModel:()=>Sa,JinaCLIPPreTrainedModel:()=>bn,JinaCLIPTextModel:()=>ka,JinaCLIPVisionModel:()=>Ia,Lfm2ForCausalLM:()=>Du,Lfm2Model:()=>qa,Lfm2PreTrainedModel:()=>Ti,LiteWhisperForConditionalGeneration:()=>ha,LlamaForCausalLM:()=>Ga,LlamaModel:()=>Wa,LlamaPreTrainedModel:()=>Qr,LlavaForConditionalGeneration:()=>gn,LlavaOnevisionForConditionalGeneration:()=>ma,LlavaPreTrainedModel:()=>di,LlavaQwen2ForCausalLM:()=>ya,LongT5ForConditionalGeneration:()=>Is,LongT5Model:()=>ps,LongT5PreTrainedModel:()=>rs,M2M100ForConditionalGeneration:()=>Bc,M2M100Model:()=>zc,M2M100PreTrainedModel:()=>xr,MBartForCausalLM:()=>ys,MBartForConditionalGeneration:()=>vs,MBartForSequenceClassification:()=>ar,MBartModel:()=>or,MBartPreTrainedModel:()=>Gs,MPNetForMaskedLM:()=>Or,MPNetForQuestionAnswering:()=>P,MPNetForSequenceClassification:()=>rn,MPNetForTokenClassification:()=>xe,MPNetModel:()=>Le,MPNetPreTrainedModel:()=>Ws,MT5ForConditionalGeneration:()=>Cs,MT5Model:()=>hr,MT5PreTrainedModel:()=>As,MarianMTModel:()=>Nr,MarianModel:()=>mr,MarianPreTrainedModel:()=>ir,MaskFormerForInstanceSegmentation:()=>mc,MaskFormerModel:()=>yo,MaskFormerPreTrainedModel:()=>Mo,MaskedLMOutput:()=>Ms,Metric3DForDepthEstimation:()=>hc,Metric3DPreTrainedModel:()=>pc,Metric3Dv2ForDepthEstimation:()=>Gu,Metric3Dv2PreTrainedModel:()=>_c,MgpstrForSceneTextRecognition:()=>Od,MgpstrModelOutput:()=>jo,MgpstrPreTrainedModel:()=>Dd,MimiDecoderModel:()=>Go,MimiDecoderOutput:()=>Nd,MimiEncoderModel:()=>Ud,MimiEncoderOutput:()=>jd,MimiModel:()=>Vd,MimiPreTrainedModel:()=>Gn,MistralForCausalLM:()=>dd,MistralModel:()=>sp,MistralPreTrainedModel:()=>So,MobileBertForMaskedLM:()=>Ut,MobileBertForQuestionAnswering:()=>Dr,MobileBertForSequenceClassification:()=>ks,MobileBertModel:()=>ns,MobileBertPreTrainedModel:()=>ft,MobileLLMForCausalLM:()=>nl,MobileLLMModel:()=>rl,MobileLLMPreTrainedModel:()=>$i,MobileNetV1ForImageClassification:()=>xd,MobileNetV1ForSemanticSegmentation:()=>zo,MobileNetV1Model:()=>vd,MobileNetV1PreTrainedModel:()=>hn,MobileNetV2ForImageClassification:()=>Ed,MobileNetV2ForSemanticSegmentation:()=>Pd,MobileNetV2Model:()=>Td,MobileNetV2PreTrainedModel:()=>Un,MobileNetV3ForImageClassification:()=>$d,MobileNetV3ForSemanticSegmentation:()=>Sd,MobileNetV3Model:()=>Cd,MobileNetV3PreTrainedModel:()=>Bo,MobileNetV4ForImageClassification:()=>kd,MobileNetV4ForSemanticSegmentation:()=>Id,MobileNetV4Model:()=>lp,MobileNetV4PreTrainedModel:()=>Wn,MobileViTForImageClassification:()=>qi,MobileViTModel:()=>Hi,MobileViTPreTrainedModel:()=>Xr,MobileViTV2ForImageClassification:()=>Xi,MobileViTV2Model:()=>Wl,MobileViTV2PreTrainedModel:()=>Qi,ModelOutput:()=>ke,ModernBertDecoderForCausalLM:()=>ds,ModernBertDecoderModel:()=>bs,ModernBertDecoderPreTrainedModel:()=>jt,ModernBertForMaskedLM:()=>vt,ModernBertForSequenceClassification:()=>Wt,ModernBertForTokenClassification:()=>Qt,ModernBertModel:()=>ht,ModernBertPreTrainedModel:()=>ct,Moondream1ForConditionalGeneration:()=>fa,MoonshineForConditionalGeneration:()=>_a,MoonshineModel:()=>Au,MoonshinePreTrainedModel:()=>_r,MptForCausalLM:()=>Il,MptModel:()=>kl,MptPreTrainedModel:()=>Xs,MultiModalityCausalLM:()=>Ro,MultiModalityPreTrainedModel:()=>Fd,MusicgenForCausalLM:()=>ap,MusicgenForConditionalGeneration:()=>Lo,MusicgenModel:()=>bd,MusicgenPreTrainedModel:()=>Vn,NeoBertForMaskedLM:()=>Mt,NeoBertForQuestionAnswering:()=>yt,NeoBertForSequenceClassification:()=>lt,NeoBertForTokenClassification:()=>pt,NeoBertModel:()=>Re,NeoBertPreTrainedModel:()=>ut,NomicBertModel:()=>Js,NomicBertPreTrainedModel:()=>Ls,OPTForCausalLM:()=>Fl,OPTModel:()=>Al,OPTPreTrainedModel:()=>Ni,Olmo2ForCausalLM:()=>on,Olmo2Model:()=>al,Olmo2PreTrainedModel:()=>ki,OlmoForCausalLM:()=>ol,OlmoModel:()=>il,OlmoPreTrainedModel:()=>Si,OpenELMForCausalLM:()=>wl,OpenELMModel:()=>gl,OpenELMPreTrainedModel:()=>Li,OwlViTForObjectDetection:()=>Ji,OwlViTModel:()=>Gl,OwlViTPreTrainedModel:()=>Cn,Owlv2ForObjectDetection:()=>Zi,Owlv2Model:()=>$n,Owlv2PreTrainedModel:()=>Yi,PaliGemmaForConditionalGeneration:()=>tr,PaliGemmaPreTrainedModel:()=>Ma,PatchTSMixerForPrediction:()=>Uo,PatchTSMixerModel:()=>zd,PatchTSMixerPreTrainedModel:()=>Vo,PatchTSTForPrediction:()=>Ld,PatchTSTModel:()=>dp,PatchTSTPreTrainedModel:()=>No,Phi3ForCausalLM:()=>Pl,Phi3Model:()=>El,Phi3PreTrainedModel:()=>ji,Phi3VForCausalLM:()=>hi,Phi3VPreTrainedModel:()=>xa,PhiForCausalLM:()=>Ri,PhiModel:()=>Tl,PhiPreTrainedModel:()=>Bi,PreTrainedModel:()=>X,PretrainedMixin:()=>Jt,PvtForImageClassification:()=>jl,PvtModel:()=>Rl,PvtPreTrainedModel:()=>Wi,PyAnnoteForAudioFrameClassification:()=>Wc,PyAnnoteModel:()=>Uc,PyAnnotePreTrainedModel:()=>Eo,QuestionAnsweringModelOutput:()=>xs,Qwen2ForCausalLM:()=>zi,Qwen2Model:()=>Ml,Qwen2PreTrainedModel:()=>En,Qwen2VLForConditionalGeneration:()=>xl,Qwen2VLPreTrainedModel:()=>vl,Qwen3ForCausalLM:()=>bl,Qwen3Model:()=>yl,Qwen3PreTrainedModel:()=>Pn,RFDetrForObjectDetection:()=>oo,RFDetrModel:()=>An,RFDetrObjectDetectionOutput:()=>ao,RFDetrPreTrainedModel:()=>io,RTDetrForObjectDetection:()=>Ru,RTDetrModel:()=>ql,RTDetrObjectDetectionOutput:()=>ln,RTDetrPreTrainedModel:()=>ro,RTDetrV2ForObjectDetection:()=>Ql,RTDetrV2Model:()=>ju,RTDetrV2ObjectDetectionOutput:()=>In,RTDetrV2PreTrainedModel:()=>no,ResNetForImageClassification:()=>Vu,ResNetModel:()=>sc,ResNetPreTrainedModel:()=>mo,RoFormerForMaskedLM:()=>Sr,RoFormerForQuestionAnswering:()=>Kr,RoFormerForSequenceClassification:()=>Gr,RoFormerForTokenClassification:()=>kr,RoFormerModel:()=>Ts,RoFormerPreTrainedModel:()=>is,RobertaForMaskedLM:()=>Ct,RobertaForQuestionAnswering:()=>qr,RobertaForSequenceClassification:()=>as,RobertaForTokenClassification:()=>ni,RobertaModel:()=>$s,RobertaPreTrainedModel:()=>cs,SamImageSegmentationOutput:()=>Xu,SamModel:()=>Lc,SamPreTrainedModel:()=>Oc,SapiensForDepthEstimation:()=>cc,SapiensForNormalEstimation:()=>dc,SapiensForSemanticSegmentation:()=>lc,SapiensPreTrainedModel:()=>dn,SegformerForImageClassification:()=>op,SegformerForSemanticSegmentation:()=>pn,SegformerModel:()=>ip,SegformerPreTrainedModel:()=>Rn,Seq2SeqLMOutput:()=>xp,SequenceClassifierOutput:()=>Bt,SiglipModel:()=>rr,SiglipPreTrainedModel:()=>yn,SiglipTextModel:()=>Ea,SiglipVisionModel:()=>Pa,SmolLM3ForCausalLM:()=>Xa,SmolLM3Model:()=>Qa,SmolLM3PreTrainedModel:()=>Ei,SmolVLMForConditionalGeneration:()=>pi,SnacDecoderModel:()=>Xd,SnacEncoderModel:()=>Qd,SnacModel:()=>up,SnacPreTrainedModel:()=>Hn,SpeechT5ForSpeechToText:()=>od,SpeechT5ForTextToSpeech:()=>ad,SpeechT5HifiGan:()=>tp,SpeechT5Model:()=>ep,SpeechT5PreTrainedModel:()=>un,SqueezeBertForMaskedLM:()=>we,SqueezeBertForQuestionAnswering:()=>je,SqueezeBertForSequenceClassification:()=>ve,SqueezeBertModel:()=>ne,SqueezeBertPreTrainedModel:()=>B,StableLmForCausalLM:()=>Oo,StableLmModel:()=>Do,StableLmPreTrainedModel:()=>jn,Starcoder2ForCausalLM:()=>hd,Starcoder2Model:()=>pd,Starcoder2PreTrainedModel:()=>Io,StyleTextToSpeech2Model:()=>Zu,StyleTextToSpeech2PreTrainedModel:()=>id,Swin2SRForImageSuperResolution:()=>oc,Swin2SRModel:()=>ic,Swin2SRPreTrainedModel:()=>fo,SwinForImageClassification:()=>nc,SwinForSemanticSegmentation:()=>Uu,SwinModel:()=>rc,SwinPreTrainedModel:()=>Fn,T5ForConditionalGeneration:()=>us,T5Model:()=>es,T5PreTrainedModel:()=>Kt,TableTransformerForObjectDetection:()=>Nu,TableTransformerModel:()=>Yl,TableTransformerObjectDetectionOutput:()=>Zl,TableTransformerPreTrainedModel:()=>Jl,TokenClassifierOutput:()=>_s,TrOCRForCausalLM:()=>cd,TrOCRPreTrainedModel:()=>ld,UltravoxModel:()=>Wo,UltravoxPreTrainedModel:()=>Bd,UniSpeechForCTC:()=>Po,UniSpeechForSequenceClassification:()=>Kc,UniSpeechModel:()=>Gc,UniSpeechPreTrainedModel:()=>On,UniSpeechSatForAudioFrameClassification:()=>Xc,UniSpeechSatForCTC:()=>qc,UniSpeechSatForSequenceClassification:()=>Qc,UniSpeechSatModel:()=>Hc,UniSpeechSatPreTrainedModel:()=>Er,ViTForImageClassification:()=>Ol,ViTMAEModel:()=>Lu,ViTMAEPreTrainedModel:()=>Nl,ViTMSNForImageClassification:()=>Rr,ViTMSNModel:()=>Br,ViTMSNPreTrainedModel:()=>vr,ViTModel:()=>Dl,ViTPreTrainedModel:()=>Vi,VisionEncoderDecoderModel:()=>ci,VitMatteForImageMatting:()=>zu,VitMattePreTrainedModel:()=>Ul,VitPoseForPoseEstimation:()=>Bl,VitPosePreTrainedModel:()=>zl,VitsModel:()=>Fo,VitsModelOutput:()=>ia,VitsPreTrainedModel:()=>wd,VoxtralForConditionalGeneration:()=>Rd,Wav2Vec2BertForCTC:()=>Co,Wav2Vec2BertForSequenceClassification:()=>Yc,Wav2Vec2BertModel:()=>Jc,Wav2Vec2BertPreTrainedModel:()=>Ln,Wav2Vec2ForAudioFrameClassification:()=>Vc,Wav2Vec2ForCTC:()=>jc,Wav2Vec2ForSequenceClassification:()=>Nc,Wav2Vec2Model:()=>Rc,Wav2Vec2PreTrainedModel:()=>Tr,WavLMForAudioFrameClassification:()=>nd,WavLMForCTC:()=>sd,WavLMForSequenceClassification:()=>rd,WavLMForXVector:()=>$o,WavLMModel:()=>td,WavLMPreTrainedModel:()=>Jr,WeSpeakerResNetModel:()=>Fs,WeSpeakerResNetPreTrainedModel:()=>Ju,WhisperForConditionalGeneration:()=>li,WhisperModel:()=>Ks,WhisperPreTrainedModel:()=>ai,XLMForQuestionAnswering:()=>aa,XLMForSequenceClassification:()=>Ue,XLMForTokenClassification:()=>xt,XLMModel:()=>Et,XLMPreTrainedModel:()=>Qs,XLMRobertaForMaskedLM:()=>ca,XLMRobertaForQuestionAnswering:()=>ii,XLMRobertaForSequenceClassification:()=>Nt,XLMRobertaForTokenClassification:()=>da,XLMRobertaModel:()=>la,XLMRobertaPreTrainedModel:()=>Lr,XLMWithLMHeadModel:()=>nn,XVectorOutput:()=>$u,YolosForObjectDetection:()=>Fc,YolosModel:()=>Qu,YolosObjectDetectionOutput:()=>Dc,YolosPreTrainedModel:()=>To});var w=r("./src/configs.js"),T=r("./src/backends/onnx.js"),L=r("./src/utils/dtypes.js"),H=r("./src/utils/generic.js"),$=r("./src/utils/core.js"),_=r("./src/utils/hub.js"),I=r("./src/utils/constants.js"),D=r("./src/generation/logits_process.js"),b=r("./src/generation/configuration_utils.js"),h=r("./src/utils/tensor.js"),U=r("./src/utils/image.js"),z=r("./src/utils/maths.js"),Q=r("./src/generation/stopping_criteria.js"),ge=r("./src/generation/logits_sampler.js"),j=r("./src/env.js"),G=r("./src/models/whisper/generation_whisper.js"),Y=r("./src/models/whisper/common_whisper.js");const O={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11,ImageAudioTextToText:12},S=new Map,E=new Map,x=new Map;async function C(p,g,F){var V;let _e=((V=F.config)==null?void 0:V["transformers.js_config"])??{},$e=F.device??_e.device;$e&&typeof $e!="string"&&($e.hasOwnProperty(g)?$e=$e[g]:(console.warn(`device not specified for "${g}". Using the default device.`),$e=null));const e=$e??(j.apis.IS_NODE_ENV?"cpu":"wasm"),t=(0,T.deviceToExecutionProviders)(e),s=_e.device_config??{};s.hasOwnProperty(e)&&(_e={..._e,...s[e]});let n=F.dtype??_e.dtype;if(typeof n!="string"&&(n&&n.hasOwnProperty(g)?n=n[g]:(n=L.DEFAULT_DEVICE_DTYPE_MAPPING[e]??L.DATA_TYPES.fp32,console.warn(`dtype not specified for "${g}". Using the default dtype (${n}) for this device (${e}).`))),n===L.DATA_TYPES.auto){let se=_e.dtype;typeof se!="string"&&(se=se==null?void 0:se[g]),se&&se!==L.DATA_TYPES.auto&&L.DATA_TYPES.hasOwnProperty(se)?n=se:n=L.DEFAULT_DEVICE_DTYPE_MAPPING[e]??L.DATA_TYPES.fp32}const i=n;if(L.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(i)){if(i===L.DATA_TYPES.fp16&&e==="webgpu"&&!await(0,L.isWebGpuFp16Supported)())throw new Error(`The device (${e}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${i}. Should be one of: ${Object.keys(L.DATA_TYPES).join(", ")}`);const o=_e.kv_cache_dtype,a=o?typeof o=="string"?o:o[i]??"float32":void 0;if(a&&!["float32","float16"].includes(a))throw new Error(`Invalid kv_cache_dtype: ${a}. Should be one of: float32, float16`);const c={dtype:i,kv_cache_dtype:a,device:e},d=L.DEFAULT_DTYPE_SUFFIX_MAPPING[i],u=`${g}${d}.onnx`,f=`${F.subfolder??""}/${u}`,M={...F.session_options};M.executionProviders??(M.executionProviders=t);const v=_e.free_dimension_overrides;v?M.freeDimensionOverrides??(M.freeDimensionOverrides=v):e.startsWith("webnn")&&!M.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 k=j.apis.IS_NODE_ENV&&j.env.useFSCache,A=(0,_.getModelFile)(p,f,!0,F,k),R=F.use_external_data_format??_e.use_external_data_format;let ee=[];if(R){let se;typeof R=="object"?R.hasOwnProperty(u)?se=R[u]:R.hasOwnProperty(g)?se=R[g]:se=!1:se=R;const oe=+se;if(oe>_.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${oe}) exceeds the maximum allowed value (${_.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let Me=0;Me{const rt=await(0,_.getModelFile)(p,Ce,!0,F,k);Be(rt instanceof Uint8Array?{path:Ie,data:rt}:Ie)}))}}else M.externalData!==void 0&&(ee=M.externalData.map(async se=>{if(typeof se.data=="string"){const oe=await(0,_.getModelFile)(p,se.data,!0,F);return{...se,data:oe}}return se}));if(ee.length>0){const se=await Promise.all(ee);j.apis.IS_NODE_ENV||(M.externalData=se)}if(e==="webgpu"){const se=(0,w.getCacheShapes)(F.config,{prefix:"present"});if(Object.keys(se).length>0&&!(0,T.isONNXProxy)()){const oe={};for(const Me in se)oe[Me]="gpu-buffer";M.preferredOutputLocation=oe}}return{buffer_or_path:await A,session_options:M,session_config:c}}async function re(p,g,F){return Object.fromEntries(await Promise.all(Object.keys(g).map(async _e=>{const{buffer_or_path:$e,session_options:e,session_config:t}=await C(p,g[_e],F),s=await(0,T.createInferenceSession)($e,e,t);return[_e,s]})))}async function q(p,g,F){return Object.fromEntries(await Promise.all(Object.keys(g).map(async _e=>{const $e=await(0,_.getModelJSON)(p,g[_e],!1,F);return[_e,$e]})))}function pe(p,g){const F=Object.create(null),_e=[];for(const t of p.inputNames){const s=g[t];if(!(s instanceof h.Tensor)){_e.push(t);continue}F[t]=(0,T.isONNXProxy)()?s.clone():s}if(_e.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${_e.join(", ")}.`);const $e=Object.keys(g).length,e=p.inputNames.length;if($e>e){let t=Object.keys(g).filter(s=>!p.inputNames.includes(s));console.warn(`WARNING: Too many inputs were provided (${$e} > ${e}). The following inputs will be ignored: "${t.join(", ")}".`)}return F}let me=Promise.resolve();async function J(p,g){const F=pe(p,g);try{const _e=Object.fromEntries(Object.entries(F).map(([t,s])=>[t,s.ort_tensor])),$e=()=>p.run(_e),e=await(j.apis.IS_BROWSER_ENV||j.apis.IS_WEBWORKER_ENV?me=me.then($e):$e());return fe(e)}catch(_e){const $e=Object.fromEntries(Object.entries(F).map(([e,t])=>{const s={type:t.type,dims:t.dims,location:t.location};return s.location!=="gpu-buffer"&&(s.data=t.data),[e,s]}));throw console.error(`An error occurred during model execution: "${_e}".`),console.error("Inputs given to model:",$e),_e}}function fe(p){for(let g in p)(0,T.isONNXTensor)(p[g])?p[g]=new h.Tensor(p[g]):typeof p[g]=="object"&&fe(p[g]);return p}function de(p){if(p instanceof h.Tensor)return p;if(p.length===0)throw Error("items must be non-empty");if(Array.isArray(p[0])){if(p.some(g=>g.length!==p[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 h.Tensor("int64",BigInt64Array.from(p.flat().map(g=>BigInt(g))),[p.length,p[0].length])}else return new h.Tensor("int64",BigInt64Array.from(p.map(g=>BigInt(g))),[1,p.length])}function Te(p){return new h.Tensor("bool",[p],[1])}async function Pe(p,g){let{encoder_outputs:F,input_ids:_e,decoder_input_ids:$e,...e}=g;if(!F){const s=(0,$.pick)(g,p.sessions.model.inputNames);F=(await be(p,s)).last_hidden_state}return e.input_ids=$e,e.encoder_hidden_states=F,p.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(e.encoder_attention_mask=g.attention_mask),await Oe(p,e,!0)}async function be(p,g){const F=p.sessions.model,_e=(0,$.pick)(g,F.inputNames);if(F.inputNames.includes("inputs_embeds")&&!_e.inputs_embeds){if(!g.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");_e.inputs_embeds=await p.encode_text({input_ids:g.input_ids})}if(F.inputNames.includes("token_type_ids")&&!_e.token_type_ids){if(!_e.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");_e.token_type_ids=(0,h.zeros_like)(_e.input_ids)}if(F.inputNames.includes("pixel_mask")&&!_e.pixel_mask){if(!_e.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const $e=_e.pixel_values.dims;_e.pixel_mask=(0,h.ones)([$e[0],$e[2],$e[3]])}return await J(F,_e)}async function He(p,g){const F=await p.encode(g);return await p.decode(F)}async function Oe(p,g,F=!1){const _e=p.sessions[F?"decoder_model_merged":"model"],{past_key_values:$e,...e}=g;if(_e.inputNames.includes("use_cache_branch")&&(e.use_cache_branch=Te(!!$e)),_e.inputNames.includes("position_ids")&&e.attention_mask&&!e.position_ids){const s=["paligemma","gemma3_text","gemma3"].includes(p.config.model_type)?1:0;e.position_ids=Ye(e,$e,s)}p.addPastKeyValues(e,$e);const t=(0,$.pick)(e,_e.inputNames);return await J(_e,t)}function he({modality_token_id:p,inputs_embeds:g,modality_features:F,input_ids:_e,attention_mask:$e}){const e=_e.tolist().map(i=>i.reduce((o,a,c)=>(a==p&&o.push(c),o),[])),t=e.reduce((i,o)=>i+o.length,0),s=F.dims[0];if(t!==s)throw new Error(`Number of tokens and features do not match: tokens: ${t}, features ${s}`);let n=0;for(let i=0;ie.dims[1]||$e[$e.at(-1)])),{...F,decoder_input_ids:de(g)}}function le(p,...g){return p.config.is_encoder_decoder?We(p,...g):wt(p,...g)}function Ee(p,g,F,_e){const $e=!!F.past_key_values;return _e.guidance_scale!==null&&_e.guidance_scale>1&&($e?F.input_ids=(0,h.cat)([F.input_ids,F.input_ids],0):(F.input_ids=(0,h.cat)([F.input_ids,(0,h.full_like)(F.input_ids,BigInt(_e.pad_token_id))],0),F.attention_mask=(0,h.cat)([F.attention_mask,(0,h.full_like)(F.attention_mask,0n)],0))),($e||!F.pixel_values)&&(F.pixel_values=(0,h.full)([0,0,3,384,384],1)),$e&&(F.images_seq_mask=new h.Tensor("bool",new Array(0+1).fill(!0).fill(!1,0,1),[1,0+1]),F.images_emb_mask=new h.Tensor("bool",new Array(0).fill(!1),[1,1,0])),F}class X extends H.Callable{constructor(F,_e,$e){super();ie(this,"main_input_name","input_ids");ie(this,"forward_params",["input_ids","attention_mask"]);this.config=F,this.sessions=_e,this.configs=$e;const e=x.get(this.constructor),t=S.get(e);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,t){case O.DecoderOnly:this.can_generate=!0,this._forward=Oe,this._prepare_inputs_for_generation=wt;break;case O.Seq2Seq:case O.Vision2Seq:case O.Musicgen:this.can_generate=!0,this._forward=Pe,this._prepare_inputs_for_generation=We;break;case O.EncoderDecoder:this._forward=Pe;break;case O.ImageTextToText:this.can_generate=!0,this._forward=Xe,this._prepare_inputs_for_generation=le;break;case O.AudioTextToText:this.can_generate=!0,this._forward=Fe,this._prepare_inputs_for_generation=le;break;case O.Phi3V:case O.ImageAudioTextToText:this.can_generate=!0,this._prepare_inputs_for_generation=le;break;case O.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=Ee;break;case O.AutoEncoder:this._forward=He;break;default:this._forward=be;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var _e;const F=[];for(const $e of Object.values(this.sessions))(_e=$e==null?void 0:$e.handler)!=null&&_e.dispose&&F.push($e.handler.dispose());return await Promise.all(F)}static async from_pretrained(F,{progress_callback:_e=null,config:$e=null,cache_dir:e=null,local_files_only:t=!1,revision:s="main",model_file_name:n=null,subfolder:i="onnx",device:o=null,dtype:a=null,use_external_data_format:c=null,session_options:d={}}={}){let u={progress_callback:_e,config:$e,cache_dir:e,local_files_only:t,revision:s,model_file_name:n,subfolder:i,device:o,dtype:a,use_external_data_format:c,session_options:d};const f=x.get(this),M=S.get(f);$e=u.config=await w.AutoConfig.from_pretrained(F,u);let v;if(M===O.DecoderOnly)v=await Promise.all([re(F,{model:u.model_file_name??"model"},u),q(F,{generation_config:"generation_config.json"},u)]);else if(M===O.Seq2Seq||M===O.Vision2Seq)v=await Promise.all([re(F,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},u),q(F,{generation_config:"generation_config.json"},u)]);else if(M===O.MaskGeneration)v=await Promise.all([re(F,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},u)]);else if(M===O.EncoderDecoder)v=await Promise.all([re(F,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},u)]);else if(M===O.ImageTextToText){const k={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};$e.is_encoder_decoder&&(k.model="encoder_model"),v=await Promise.all([re(F,k,u),q(F,{generation_config:"generation_config.json"},u)])}else if(M===O.AudioTextToText){const k={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};v=await Promise.all([re(F,k,u),q(F,{generation_config:"generation_config.json"},u)])}else if(M===O.ImageAudioTextToText){const k={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};v=await Promise.all([re(F,k,u),q(F,{generation_config:"generation_config.json"},u)])}else if(M===O.Musicgen)v=await Promise.all([re(F,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},u),q(F,{generation_config:"generation_config.json"},u)]);else if(M===O.MultiModality)v=await Promise.all([re(F,{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"},u),q(F,{generation_config:"generation_config.json"},u)]);else if(M===O.Phi3V)v=await Promise.all([re(F,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},u),q(F,{generation_config:"generation_config.json"},u)]);else if(M===O.AutoEncoder)v=await Promise.all([re(F,{encoder_model:"encoder_model",decoder_model:"decoder_model"},u)]);else{if(M!==O.EncoderOnly){const k=f??($e==null?void 0:$e.model_type);k!=="custom"&&console.warn(`Model type for '${k}' not found, assuming encoder-only architecture. Please report this at ${I.GITHUB_ISSUE_URL}.`)}v=await Promise.all([re(F,{model:u.model_file_name??"model"},u)])}return new this($e,...v)}async _call(F){return await this.forward(F)}async forward(F){return await this._forward(this,F)}get generation_config(){var F;return((F=this.configs)==null?void 0:F.generation_config)??null}_get_logits_warper(F){const _e=new D.LogitsProcessorList;return F.temperature!==null&&F.temperature!==1&&_e.push(new D.TemperatureLogitsWarper(F.temperature)),F.top_k!==null&&F.top_k!==0&&_e.push(new D.TopKLogitsWarper(F.top_k)),F.top_p!==null&&F.top_p<1&&_e.push(new D.TopPLogitsWarper(F.top_p)),_e}_get_logits_processor(F,_e,$e=null){const e=new D.LogitsProcessorList;if(F.repetition_penalty!==null&&F.repetition_penalty!==1&&e.push(new D.RepetitionPenaltyLogitsProcessor(F.repetition_penalty)),F.no_repeat_ngram_size!==null&&F.no_repeat_ngram_size>0&&e.push(new D.NoRepeatNGramLogitsProcessor(F.no_repeat_ngram_size)),F.bad_words_ids!==null&&e.push(new D.NoBadWordsLogitsProcessor(F.bad_words_ids,F.eos_token_id)),F.min_length!==null&&F.eos_token_id!==null&&F.min_length>0&&e.push(new D.MinLengthLogitsProcessor(F.min_length,F.eos_token_id)),F.min_new_tokens!==null&&F.eos_token_id!==null&&F.min_new_tokens>0&&e.push(new D.MinNewTokensLengthLogitsProcessor(_e,F.min_new_tokens,F.eos_token_id)),F.forced_bos_token_id!==null&&e.push(new D.ForcedBOSTokenLogitsProcessor(F.forced_bos_token_id)),F.forced_eos_token_id!==null&&e.push(new D.ForcedEOSTokenLogitsProcessor(F.max_length,F.forced_eos_token_id)),F.begin_suppress_tokens!==null){const t=_e>1||F.forced_bos_token_id===null?_e:_e+1;e.push(new D.SuppressTokensAtBeginLogitsProcessor(F.begin_suppress_tokens,t))}return F.guidance_scale!==null&&F.guidance_scale>1&&e.push(new D.ClassifierFreeGuidanceLogitsProcessor(F.guidance_scale)),$e!==null&&e.extend($e),e}_prepare_generation_config(F,_e,$e=b.GenerationConfig){const e={...this.config};for(const s of["decoder","generator","text_config"])s in e&&Object.assign(e,e[s]);const t=new $e(e);return Object.assign(t,this.generation_config??{}),F&&Object.assign(t,F),_e&&Object.assign(t,(0,$.pick)(_e,Object.getOwnPropertyNames(t))),t}_get_stopping_criteria(F,_e=null){const $e=new Q.StoppingCriteriaList;return F.max_length!==null&&$e.push(new Q.MaxLengthCriteria(F.max_length,this.config.max_position_embeddings??null)),F.eos_token_id!==null&&$e.push(new Q.EosTokenCriteria(F.eos_token_id)),_e&&$e.extend(_e),$e}_validate_model_class(){if(!this.can_generate){const F=[Ko,nu,tu,Qn],_e=x.get(this.constructor),$e=new Set,e=this.config.model_type;for(const s of F){const n=s.get(e);n&&$e.add(n[0])}let t=`The current model class (${_e}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw $e.size>0&&(t+=` Please use the following class instead: ${[...$e].join(", ")}`),Error(t)}}prepare_inputs_for_generation(...F){return this._prepare_inputs_for_generation(this,...F)}_update_model_kwargs_for_generation({generated_input_ids:F,outputs:_e,model_inputs:$e,is_encoder_decoder:e}){return $e.past_key_values=this.getPastKeyValues(_e,$e.past_key_values),$e.input_ids=new h.Tensor("int64",F.flat(),[F.length,1]),e||($e.attention_mask=(0,h.cat)([$e.attention_mask,(0,h.ones)([$e.attention_mask.dims[0],1])],1)),$e.position_ids=null,$e}_prepare_model_inputs({inputs:F,bos_token_id:_e,model_kwargs:$e}){const e=(0,$.pick)($e,this.forward_params),t=this.main_input_name;if(t in e){if(F)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[t]=F;return{inputs_tensor:e[t],model_inputs:e,model_input_name:t}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:F,model_inputs:_e,model_input_name:$e,generation_config:e}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!_e.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:s,pixel_values:n,attention_mask:i,...o}=_e,a=await this._prepare_inputs_embeds(_e);_e={...o,...(0,$.pick)(a,["inputs_embeds","attention_mask"])}}let{last_hidden_state:t}=await be(this,_e);if(e.guidance_scale!==null&&e.guidance_scale>1)t=(0,h.cat)([t,(0,h.full_like)(t,0)],0),"attention_mask"in _e&&(_e.attention_mask=(0,h.cat)([_e.attention_mask,(0,h.zeros_like)(_e.attention_mask)],0));else if(_e.decoder_input_ids){const s=de(_e.decoder_input_ids).dims[0];if(s!==t.dims[0]){if(t.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${t.dims[0]}) than the decoder inputs (${s}).`);t=(0,h.cat)(Array.from({length:s},()=>t),0)}}return _e.encoder_outputs=t,_e}_prepare_decoder_input_ids_for_generation({batch_size:F,model_input_name:_e,model_kwargs:$e,decoder_start_token_id:e,bos_token_id:t,generation_config:s}){let{decoder_input_ids:n,...i}=$e;if(!(n instanceof h.Tensor)){if(n)Array.isArray(n[0])||(n=Array.from({length:F},()=>n));else if(e??(e=t),this.config.model_type==="musicgen")n=Array.from({length:F*this.config.decoder.num_codebooks},()=>[e]);else if(Array.isArray(e)){if(e.length!==F)throw new Error(`\`decoder_start_token_id\` expcted to have length ${F} but got ${e.length}`);n=e}else n=Array.from({length:F},()=>[e]);n=de(n)}return $e.decoder_attention_mask=(0,h.ones_like)(n),{input_ids:n,model_inputs:i}}async generate({inputs:F=null,generation_config:_e=null,logits_processor:$e=null,stopping_criteria:e=null,streamer:t=null,...s}){this._validate_model_class(),_e=this._prepare_generation_config(_e,s);let{inputs_tensor:n,model_inputs:i,model_input_name:o}=this._prepare_model_inputs({inputs:F,model_kwargs:s});const a=this.config.is_encoder_decoder;a&&("encoder_outputs"in i||(i=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:n,model_inputs:i,model_input_name:o,generation_config:_e})));let c;a?{input_ids:c,model_inputs:i}=this._prepare_decoder_input_ids_for_generation({batch_size:i[o].dims.at(0),model_input_name:o,model_kwargs:i,decoder_start_token_id:_e.decoder_start_token_id,bos_token_id:_e.bos_token_id,generation_config:_e}):c=i[o];let d=c.dims.at(-1);_e.max_new_tokens!==null&&(_e.max_length=d+_e.max_new_tokens);const u=this._get_logits_processor(_e,d,$e),f=this._get_stopping_criteria(_e,e),M=i[o].dims.at(0),v=ge.LogitsSampler.getSampler(_e),k=new Array(M).fill(0),A=c.tolist();t&&t.put(A);let R,ee={};for(;;){if(i=this.prepare_inputs_for_generation(A,i,_e),R=await this.forward(i),_e.output_attentions&&_e.return_dict_in_generate){const Ce=this.getAttentions(R);for(const Be in Ce)Be in ee||(ee[Be]=[]),ee[Be].push(Ce[Be])}const se=R.logits.slice(null,-1,null),oe=u(A,se),Me=[];for(let Ce=0;CeCe))break;i=this._update_model_kwargs_for_generation({generated_input_ids:Me,outputs:R,model_inputs:i,is_encoder_decoder:a})}t&&t.end();const W=this.getPastKeyValues(R,i.past_key_values,!0),V=new h.Tensor("int64",A.flat(),[A.length,A[0].length]);if(_e.return_dict_in_generate)return{sequences:V,past_key_values:W,...ee};for(const se of Object.values(R))se.location==="gpu-buffer"&&se.dispose();return V}getPastKeyValues(F,_e,$e=!1){const e=Object.create(null);for(const t in F)if(t.startsWith("present")){const s=t.replace("present_conv","past_conv").replace("present","past_key_values"),n=t.includes("encoder");if(n&&_e?e[s]=_e[s]:e[s]=F[t],_e&&(!n||$e)){const i=_e[s];i.location==="gpu-buffer"&&i.dispose()}}return e}getAttentions(F){const _e={};for(const $e of["cross_attentions","encoder_attentions","decoder_attentions"])for(const e in F)e.startsWith($e)&&($e in _e||(_e[$e]=[]),_e[$e].push(F[e]));return _e}addPastKeyValues(F,_e){var $e,e,t;if(_e)Object.assign(F,_e);else{const s=this.sessions.decoder_model_merged??this.sessions.model,n=((e=($e=F[this.main_input_name]??F.attention_mask)==null?void 0:$e.dims)==null?void 0:e[0])??1,i=((t=s==null?void 0:s.config)==null?void 0:t.kv_cache_dtype)??"float32",o=i==="float16"?h.DataTypeMap.float16:h.DataTypeMap.float32,a=(0,w.getCacheShapes)(this.config,{batch_size:n});for(const c in a){const d=a[c].reduce((u,f)=>u*f,1);F[c]=new h.Tensor(i,new o(d),a[c])}}}async encode_image({pixel_values:F}){return(await J(this.sessions.vision_encoder,{pixel_values:F})).image_features}async encode_text({input_ids:F}){return(await J(this.sessions.embed_tokens,{input_ids:F})).inputs_embeds}async encode_audio({audio_values:F}){return(await J(this.sessions.audio_encoder,{audio_values:F})).audio_features}}class ke{}class Ne extends ke{constructor({last_hidden_state:g,hidden_states:F=null,attentions:_e=null}){super(),this.last_hidden_state=g,this.hidden_states=F,this.attentions=_e}}class Ve extends X{}class De extends Ve{}class Ke extends Ve{async _call(g){return new Ms(await super._call(g))}}class Ae extends Ve{async _call(g){return new Bt(await super._call(g))}}class qe extends Ve{async _call(g){return new _s(await super._call(g))}}class et extends Ve{async _call(g){return new xs(await super._call(g))}}class ut extends X{}class Re extends ut{}class Mt extends ut{async _call(g){return new Ms(await super._call(g))}}class lt extends ut{async _call(g){return new Bt(await super._call(g))}}class pt extends ut{async _call(g){return new _s(await super._call(g))}}class yt extends ut{async _call(g){return new xs(await super._call(g))}}class ct extends X{}class ht extends ct{}class vt extends ct{async _call(g){return new Ms(await super._call(g))}}class Wt extends ct{async _call(g){return new Bt(await super._call(g))}}class Qt extends ct{async _call(g){return new _s(await super._call(g))}}class jt extends X{}class bs extends jt{}class ds extends jt{}class Ls extends X{}class Js extends Ls{}class is extends X{}class Ts extends is{}class Sr extends is{async _call(g){return new Ms(await super._call(g))}}class Gr extends is{async _call(g){return new Bt(await super._call(g))}}class kr extends is{async _call(g){return new _s(await super._call(g))}}class Kr extends is{async _call(g){return new xs(await super._call(g))}}class At extends X{}class Ir extends At{}class wr extends At{async _call(g){return new Ms(await super._call(g))}}class Vt extends At{async _call(g){return new Bt(await super._call(g))}}class dr extends At{async _call(g){return new _s(await super._call(g))}}class y extends At{async _call(g){return new xs(await super._call(g))}}class te extends X{}class N extends te{}class Z extends te{async _call(g){return new Ms(await super._call(g))}}class ue extends te{async _call(g){return new Bt(await super._call(g))}}class Se extends te{async _call(g){return new _s(await super._call(g))}}class ze extends te{async _call(g){return new xs(await super._call(g))}}class _t extends X{}class $t extends _t{}class kt extends _t{async _call(g){return new Ms(await super._call(g))}}class mt extends _t{async _call(g){return new Bt(await super._call(g))}}class bt extends _t{async _call(g){return new _s(await super._call(g))}}class Yt extends _t{async _call(g){return new xs(await super._call(g))}}class ss extends X{}class Ns extends ss{}class Hs extends ss{async _call(g){return new Ms(await super._call(g))}}class Es extends ss{async _call(g){return new Bt(await super._call(g))}}class ms extends ss{async _call(g){return new _s(await super._call(g))}}class Mr extends ss{async _call(g){return new xs(await super._call(g))}}class qs extends X{}class Ar extends qs{}class Vs extends qs{async _call(g){return new Ms(await super._call(g))}}class zs extends qs{async _call(g){return new Bt(await super._call(g))}}class Us extends qs{async _call(g){return new _s(await super._call(g))}}class yr extends qs{async _call(g){return new xs(await super._call(g))}}class Ps extends X{}class Ys extends Ps{}class ur extends Ps{async _call(g){return new Bt(await super._call(g))}}class br extends Ps{async _call(g){return new _s(await super._call(g))}}class It extends Ps{async _call(g){return new xs(await super._call(g))}}class pr extends Ps{async _call(g){return new Ms(await super._call(g))}}class Zs extends X{}class Fr extends Zs{}class Bs extends Zs{async _call(g){return new Ms(await super._call(g))}}class Ze extends Zs{async _call(g){return new Bt(await super._call(g))}}class tt extends Zs{async _call(g){return new _s(await super._call(g))}}class ft extends X{}class ns extends ft{}class Ut extends ft{async _call(g){return new Ms(await super._call(g))}}class ks extends ft{async _call(g){return new Bt(await super._call(g))}}class Dr extends ft{async _call(g){return new xs(await super._call(g))}}class Ws extends X{}class Le extends Ws{}class Or extends Ws{async _call(g){return new Ms(await super._call(g))}}class rn extends Ws{async _call(g){return new Bt(await super._call(g))}}class xe extends Ws{async _call(g){return new _s(await super._call(g))}}class P extends Ws{async _call(g){return new xs(await super._call(g))}}class B extends X{}class ne extends B{}class we extends B{async _call(g){return new Ms(await super._call(g))}}class ve extends B{async _call(g){return new Bt(await super._call(g))}}class je extends B{async _call(g){return new xs(await super._call(g))}}class st extends X{}class dt extends st{}class nt extends st{async _call(g){return new Bt(await super._call(g))}}class gt extends st{async _call(g){return new xs(await super._call(g))}}class Ot extends st{async _call(g){return new Ms(await super._call(g))}}class Kt extends X{constructor(){super(...arguments);ie(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class es extends Kt{}class us extends Kt{}class rs extends X{}class ps extends rs{}class Is extends rs{}class As extends X{}class hr extends As{}class Cs extends As{}class er extends X{}class os extends er{}class fs extends er{}class Rs extends er{async _call(g){return new Bt(await super._call(g))}}class Gs extends X{}class or extends Gs{}class vs extends Gs{}class ar extends Gs{async _call(g){return new Bt(await super._call(g))}}class ys extends Gs{}class hs extends X{}class gs extends hs{}class Lt extends hs{}class Ht extends X{}class lr extends Ht{}class Hr extends Ht{}class cs extends X{}class $s extends cs{}class Ct extends cs{async _call(g){return new Ms(await super._call(g))}}class as extends cs{async _call(g){return new Bt(await super._call(g))}}class ni extends cs{async _call(g){return new _s(await super._call(g))}}class qr extends cs{async _call(g){return new xs(await super._call(g))}}class Qs extends X{}class Et extends Qs{}class nn extends Qs{async _call(g){return new Ms(await super._call(g))}}class Ue extends Qs{async _call(g){return new Bt(await super._call(g))}}class xt extends Qs{async _call(g){return new _s(await super._call(g))}}class aa extends Qs{async _call(g){return new xs(await super._call(g))}}class Lr extends X{}class la extends Lr{}class ca extends Lr{async _call(g){return new Ms(await super._call(g))}}class Nt extends Lr{async _call(g){return new Bt(await super._call(g))}}class da extends Lr{async _call(g){return new _s(await super._call(g))}}class ii extends Lr{async _call(g){return new xs(await super._call(g))}}class oi extends X{}class ua extends oi{}class pa extends oi{}class ai extends X{constructor(){super(...arguments);ie(this,"requires_attention_mask",!1);ie(this,"main_input_name","input_features");ie(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Ks extends ai{}class li extends ai{_prepare_generation_config(g,F){return super._prepare_generation_config(g,F,G.WhisperGenerationConfig)}_retrieve_init_tokens(g){const F=[g.decoder_start_token_id];let _e=g.language;const $e=g.task;if(g.is_multilingual){_e||(console.warn("No language specified - defaulting to English (en)."),_e="en");const t=`<|${(0,Y.whisper_language_to_code)(_e)}|>`;F.push(g.lang_to_id[t]),F.push(g.task_to_id[$e??"transcribe"])}else if(_e||$e)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!g.return_timestamps&&g.no_timestamps_token_id&&F.at(-1)!==g.no_timestamps_token_id?F.push(g.no_timestamps_token_id):g.return_timestamps&&F.at(-1)===g.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),F.pop()),F.filter(e=>e!=null)}async generate({inputs:g=null,generation_config:F=null,logits_processor:_e=null,stopping_criteria:$e=null,...e}){F=this._prepare_generation_config(F,e);const t=e.decoder_input_ids??this._retrieve_init_tokens(F);if(F.return_timestamps&&(_e??(_e=new D.LogitsProcessorList),_e.push(new D.WhisperTimeStampLogitsProcessor(F,t))),F.begin_suppress_tokens&&(_e??(_e=new D.LogitsProcessorList),_e.push(new D.SuppressTokensAtBeginLogitsProcessor(F.begin_suppress_tokens,t.length))),F.return_token_timestamps){if(!F.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.");F.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),F.output_attentions=!0,F.return_dict_in_generate=!0}const s=await super.generate({inputs:g,generation_config:F,logits_processor:_e,decoder_input_ids:t,...e});return F.return_token_timestamps&&(s.token_timestamps=this._extract_token_timestamps(s,F.alignment_heads,F.num_frames)),s}_extract_token_timestamps(g,F,_e=null,$e=.02){if(!g.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`.");_e==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 t=g.cross_attentions,s=Array.from({length:this.config.decoder_layers},(f,M)=>(0,h.cat)(t.map(v=>v[M]),2)),n=(0,h.stack)(F.map(([f,M])=>{if(f>=s.length)throw new Error(`Layer index ${f} is out of bounds for cross attentions (length ${s.length}).`);return _e?s[f].slice(null,M,null,[0,_e]):s[f].slice(null,M)})).transpose(1,0,2,3),[i,o]=(0,h.std_mean)(n,-2,0,!0),a=n.clone();for(let f=0;fv[V+1]-v[V]),R=(0,$.mergeArrays)([1],A).map(W=>!!W),ee=[];for(let W=0;WArray.from({length:g.dims[0]},A=>Array.from({length:g.dims[1]},R=>1))),u=F?F.tolist():[],f=_e?_e.tolist():[];let M=0,v=0;for(let k=0;kc[k][Dt]==1),ee=A.reduce((ot,Dt,zt)=>(Dt==n&&ot.push(zt),ot),[]).map(ot=>A[ot+1]),W=ee.filter(ot=>ot==t).length,V=ee.filter(ot=>ot==s).length;let se=[],oe=0,Me=W,Ie=V;for(let ot=0;otSs>oe&&ls==t),zt=A.findIndex((ls,Ss)=>Ss>oe&&ls==s),Pt=Me>0&&Dt!==-1?Dt:A.length+1,at=Ie>0&&zt!==-1?zt:A.length+1;let Zt,Rt,Gt,Je;Pt0?(0,z.max)(se.at(-1))[0]+1:0;se.push(Array.from({length:3*Ds},(ls,Ss)=>ei+Ss%Ds));const Su=Ds+ei,fr=it*Ft*qt,tn=Array.from({length:fr},(ls,Ss)=>Su+Math.floor(Ss/(Ft*qt))),oa=Array.from({length:fr},(ls,Ss)=>Su+Math.floor(Ss/qt)%Ft),Os=Array.from({length:fr},(ls,Ss)=>Su+Ss%qt);se.push([tn,oa,Os].flat()),oe=Zt+fr}if(oe0?(0,z.max)(se.at(-1))[0]+1:0,Dt=A.length-oe;se.push(Array.from({length:3*Dt},(zt,Pt)=>ot+Pt%Dt))}const Ce=se.reduce((ot,Dt)=>ot+Dt.length,0),Be=new Array(Ce);let Ge=0;for(let ot=0;ot<3;++ot)for(let Dt=0;Dta[M%a.length]),u=Array.from({length:c[0]},(f,M)=>(0,z.max)(a.subarray(c[1]*M,c[1]*(M+1)))[0]+1n+BigInt(c[1]));return[new h.Tensor("int64",d,[3,...c]),new h.Tensor("int64",u,[u.length,1])]}else{const[a,c]=g.dims,d=BigInt64Array.from({length:3*a*c},(u,f)=>BigInt(Math.floor(f%c/a)));return[new h.Tensor("int64",d,[3,...g.dims]),(0,h.zeros)([a,1])]}}async encode_image({pixel_values:g,image_grid_thw:F}){return(await J(this.sessions.vision_encoder,{pixel_values:g,grid_thw:F})).image_features}_merge_input_ids_with_image_features(g){return K({image_token_id:this.config.image_token_id,...g})}prepare_inputs_for_generation(g,F,_e){if(F.attention_mask&&!F.position_ids)if(!F.past_key_values)[F.position_ids,F.rope_deltas]=this.get_rope_index(F.input_ids,F.image_grid_thw,F.video_grid_thw,F.attention_mask);else{F.pixel_values=null;const $e=BigInt(Object.values(F.past_key_values)[0].dims.at(-2)),e=F.rope_deltas.map(t=>$e+t);F.position_ids=(0,h.stack)([e,e,e],0)}return F}}class Bi extends X{}class Tl extends Bi{}class Ri extends Bi{}class ji extends X{}class El extends ji{}class Pl extends ji{}class Cl extends X{}class $l extends Cl{}class Sl extends Cl{}class Xs extends X{}class kl extends Xs{}class Il extends Xs{}class Ni extends X{}class Al extends Ni{}class Fl extends Ni{}class Vi extends X{}class Dl extends Vi{}class Ol extends Vi{async _call(g){return new Bt(await super._call(g))}}class Ui extends X{}class Ll extends Ui{}class Ou extends Ui{async _call(g){return new Bt(await super._call(g))}}class zl extends X{}class Bl extends zl{}class Wi extends X{}class Rl extends Wi{}class jl extends Wi{async _call(g){return new Bt(await super._call(g))}}class Nl extends X{}class Lu extends Nl{}class vr extends X{}class Br extends vr{}class Rr extends vr{async _call(g){return new Bt(await super._call(g))}}class Gi extends X{}class jr extends Gi{}class ws extends X{}class Vl extends ws{}class Ki extends ws{async _call(g){return new Bt(await super._call(g))}}class Ul extends X{}class zu extends Ul{async _call(g){return new na(await super._call(g))}}class Xr extends X{}class Hi extends Xr{}class qi extends Xr{async _call(g){return new Bt(await super._call(g))}}class Qi extends X{}class Wl extends Qi{}class Xi extends Qi{async _call(g){return new Bt(await super._call(g))}}class Cn extends X{}class Gl extends Cn{}class Ji extends Cn{}class Yi extends X{}class $n extends Yi{}class Zi extends Yi{}class eo extends X{}class Kl extends eo{}class Bu extends eo{async _call(g){return new Bt(await super._call(g))}}class Sn extends X{}class to extends Sn{}class an extends Sn{async _call(g){return new kn(await super._call(g))}}class so extends Sn{async _call(g){return new Hl(await super._call(g))}}class kn extends ke{constructor({logits:g,pred_boxes:F}){super(),this.logits=g,this.pred_boxes=F}}class Hl extends ke{constructor({logits:g,pred_boxes:F,pred_masks:_e}){super(),this.logits=g,this.pred_boxes=F,this.pred_masks=_e}}class ro extends X{}class ql extends ro{}class Ru extends ro{async _call(g){return new ln(await super._call(g))}}class ln extends ke{constructor({logits:g,pred_boxes:F}){super(),this.logits=g,this.pred_boxes=F}}class no extends X{}class ju extends no{}class Ql extends no{async _call(g){return new In(await super._call(g))}}class In extends ln{}class io extends X{}class An extends io{}class oo extends io{async _call(g){return new ao(await super._call(g))}}class ao extends ln{}class lo extends X{}class Xl extends lo{}class co extends lo{async _call(g){return new ln(await super._call(g))}}class Jl extends X{}class Yl extends Jl{}class Nu extends Jl{async _call(g){return new Zl(await super._call(g))}}class Zl extends kn{}class uo extends X{}class ec extends uo{}class po extends uo{async _call(g){return new Bt(await super._call(g))}}class ho extends X{}class tc extends ho{}class _o extends ho{async _call(g){return new Bt(await super._call(g))}}class mo extends X{}class sc extends mo{}class Vu extends mo{async _call(g){return new Bt(await super._call(g))}}class Fn extends X{}class rc extends Fn{}class nc extends Fn{async _call(g){return new Bt(await super._call(g))}}class Uu extends Fn{}class fo extends X{}class ic extends fo{}class oc extends fo{}class go extends X{}class ac extends go{}class Wu extends go{}class Dn extends X{}class cn extends Dn{}class dn extends X{}class lc extends dn{}class cc extends dn{}class dc extends dn{}class uc extends X{}class wo extends uc{}class pc extends X{}class hc extends pc{}class _c extends X{}class Gu extends _c{}class Mo extends X{}class yo extends Mo{}class mc extends Mo{}class bo extends X{}class fc extends bo{}class Ku extends bo{}class gc extends X{}class wc extends gc{}class Mc extends X{}class yc extends Mc{}class bc extends Mc{async _call(g){return new Bt(await super._call(g))}}class vo extends X{}class vc extends vo{}class Hu extends vo{async _call(g){return new Bt(await super._call(g))}}class xo extends X{}class xc extends xo{}class Tc extends xo{async _call(g){return new Bt(await super._call(g))}}class Ec extends X{}class Pc extends Ec{}class Cc extends Ec{async _call(g){return new Bt(await super._call(g))}}class $c extends X{}class Sc extends $c{}class qu extends X{}class kc extends qu{}class Ic extends X{}class Ac extends Ic{}class To extends X{}class Qu extends To{}class Fc extends To{async _call(g){return new Dc(await super._call(g))}}class Dc extends ke{constructor({logits:g,pred_boxes:F}){super(),this.logits=g,this.pred_boxes=F}}class Oc extends X{}class Lc extends Oc{async get_image_embeddings({pixel_values:g}){return await be(this,{pixel_values:g})}async forward(g){if((!g.image_embeddings||!g.image_positional_embeddings)&&(g={...g,...await this.get_image_embeddings(g)}),!g.input_labels&&g.input_points){const _e=g.input_points.dims.slice(0,-1),$e=_e.reduce((e,t)=>e*t,1);g.input_labels=new h.Tensor("int64",new BigInt64Array($e).fill(1n),_e)}const F={image_embeddings:g.image_embeddings,image_positional_embeddings:g.image_positional_embeddings};return g.input_points&&(F.input_points=g.input_points),g.input_labels&&(F.input_labels=g.input_labels),g.input_boxes&&(F.input_boxes=g.input_boxes),await J(this.sessions.prompt_encoder_mask_decoder,F)}async _call(g){return new Xu(await super._call(g))}}class Xu extends ke{constructor({iou_scores:g,pred_masks:F}){super(),this.iou_scores=g,this.pred_masks=F}}class ir extends X{}class mr extends ir{}class Nr extends ir{}class xr extends X{}class zc extends xr{}class Bc extends xr{}class Tr extends X{}class Rc extends Tr{}class jc extends Tr{async _call(g){return new en(await super._call(g))}}class Nc extends Tr{async _call(g){return new Bt(await super._call(g))}}class Vc extends Tr{async _call(g){return new _s(await super._call(g))}}class Eo extends X{}class Uc extends Eo{}class Wc extends Eo{async _call(g){return new _s(await super._call(g))}}class Ju extends X{}class Fs extends Ju{}class On extends X{}class Gc extends On{}class Po extends On{async _call(g){return new en(await super._call(g))}}class Kc extends On{async _call(g){return new Bt(await super._call(g))}}class Er extends X{}class Hc extends Er{}class qc extends Er{async _call(g){return new en(await super._call(g))}}class Qc extends Er{async _call(g){return new Bt(await super._call(g))}}class Xc extends Er{async _call(g){return new _s(await super._call(g))}}class Ln extends X{}class Jc extends Ln{}class Co extends Ln{async _call(g){return new en(await super._call(g))}}class Yc extends Ln{async _call(g){return new Bt(await super._call(g))}}class Yu extends X{}class Zc extends Tr{}class ed extends Tr{async _call(g){return new en(await super._call(g))}}class zn extends Tr{async _call(g){return new Bt(await super._call(g))}}class Jr extends X{}class td extends Jr{}class sd extends Jr{async _call(g){return new en(await super._call(g))}}class rd extends Jr{async _call(g){return new Bt(await super._call(g))}}class $o extends Jr{async _call(g){return new $u(await super._call(g))}}class nd extends Jr{async _call(g){return new _s(await super._call(g))}}class id extends X{}class Zu extends id{}class un extends X{}class ep extends un{}class od extends un{}class ad extends un{async generate_speech(g,F,{threshold:_e=.5,minlenratio:$e=0,maxlenratio:e=20,vocoder:t=null}={}){const s={input_ids:g},{encoder_outputs:n,encoder_attention_mask:i}=await be(this,s),o=n.dims[1]/this.config.reduction_factor,a=Math.floor(o*e),c=Math.floor(o*$e),d=this.config.num_mel_bins;let u=[],f=null,M=null,v=0;for(;;){++v;const R=Te(!!M);let ee;M?ee=M.output_sequence_out:ee=new h.Tensor("float32",new Float32Array(d),[1,1,d]);let W={use_cache_branch:R,output_sequence:ee,encoder_attention_mask:i,speaker_embeddings:F,encoder_hidden_states:n};this.addPastKeyValues(W,f),M=await J(this.sessions.decoder_model_merged,W),f=this.getPastKeyValues(M,f);const{prob:V,spectrum:se}=M;if(u.push(se),v>=c&&(Array.from(V.data).filter(oe=>oe>=_e).length>0||v>=a))break}const k=(0,h.cat)(u),{waveform:A}=await J(t.sessions.model,{spectrogram:k});return{spectrogram:k,waveform:A}}}class tp extends X{constructor(){super(...arguments);ie(this,"main_input_name","spectrogram")}}class ld extends X{}class cd extends ld{}class So extends X{}class sp extends So{}class dd extends So{}class ko extends X{}class rp extends ko{}class ud extends ko{}class Io extends X{}class pd extends Io{}class hd extends Io{}class Ao extends X{}class np extends Ao{}class _d extends Ao{}class Bn extends X{}class md extends Bn{}class fd extends Bn{static async from_pretrained(g,F={}){return super.from_pretrained(g,{...F,model_file_name:F.model_file_name??"text_model"})}}class gd extends Bn{static async from_pretrained(g,F={}){return super.from_pretrained(g,{...F,model_file_name:F.model_file_name??"audio_model"})}}class wd extends X{}class Fo extends wd{async _call(g){return new ia(await super._call(g))}}class Rn extends X{}class ip extends Rn{}class op extends Rn{}class pn extends Rn{}class jn extends X{}class Do extends jn{}class Oo extends jn{}class Nn extends X{}class Md extends Nn{}class yd extends Nn{async _call(g){return new Bt(await super._call(g))}}class Vn extends X{}class bd extends Vn{}class ap extends Vn{}class Lo extends X{constructor(){super(...arguments);ie(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(F){const[_e,$e]=F.dims,e=this.config.decoder.num_codebooks,t=$e-e;let s=0;for(let o=0;o0&&d<=t&&(F.data[s++]=F.data[o])}const n=Math.floor(_e/e),i=s/(n*e);return new h.Tensor(F.type,F.data.slice(0,s),[n,e,i])}prepare_inputs_for_generation(F,_e,$e){let e=structuredClone(F);for(let s=0;s=n&&(e[s][n]=BigInt(this.config.decoder.pad_token_id));return $e.guidance_scale!==null&&$e.guidance_scale>1&&(e=e.concat(e)),super.prepare_inputs_for_generation(e,_e,$e)}async generate(F){const _e=await super.generate(F),$e=this._apply_and_filter_by_delay_pattern_mask(_e).unsqueeze_(0),{audio_values:e}=await J(this.sessions.encodec_decode,{audio_codes:$e});return e}}class hn extends X{}class vd extends hn{}class xd extends hn{async _call(g){return new Bt(await super._call(g))}}class zo extends hn{}class Un extends X{}class Td extends Un{}class Ed extends Un{async _call(g){return new Bt(await super._call(g))}}class Pd extends Un{}class Bo extends X{}class Cd extends Bo{}class $d extends Bo{async _call(g){return new Bt(await super._call(g))}}class Sd extends Bo{}class Wn extends X{}class lp extends Wn{}class kd extends Wn{async _call(g){return new Bt(await super._call(g))}}class Id extends Wn{}class Ad extends X{}class cp extends Ad{}class Fd extends X{}class Ro extends Fd{constructor(...F){super(...F);ie(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(F){const _e=this._generation_mode??"text";let $e;if(_e==="text"||!F.past_key_values){const i=this.sessions.prepare_inputs_embeds,o=(0,$.pick)(F,i.inputNames);$e=await J(i,o)}else{const i=this.sessions.gen_img_embeds,o=(0,$.pick)({image_ids:F.input_ids},i.inputNames);$e=await J(i,o)}const e={...F,...$e},t=await Oe(this,e),s=this.sessions[_e==="text"?"lm_head":"gen_head"];if(!s)throw new Error(`Unable to find "${s}" generation head`);const n=await J(s,(0,$.pick)(t,s.inputNames));return{...$e,...t,...n}}async generate(F){return this._generation_mode="text",super.generate(F)}async generate_images(F){this._generation_mode="image";const _e=(F.inputs??F[this.main_input_name]).dims[1],e=(await super.generate(F)).slice(null,[_e,null]),t=this.sessions.image_decode,{decoded_image:s}=await J(t,{generated_tokens:e}),n=s.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),i=[];for(const o of n){const a=U.RawImage.fromTensor(o);i.push(a)}return i}}class jo extends ke{constructor({char_logits:g,bpe_logits:F,wp_logits:_e}){super(),this.char_logits=g,this.bpe_logits=F,this.wp_logits=_e}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Dd extends X{}class Od extends Dd{async _call(g){return new jo(await super._call(g))}}class No extends X{}class dp extends No{}class Ld extends No{}class Vo extends X{}class zd extends Vo{}class Uo extends Vo{}class Bd extends X{constructor(){super(...arguments);ie(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class Wo extends Bd{_merge_input_ids_with_audio_features(g){const F=g.audio_features.dims.at(-1),_e=g.audio_features.view(-1,F);return ce({audio_token_id:this.config.ignore_index??this.config.audio_token_id,...g,audio_features:_e})}}class Rd extends Wo{}class Gn extends X{constructor(){super(...arguments);ie(this,"main_input_name","input_values");ie(this,"forward_params",["input_values"])}}class jd extends ke{constructor({audio_codes:g}){super(),this.audio_codes=g}}class Nd extends ke{constructor({audio_values:g}){super(),this.audio_values=g}}class Vd extends Gn{async encode(g){return new jd(await J(this.sessions.encoder_model,g))}async decode(g){return new Nd(await J(this.sessions.decoder_model,g))}}class Ud extends Gn{static async from_pretrained(g,F={}){return super.from_pretrained(g,{...F,model_file_name:F.model_file_name??"encoder_model"})}}class Go extends Gn{static async from_pretrained(g,F={}){return super.from_pretrained(g,{...F,model_file_name:F.model_file_name??"decoder_model"})}}class Kn extends X{constructor(){super(...arguments);ie(this,"main_input_name","input_values");ie(this,"forward_params",["input_values"])}}class Wd extends ke{constructor({audio_codes:g}){super(),this.audio_codes=g}}class Gd extends ke{constructor({audio_values:g}){super(),this.audio_values=g}}class Kd extends Kn{async encode(g){return new Wd(await J(this.sessions.encoder_model,g))}async decode(g){return new Gd(await J(this.sessions.decoder_model,g))}}class Hd extends Kn{static async from_pretrained(g,F={}){return super.from_pretrained(g,{...F,model_file_name:F.model_file_name??"encoder_model"})}}class qd extends Kn{static async from_pretrained(g,F={}){return super.from_pretrained(g,{...F,model_file_name:F.model_file_name??"decoder_model"})}}class Hn extends X{constructor(){super(...arguments);ie(this,"main_input_name","input_values");ie(this,"forward_params",["input_values"])}}class up extends Hn{async encode(g){return await J(this.sessions.encoder_model,g)}async decode(g){return await J(this.sessions.decoder_model,g)}}class Qd extends Hn{static async from_pretrained(g,F={}){return super.from_pretrained(g,{...F,model_file_name:F.model_file_name??"encoder_model"})}}class Xd extends Hn{static async from_pretrained(g,F={}){return super.from_pretrained(g,{...F,model_file_name:F.model_file_name??"decoder_model"})}}class Jt{static async from_pretrained(g,{progress_callback:F=null,config:_e=null,cache_dir:$e=null,local_files_only:e=!1,revision:t="main",model_file_name:s=null,subfolder:n="onnx",device:i=null,dtype:o=null,use_external_data_format:a=null,session_options:c={}}={}){const d={progress_callback:F,config:_e,cache_dir:$e,local_files_only:e,revision:t,model_file_name:s,subfolder:n,device:i,dtype:o,use_external_data_format:a,session_options:c};if(d.config=await w.AutoConfig.from_pretrained(g,d),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const u=d.config.model_type;for(const f of this.MODEL_CLASS_MAPPINGS){let M=f.get(u);if(!M){for(const v of f.values())if(v[0]===u){M=v;break}if(!M)continue}return await M[1].from_pretrained(g,d)}if(this.BASE_IF_FAIL)return gu.has(u)||console.warn(`Unknown model class "${u}", attempting to construct from base class.`),await X.from_pretrained(g,d);throw Error(`Unsupported model type: ${u}`)}}ie(Jt,"MODEL_CLASS_MAPPINGS",null),ie(Jt,"BASE_IF_FAIL",!1);const kp=new Map([["bert",["BertModel",De]],["neobert",["NeoBertModel",Re]],["modernbert",["ModernBertModel",ht]],["nomic_bert",["NomicBertModel",Js]],["roformer",["RoFormerModel",Ts]],["electra",["ElectraModel",N]],["esm",["EsmModel",Fr]],["convbert",["ConvBertModel",Ir]],["camembert",["CamembertModel",$t]],["deberta",["DebertaModel",Ns]],["deberta-v2",["DebertaV2Model",Ar]],["mpnet",["MPNetModel",Le]],["albert",["AlbertModel",dt]],["distilbert",["DistilBertModel",Ys]],["roberta",["RobertaModel",$s]],["xlm",["XLMModel",Et]],["xlm-roberta",["XLMRobertaModel",la]],["clap",["ClapModel",md]],["clip",["CLIPModel",Ta]],["clipseg",["CLIPSegModel",Aa]],["chinese_clip",["ChineseCLIPModel",$a]],["siglip",["SiglipModel",rr]],["jina_clip",["JinaCLIPModel",Sa]],["mobilebert",["MobileBertModel",ns]],["squeezebert",["SqueezeBertModel",ne]],["wav2vec2",["Wav2Vec2Model",Rc]],["wav2vec2-bert",["Wav2Vec2BertModel",Jc]],["unispeech",["UniSpeechModel",Gc]],["unispeech-sat",["UniSpeechSatModel",Hc]],["hubert",["HubertModel",Zc]],["wavlm",["WavLMModel",td]],["audio-spectrogram-transformer",["ASTModel",ua]],["vits",["VitsModel",Fo]],["pyannote",["PyAnnoteModel",Uc]],["wespeaker-resnet",["WeSpeakerResNetModel",Fs]],["detr",["DetrModel",to]],["rt_detr",["RTDetrModel",ql]],["rt_detr_v2",["RTDetrV2Model",ju]],["rf_detr",["RFDetrModel",An]],["d_fine",["DFineModel",Xl]],["table-transformer",["TableTransformerModel",Yl]],["vit",["ViTModel",Dl]],["ijepa",["IJepaModel",Ll]],["pvt",["PvtModel",Rl]],["vit_msn",["ViTMSNModel",Br]],["vit_mae",["ViTMAEModel",Lu]],["groupvit",["GroupViTModel",jr]],["fastvit",["FastViTModel",Vl]],["mobilevit",["MobileViTModel",Hi]],["mobilevitv2",["MobileViTV2Model",Wl]],["owlvit",["OwlViTModel",Gl]],["owlv2",["Owlv2Model",$n]],["beit",["BeitModel",Kl]],["deit",["DeiTModel",ec]],["hiera",["HieraModel",tc]],["convnext",["ConvNextModel",yc]],["convnextv2",["ConvNextV2Model",vc]],["dinov2",["Dinov2Model",xc]],["dinov2_with_registers",["Dinov2WithRegistersModel",Pc]],["dinov3_vit",["DINOv3ViTModel",Sc]],["dinov3_convnext",["DINOv3ConvNextModel",kc]],["resnet",["ResNetModel",sc]],["swin",["SwinModel",rc]],["swin2sr",["Swin2SRModel",ic]],["donut-swin",["DonutSwinModel",wc]],["yolos",["YolosModel",Qu]],["dpt",["DPTModel",ac]],["glpn",["GLPNModel",fc]],["hifigan",["SpeechT5HifiGan",tp]],["efficientnet",["EfficientNetModel",Md]],["decision_transformer",["DecisionTransformerModel",cp]],["patchtst",["PatchTSTForPrediction",dp]],["patchtsmixer",["PatchTSMixerForPrediction",zd]],["mobilenet_v1",["MobileNetV1Model",vd]],["mobilenet_v2",["MobileNetV2Model",Td]],["mobilenet_v3",["MobileNetV3Model",Cd]],["mobilenet_v4",["MobileNetV4Model",lp]],["maskformer",["MaskFormerModel",yo]],["mgp-str",["MgpstrForSceneTextRecognition",Od]],["style_text_to_speech_2",["StyleTextToSpeech2Model",Zu]]]),pp=new Map([["t5",["T5Model",es]],["longt5",["LongT5Model",ps]],["mt5",["MT5Model",hr]],["bart",["BartModel",os]],["mbart",["MBartModel",or]],["marian",["MarianModel",mr]],["whisper",["WhisperModel",Ks]],["m2m_100",["M2M100Model",zc]],["blenderbot",["BlenderbotModel",gs]],["blenderbot-small",["BlenderbotSmallModel",lr]]]),qn=new Map([["mimi",["MimiModel",Vd]],["dac",["DacModel",Kd]],["snac",["SnacModel",up]]]),hp=new Map([["bloom",["BloomModel",$l]],["jais",["JAISModel",Oa]],["gpt2",["GPT2Model",Fa]],["gptj",["GPTJModel",Ra]],["gpt_bigcode",["GPTBigCodeModel",Na]],["gpt_neo",["GPTNeoModel",za]],["gpt_neox",["GPTNeoXModel",Mi]],["codegen",["CodeGenModel",Va]],["llama",["LlamaModel",Wa]],["arcee",["ArceeModel",Ka]],["lfm2",["Lfm2Model",qa]],["smollm3",["SmolLM3Model",Qa]],["exaone",["ExaoneModel",tl]],["olmo",["OlmoModel",il]],["olmo2",["Olmo2Model",al]],["mobilellm",["MobileLLMModel",rl]],["granite",["GraniteModel",Tn]],["cohere",["CohereModel",cl]],["gemma",["GemmaModel",ul]],["gemma2",["Gemma2Model",hl]],["gemma3_text",["Gemma3Model",ml]],["helium",["HeliumModel",Ya]],["glm",["GlmModel",Za]],["openelm",["OpenELMModel",gl]],["qwen2",["Qwen2Model",Ml]],["qwen3",["Qwen3Model",yl]],["phi",["PhiModel",Tl]],["phi3",["Phi3Model",El]],["mpt",["MptModel",kl]],["opt",["OPTModel",Al]],["mistral",["MistralModel",sp]],["ernie4_5",["Ernie4_5_Model",rp]],["starcoder2",["Starcoder2Model",pd]],["falcon",["FalconModel",np]],["stablelm",["StableLmModel",Do]],["modernbert-decoder",["ModernBertDecoderModel",bs]]]),Qn=new Map([["speecht5",["SpeechT5ForSpeechToText",od]],["whisper",["WhisperForConditionalGeneration",li]],["lite-whisper",["LiteWhisperForConditionalGeneration",ha]],["moonshine",["MoonshineForConditionalGeneration",_a]]]),Jd=new Map([["speecht5",["SpeechT5ForTextToSpeech",ad]]]),Yd=new Map([["vits",["VitsModel",Fo]],["musicgen",["MusicgenForConditionalGeneration",Lo]]]),Zd=new Map([["bert",["BertForSequenceClassification",Ae]],["neobert",["NeoBertForSequenceClassification",lt]],["modernbert",["ModernBertForSequenceClassification",Wt]],["roformer",["RoFormerForSequenceClassification",Gr]],["electra",["ElectraForSequenceClassification",ue]],["esm",["EsmForSequenceClassification",Ze]],["convbert",["ConvBertForSequenceClassification",Vt]],["camembert",["CamembertForSequenceClassification",mt]],["deberta",["DebertaForSequenceClassification",Es]],["deberta-v2",["DebertaV2ForSequenceClassification",zs]],["mpnet",["MPNetForSequenceClassification",rn]],["albert",["AlbertForSequenceClassification",nt]],["distilbert",["DistilBertForSequenceClassification",ur]],["roberta",["RobertaForSequenceClassification",as]],["xlm",["XLMForSequenceClassification",Ue]],["xlm-roberta",["XLMRobertaForSequenceClassification",Nt]],["bart",["BartForSequenceClassification",Rs]],["mbart",["MBartForSequenceClassification",ar]],["mobilebert",["MobileBertForSequenceClassification",ks]],["squeezebert",["SqueezeBertForSequenceClassification",ve]]]),eu=new Map([["bert",["BertForTokenClassification",qe]],["neobert",["NeoBertForTokenClassification",pt]],["modernbert",["ModernBertForTokenClassification",Qt]],["roformer",["RoFormerForTokenClassification",kr]],["electra",["ElectraForTokenClassification",Se]],["esm",["EsmForTokenClassification",tt]],["convbert",["ConvBertForTokenClassification",dr]],["camembert",["CamembertForTokenClassification",bt]],["deberta",["DebertaForTokenClassification",ms]],["deberta-v2",["DebertaV2ForTokenClassification",Us]],["mpnet",["MPNetForTokenClassification",xe]],["distilbert",["DistilBertForTokenClassification",br]],["roberta",["RobertaForTokenClassification",ni]],["xlm",["XLMForTokenClassification",xt]],["xlm-roberta",["XLMRobertaForTokenClassification",da]]]),tu=new Map([["t5",["T5ForConditionalGeneration",us]],["longt5",["LongT5ForConditionalGeneration",Is]],["mt5",["MT5ForConditionalGeneration",Cs]],["bart",["BartForConditionalGeneration",fs]],["mbart",["MBartForConditionalGeneration",vs]],["marian",["MarianMTModel",Nr]],["m2m_100",["M2M100ForConditionalGeneration",Bc]],["blenderbot",["BlenderbotForConditionalGeneration",Lt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",Hr]]]),Ko=new Map([["bloom",["BloomForCausalLM",Sl]],["gpt2",["GPT2LMHeadModel",Da]],["jais",["JAISLMHeadModel",La]],["gptj",["GPTJForCausalLM",vi]],["gpt_bigcode",["GPTBigCodeForCausalLM",vn]],["gpt_neo",["GPTNeoForCausalLM",Ba]],["gpt_neox",["GPTNeoXForCausalLM",yi]],["codegen",["CodeGenForCausalLM",Ua]],["llama",["LlamaForCausalLM",Ga]],["arcee",["ArceeForCausalLM",Ha]],["lfm2",["Lfm2ForCausalLM",Du]],["smollm3",["SmolLM3ForCausalLM",Xa]],["exaone",["ExaoneForCausalLM",sl]],["olmo",["OlmoForCausalLM",ol]],["olmo2",["Olmo2ForCausalLM",on]],["mobilellm",["MobileLLMForCausalLM",nl]],["granite",["GraniteForCausalLM",ll]],["cohere",["CohereForCausalLM",dl]],["gemma",["GemmaForCausalLM",pl]],["gemma2",["Gemma2ForCausalLM",_l]],["gemma3_text",["Gemma3ForCausalLM",fl]],["helium",["HeliumForCausalLM",Xt]],["glm",["GlmForCausalLM",el]],["openelm",["OpenELMForCausalLM",wl]],["qwen2",["Qwen2ForCausalLM",zi]],["qwen3",["Qwen3ForCausalLM",bl]],["phi",["PhiForCausalLM",Ri]],["phi3",["Phi3ForCausalLM",Pl]],["mpt",["MptForCausalLM",Il]],["opt",["OPTForCausalLM",Fl]],["mbart",["MBartForCausalLM",ys]],["mistral",["MistralForCausalLM",dd]],["ernie4_5",["Ernie4_5_ForCausalLM",ud]],["starcoder2",["Starcoder2ForCausalLM",hd]],["falcon",["FalconForCausalLM",_d]],["trocr",["TrOCRForCausalLM",cd]],["stablelm",["StableLmForCausalLM",Oo]],["modernbert-decoder",["ModernBertDecoderForCausalLM",ds]],["phi3_v",["Phi3VForCausalLM",hi]]]),_p=new Map([["multi_modality",["MultiModalityCausalLM",Ro]]]),su=new Map([["bert",["BertForMaskedLM",Ke]],["neobert",["NeoBertForMaskedLM",Mt]],["modernbert",["ModernBertForMaskedLM",vt]],["roformer",["RoFormerForMaskedLM",Sr]],["electra",["ElectraForMaskedLM",Z]],["esm",["EsmForMaskedLM",Bs]],["convbert",["ConvBertForMaskedLM",wr]],["camembert",["CamembertForMaskedLM",kt]],["deberta",["DebertaForMaskedLM",Hs]],["deberta-v2",["DebertaV2ForMaskedLM",Vs]],["mpnet",["MPNetForMaskedLM",Or]],["albert",["AlbertForMaskedLM",Ot]],["distilbert",["DistilBertForMaskedLM",pr]],["roberta",["RobertaForMaskedLM",Ct]],["xlm",["XLMWithLMHeadModel",nn]],["xlm-roberta",["XLMRobertaForMaskedLM",ca]],["mobilebert",["MobileBertForMaskedLM",Ut]],["squeezebert",["SqueezeBertForMaskedLM",we]]]),ru=new Map([["bert",["BertForQuestionAnswering",et]],["neobert",["NeoBertForQuestionAnswering",yt]],["roformer",["RoFormerForQuestionAnswering",Kr]],["electra",["ElectraForQuestionAnswering",ze]],["convbert",["ConvBertForQuestionAnswering",y]],["camembert",["CamembertForQuestionAnswering",Yt]],["deberta",["DebertaForQuestionAnswering",Mr]],["deberta-v2",["DebertaV2ForQuestionAnswering",yr]],["mpnet",["MPNetForQuestionAnswering",P]],["albert",["AlbertForQuestionAnswering",gt]],["distilbert",["DistilBertForQuestionAnswering",It]],["roberta",["RobertaForQuestionAnswering",qr]],["xlm",["XLMForQuestionAnswering",aa]],["xlm-roberta",["XLMRobertaForQuestionAnswering",ii]],["mobilebert",["MobileBertForQuestionAnswering",Dr]],["squeezebert",["SqueezeBertForQuestionAnswering",je]]]),nu=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ci]],["idefics3",["Idefics3ForConditionalGeneration",wn]],["smolvlm",["SmolVLMForConditionalGeneration",pi]]]),Ho=new Map([["llava",["LlavaForConditionalGeneration",gn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",ma]],["moondream1",["Moondream1ForConditionalGeneration",fa]],["florence2",["Florence2ForConditionalGeneration",wa]],["qwen2-vl",["Qwen2VLForConditionalGeneration",xl]],["idefics3",["Idefics3ForConditionalGeneration",wn]],["smolvlm",["SmolVLMForConditionalGeneration",pi]],["paligemma",["PaliGemmaForConditionalGeneration",tr]],["llava_qwen2",["LlavaQwen2ForCausalLM",ya]],["gemma3n",["Gemma3nForConditionalGeneration",ui]]]),iu=new Map([["ultravox",["UltravoxModel",Wo]],["voxtral",["VoxtralForConditionalGeneration",Rd]]]),mp=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",ci]]]),ou=new Map([["vit",["ViTForImageClassification",Ol]],["ijepa",["IJepaForImageClassification",Ou]],["pvt",["PvtForImageClassification",jl]],["vit_msn",["ViTMSNForImageClassification",Rr]],["fastvit",["FastViTForImageClassification",Ki]],["mobilevit",["MobileViTForImageClassification",qi]],["mobilevitv2",["MobileViTV2ForImageClassification",Xi]],["beit",["BeitForImageClassification",Bu]],["deit",["DeiTForImageClassification",po]],["hiera",["HieraForImageClassification",_o]],["convnext",["ConvNextForImageClassification",bc]],["convnextv2",["ConvNextV2ForImageClassification",Hu]],["dinov2",["Dinov2ForImageClassification",Tc]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",Cc]],["resnet",["ResNetForImageClassification",Vu]],["swin",["SwinForImageClassification",nc]],["segformer",["SegformerForImageClassification",op]],["efficientnet",["EfficientNetForImageClassification",yd]],["mobilenet_v1",["MobileNetV1ForImageClassification",xd]],["mobilenet_v2",["MobileNetV2ForImageClassification",Ed]],["mobilenet_v3",["MobileNetV3ForImageClassification",$d]],["mobilenet_v4",["MobileNetV4ForImageClassification",kd]]]),au=new Map([["detr",["DetrForObjectDetection",an]],["rt_detr",["RTDetrForObjectDetection",Ru]],["rt_detr_v2",["RTDetrV2ForObjectDetection",Ql]],["rf_detr",["RFDetrForObjectDetection",oo]],["d_fine",["DFineForObjectDetection",co]],["table-transformer",["TableTransformerForObjectDetection",Nu]],["yolos",["YolosForObjectDetection",Fc]]]),fp=new Map([["owlvit",["OwlViTForObjectDetection",Ji]],["owlv2",["Owlv2ForObjectDetection",Zi]],["grounding-dino",["GroundingDinoForObjectDetection",Ac]]]),Yr=new Map([["detr",["DetrForSegmentation",so]],["clipseg",["CLIPSegForImageSegmentation",nr]]]),lu=new Map([["segformer",["SegformerForSemanticSegmentation",pn]],["sapiens",["SapiensForSemanticSegmentation",lc]],["swin",["SwinForSemanticSegmentation",Uu]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",zo]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",Pd]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",Sd]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Id]]]),cu=new Map([["detr",["DetrForSegmentation",so]],["maskformer",["MaskFormerForInstanceSegmentation",mc]]]),gp=new Map([["sam",["SamModel",Lc]]]),du=new Map([["wav2vec2",["Wav2Vec2ForCTC",jc]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Co]],["unispeech",["UniSpeechForCTC",Po]],["unispeech-sat",["UniSpeechSatForCTC",qc]],["wavlm",["WavLMForCTC",sd]],["hubert",["HubertForCTC",ed]]]),wp=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",Nc]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",Yc]],["unispeech",["UniSpeechForSequenceClassification",Kc]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Qc]],["wavlm",["WavLMForSequenceClassification",rd]],["hubert",["HubertForSequenceClassification",zn]],["audio-spectrogram-transformer",["ASTForAudioClassification",pa]]]),uu=new Map([["wavlm",["WavLMForXVector",$o]]]),Mp=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Xc]],["wavlm",["WavLMForAudioFrameClassification",nd]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",Vc]],["pyannote",["PyAnnoteForAudioFrameClassification",Wc]]]),pu=new Map([["vitmatte",["VitMatteForImageMatting",zu]]]),yp=new Map([["patchtst",["PatchTSTForPrediction",Ld]],["patchtsmixer",["PatchTSMixerForPrediction",Uo]]]),hu=new Map([["swin2sr",["Swin2SRForImageSuperResolution",oc]]]),_u=new Map([["dpt",["DPTForDepthEstimation",Wu]],["depth_anything",["DepthAnythingForDepthEstimation",cn]],["glpn",["GLPNForDepthEstimation",Ku]],["sapiens",["SapiensForDepthEstimation",cc]],["depth_pro",["DepthProForDepthEstimation",wo]],["metric3d",["Metric3DForDepthEstimation",hc]],["metric3dv2",["Metric3Dv2ForDepthEstimation",Gu]]]),mu=new Map([["sapiens",["SapiensForNormalEstimation",dc]]]),bp=new Map([["vitpose",["VitPoseForPoseEstimation",Bl]]]),fu=new Map([["clip",["CLIPVisionModelWithProjection",Mn]],["siglip",["SiglipVisionModel",Pa]],["jina_clip",["JinaCLIPVisionModel",Ia]]]),Xn=[[kp,O.EncoderOnly],[pp,O.EncoderDecoder],[hp,O.DecoderOnly],[qn,O.AutoEncoder],[Zd,O.EncoderOnly],[eu,O.EncoderOnly],[tu,O.Seq2Seq],[Qn,O.Seq2Seq],[Ko,O.DecoderOnly],[_p,O.MultiModality],[su,O.EncoderOnly],[ru,O.EncoderOnly],[nu,O.Vision2Seq],[Ho,O.ImageTextToText],[iu,O.AudioTextToText],[ou,O.EncoderOnly],[Yr,O.EncoderOnly],[cu,O.EncoderOnly],[lu,O.EncoderOnly],[pu,O.EncoderOnly],[yp,O.EncoderOnly],[hu,O.EncoderOnly],[_u,O.EncoderOnly],[mu,O.EncoderOnly],[bp,O.EncoderOnly],[au,O.EncoderOnly],[fp,O.EncoderOnly],[gp,O.MaskGeneration],[du,O.EncoderOnly],[wp,O.EncoderOnly],[Jd,O.Seq2Seq],[Yd,O.EncoderOnly],[uu,O.EncoderOnly],[Mp,O.EncoderOnly],[fu,O.EncoderOnly]];for(const[p,g]of Xn)for(const[F,_e]of p.values())S.set(F,g),x.set(_e,F),E.set(F,_e);const vp=[["MusicgenForConditionalGeneration",Lo,O.Musicgen],["Phi3VForCausalLM",hi,O.Phi3V],["CLIPTextModelWithProjection",sr,O.EncoderOnly],["SiglipTextModel",Ea,O.EncoderOnly],["JinaCLIPTextModel",ka,O.EncoderOnly],["ClapTextModelWithProjection",fd,O.EncoderOnly],["ClapAudioModelWithProjection",gd,O.EncoderOnly],["DacEncoderModel",Hd,O.EncoderOnly],["DacDecoderModel",qd,O.EncoderOnly],["MimiEncoderModel",Ud,O.EncoderOnly],["MimiDecoderModel",Go,O.EncoderOnly],["SnacEncoderModel",Qd,O.EncoderOnly],["SnacDecoderModel",Xd,O.EncoderOnly],["Gemma3nForConditionalGeneration",ui,O.ImageAudioTextToText]];for(const[p,g,F]of vp)S.set(p,F),x.set(g,p),E.set(p,g);const gu=new Map([["modnet",Yr],["birefnet",Yr],["isnet",Yr],["ben",Yr]]);for(const[p,g]of gu.entries())g.set(p,["PreTrainedModel",X]),S.set(p,O.EncoderOnly),x.set(X,p),E.set(p,X);class wu extends Jt{}ie(wu,"MODEL_CLASS_MAPPINGS",Xn.map(g=>g[0])),ie(wu,"BASE_IF_FAIL",!0);class Mu extends Jt{}ie(Mu,"MODEL_CLASS_MAPPINGS",[Zd]);class qo extends Jt{}ie(qo,"MODEL_CLASS_MAPPINGS",[eu]);class Qo extends Jt{}ie(Qo,"MODEL_CLASS_MAPPINGS",[tu]);class Pr extends Jt{}ie(Pr,"MODEL_CLASS_MAPPINGS",[Qn]);class yu extends Jt{}ie(yu,"MODEL_CLASS_MAPPINGS",[Jd]);class Xo extends Jt{}ie(Xo,"MODEL_CLASS_MAPPINGS",[Yd]);class Jn extends Jt{}ie(Jn,"MODEL_CLASS_MAPPINGS",[Ko]);class Jo extends Jt{}ie(Jo,"MODEL_CLASS_MAPPINGS",[su]);class Yo extends Jt{}ie(Yo,"MODEL_CLASS_MAPPINGS",[ru]);class Zo extends Jt{}ie(Zo,"MODEL_CLASS_MAPPINGS",[nu]);class ea extends Jt{}ie(ea,"MODEL_CLASS_MAPPINGS",[ou]);class ta extends Jt{}ie(ta,"MODEL_CLASS_MAPPINGS",[Yr]);class sa extends Jt{}ie(sa,"MODEL_CLASS_MAPPINGS",[lu]);class bu extends Jt{}ie(bu,"MODEL_CLASS_MAPPINGS",[cu]);class Cr extends Jt{}ie(Cr,"MODEL_CLASS_MAPPINGS",[au]);class js extends Jt{}ie(js,"MODEL_CLASS_MAPPINGS",[fp]);class Zr extends Jt{}ie(Zr,"MODEL_CLASS_MAPPINGS",[gp]);class _n extends Jt{}ie(_n,"MODEL_CLASS_MAPPINGS",[du]);class mn extends Jt{}ie(mn,"MODEL_CLASS_MAPPINGS",[wp]);class Yn extends Jt{}ie(Yn,"MODEL_CLASS_MAPPINGS",[uu]);class ra extends Jt{}ie(ra,"MODEL_CLASS_MAPPINGS",[Mp]);class Zn extends Jt{}ie(Zn,"MODEL_CLASS_MAPPINGS",[mp]);class Vr extends Jt{}ie(Vr,"MODEL_CLASS_MAPPINGS",[pu]);class Ur extends Jt{}ie(Ur,"MODEL_CLASS_MAPPINGS",[hu]);class vu extends Jt{}ie(vu,"MODEL_CLASS_MAPPINGS",[_u]);class xu extends Jt{}ie(xu,"MODEL_CLASS_MAPPINGS",[mu]);class Tu extends Jt{}ie(Tu,"MODEL_CLASS_MAPPINGS",[bp]);class Eu extends Jt{}ie(Eu,"MODEL_CLASS_MAPPINGS",[fu]);class Pu extends Jt{}ie(Pu,"MODEL_CLASS_MAPPINGS",[Ho]);class Cu extends Jt{}ie(Cu,"MODEL_CLASS_MAPPINGS",[iu]);class xp extends ke{constructor({logits:g,past_key_values:F,encoder_outputs:_e,decoder_attentions:$e=null,cross_attentions:e=null}){super(),this.logits=g,this.past_key_values=F,this.encoder_outputs=_e,this.decoder_attentions=$e,this.cross_attentions=e}}class Bt extends ke{constructor({logits:g,...F}){super(),this.logits=g;const _e=Object.values(F);_e.length>0&&(this.attentions=_e)}}class $u extends ke{constructor({logits:g,embeddings:F}){super(),this.logits=g,this.embeddings=F}}class _s extends ke{constructor({logits:g}){super(),this.logits=g}}class Ms extends ke{constructor({logits:g}){super(),this.logits=g}}class xs extends ke{constructor({start_logits:g,end_logits:F}){super(),this.start_logits=g,this.end_logits=F}}class en extends ke{constructor({logits:g}){super(),this.logits=g}}class Tp extends ke{constructor({logits:g,past_key_values:F}){super(),this.logits=g,this.past_key_values=F}}class na extends ke{constructor({alphas:g}){super(),this.alphas=g}}class ia extends ke{constructor({waveform:g,spectrogram:F}){super(),this.waveform=g,this.spectrogram=F}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(ae,m,r)=>{r.r(m),r.d(m,{ASTFeatureExtractor:()=>L});var w=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var T=r("./src/utils/audio.js");class L extends w.FeatureExtractor{constructor($){super($);const _=this.config.sampling_rate,I=(0,T.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(_/2),_,null,"kaldi",!0);this.mel_filters=I,this.window=(0,T.window_function)(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features($,_){return(0,T.spectrogram)($,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:_,transpose:!0})}async _call($){(0,w.validate_audio_inputs)($,"ASTFeatureExtractor");const _=await this._extract_fbank_features($,this.config.max_length);if(this.config.do_normalize){const I=this.std*2,D=_.data;for(let b=0;b{r.r(m),r.d(m,{AutoFeatureExtractor:()=>H});var w=r("./src/utils/constants.js"),T=r("./src/utils/hub.js");r("./src/base/feature_extraction_utils.js");var L=r("./src/models/feature_extractors.js");class H{static async from_pretrained(_,I={}){const D=await(0,T.getModelJSON)(_,w.FEATURE_EXTRACTOR_NAME,!0,I),b=D.feature_extractor_type,h=L[b];if(!h)throw new Error(`Unknown feature_extractor_type: '${b}'. Please report this at ${w.GITHUB_ISSUE_URL}.`);return new h(D)}}},"./src/models/auto/image_processing_auto.js":(ae,m,r)=>{r.r(m),r.d(m,{AutoImageProcessor:()=>$});var w=r("./src/utils/constants.js"),T=r("./src/utils/hub.js"),L=r("./src/base/image_processors_utils.js"),H=r("./src/models/image_processors.js");class ${static async from_pretrained(I,D={}){const b=await(0,T.getModelJSON)(I,w.IMAGE_PROCESSOR_NAME,!0,D),h=b.image_processor_type??b.feature_extractor_type;let U=H[h==null?void 0:h.replace(/Fast$/,"")];return U||(h!==void 0&&console.warn(`Image processor type '${h}' not found, assuming base ImageProcessor. Please report this at ${w.GITHUB_ISSUE_URL}.`),U=L.ImageProcessor),new U(b)}}},"./src/models/auto/processing_auto.js":(ae,m,r)=>{r.r(m),r.d(m,{AutoProcessor:()=>I});var w=r("./src/utils/constants.js"),T=r("./src/utils/hub.js"),L=r("./src/base/processing_utils.js"),H=r("./src/models/processors.js"),$=r("./src/models/image_processors.js"),_=r("./src/models/feature_extractors.js");class I{static async from_pretrained(b,h={}){const U=await(0,T.getModelJSON)(b,w.IMAGE_PROCESSOR_NAME,!0,h),{image_processor_type:z,feature_extractor_type:Q,processor_class:ge}=U;if(ge&&H[ge])return H[ge].from_pretrained(b,h);if(!z&&!Q)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const j={};if(z){const Y=$[z.replace(/Fast$/,"")];if(!Y)throw new Error(`Unknown image_processor_type: '${z}'.`);j.image_processor=new Y(U)}if(Q){const Y=$[Q];if(Y)j.image_processor=new Y(U);else{const O=_[Q];if(!O)throw new Error(`Unknown feature_extractor_type: '${Q}'.`);j.feature_extractor=new O(U)}}const G={};return new L.Processor(G,j,null)}}},"./src/models/beit/image_processing_beit.js":(ae,m,r)=>{r.r(m),r.d(m,{BeitFeatureExtractor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(ae,m,r)=>{r.r(m),r.d(m,{BitImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(ae,m,r)=>{r.r(m),r.d(m,{ChineseCLIPFeatureExtractor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(ae,m,r)=>{r.r(m),r.d(m,{ClapFeatureExtractor:()=>L});var w=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var T=r("./src/utils/audio.js");class L extends w.FeatureExtractor{constructor($){super($),this.mel_filters=(0,T.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,T.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,T.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel($,_,I,D){let b;const h=$.length-_;if(h>0)if(I==="rand_trunc"){const U=Math.floor(Math.random()*(h+1));$=$.subarray(U,U+_),b=await this._extract_fbank_features($,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${I}" not implemented`);else{if(h<0){let U=new Float64Array(_);if(U.set($),D==="repeat")for(let z=$.length;z<_;z+=$.length)U.set($.subarray(0,Math.min($.length,_-z)),z);else if(D==="repeatpad")for(let z=$.length;z<-h;z+=$.length)U.set($,z);$=U}if(I==="fusion")throw new Error(`Truncation strategy "${I}" not implemented`);b=await this._extract_fbank_features($,this.mel_filters_slaney,this.config.nb_max_samples)}return b.unsqueeze_(0)}async _extract_fbank_features($,_,I=null){return(0,T.spectrogram)($,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:_,log_mel:"dB",max_num_frames:I,do_pad:!1,transpose:!0})}async _call($,{max_length:_=null}={}){return(0,w.validate_audio_inputs)($,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel($,_??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}}},"./src/models/clip/image_processing_clip.js":(ae,m,r)=>{r.r(m),r.d(m,{CLIPFeatureExtractor:()=>L,CLIPImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}class L extends T{}},"./src/models/convnext/image_processing_convnext.js":(ae,m,r)=>{r.r(m),r.d(m,{ConvNextFeatureExtractor:()=>L,ConvNextImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{constructor($){super($),this.crop_pct=this.config.crop_pct??224/256}async resize($){var I;const _=(I=this.size)==null?void 0:I.shortest_edge;if(_===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(_<384){const D=Math.floor(_/this.crop_pct),[b,h]=this.get_resize_output_image_size($,{shortest_edge:D});$=await $.resize(b,h,{resample:this.resample}),$=await $.center_crop(_,_)}else $=await $.resize(_,_,{resample:this.resample});return $}}class L extends T{}},"./src/models/dac/feature_extraction_dac.js":(ae,m,r)=>{r.r(m),r.d(m,{DacFeatureExtractor:()=>T});var w=r("./src/models/encodec/feature_extraction_encodec.js");class T extends w.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(ae,m,r)=>{r.r(m),r.d(m,{DeiTFeatureExtractor:()=>L,DeiTImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}class L extends T{}},"./src/models/detr/image_processing_detr.js":(ae,m,r)=>{r.r(m),r.d(m,{DetrFeatureExtractor:()=>H,DetrImageProcessor:()=>L});var w=r("./src/base/image_processors_utils.js"),T=r("./src/utils/tensor.js");class L extends w.ImageProcessor{async _call(_){const I=await super._call(_),D=[I.pixel_values.dims[0],64,64],b=(0,T.full)(D,1n);return{...I,pixel_mask:b}}post_process_object_detection(..._){return(0,w.post_process_object_detection)(..._)}post_process_panoptic_segmentation(..._){return(0,w.post_process_panoptic_segmentation)(..._)}post_process_instance_segmentation(..._){return(0,w.post_process_instance_segmentation)(..._)}}class H extends L{}},"./src/models/dinov3_vit/image_processing_dinov3_vit.js":(ae,m,r)=>{r.r(m),r.d(m,{DINOv3ViTImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}},"./src/models/donut/image_processing_donut.js":(ae,m,r)=>{r.r(m),r.d(m,{DonutFeatureExtractor:()=>L,DonutImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{pad_image($,_,I,D={}){const[b,h,U]=_;let z=this.image_mean;Array.isArray(this.image_mean)||(z=new Array(U).fill(z));let Q=this.image_std;Array.isArray(Q)||(Q=new Array(U).fill(z));const ge=z.map((j,G)=>-j/Q[G]);return super.pad_image($,_,I,{center:!0,constant_values:ge,...D})}}class L extends T{}},"./src/models/dpt/image_processing_dpt.js":(ae,m,r)=>{r.r(m),r.d(m,{DPTFeatureExtractor:()=>L,DPTImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}class L extends T{}},"./src/models/efficientnet/image_processing_efficientnet.js":(ae,m,r)=>{r.r(m),r.d(m,{EfficientNetImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{constructor(H){super(H),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map($=>$*$))}}},"./src/models/encodec/feature_extraction_encodec.js":(ae,m,r)=>{r.r(m),r.d(m,{EncodecFeatureExtractor:()=>L});var w=r("./src/base/feature_extraction_utils.js"),T=r("./src/utils/tensor.js");class L extends w.FeatureExtractor{async _call($){(0,w.validate_audio_inputs)($,"EncodecFeatureExtractor"),$ instanceof Float64Array&&($=new Float32Array($));const _=this.config.feature_size;if($.length%_!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${_}).`);const I=[1,_,$.length/_];return{input_values:new T.Tensor("float32",$,I)}}}},"./src/models/feature_extractors.js":(ae,m,r)=>{r.r(m),r.d(m,{ASTFeatureExtractor:()=>w.ASTFeatureExtractor,ClapFeatureExtractor:()=>L.ClapFeatureExtractor,DacFeatureExtractor:()=>H.DacFeatureExtractor,EncodecFeatureExtractor:()=>T.EncodecFeatureExtractor,Gemma3nAudioFeatureExtractor:()=>$.Gemma3nAudioFeatureExtractor,ImageFeatureExtractor:()=>ge.ImageProcessor,MoonshineFeatureExtractor:()=>_.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>I.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>D.SeamlessM4TFeatureExtractor,SnacFeatureExtractor:()=>b.SnacFeatureExtractor,SpeechT5FeatureExtractor:()=>h.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>U.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>z.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>Q.WhisperFeatureExtractor});var w=r("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),T=r("./src/models/encodec/feature_extraction_encodec.js"),L=r("./src/models/clap/feature_extraction_clap.js"),H=r("./src/models/dac/feature_extraction_dac.js"),$=r("./src/models/gemma3n/feature_extraction_gemma3n.js"),_=r("./src/models/moonshine/feature_extraction_moonshine.js"),I=r("./src/models/pyannote/feature_extraction_pyannote.js"),D=r("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),b=r("./src/models/snac/feature_extraction_snac.js"),h=r("./src/models/speecht5/feature_extraction_speecht5.js"),U=r("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),z=r("./src/models/wespeaker/feature_extraction_wespeaker.js"),Q=r("./src/models/whisper/feature_extraction_whisper.js"),ge=r("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(ae,m,r)=>{r.r(m),r.d(m,{Florence2Processor:()=>H});var w=r("./src/base/processing_utils.js"),T=r("./src/models/auto/image_processing_auto.js"),L=r("./src/tokenizers.js");class H extends w.Processor{constructor(_,I,D){super(_,I,D);const{tasks_answer_post_processing_type:b,task_prompts_without_inputs:h,task_prompts_with_input:U}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(b??{})),this.task_prompts_without_inputs=new Map(Object.entries(h??{})),this.task_prompts_with_input=new Map(Object.entries(U??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(_){typeof _=="string"&&(_=[_]);const I=[];for(const D of _)if(this.task_prompts_without_inputs.has(D))I.push(this.task_prompts_without_inputs.get(D));else{for(const[b,h]of this.task_prompts_with_input)if(D.includes(b)){I.push(h.replaceAll("{input}",D).replaceAll(b,""));break}I.length!==_.length&&I.push(D)}return I}post_process_generation(_,I,D){const b=this.tasks_answer_post_processing_type.get(I)??"pure_text";_=_.replaceAll("","").replaceAll("","");let h;switch(b){case"pure_text":h=_;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const U=b==="ocr"?"quad_boxes":"bboxes",z=_.matchAll(this.regexes[U]),Q=[],ge=[];for(const[j,G,...Y]of z)Q.push(G?G.trim():Q.at(-1)??""),ge.push(Y.map((O,S)=>(Number(O)+.5)/this.size_per_bin*D[S%2]));h={labels:Q,[U]:ge};break;default:throw new Error(`Task "${I}" (of type "${b}") not yet implemented.`)}return{[I]:h}}async _call(_,I=null,D={}){if(!_&&!I)throw new Error("Either text or images must be provided");const b=await this.image_processor(_,D),h=I?this.tokenizer(this.construct_prompts(I),D):{};return{...b,...h}}}ie(H,"tokenizer_class",L.AutoTokenizer),ie(H,"image_processor_class",T.AutoImageProcessor)},"./src/models/gemma3n/feature_extraction_gemma3n.js":(ae,m,r)=>{r.r(m),r.d(m,{Gemma3nAudioFeatureExtractor:()=>H});var w=r("./src/base/feature_extraction_utils.js"),T=r("./src/utils/tensor.js"),L=r("./src/utils/audio.js");class H extends w.FeatureExtractor{constructor(_){super(_);const{fft_length:I,feature_size:D,min_frequency:b,max_frequency:h,sampling_rate:U,frame_length:z}=this.config,Q=(0,L.mel_filter_bank)(Math.floor(1+I/2),D,b,h,U,null,"htk",!1);this.mel_filters=Q,this.window=(0,L.window_function)(z,"hann")}async _extract_fbank_features(_,I){return(0,L.spectrogram)(_,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(_,{max_length:I=48e4,truncation:D=!0,padding:b=!0,pad_to_multiple_of:h=128}={}){if((0,w.validate_audio_inputs)(_,"Gemma3nAudioFeatureExtractor"),D&&_.length>I&&(_=_.slice(0,I)),b&&_.length%h!==0){const Q=h-_.length%h,ge=new Float64Array(_.length+Q);ge.set(_),this.config.padding_value!==0&&ge.fill(this.config.padding_value,_.length),_=ge}const U=await this._extract_fbank_features(_,this.config.max_length),z=(0,T.full)([1,U.dims[0]],!0);return{input_features:U.unsqueeze_(0),input_features_mask:z}}}},"./src/models/gemma3n/processing_gemma3n.js":(ae,m,r)=>{r.r(m),r.d(m,{Gemma3nProcessor:()=>$});var w=r("./src/base/processing_utils.js"),T=r("./src/models/auto/image_processing_auto.js"),L=r("./src/models/auto/feature_extraction_auto.js"),H=r("./src/tokenizers.js");r("./src/utils/image.js"),r("./src/utils/audio.js");class $ extends w.Processor{constructor(I,D,b){super(I,D,b),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;const{audio_token_id:h,boa_token:U,audio_token:z,eoa_token:Q,image_token_id:ge,boi_token:j,image_token:G,eoi_token:Y}=this.tokenizer.config;this.audio_token_id=h,this.boa_token=U,this.audio_token=z;const O=z.repeat(this.audio_seq_length);this.full_audio_sequence=` + +${U}${O}${Q} + +`,this.image_token_id=ge,this.boi_token=j,this.image_token=G;const S=G.repeat(this.image_seq_length);this.full_image_sequence=` + +${j}${S}${Y} + +`}async _call(I,D=null,b=null,h={}){typeof I=="string"&&(I=[I]);let U;b&&(U=await this.feature_extractor(b,h),I=I.map(ge=>ge.replaceAll(this.audio_token,this.full_audio_sequence)));let z;return D&&(z=await this.image_processor(D,h),I=I.map(ge=>ge.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(I,h),...z,...U}}}ie($,"image_processor_class",T.AutoImageProcessor),ie($,"feature_extractor_class",L.AutoFeatureExtractor),ie($,"tokenizer_class",H.AutoTokenizer),ie($,"uses_processor_config",!0),ie($,"uses_chat_template_file",!0)},"./src/models/glpn/image_processing_glpn.js":(ae,m,r)=>{r.r(m),r.d(m,{GLPNFeatureExtractor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(ae,m,r)=>{r.r(m),r.d(m,{GroundingDinoImageProcessor:()=>L});var w=r("./src/base/image_processors_utils.js"),T=r("./src/utils/tensor.js");class L extends w.ImageProcessor{async _call($){const _=await super._call($),I=_.pixel_values.dims,D=(0,T.ones)([I[0],I[2],I[3]]);return{..._,pixel_mask:D}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(ae,m,r)=>{r.r(m),r.d(m,{GroundingDinoProcessor:()=>_});var w=r("./src/base/processing_utils.js"),T=r("./src/models/auto/image_processing_auto.js"),L=r("./src/tokenizers.js"),H=r("./src/base/image_processors_utils.js");function $(I,D){const h=I.dims.at(-1)-1,U=I.tolist();U.fill(!1,0,0+1),U.fill(!1,h);const z=D.tolist();return U.map((Q,ge)=>Q?ge:null).filter(Q=>Q!==null).map(Q=>z[Q])}class _ extends w.Processor{async _call(D,b,h={}){const U=D?await this.image_processor(D,h):{};return{...b?this.tokenizer(b,h):{},...U}}post_process_grounded_object_detection(D,b,{box_threshold:h=.25,text_threshold:U=.25,target_sizes:z=null}={}){const{logits:Q,pred_boxes:ge}=D,j=Q.dims[0];if(z!==null&&z.length!==j)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const G=Q.dims.at(1),Y=Q.sigmoid(),O=Y.max(-1).tolist(),S=ge.tolist().map(x=>x.map(C=>(0,H.center_to_corners_format)(C))),E=[];for(let x=0;xJ.map((fe,de)=>fe*C[(de+1)%2])));const re=O[x],q=[],pe=[],me=[];for(let J=0;J{r.r(m),r.d(m,{Idefics3ImageProcessor:()=>L});var w=r("./src/base/image_processors_utils.js"),T=r("./src/utils/tensor.js");class L extends w.ImageProcessor{constructor($){super($),this.do_image_splitting=$.do_image_splitting??!0,this.max_image_size=$.max_image_size}get_resize_for_vision_encoder($,_){let[I,D]=$.dims.slice(-2);const b=D/I;return D>=I?(D=Math.ceil(D/_)*_,I=Math.floor(D/b),I=Math.ceil(I/_)*_):(I=Math.ceil(I/_)*_,D=Math.floor(I*b),D=Math.ceil(D/_)*_),{height:I,width:D}}async _call($,{do_image_splitting:_=null,return_row_col_info:I=!1}={}){let D;if(!Array.isArray($))D=[[$]];else{if($.length===0||!$[0])throw new Error("No images provided.");Array.isArray($[0])?D=$:D=[$]}let b=[],h=[],U=[];const z=[],Q=[];for(const x of D){let C=await Promise.all(x.map(pe=>this.preprocess(pe)));z.push(...C.map(pe=>pe.original_size)),Q.push(...C.map(pe=>pe.reshaped_input_size)),C.forEach(pe=>pe.pixel_values.unsqueeze_(0));const{longest_edge:re}=this.max_image_size;let q;if(_??this.do_image_splitting){let pe=new Array(C.length),me=new Array(C.length);q=await Promise.all(C.map(async(J,fe)=>{const de=this.get_resize_for_vision_encoder(J.pixel_values,re),Te=await(0,T.interpolate_4d)(J.pixel_values,{size:[de.height,de.width]}),{frames:Pe,num_splits_h:be,num_splits_w:He}=await this.split_image(Te,this.max_image_size);return pe[fe]=be,me[fe]=He,(0,T.cat)(Pe,0)})),h.push(pe),U.push(me)}else{const pe=[re,re];q=await Promise.all(C.map(me=>(0,T.interpolate_4d)(me.pixel_values,{size:pe}))),h.push(new Array(C.length).fill(0)),U.push(new Array(C.length).fill(0))}b.push((0,T.cat)(q,0))}const ge=b.length,[j,G,Y,O]=b[0].dims;let S,E;if(ge===1)S=b[0].unsqueeze_(0),E=(0,T.full)([ge,j,Y,O],!0);else{const x=Math.max(...b.map(q=>q.dims.at(0)));E=(0,T.full)([ge,x,Y,O],!0);const C=E.data,re=x*Y*O;for(let q=0;qI||U>D){z=Math.ceil(h/I),Q=Math.ceil(U/D);const ge=Math.ceil(h/z),j=Math.ceil(U/Q);for(let O=0;O{r.r(m),r.d(m,{Idefics3Processor:()=>D});var w=r("./src/base/processing_utils.js"),T=r("./src/models/auto/image_processing_auto.js"),L=r("./src/tokenizers.js");r("./src/utils/image.js");var H=r("./src/utils/core.js");function $(b,h,U,z,Q,ge){let j="";for(let G=0;G`+Q.repeat(b);j+=` +`}return j+=` +${z}${ge}`+Q.repeat(b)+`${z}`,j}function _(b,h,U,z){return`${h}${z}`+U.repeat(b)+`${h}`}function I(b,h,U,z,Q,ge){return b===0&&h===0?_(U,z,Q,ge):$(U,b,h,z,Q,ge)}class D extends w.Processor{constructor(){super(...arguments);ie(this,"fake_image_token","");ie(this,"image_token","");ie(this,"global_img_token","")}async _call(U,z=null,Q={}){Q.return_row_col_info??(Q.return_row_col_info=!0);let ge;z&&(ge=await this.image_processor(z,Q)),Array.isArray(U)||(U=[U]);const j=ge.rows??[new Array(U.length).fill(0)],G=ge.cols??[new Array(U.length).fill(0)],Y=this.config.image_seq_len,O=[],S=[];for(let x=0;xI(fe,q[de],Y,this.fake_image_token,this.image_token,this.global_img_token)),me=C.split(this.image_token);if(me.length===0)throw new Error("The image token should be present in the text.");let J=me[0];for(let fe=0;fe{r.r(m),r.d(m,{BeitFeatureExtractor:()=>w.BeitFeatureExtractor,BitImageProcessor:()=>T.BitImageProcessor,CLIPFeatureExtractor:()=>H.CLIPFeatureExtractor,CLIPImageProcessor:()=>H.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>L.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>$.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>$.ConvNextImageProcessor,DINOv3ViTImageProcessor:()=>D.DINOv3ViTImageProcessor,DPTFeatureExtractor:()=>h.DPTFeatureExtractor,DPTImageProcessor:()=>h.DPTImageProcessor,DeiTFeatureExtractor:()=>_.DeiTFeatureExtractor,DeiTImageProcessor:()=>_.DeiTImageProcessor,DetrFeatureExtractor:()=>I.DetrFeatureExtractor,DetrImageProcessor:()=>I.DetrImageProcessor,DonutFeatureExtractor:()=>b.DonutFeatureExtractor,DonutImageProcessor:()=>b.DonutImageProcessor,EfficientNetImageProcessor:()=>U.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>z.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>Q.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>ge.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>G.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>Y.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>O.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>S.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>S.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>E.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>E.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>x.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>x.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>C.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>C.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>re.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>re.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>q.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>q.MobileViTImageProcessor,NougatImageProcessor:()=>pe.NougatImageProcessor,OwlViTFeatureExtractor:()=>J.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>J.OwlViTImageProcessor,Owlv2ImageProcessor:()=>me.Owlv2ImageProcessor,Phi3VImageProcessor:()=>fe.Phi3VImageProcessor,PvtImageProcessor:()=>de.PvtImageProcessor,Qwen2VLImageProcessor:()=>Te.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Pe.RTDetrImageProcessor,SamImageProcessor:()=>be.SamImageProcessor,SegformerFeatureExtractor:()=>He.SegformerFeatureExtractor,SegformerImageProcessor:()=>He.SegformerImageProcessor,SiglipImageProcessor:()=>Oe.SiglipImageProcessor,SmolVLMImageProcessor:()=>he.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>K.Swin2SRImageProcessor,VLMImageProcessor:()=>j.VLMImageProcessor,ViTFeatureExtractor:()=>ce.ViTFeatureExtractor,ViTImageProcessor:()=>ce.ViTImageProcessor,VitMatteImageProcessor:()=>ye.VitMatteImageProcessor,VitPoseImageProcessor:()=>Fe.VitPoseImageProcessor,YolosFeatureExtractor:()=>Xe.YolosFeatureExtractor,YolosImageProcessor:()=>Xe.YolosImageProcessor});var w=r("./src/models/beit/image_processing_beit.js"),T=r("./src/models/bit/image_processing_bit.js"),L=r("./src/models/chinese_clip/image_processing_chinese_clip.js"),H=r("./src/models/clip/image_processing_clip.js"),$=r("./src/models/convnext/image_processing_convnext.js"),_=r("./src/models/deit/image_processing_deit.js"),I=r("./src/models/detr/image_processing_detr.js"),D=r("./src/models/dinov3_vit/image_processing_dinov3_vit.js"),b=r("./src/models/donut/image_processing_donut.js"),h=r("./src/models/dpt/image_processing_dpt.js"),U=r("./src/models/efficientnet/image_processing_efficientnet.js"),z=r("./src/models/glpn/image_processing_glpn.js"),Q=r("./src/models/grounding_dino/image_processing_grounding_dino.js"),ge=r("./src/models/idefics3/image_processing_idefics3.js"),j=r("./src/models/janus/image_processing_janus.js"),G=r("./src/models/jina_clip/image_processing_jina_clip.js"),Y=r("./src/models/llava_onevision/image_processing_llava_onevision.js"),O=r("./src/models/mask2former/image_processing_mask2former.js"),S=r("./src/models/maskformer/image_processing_maskformer.js"),E=r("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),x=r("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),C=r("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),re=r("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),q=r("./src/models/mobilevit/image_processing_mobilevit.js"),pe=r("./src/models/nougat/image_processing_nougat.js"),me=r("./src/models/owlv2/image_processing_owlv2.js"),J=r("./src/models/owlvit/image_processing_owlvit.js"),fe=r("./src/models/phi3_v/image_processing_phi3_v.js"),de=r("./src/models/pvt/image_processing_pvt.js"),Te=r("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Pe=r("./src/models/rt_detr/image_processing_rt_detr.js"),be=r("./src/models/sam/image_processing_sam.js"),He=r("./src/models/segformer/image_processing_segformer.js"),Oe=r("./src/models/siglip/image_processing_siglip.js"),he=r("./src/models/smolvlm/image_processing_smolvlm.js"),K=r("./src/models/swin2sr/image_processing_swin2sr.js"),ce=r("./src/models/vit/image_processing_vit.js"),ye=r("./src/models/vitmatte/image_processing_vitmatte.js"),Fe=r("./src/models/vitpose/image_processing_vitpose.js"),Xe=r("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(ae,m,r)=>{r.r(m),r.d(m,{VLMImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{constructor(H){super({do_pad:!0,pad_size:{width:H.image_size,height:H.image_size},...H}),this.constant_values=this.config.background_color.map($=>$*this.rescale_factor)}pad_image(H,$,_,I){return super.pad_image(H,$,_,{constant_values:this.constant_values,center:!0,...I})}}},"./src/models/janus/processing_janus.js":(ae,m,r)=>{r.r(m),r.d(m,{VLChatProcessor:()=>I});var w=r("./src/base/processing_utils.js"),T=r("./src/models/auto/image_processing_auto.js"),L=r("./src/tokenizers.js"),H=r("./src/utils/core.js"),$=r("./src/utils/tensor.js"),_=r("./src/utils/image.js");class I extends w.Processor{constructor(b,h,U){super(b,h,U),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(b,{images:h=null,chat_template:U="default"}={}){h?Array.isArray(h)||(h=[h]):h=await Promise.all(b.filter(q=>q.images).flatMap(q=>q.images).map(q=>_.RawImage.read(q)));const z=this.tokenizer,Q=z.apply_chat_template(b,{tokenize:!1,add_generation_prompt:!0,chat_template:U}),ge=q=>z.encode(q,{add_special_tokens:!1}),j=Q.split(this.image_tag),G=j.length-1;if(h.length!==G)throw new Error(`Number of images provided (${h.length}) does not match number of "${this.image_tag}" image tags (${G})`);const[Y,O,S]=z.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let E=ge(j[0]),x=new Array(E.length).fill(!1);for(let q=1;q0){const q=await this.image_processor(h);return q.pixel_values.unsqueeze_(0),{...re,...q}}return re}}ie(I,"image_processor_class",T.AutoImageProcessor),ie(I,"tokenizer_class",L.AutoTokenizer),ie(I,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(ae,m,r)=>{r.r(m),r.d(m,{JinaCLIPImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{constructor(H){const{resize_mode:$,fill_color:_,interpolation:I,size:D,...b}=H,h=$==="squash"?{width:D,height:D}:$==="shortest"?{shortest_edge:D}:{longest_edge:D},U=I==="bicubic"?3:2;super({...b,size:h,resample:U,do_center_crop:!0,crop_size:D,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(ae,m,r)=>{r.r(m),r.d(m,{JinaCLIPProcessor:()=>H});var w=r("./src/base/processing_utils.js"),T=r("./src/models/auto/image_processing_auto.js"),L=r("./src/tokenizers.js");class H extends w.Processor{async _call(_=null,I=null,D={}){if(!_&&!I)throw new Error("Either text or images must be provided");const b=_?this.tokenizer(_,D):{},h=I?await this.image_processor(I,D):{};return{...b,...h}}}ie(H,"tokenizer_class",L.AutoTokenizer),ie(H,"image_processor_class",T.AutoImageProcessor)},"./src/models/llava/processing_llava.js":(ae,m,r)=>{r.r(m),r.d(m,{LlavaProcessor:()=>H});var w=r("./src/base/processing_utils.js"),T=r("./src/models/auto/image_processing_auto.js"),L=r("./src/tokenizers.js");class H extends w.Processor{async _call(_,I=null,D={}){const b=await this.image_processor(_,D);if(I){const[U,z]=b.pixel_values.dims.slice(-2),{image_token:Q,patch_size:ge,num_additional_image_tokens:j}=this.config,G=Math.floor(U/ge)*Math.floor(z/ge)+j;I=structuredClone(I),Array.isArray(I)||(I=[I]);for(let Y=0;Y{r.r(m),r.d(m,{LlavaOnevisionImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(ae,m,r)=>{r.r(m),r.d(m,{Mask2FormerImageProcessor:()=>T});var w=r("./src/models/maskformer/image_processing_maskformer.js");class T extends w.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(ae,m,r)=>{r.r(m),r.d(m,{MaskFormerFeatureExtractor:()=>L,MaskFormerImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{post_process_panoptic_segmentation(...$){return(0,w.post_process_panoptic_segmentation)(...$)}post_process_instance_segmentation(...$){return(0,w.post_process_instance_segmentation)(...$)}}class L extends T{}},"./src/models/mgp_str/processing_mgp_str.js":(ae,m,r)=>{r.r(m),r.d(m,{MgpstrProcessor:()=>_});var w=r("./src/base/processing_utils.js"),T=r("./src/models/auto/image_processing_auto.js"),L=r("./src/tokenizers.js"),H=r("./src/utils/maths.js");const $={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class _ extends w.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(D,b){if(!$.hasOwnProperty(b))throw new Error(`Format ${b} is not supported.`);const[h,U]=$[b],z=this[h].bind(this),[Q,ge]=D.dims,j=[],G=[],Y=D.tolist();for(let S=0;S0?C.reduce((q,pe)=>q*pe,1):0;G.push(x),j.push(re)}return[z(G),j]}char_decode(D){return this.char_tokenizer.batch_decode(D).map(b=>b.replaceAll(" ",""))}bpe_decode(D){return this.bpe_tokenizer.batch_decode(D)}wp_decode(D){return this.wp_tokenizer.batch_decode(D).map(b=>b.replaceAll(" ",""))}batch_decode([D,b,h]){const[U,z]=this._decode_helper(D,"char"),[Q,ge]=this._decode_helper(b,"bpe"),[j,G]=this._decode_helper(h,"wp"),Y=[],O=[];for(let S=0;S{r.r(m),r.d(m,{MobileNetV1FeatureExtractor:()=>L,MobileNetV1ImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}class L extends T{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(ae,m,r)=>{r.r(m),r.d(m,{MobileNetV2FeatureExtractor:()=>L,MobileNetV2ImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}class L extends T{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(ae,m,r)=>{r.r(m),r.d(m,{MobileNetV3FeatureExtractor:()=>L,MobileNetV3ImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}class L extends T{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(ae,m,r)=>{r.r(m),r.d(m,{MobileNetV4FeatureExtractor:()=>L,MobileNetV4ImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}class L extends T{}},"./src/models/mobilevit/image_processing_mobilevit.js":(ae,m,r)=>{r.r(m),r.d(m,{MobileViTFeatureExtractor:()=>L,MobileViTImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}class L extends T{}},"./src/models/moonshine/feature_extraction_moonshine.js":(ae,m,r)=>{r.r(m),r.d(m,{MoonshineFeatureExtractor:()=>L});var w=r("./src/base/feature_extraction_utils.js"),T=r("./src/utils/tensor.js");class L extends w.FeatureExtractor{async _call($){(0,w.validate_audio_inputs)($,"MoonshineFeatureExtractor"),$ instanceof Float64Array&&($=new Float32Array($));const _=[1,$.length];return{input_values:new T.Tensor("float32",$,_)}}}},"./src/models/moonshine/processing_moonshine.js":(ae,m,r)=>{r.r(m),r.d(m,{MoonshineProcessor:()=>H});var w=r("./src/models/auto/feature_extraction_auto.js"),T=r("./src/tokenizers.js"),L=r("./src/base/processing_utils.js");class H extends L.Processor{async _call(_){return await this.feature_extractor(_)}}ie(H,"tokenizer_class",T.AutoTokenizer),ie(H,"feature_extractor_class",w.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(ae,m,r)=>{r.r(m),r.d(m,{NougatImageProcessor:()=>T});var w=r("./src/models/donut/image_processing_donut.js");class T extends w.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(ae,m,r)=>{r.r(m),r.d(m,{Owlv2ImageProcessor:()=>T});var w=r("./src/models/owlvit/image_processing_owlvit.js");class T extends w.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(ae,m,r)=>{r.r(m),r.d(m,{OwlViTFeatureExtractor:()=>L,OwlViTImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{post_process_object_detection(...$){return(0,w.post_process_object_detection)(...$)}}class L extends T{}},"./src/models/owlvit/processing_owlvit.js":(ae,m,r)=>{r.r(m),r.d(m,{OwlViTProcessor:()=>H});var w=r("./src/base/processing_utils.js"),T=r("./src/models/auto/image_processing_auto.js"),L=r("./src/tokenizers.js");class H extends w.Processor{}ie(H,"tokenizer_class",L.AutoTokenizer),ie(H,"image_processor_class",T.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(ae,m,r)=>{r.r(m),r.d(m,{PaliGemmaProcessor:()=>_});var w=r("./src/base/processing_utils.js"),T=r("./src/models/auto/image_processing_auto.js"),L=r("./src/tokenizers.js");const H="";function $(I,D,b,h,U){return`${h.repeat(b*U)}${D}${I} +`}class _ extends w.Processor{async _call(D,b=null,h={}){b||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),b=""),Array.isArray(D)||(D=[D]),Array.isArray(b)||(b=[b]);const U=this.tokenizer.bos_token,z=this.image_processor.config.image_seq_length;let Q;b.some(G=>G.includes(H))?Q=b.map(G=>{const Y=G.replaceAll(H,H.repeat(z)),O=Y.lastIndexOf(H),S=O===-1?0:O+H.length;return Y.slice(0,S)+U+Y.slice(S)+` +`}):(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."),Q=b.map(G=>$(G,U,z,H,D.length)));const ge=this.tokenizer(Q,h);return{...await this.image_processor(D,h),...ge}}}ie(_,"tokenizer_class",L.AutoTokenizer),ie(_,"image_processor_class",T.AutoImageProcessor),ie(_,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(ae,m,r)=>{r.r(m),r.d(m,{Phi3VImageProcessor:()=>D});var w=r("./src/base/image_processors_utils.js"),T=r("./src/utils/tensor.js");const L=336,H=[2,3],{ceil:$,floor:_,sqrt:I}=Math;class D extends w.ImageProcessor{constructor(h){super({...h,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0}),this._num_crops=h.num_crops}calc_num_image_tokens_from_image_size(h,U){const{num_img_tokens:z}=this.config;return _((_(U/L)*_(h/L)+1)*z+1+(_(U/L)+1)*I(z))}get_resize_output_image_size(h,U){const z=this._num_crops,[Q,ge]=h.size;let j=Q/ge,G=1;for(;G*Math.ceil(G/j)<=z;)G+=1;G-=1;const Y=Math.floor(G*336),O=Math.floor(Y/j);return[Y,O]}pad_image(h,U,z,Q={}){const[ge,j]=U,G=L*$(ge/L),Y=L*$(j/L),O=[1,1,1].map((S,E)=>(S-this.image_mean[E])/this.image_std[E]);return super.pad_image(h,U,{width:Y,height:G},{center:!0,constant_values:O,...Q})}async _call(h,{num_crops:U=null}={}){if(this._num_crops=U??(U=this.config.num_crops),U<4||I(U)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(h)||(h=[h]);const z=h.length,Q=await Promise.all(h.map(x=>this.preprocess(x))),ge=Q.map(x=>x.original_size),j=Q.map(x=>x.reshaped_input_size),G=[];for(const{pixel_values:x}of Q){x.unsqueeze_(0);const[C,re]=x.dims.slice(-2),q=await(0,T.interpolate_4d)(x,{size:[L,L],mode:"bicubic"});if(U>0){const pe=[],me=I(U),J=_(re/me),fe=_(C/me);for(let Te=0;Tex.map(C=>L*$(C/L))),S=new T.Tensor("int64",O.flat(),[z,2]),E=O.map(([x,C])=>this.calc_num_image_tokens_from_image_size(C,x));return{pixel_values:Y,original_sizes:ge,reshaped_input_sizes:j,image_sizes:S,num_img_tokens:E}}}},"./src/models/phi3_v/processing_phi3_v.js":(ae,m,r)=>{r.r(m),r.d(m,{Phi3VProcessor:()=>_});var w=r("./src/base/processing_utils.js"),T=r("./src/models/auto/image_processing_auto.js"),L=r("./src/tokenizers.js");r("./src/utils/image.js");const H="<|image|>",$=/<\|image_\d+\|>/g;class _ extends w.Processor{async _call(D,b=null,{padding:h=!0,truncation:U=!0,num_crops:z=null}={}){Array.isArray(D)||(D=[D]);let Q,ge;if(b){ge=await this.image_processor(b,{num_crops:z});const{num_img_tokens:j}=ge,G=D.map((O,S)=>O.split($).join(H.repeat(j[S])));Q=this.tokenizer(G,{padding:h,truncation:U});const Y=this.tokenizer.model.convert_tokens_to_ids([H])[0];Q.input_ids.map_(O=>O==Y?-O:O)}else Q=this.tokenizer(D);return{...Q,...ge}}}ie(_,"image_processor_class",T.AutoImageProcessor),ie(_,"tokenizer_class",L.AutoTokenizer)},"./src/models/processors.js":(ae,m,r)=>{r.r(m),r.d(m,{Florence2Processor:()=>w.Florence2Processor,Gemma3nProcessor:()=>T.Gemma3nProcessor,GroundingDinoProcessor:()=>L.GroundingDinoProcessor,Idefics3Processor:()=>H.Idefics3Processor,JinaCLIPProcessor:()=>_.JinaCLIPProcessor,LlavaProcessor:()=>I.LlavaProcessor,MgpstrProcessor:()=>D.MgpstrProcessor,MoonshineProcessor:()=>b.MoonshineProcessor,OwlViTProcessor:()=>h.OwlViTProcessor,PaliGemmaProcessor:()=>z.PaliGemmaProcessor,Phi3VProcessor:()=>U.Phi3VProcessor,PyAnnoteProcessor:()=>Q.PyAnnoteProcessor,Qwen2VLProcessor:()=>ge.Qwen2VLProcessor,SamProcessor:()=>j.SamProcessor,SmolVLMProcessor:()=>G.SmolVLMProcessor,SpeechT5Processor:()=>Y.SpeechT5Processor,UltravoxProcessor:()=>O.UltravoxProcessor,VLChatProcessor:()=>$.VLChatProcessor,VoxtralProcessor:()=>S.VoxtralProcessor,Wav2Vec2Processor:()=>E.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>x.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>C.WhisperProcessor});var w=r("./src/models/florence2/processing_florence2.js"),T=r("./src/models/gemma3n/processing_gemma3n.js"),L=r("./src/models/grounding_dino/processing_grounding_dino.js"),H=r("./src/models/idefics3/processing_idefics3.js"),$=r("./src/models/janus/processing_janus.js"),_=r("./src/models/jina_clip/processing_jina_clip.js"),I=r("./src/models/llava/processing_llava.js"),D=r("./src/models/mgp_str/processing_mgp_str.js"),b=r("./src/models/moonshine/processing_moonshine.js"),h=r("./src/models/owlvit/processing_owlvit.js"),U=r("./src/models/phi3_v/processing_phi3_v.js"),z=r("./src/models/paligemma/processing_paligemma.js"),Q=r("./src/models/pyannote/processing_pyannote.js"),ge=r("./src/models/qwen2_vl/processing_qwen2_vl.js"),j=r("./src/models/sam/processing_sam.js"),G=r("./src/models/smolvlm/processing_smolvlm.js"),Y=r("./src/models/speecht5/processing_speecht5.js"),O=r("./src/models/ultravox/processing_ultravox.js"),S=r("./src/models/voxtral/processing_voxtral.js"),E=r("./src/models/wav2vec2/processing_wav2vec2.js"),x=r("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),C=r("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(ae,m,r)=>{r.r(m),r.d(m,{PvtImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(ae,m,r)=>{r.r(m),r.d(m,{PyAnnoteFeatureExtractor:()=>H});var w=r("./src/base/feature_extraction_utils.js"),T=r("./src/utils/tensor.js"),L=r("./src/utils/maths.js");class H extends w.FeatureExtractor{async _call(_){(0,w.validate_audio_inputs)(_,"PyAnnoteFeatureExtractor"),_ instanceof Float64Array&&(_=new Float32Array(_));const I=[1,1,_.length];return{input_values:new T.Tensor("float32",_,I)}}samples_to_frames(_){return(_-this.config.offset)/this.config.step}post_process_speaker_diarization(_,I){const D=I/this.samples_to_frames(I)/this.config.sampling_rate,b=[];for(const h of _.tolist()){const U=[];let z=-1;for(let Q=0;Q({id:Q,start:ge*D,end:j*D,confidence:G/(j-ge)})))}return b}}},"./src/models/pyannote/processing_pyannote.js":(ae,m,r)=>{r.r(m),r.d(m,{PyAnnoteProcessor:()=>L});var w=r("./src/base/processing_utils.js"),T=r("./src/models/pyannote/feature_extraction_pyannote.js");class L extends w.Processor{async _call($){return await this.feature_extractor($)}post_process_speaker_diarization(...$){return this.feature_extractor.post_process_speaker_diarization(...$)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}ie(L,"feature_extractor_class",T.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(ae,m,r)=>{r.r(m),r.d(m,{Qwen2VLImageProcessor:()=>L});var w=r("./src/base/image_processors_utils.js"),T=r("./src/utils/tensor.js");class L extends w.ImageProcessor{async _call($,..._){const{pixel_values:I,original_sizes:D,reshaped_input_sizes:b}=await super._call($,..._);let h=I;const{temporal_patch_size:U,merge_size:z,patch_size:Q}=this.config;h.dims[0]===1&&(h=(0,T.cat)(Array.from({length:U},()=>h),0));const ge=h.dims[0]/U,j=h.dims[1],G=Math.floor(h.dims[2]/Q),Y=Math.floor(h.dims[3]/Q),O=h.view(ge,U,j,Math.floor(G/z),z,Q,Math.floor(Y/z),z,Q).permute(0,3,6,4,7,2,1,5,8).view(ge*G*Y,j*U*Q*Q),S=new T.Tensor("int64",[ge,G,Y],[1,3]);return{pixel_values:O,image_grid_thw:S,original_sizes:D,reshaped_input_sizes:b}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(ae,m,r)=>{r.r(m),r.d(m,{Qwen2VLProcessor:()=>H});var w=r("./src/base/processing_utils.js"),T=r("./src/models/auto/image_processing_auto.js"),L=r("./src/tokenizers.js");r("./src/utils/image.js");class H extends w.Processor{async _call(_,I=null,...D){Array.isArray(_)||(_=[_]);let b,h;if(I&&(b=await this.image_processor(I),h=b.image_grid_thw),h){let z=this.image_processor.config.merge_size**2,Q=0;const ge=h.tolist();_=_.map(j=>{for(;j.includes("<|image_pad|>");){const G=Number(ge[Q++].reduce((Y,O)=>Y*O,1n));j=j.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(G/z)))}return j.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(_),...b}}}ie(H,"image_processor_class",T.AutoImageProcessor),ie(H,"tokenizer_class",L.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(ae,m,r)=>{r.r(m),r.d(m,{RTDetrImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{post_process_object_detection(...H){return(0,w.post_process_object_detection)(...H)}}},"./src/models/sam/image_processing_sam.js":(ae,m,r)=>{r.r(m),r.d(m,{SamImageProcessor:()=>H});var w=r("./src/base/image_processors_utils.js"),T=r("./src/utils/core.js"),L=r("./src/utils/tensor.js");class H extends w.ImageProcessor{reshape_input_points(_,I,D,b=!1){_=structuredClone(_);let h=(0,T.calculateDimensions)(_);if(h.length===3)b||(h=[1,...h]),_=[_];else if(h.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 U=0;U<_.length;++U){let z=I[U],Q=D[U],ge=[Q[0]/z[0],Q[1]/z[1]];for(let j=0;j<_[U].length;++j)for(let G=0;G<_[U][j].length;++G)for(let Y=0;Y<_[U][j][G].length;++Y)_[U][j][G][Y]*=ge[Y%2]}return new L.Tensor("float32",Float32Array.from(_.flat(1/0)),h)}add_input_labels(_,I){let D=(0,T.calculateDimensions)(_);if(D.length===2)D=[1,...D],_=[_];else if(D.length!==3)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");if(D.some((b,h)=>b!==I.dims[h]))throw Error(`The first ${D.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new L.Tensor("int64",_.flat(1/0).map(BigInt),D)}async _call(_,{input_points:I=null,input_labels:D=null,input_boxes:b=null}={}){const h=await super._call(_);if(I&&(h.input_points=this.reshape_input_points(I,h.original_sizes,h.reshaped_input_sizes)),D){if(!h.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");h.input_labels=this.add_input_labels(D,h.input_points)}return b&&(h.input_boxes=this.reshape_input_points(b,h.original_sizes,h.reshaped_input_sizes,!0)),h}async post_process_masks(_,I,D,{mask_threshold:b=0,binarize:h=!0,pad_size:U=null}={}){const z=[];U=U??this.pad_size;const Q=[U.height,U.width];for(let ge=0;geb&&(S[E]=1);Y=new L.Tensor("bool",S,Y.dims)}z.push(Y)}return z}generate_crop_boxes(_,I,{crop_n_layers:D=0,overlap_ratio:b=512/1500,points_per_crop:h=32,crop_n_points_downscale_factor:U=1}={}){}}},"./src/models/sam/processing_sam.js":(ae,m,r)=>{r.r(m),r.d(m,{SamProcessor:()=>L});var w=r("./src/base/processing_utils.js"),T=r("./src/models/auto/image_processing_auto.js");class L extends w.Processor{async _call(...$){return await this.image_processor(...$)}post_process_masks(...$){return this.image_processor.post_process_masks(...$)}reshape_input_points(...$){return this.image_processor.reshape_input_points(...$)}}ie(L,"image_processor_class",T.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(ae,m,r)=>{r.r(m),r.d(m,{SeamlessM4TFeatureExtractor:()=>H});var w=r("./src/base/feature_extraction_utils.js"),T=r("./src/utils/tensor.js"),L=r("./src/utils/audio.js");class H extends w.FeatureExtractor{constructor(_){super(_);const I=this.config.sampling_rate,D=(0,L.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(I/2),I,null,"kaldi",!0);this.mel_filters=D,this.window=(0,L.window_function)(400,"povey",{periodic:!1})}async _extract_fbank_features(_,I){return _=_.map(D=>D*32768),(0,L.spectrogram)(_,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:I,transpose:!0})}async _call(_,{padding:I=!0,pad_to_multiple_of:D=2,do_normalize_per_mel_bins:b=!0,return_attention_mask:h=!0}={}){(0,w.validate_audio_inputs)(_,"SeamlessM4TFeatureExtractor");let U=await this._extract_fbank_features(_,this.config.max_length);if(b){const[S,E]=U.dims,x=U.data;for(let C=0;C0){const re=new Float32Array(E*(S+C));re.set(x),re.fill(this.config.padding_value,x.length);const q=S+C;U=new T.Tensor(U.type,re,[q,E]),h&&(z=new T.Tensor("int64",new BigInt64Array(q),[1,q]),z.data.fill(1n,0,S))}}const[Q,ge]=U.dims,j=this.config.stride;if(Q%j!==0)throw new Error(`The number of frames (${Q}) must be a multiple of the stride (${j}).`);const Y=U.view(1,Math.floor(Q/j),ge*j),O={input_features:Y};if(h){const S=Y.dims[1],E=new BigInt64Array(S);if(z){const x=z.data;for(let C=1,re=0;C{r.r(m),r.d(m,{SegformerFeatureExtractor:()=>L,SegformerImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{post_process_semantic_segmentation(...$){return(0,w.post_process_semantic_segmentation)(...$)}}class L extends T{}},"./src/models/siglip/image_processing_siglip.js":(ae,m,r)=>{r.r(m),r.d(m,{SiglipImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}},"./src/models/smolvlm/image_processing_smolvlm.js":(ae,m,r)=>{r.r(m),r.d(m,{SmolVLMImageProcessor:()=>w.Idefics3ImageProcessor});var w=r("./src/models/idefics3/image_processing_idefics3.js")},"./src/models/smolvlm/processing_smolvlm.js":(ae,m,r)=>{r.r(m),r.d(m,{SmolVLMProcessor:()=>w.Idefics3Processor});var w=r("./src/models/idefics3/processing_idefics3.js")},"./src/models/snac/feature_extraction_snac.js":(ae,m,r)=>{r.r(m),r.d(m,{SnacFeatureExtractor:()=>T});var w=r("./src/models/dac/feature_extraction_dac.js");class T extends w.DacFeatureExtractor{}},"./src/models/speecht5/feature_extraction_speecht5.js":(ae,m,r)=>{r.r(m),r.d(m,{SpeechT5FeatureExtractor:()=>T});var w=r("./src/base/feature_extraction_utils.js");class T extends w.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(ae,m,r)=>{r.r(m),r.d(m,{SpeechT5Processor:()=>H});var w=r("./src/base/processing_utils.js"),T=r("./src/tokenizers.js"),L=r("./src/models/auto/feature_extraction_auto.js");class H extends w.Processor{async _call(_){return await this.feature_extractor(_)}}ie(H,"tokenizer_class",T.AutoTokenizer),ie(H,"feature_extractor_class",L.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(ae,m,r)=>{r.r(m),r.d(m,{Swin2SRImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{pad_image(H,$,_,I={}){const[D,b,h]=$;return super.pad_image(H,$,{width:b+(_-b%_)%_,height:D+(_-D%_)%_},{mode:"symmetric",center:!1,constant_values:-1,...I})}}},"./src/models/ultravox/processing_ultravox.js":(ae,m,r)=>{r.r(m),r.d(m,{UltravoxProcessor:()=>H});var w=r("./src/models/auto/feature_extraction_auto.js"),T=r("./src/tokenizers.js"),L=r("./src/base/processing_utils.js");class H extends L.Processor{async _call(_,I=null,D={}){if(Array.isArray(_))throw new Error("Batched inputs are not supported yet.");let b={};if(I){const U=I.length,{input_features:z}=await this.feature_extractor(I,{...D,max_length:U}),Q=Math.round(U/this.config.encoder_ds_factor+1e-4),ge=1+Math.ceil(Q/this.config.stack_factor);b.audio_token_len=[ge],b.audio_values=z;const j=this.config.audio_placeholder;if(!_.includes(j))throw new Error(`The input text does not contain the image token ${j}.`);_=_.replaceAll(j,j.repeat(ge))}return{...this.tokenizer(_,{add_special_tokens:!1,...D}),...b}}}ie(H,"tokenizer_class",T.AutoTokenizer),ie(H,"feature_extractor_class",w.AutoFeatureExtractor),ie(H,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(ae,m,r)=>{r.r(m),r.d(m,{ViTFeatureExtractor:()=>L,ViTImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{}class L extends T{}},"./src/models/vitmatte/image_processing_vitmatte.js":(ae,m,r)=>{r.r(m),r.d(m,{VitMatteImageProcessor:()=>L});var w=r("./src/base/image_processors_utils.js"),T=r("./src/utils/tensor.js");class L extends w.ImageProcessor{async _call($,_){Array.isArray($)||($=[$]),Array.isArray(_)||(_=[_]);const I=await Promise.all($.map(h=>this.preprocess(h))),D=await Promise.all(_.map(h=>this.preprocess(h,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,T.stack)(I.map((h,U)=>(0,T.cat)([h.pixel_values,D[U].pixel_values],0)),0),original_sizes:I.map(h=>h.original_size),reshaped_input_sizes:I.map(h=>h.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(ae,m,r)=>{r.r(m),r.d(m,{VitPoseImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{post_process_pose_estimation(H,$,{threshold:_=null}={}){const I=H.tolist(),[D,b,h,U]=H.dims,z=[];for(let Q=0;Q{r.r(m),r.d(m,{VoxtralProcessor:()=>b});var w=r("./src/models/auto/feature_extraction_auto.js"),T=r("./src/tokenizers.js"),L=r("./src/base/processing_utils.js"),H=r("./src/utils/tensor.js");const $="[AUDIO]",_="[BEGIN_AUDIO]",I=375;function D(h,U){const z=[];for(let Q=0;QD(q,O)),E=S.map(q=>q.length),x=S.flat(),C=(await Promise.all(x.map(q=>this.feature_extractor(q,Q)))).map(q=>q.input_features);ge.audio_values=C.length>1?(0,H.cat)(C,0):C[0];let re=G[0];for(let q=0;q{r.r(m),r.d(m,{Wav2Vec2FeatureExtractor:()=>L});var w=r("./src/base/feature_extraction_utils.js"),T=r("./src/utils/tensor.js");class L extends w.FeatureExtractor{_zero_mean_unit_var_norm($){const I=$.reduce((b,h)=>b+h,0)/$.length,D=$.reduce((b,h)=>b+(h-I)**2,0)/$.length;return $.map(b=>(b-I)/Math.sqrt(D+1e-7))}async _call($){(0,w.validate_audio_inputs)($,"Wav2Vec2FeatureExtractor"),$ instanceof Float64Array&&($=new Float32Array($));let _=$;this.config.do_normalize&&(_=this._zero_mean_unit_var_norm(_));const I=[1,_.length];return{input_values:new T.Tensor("float32",_,I),attention_mask:new T.Tensor("int64",new BigInt64Array(_.length).fill(1n),I)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(ae,m,r)=>{r.r(m),r.d(m,{Wav2Vec2Processor:()=>H});var w=r("./src/tokenizers.js"),T=r("./src/models/auto/feature_extraction_auto.js"),L=r("./src/base/processing_utils.js");class H extends L.Processor{async _call(_){return await this.feature_extractor(_)}}ie(H,"tokenizer_class",w.AutoTokenizer),ie(H,"feature_extractor_class",T.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(ae,m,r)=>{r.r(m),r.d(m,{Wav2Vec2ProcessorWithLM:()=>H});var w=r("./src/tokenizers.js"),T=r("./src/models/auto/feature_extraction_auto.js"),L=r("./src/base/processing_utils.js");class H extends L.Processor{async _call(_){return await this.feature_extractor(_)}}ie(H,"tokenizer_class",w.AutoTokenizer),ie(H,"feature_extractor_class",T.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(ae,m,r)=>{r.r(m),r.d(m,{WeSpeakerFeatureExtractor:()=>L});var w=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var T=r("./src/utils/audio.js");class L extends w.FeatureExtractor{constructor($){super($);const _=this.config.sampling_rate,I=(0,T.mel_filter_bank)(257,this.config.num_mel_bins,20,Math.floor(_/2),_,null,"kaldi",!0);this.mel_filters=I,this.window=(0,T.window_function)(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features($){return $=$.map(_=>_*32768),(0,T.spectrogram)($,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($){(0,w.validate_audio_inputs)($,"WeSpeakerFeatureExtractor");const _=(await this._extract_fbank_features($)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const I=_.mean(1).data,D=_.data,[b,h,U]=_.dims;for(let z=0;z{r.r(m),r.d(m,{WHISPER_LANGUAGE_MAPPING:()=>T,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>L,whisper_language_to_code:()=>H});const w=[["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"]],T=new Map(w),L=new Map([...w.map(([$,_])=>[_,$]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function H($){$=$.toLowerCase();let _=L.get($);if(_===void 0){const I=$.match(/^<\|([a-z]{2})\|>$/);if(I&&($=I[1]),T.has($))_=$;else{const b=$.length===2?T.keys():T.values();throw new Error(`Language "${$}" is not supported. Must be one of: ${JSON.stringify(Array.from(b))}`)}}return _}},"./src/models/whisper/feature_extraction_whisper.js":(ae,m,r)=>{r.r(m),r.d(m,{WhisperFeatureExtractor:()=>H});var w=r("./src/base/feature_extraction_utils.js");r("./src/utils/tensor.js");var T=r("./src/utils/audio.js"),L=r("./src/utils/maths.js");class H extends w.FeatureExtractor{constructor(_){var I;super(_),(I=this.config).mel_filters??(I.mel_filters=(0,T.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,T.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(_){const I=await(0,T.spectrogram)(_,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(_.length/this.config.hop_length),this.config.nb_max_frames)}),D=I.data,b=(0,L.max)(D)[0];for(let h=0;hb?(_.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`."),D=_.slice(0,b)):(D=new Float32Array(b),D.set(_)),{input_features:(await this._extract_fbank_features(D)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(ae,m,r)=>{r.r(m),r.d(m,{WhisperGenerationConfig:()=>T});var w=r("./src/generation/configuration_utils.js");class T extends w.GenerationConfig{constructor(){super(...arguments);ie(this,"return_timestamps",null);ie(this,"return_token_timestamps",null);ie(this,"num_frames",null);ie(this,"alignment_heads",null);ie(this,"task",null);ie(this,"language",null);ie(this,"no_timestamps_token_id",null);ie(this,"prompt_ids",null);ie(this,"is_multilingual",null);ie(this,"lang_to_id",null);ie(this,"task_to_id",null);ie(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(ae,m,r)=>{r.r(m),r.d(m,{WhisperProcessor:()=>H});var w=r("./src/models/auto/feature_extraction_auto.js"),T=r("./src/tokenizers.js"),L=r("./src/base/processing_utils.js");class H extends L.Processor{async _call(_){return await this.feature_extractor(_)}}ie(H,"tokenizer_class",T.AutoTokenizer),ie(H,"feature_extractor_class",w.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(ae,m,r)=>{r.r(m),r.d(m,{YolosFeatureExtractor:()=>L,YolosImageProcessor:()=>T});var w=r("./src/base/image_processors_utils.js");class T extends w.ImageProcessor{post_process_object_detection(...$){return(0,w.post_process_object_detection)(...$)}}class L extends T{}},"./src/ops/registry.js":(ae,m,r)=>{r.r(m),r.d(m,{TensorOpRegistry:()=>_});var w=r("./src/backends/onnx.js"),T=r("./src/utils/tensor.js"),L=r("./src/env.js");const H=L.apis.IS_BROWSER_ENV||L.apis.IS_WEBWORKER_ENV,$=async(I,D,b)=>{const h=await(0,w.createInferenceSession)(new Uint8Array(I),D);let U=Promise.resolve();return async z=>{const Q=(0,w.isONNXProxy)(),ge=Object.fromEntries(Object.entries(z).map(([G,Y])=>[G,(Q?Y.clone():Y).ort_tensor])),j=await(U=H?U.then(()=>h.run(ge)):h.run(ge));return Array.isArray(b)?b.map(G=>new T.Tensor(j[G])):new T.Tensor(j[b])}};class _{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=$([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=$([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=$([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=$([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=$([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=$([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=$([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=$([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}}ie(_,"session_options",{})},"./src/pipelines.js":(ae,m,r)=>{r.r(m),r.d(m,{AudioClassificationPipeline:()=>me,AutomaticSpeechRecognitionPipeline:()=>fe,BackgroundRemovalPipeline:()=>be,DepthEstimationPipeline:()=>Fe,DocumentQuestionAnsweringPipeline:()=>K,FeatureExtractionPipeline:()=>q,FillMaskPipeline:()=>Y,ImageClassificationPipeline:()=>Te,ImageFeatureExtractionPipeline:()=>pe,ImageSegmentationPipeline:()=>Pe,ImageToImagePipeline:()=>ye,ImageToTextPipeline:()=>de,ObjectDetectionPipeline:()=>Oe,Pipeline:()=>Q,QuestionAnsweringPipeline:()=>G,SummarizationPipeline:()=>S,Text2TextGenerationPipeline:()=>O,TextClassificationPipeline:()=>ge,TextGenerationPipeline:()=>C,TextToAudioPipeline:()=>ce,TokenClassificationPipeline:()=>j,TranslationPipeline:()=>E,ZeroShotAudioClassificationPipeline:()=>J,ZeroShotClassificationPipeline:()=>re,ZeroShotImageClassificationPipeline:()=>He,ZeroShotObjectDetectionPipeline:()=>he,pipeline:()=>Ye});var w=r("./src/tokenizers.js"),T=r("./src/models.js"),L=r("./src/models/auto/processing_auto.js");r("./src/base/processing_utils.js");var H=r("./src/utils/generic.js"),$=r("./src/utils/core.js"),_=r("./src/utils/maths.js"),I=r("./src/utils/audio.js"),D=r("./src/utils/tensor.js"),b=r("./src/utils/image.js");async function h(We){return Array.isArray(We)||(We=[We]),await Promise.all(We.map(le=>b.RawImage.read(le)))}async function U(We,le){return Array.isArray(We)||(We=[We]),await Promise.all(We.map(Ee=>typeof Ee=="string"||Ee instanceof URL?(0,I.read_audio)(Ee,le):Ee instanceof Float64Array?new Float32Array(Ee):Ee))}function z(We,le){le&&(We=We.map(Ve=>Ve|0));const[Ee,X,ke,Ne]=We;return{xmin:Ee,ymin:X,xmax:ke,ymax:Ne}}class Q extends H.Callable{constructor({task:le,model:Ee,tokenizer:X=null,processor:ke=null}){super(),this.task=le,this.model=Ee,this.tokenizer=X,this.processor=ke}async dispose(){await this.model.dispose()}}class ge extends Q{constructor(le){super(le)}async _call(le,{top_k:Ee=1}={}){const X=this.tokenizer(le,{padding:!0,truncation:!0}),ke=await this.model(X),Ne=this.model.config.problem_type==="multi_label_classification"?Ke=>Ke.sigmoid():Ke=>new D.Tensor("float32",(0,_.softmax)(Ke.data),Ke.dims),Ve=this.model.config.id2label,De=[];for(const Ke of ke.logits){const Ae=Ne(Ke),qe=await(0,D.topk)(Ae,Ee),et=qe[0].tolist(),Re=qe[1].tolist().map((Mt,lt)=>({label:Ve?Ve[Mt]:`LABEL_${Mt}`,score:et[lt]}));Ee===1?De.push(...Re):De.push(Re)}return Array.isArray(le)||Ee===1?De:De[0]}}class j extends Q{constructor(le){super(le)}async _call(le,{ignore_labels:Ee=["O"]}={}){const X=Array.isArray(le),ke=this.tokenizer(X?le:[le],{padding:!0,truncation:!0}),Ve=(await this.model(ke)).logits,De=this.model.config.id2label,Ke=[];for(let Ae=0;Aeht==this.tokenizer.sep_token_id);Ke[et].map((ht,vt)=>ht==1&&(vt===0||vt>Re&&Ae.findIndex(Wt=>Wt==ut[vt])===-1));const Mt=Ne[et].tolist(),lt=Ve[et].tolist();for(let ht=1;htvt==ut[ht])!==-1)&&(Mt[ht]=-1/0,lt[ht]=-1/0);const pt=(0,_.softmax)(Mt).map((ht,vt)=>[ht,vt]),yt=(0,_.softmax)(lt).map((ht,vt)=>[ht,vt]);pt[0][0]=0,yt[0][0]=0;const ct=(0,$.product)(pt,yt).filter(ht=>ht[0][1]<=ht[1][1]).map(ht=>[ht[0][1],ht[1][1],ht[0][0]*ht[1][0]]).sort((ht,vt)=>vt[2]-ht[2]);for(let ht=0;htMt==this.tokenizer.mask_token_id);if(Ae===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const qe=ke[De][Ae],et=await(0,D.topk)(new D.Tensor("float32",(0,_.softmax)(qe.data),qe.dims),Ee),ut=et[0].tolist(),Re=et[1].tolist();Ne.push(Re.map((Mt,lt)=>{const pt=Ke.slice();return pt[Ae]=Mt,{score:ut[lt],token:Number(Mt),token_str:this.tokenizer.decode([Mt]),sequence:this.tokenizer.decode(pt,{skip_special_tokens:!0})}}))}return Array.isArray(le)?Ne:Ne[0]}}class O extends Q{constructor(Ee){super(Ee);ie(this,"_key","generated_text")}async _call(Ee,X={}){Array.isArray(Ee)||(Ee=[Ee]),this.model.config.prefix&&(Ee=Ee.map(Ae=>this.model.config.prefix+Ae));const ke=this.model.config.task_specific_params;ke&&ke[this.task]&&ke[this.task].prefix&&(Ee=Ee.map(Ae=>ke[this.task].prefix+Ae));const Ne=this.tokenizer,Ve={padding:!0,truncation:!0};let De;this instanceof E&&"_build_translation_inputs"in Ne?De=Ne._build_translation_inputs(Ee,Ve,X):De=Ne(Ee,Ve);const Ke=await this.model.generate({...De,...X});return Ne.batch_decode(Ke,{skip_special_tokens:!0}).map(Ae=>({[this._key]:Ae}))}}class S extends O{constructor(Ee){super(Ee);ie(this,"_key","summary_text")}}class E extends O{constructor(Ee){super(Ee);ie(this,"_key","translation_text")}}function x(We){return Array.isArray(We)&&We.every(le=>"role"in le&&"content"in le)}class C extends Q{constructor(le){super(le)}async _call(le,Ee={}){let X=!1,ke=!1,Ne=Ee.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,Ve;if(typeof le=="string")Ve=le=[le];else if(Array.isArray(le)&&le.every(Re=>typeof Re=="string"))X=!0,Ve=le;else{if(x(le))le=[le];else if(Array.isArray(le)&&le.every(x))X=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");ke=!0,Ve=le.map(Re=>this.tokenizer.apply_chat_template(Re,{tokenize:!1,add_generation_prompt:!0})),Ne=!1}const De=ke?!1:Ee.return_full_text??!0;this.tokenizer.padding_side="left";const Ke=this.tokenizer(Ve,{add_special_tokens:Ne,padding:!0,truncation:!0}),Ae=await this.model.generate({...Ke,...Ee}),qe=this.tokenizer.batch_decode(Ae,{skip_special_tokens:!0});let et;!De&&Ke.input_ids.dims.at(-1)>0&&(et=this.tokenizer.batch_decode(Ke.input_ids,{skip_special_tokens:!0}).map(Re=>Re.length));const ut=Array.from({length:le.length},Re=>[]);for(let Re=0;Re[Ee.toLowerCase(),X])),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(le,Ee,{hypothesis_template:X="This example is {}.",multi_label:ke=!1}={}){const Ne=Array.isArray(le);Ne||(le=[le]),Array.isArray(Ee)||(Ee=[Ee]);const Ve=Ee.map(Ae=>X.replace("{}",Ae)),De=ke||Ee.length===1,Ke=[];for(const Ae of le){const qe=[];for(const Re of Ve){const Mt=this.tokenizer(Ae,{text_pair:Re,padding:!0,truncation:!0}),lt=await this.model(Mt);De?qe.push([lt.logits.data[this.contradiction_id],lt.logits.data[this.entailment_id]]):qe.push(lt.logits.data[this.entailment_id])}const ut=(De?qe.map(Re=>(0,_.softmax)(Re)[1]):(0,_.softmax)(qe)).map((Re,Mt)=>[Re,Mt]).sort((Re,Mt)=>Mt[0]-Re[0]);Ke.push({sequence:Ae,labels:ut.map(Re=>Ee[Re[1]]),scores:ut.map(Re=>Re[0])})}return Ne?Ke:Ke[0]}}class q extends Q{constructor(le){super(le)}async _call(le,{pooling:Ee="none",normalize:X=!1,quantize:ke=!1,precision:Ne="binary"}={}){const Ve=this.tokenizer(le,{padding:!0,truncation:!0}),De=await this.model(Ve);let Ke=De.last_hidden_state??De.logits??De.token_embeddings;switch(Ee){case"none":break;case"mean":Ke=(0,D.mean_pooling)(Ke,Ve.attention_mask);break;case"first_token":case"cls":Ke=Ke.slice(null,0);break;case"last_token":case"eos":Ke=Ke.slice(null,-1);break;default:throw Error(`Pooling method '${Ee}' not supported.`)}return X&&(Ke=Ke.normalize(2,-1)),ke&&(Ke=(0,D.quantize_embeddings)(Ke,Ne)),Ke}}class pe extends Q{constructor(le){super(le)}async _call(le,{pool:Ee=null}={}){const X=await h(le),{pixel_values:ke}=await this.processor(X),Ne=await this.model({pixel_values:ke});let Ve;if(Ee){if(!("pooler_output"in Ne))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Ve=Ne.pooler_output}else Ve=Ne.last_hidden_state??Ne.logits??Ne.image_embeds;return Ve}}class me extends Q{constructor(le){super(le)}async _call(le,{top_k:Ee=5}={}){const X=this.processor.feature_extractor.config.sampling_rate,ke=await U(le,X),Ne=this.model.config.id2label,Ve=[];for(const De of ke){const Ke=await this.processor(De),qe=(await this.model(Ke)).logits[0],et=await(0,D.topk)(new D.Tensor("float32",(0,_.softmax)(qe.data),qe.dims),Ee),ut=et[0].tolist(),Mt=et[1].tolist().map((lt,pt)=>({label:Ne?Ne[lt]:`LABEL_${lt}`,score:ut[pt]}));Ve.push(Mt)}return Array.isArray(le)?Ve:Ve[0]}}class J extends Q{constructor(le){super(le)}async _call(le,Ee,{hypothesis_template:X="This is a sound of {}."}={}){const ke=!Array.isArray(le);ke&&(le=[le]);const Ne=Ee.map(qe=>X.replace("{}",qe)),Ve=this.tokenizer(Ne,{padding:!0,truncation:!0}),De=this.processor.feature_extractor.config.sampling_rate,Ke=await U(le,De),Ae=[];for(const qe of Ke){const et=await this.processor(qe),ut=await this.model({...Ve,...et}),Re=(0,_.softmax)(ut.logits_per_audio.data);Ae.push([...Re].map((Mt,lt)=>({score:Mt,label:Ee[lt]})))}return ke?Ae[0]:Ae}}class fe extends Q{constructor(le){super(le)}async _call(le,Ee={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(le,Ee);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(le,Ee);case"moonshine":return this._call_moonshine(le,Ee);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(le,Ee){Ee.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),Ee.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const X=!Array.isArray(le);X&&(le=[le]);const ke=this.processor.feature_extractor.config.sampling_rate,Ne=await U(le,ke),Ve=[];for(const De of Ne){const Ke=await this.processor(De),qe=(await this.model(Ke)).logits[0],et=[];for(const Re of qe)et.push((0,_.max)(Re.data)[1]);const ut=this.tokenizer.decode(et);Ve.push({text:ut})}return X?Ve[0]:Ve}async _call_whisper(le,Ee){const X=Ee.return_timestamps??!1,ke=Ee.chunk_length_s??0,Ne=Ee.force_full_sequences??!1;let Ve=Ee.stride_length_s??null;const De={...Ee};X==="word"&&(De.return_token_timestamps=!0,De.return_timestamps=!1);const Ke=!Array.isArray(le);Ke&&(le=[le]);const Ae=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,qe=this.processor.feature_extractor.config.hop_length,et=this.processor.feature_extractor.config.sampling_rate,ut=await U(le,et),Re=[];for(const Mt of ut){let lt=[];if(ke>0){if(Ve===null)Ve=ke/6;else if(ke<=Ve)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const ct=et*ke,ht=et*Ve,vt=ct-2*ht;let Wt=0;for(;;){const Qt=Wt+ct,jt=Mt.subarray(Wt,Qt),bs=await this.processor(jt),ds=Wt===0,Ls=Qt>=Mt.length;if(lt.push({stride:[jt.length,ds?0:ht,Ls?0:ht],input_features:bs.input_features,is_last:Ls}),Ls)break;Wt+=vt}}else lt=[{stride:[Mt.length,0,0],input_features:(await this.processor(Mt)).input_features,is_last:!0}];for(const ct of lt){De.num_frames=Math.floor(ct.stride[0]/qe);const ht=await this.model.generate({inputs:ct.input_features,...De});X==="word"?(ct.tokens=ht.sequences.tolist()[0],ct.token_timestamps=ht.token_timestamps.tolist()[0].map(vt=>(0,_.round)(vt,2))):ct.tokens=ht[0].tolist(),ct.stride=ct.stride.map(vt=>vt/et)}const[pt,yt]=this.tokenizer._decode_asr(lt,{time_precision:Ae,return_timestamps:X,force_full_sequences:Ne});Re.push({text:pt,...yt})}return Ke?Re[0]:Re}async _call_moonshine(le,Ee){const X=!Array.isArray(le);X&&(le=[le]);const ke=this.processor.feature_extractor.config.sampling_rate,Ne=await U(le,ke),Ve=[];for(const De of Ne){const Ke=await this.processor(De),Ae=Math.floor(De.length/ke)*6,qe=await this.model.generate({max_new_tokens:Ae,...Ee,...Ke}),et=this.processor.batch_decode(qe,{skip_special_tokens:!0})[0];Ve.push({text:et})}return X?Ve[0]:Ve}}class de extends Q{constructor(le){super(le)}async _call(le,Ee={}){const X=Array.isArray(le),ke=await h(le),{pixel_values:Ne}=await this.processor(ke),Ve=[];for(const De of Ne){De.dims=[1,...De.dims];const Ke=await this.model.generate({inputs:De,...Ee}),Ae=this.tokenizer.batch_decode(Ke,{skip_special_tokens:!0}).map(qe=>({generated_text:qe.trim()}));Ve.push(Ae)}return X?Ve:Ve[0]}}class Te extends Q{constructor(le){super(le)}async _call(le,{top_k:Ee=5}={}){const X=await h(le),{pixel_values:ke}=await this.processor(X),Ne=await this.model({pixel_values:ke}),Ve=this.model.config.id2label,De=[];for(const Ke of Ne.logits){const Ae=await(0,D.topk)(new D.Tensor("float32",(0,_.softmax)(Ke.data),Ke.dims),Ee),qe=Ae[0].tolist(),ut=Ae[1].tolist().map((Re,Mt)=>({label:Ve?Ve[Re]:`LABEL_${Re}`,score:qe[Mt]}));De.push(ut)}return Array.isArray(le)?De:De[0]}}class Pe extends Q{constructor(le){super(le),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(le,{threshold:Ee=.5,mask_threshold:X=.5,overlap_mask_area_threshold:ke=.8,label_ids_to_fuse:Ne=null,target_sizes:Ve=null,subtask:De=null}={}){if(Array.isArray(le)&&le.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const Ae=await h(le),qe=Ae.map(ct=>[ct.height,ct.width]),et=await this.processor(Ae),{inputNames:ut,outputNames:Re}=this.model.sessions.model;if(!ut.includes("pixel_values")){if(ut.length!==1)throw Error(`Expected a single input name, but got ${ut.length} inputs: ${ut}.`);const ct=ut[0];if(ct in et)throw Error(`Input name ${ct} already exists in the inputs.`);et[ct]=et.pixel_values}const Mt=await this.model(et);let lt=null;if(De!==null)lt=this.subtasks_mapping[De];else if(this.processor.image_processor){for(const[ct,ht]of Object.entries(this.subtasks_mapping))if(ht in this.processor.image_processor){lt=this.processor.image_processor[ht].bind(this.processor.image_processor),De=ct;break}}const pt=this.model.config.id2label,yt=[];if(De)if(De==="panoptic"||De==="instance"){const ct=lt(Mt,Ee,X,ke,Ne,Ve??qe)[0],ht=ct.segmentation;for(const vt of ct.segments_info){const Wt=new Uint8ClampedArray(ht.data.length);for(let jt=0;jtbs<-1e-5||bs>1+1e-5)&&Qt.sigmoid_();const jt=await b.RawImage.fromTensor(Qt.mul_(255).to("uint8")).resize(Wt[1],Wt[0]);yt.push({label:null,score:null,mask:jt})}}return yt}}class be extends Pe{constructor(le){super(le)}async _call(le,Ee={}){if(Array.isArray(le)&&le.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const ke=await h(le),Ne=await super._call(le,Ee);return ke.map((De,Ke)=>{const Ae=De.clone();return Ae.putAlpha(Ne[Ke].mask),Ae})}}class He extends Q{constructor(le){super(le)}async _call(le,Ee,{hypothesis_template:X="This is a photo of {}"}={}){const ke=Array.isArray(le),Ne=await h(le),Ve=Ee.map(ut=>X.replace("{}",ut)),De=this.tokenizer(Ve,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:Ke}=await this.processor(Ne),Ae=await this.model({...De,pixel_values:Ke}),qe=this.model.config.model_type==="siglip"?ut=>ut.sigmoid().data:ut=>(0,_.softmax)(ut.data),et=[];for(const ut of Ae.logits_per_image){const Mt=[...qe(ut)].map((lt,pt)=>({score:lt,label:Ee[pt]}));Mt.sort((lt,pt)=>pt.score-lt.score),et.push(Mt)}return ke?et:et[0]}}class Oe extends Q{constructor(le){super(le)}async _call(le,{threshold:Ee=.9,percentage:X=!1}={}){const ke=Array.isArray(le);if(ke&&le.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ne=await h(le),Ve=X?null:Ne.map(Re=>[Re.height,Re.width]),{pixel_values:De,pixel_mask:Ke}=await this.processor(Ne),Ae=await this.model({pixel_values:De,pixel_mask:Ke}),qe=this.processor.image_processor.post_process_object_detection(Ae,Ee,Ve),et=this.model.config.id2label,ut=qe.map(Re=>Re.boxes.map((Mt,lt)=>({score:Re.scores[lt],label:et[Re.classes[lt]],box:z(Mt,!X)})));return ke?ut:ut[0]}}class he extends Q{constructor(le){super(le)}async _call(le,Ee,{threshold:X=.1,top_k:ke=null,percentage:Ne=!1}={}){const Ve=Array.isArray(le),De=await h(le),Ke=this.tokenizer(Ee,{padding:!0,truncation:!0}),Ae=await this.processor(De),qe=[];for(let et=0;et({score:yt.scores[ht],label:yt.labels[ht],box:z(ct,!Ne)}))}else{const yt=this.processor.image_processor.post_process_object_detection(lt,X,Re,!0)[0];pt=yt.boxes.map((ct,ht)=>({score:yt.scores[ht],label:Ee[yt.classes[ht]],box:z(ct,!Ne)}))}pt.sort((yt,ct)=>ct.score-yt.score),ke!==null&&(pt=pt.slice(0,ke)),qe.push(pt)}return Ve?qe:qe[0]}}class K extends Q{constructor(le){super(le)}async _call(le,Ee,X={}){const ke=(await h(le))[0],{pixel_values:Ne}=await this.processor(ke),Ve=`${Ee}`,De=this.tokenizer(Ve,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,Ke=await this.model.generate({inputs:Ne,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:De,...X}),qe=this.tokenizer.batch_decode(Ke)[0].match(/(.*?)<\/s_answer>/);let et=null;return qe&&qe.length>=2&&(et=qe[1].trim()),[{answer:et}]}}class ce extends Q{constructor(Ee){super(Ee);ie(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=Ee.vocoder??null}async _call(Ee,{speaker_embeddings:X=null}={}){return this.processor?this._call_text_to_spectrogram(Ee,{speaker_embeddings:X}):this._call_text_to_waveform(Ee)}async _call_text_to_waveform(Ee){const X=this.tokenizer(Ee,{padding:!0,truncation:!0}),{waveform:ke}=await this.model(X),Ne=this.model.config.sampling_rate;return new I.RawAudio(ke.data,Ne)}async _call_text_to_spectrogram(Ee,{speaker_embeddings:X}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await T.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof X=="string"||X instanceof URL)&&(X=new Float32Array(await(await fetch(X)).arrayBuffer())),X instanceof Float32Array)X=new D.Tensor("float32",X,[1,X.length]);else if(!(X instanceof D.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:ke}=this.tokenizer(Ee,{padding:!0,truncation:!0}),{waveform:Ne}=await this.model.generate_speech(ke,X,{vocoder:this.vocoder}),Ve=this.processor.feature_extractor.config.sampling_rate;return new I.RawAudio(Ne.data,Ve)}}class ye extends Q{constructor(le){super(le)}async _call(le){const Ee=await h(le),X=await this.processor(Ee),ke=await this.model(X),Ne=[];for(const Ve of ke.reconstruction){const De=Ve.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ne.push(b.RawImage.fromTensor(De))}return Ne.length>1?Ne:Ne[0]}}class Fe extends Q{constructor(le){super(le)}async _call(le){const Ee=await h(le),X=await this.processor(Ee),{predicted_depth:ke}=await this.model(X),Ne=[];for(let Ve=0;Ve1?Ne:Ne[0]}}const Xe=Object.freeze({"text-classification":{tokenizer:w.AutoTokenizer,pipeline:ge,model:T.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:w.AutoTokenizer,pipeline:j,model:T.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:w.AutoTokenizer,pipeline:G,model:T.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:w.AutoTokenizer,pipeline:Y,model:T.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:w.AutoTokenizer,pipeline:S,model:T.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:w.AutoTokenizer,pipeline:E,model:T.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:w.AutoTokenizer,pipeline:O,model:T.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:w.AutoTokenizer,pipeline:C,model:T.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:w.AutoTokenizer,pipeline:re,model:T.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:me,model:T.AutoModelForAudioClassification,processor:L.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:w.AutoTokenizer,pipeline:J,model:T.AutoModel,processor:L.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:w.AutoTokenizer,pipeline:fe,model:[T.AutoModelForSpeechSeq2Seq,T.AutoModelForCTC],processor:L.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:w.AutoTokenizer,pipeline:ce,model:[T.AutoModelForTextToWaveform,T.AutoModelForTextToSpectrogram],processor:[L.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:w.AutoTokenizer,pipeline:de,model:T.AutoModelForVision2Seq,processor:L.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Te,model:T.AutoModelForImageClassification,processor:L.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:Pe,model:[T.AutoModelForImageSegmentation,T.AutoModelForSemanticSegmentation,T.AutoModelForUniversalSegmentation],processor:L.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:be,model:[T.AutoModelForImageSegmentation,T.AutoModelForSemanticSegmentation,T.AutoModelForUniversalSegmentation],processor:L.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:w.AutoTokenizer,pipeline:He,model:T.AutoModel,processor:L.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:Oe,model:T.AutoModelForObjectDetection,processor:L.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:w.AutoTokenizer,pipeline:he,model:T.AutoModelForZeroShotObjectDetection,processor:L.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:w.AutoTokenizer,pipeline:K,model:T.AutoModelForDocumentQuestionAnswering,processor:L.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ye,model:T.AutoModelForImageToImage,processor:L.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:Fe,model:T.AutoModelForDepthEstimation,processor:L.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:w.AutoTokenizer,pipeline:q,model:T.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:L.AutoProcessor,pipeline:pe,model:[T.AutoModelForImageFeatureExtraction,T.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),Qe=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function Ye(We,le=null,{progress_callback:Ee=null,config:X=null,cache_dir:ke=null,local_files_only:Ne=!1,revision:Ve="main",device:De=null,dtype:Ke=null,subfolder:Ae="onnx",use_external_data_format:qe=null,model_file_name:et=null,session_options:ut={}}={}){We=Qe[We]??We;const Re=Xe[We.split("_",1)[0]];if(!Re)throw Error(`Unsupported pipeline: ${We}. Must be one of [${Object.keys(Xe)}]`);le||(le=Re.default.model,console.log(`No model specified. Using default model: "${le}".`));const Mt={progress_callback:Ee,config:X,cache_dir:ke,local_files_only:Ne,revision:Ve,device:De,dtype:Ke,subfolder:Ae,use_external_data_format:qe,model_file_name:et,session_options:ut},lt=new Map([["tokenizer",Re.tokenizer],["model",Re.model],["processor",Re.processor]]),pt=await wt(lt,le,Mt);pt.task=We,(0,$.dispatchCallback)(Ee,{status:"ready",task:We,model:le});const yt=Re.pipeline;return new yt(pt)}async function wt(We,le,Ee){const X=Object.create(null),ke=[];for(const[Ne,Ve]of We.entries()){if(!Ve)continue;let De;Array.isArray(Ve)?De=new Promise(async(Ke,Ae)=>{var et,ut;let qe;for(const Re of Ve){if(Re===null){Ke(null);return}try{Ke(await Re.from_pretrained(le,Ee));return}catch(Mt){if((et=Mt.message)!=null&&et.includes("Unsupported model type"))qe=Mt;else if((ut=Mt.message)!=null&&ut.includes("Could not locate file"))qe=Mt;else{Ae(Mt);return}}}Ae(qe)}):De=Ve.from_pretrained(le,Ee),X[Ne]=De,ke.push(De)}await Promise.all(ke);for(const[Ne,Ve]of Object.entries(X))X[Ne]=await Ve;return X}},"./src/tokenizers.js":(ae,m,r)=>{r.r(m),r.d(m,{AlbertTokenizer:()=>wr,AutoTokenizer:()=>rn,BartTokenizer:()=>bt,BertTokenizer:()=>Ir,BlenderbotSmallTokenizer:()=>ns,BlenderbotTokenizer:()=>ft,BloomTokenizer:()=>Hs,CLIPTokenizer:()=>Fr,CamembertTokenizer:()=>ze,CodeGenTokenizer:()=>Zs,CodeLlamaTokenizer:()=>Mr,CohereTokenizer:()=>Ws,ConvBertTokenizer:()=>Z,DebertaTokenizer:()=>y,DebertaV2Tokenizer:()=>te,DistilBertTokenizer:()=>Se,ElectraTokenizer:()=>$t,Ernie4_5_Tokenizer:()=>Or,EsmTokenizer:()=>Us,FalconTokenizer:()=>Vs,GPT2Tokenizer:()=>mt,GPTNeoXTokenizer:()=>zs,GemmaTokenizer:()=>Ps,Grok1Tokenizer:()=>Ys,HerbertTokenizer:()=>N,LlamaTokenizer:()=>ms,M2M100Tokenizer:()=>It,MBart50Tokenizer:()=>ss,MBartTokenizer:()=>Yt,MPNetTokenizer:()=>Ar,MarianTokenizer:()=>Ze,MgpstrTokenizer:()=>Le,MobileBertTokenizer:()=>Vt,NllbTokenizer:()=>br,NougatTokenizer:()=>ks,PreTrainedTokenizer:()=>At,Qwen2Tokenizer:()=>yr,RoFormerTokenizer:()=>ue,RobertaTokenizer:()=>Ns,SiglipTokenizer:()=>Bs,SpeechT5Tokenizer:()=>Ut,SqueezeBertTokenizer:()=>dr,T5Tokenizer:()=>kt,TokenizerModel:()=>pe,VitsTokenizer:()=>Dr,Wav2Vec2CTCTokenizer:()=>tt,WhisperTokenizer:()=>pr,XLMRobertaTokenizer:()=>qs,XLMTokenizer:()=>_t,is_chinese_char:()=>Y});var w=r("./src/utils/generic.js"),T=r("./src/utils/core.js"),L=r("./src/utils/hub.js"),H=r("./src/utils/maths.js"),$=r("./src/utils/tensor.js"),_=r("./src/utils/data-structures.js"),I=r("./node_modules/@huggingface/jinja/dist/index.js"),D=r("./src/models/whisper/common_whisper.js");async function b(xe,P){const B=await Promise.all([(0,L.getModelJSON)(xe,"tokenizer.json",!0,P),(0,L.getModelJSON)(xe,"tokenizer_config.json",!0,P)]);return P.legacy!==null&&(B[1].legacy=P.legacy),B}function h(xe,P){const B=[];let ne=0;for(const we of xe.matchAll(P)){const ve=we[0];ne0&&B.push(ve),ne=we.index+ve.length}return ne=19968&&xe<=40959||xe>=13312&&xe<=19903||xe>=131072&&xe<=173791||xe>=173824&&xe<=177983||xe>=177984&&xe<=178207||xe>=178208&&xe<=183983||xe>=63744&&xe<=64255||xe>=194560&&xe<=195103}function O(xe,P,B){const ne=[];let we=0;for(;wethis.tokens_to_ids.get(B)??this.unk_token_id)}convert_ids_to_tokens(P){return P.map(B=>this.vocab[B]??this.unk_token)}}class me extends pe{constructor(P){super(P),this.tokens_to_ids=z(P.vocab),this.unk_token_id=this.tokens_to_ids.get(P.unk_token),this.unk_token=P.unk_token,this.max_input_chars_per_word=P.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[B,ne]of this.tokens_to_ids)this.vocab[ne]=B}encode(P){const B=[];for(const ne of P){const we=[...ne];if(we.length>this.max_input_chars_per_word){B.push(this.unk_token);continue}let ve=!1,je=0;const st=[];for(;je0&&(gt=this.config.continuing_subword_prefix+gt),this.tokens_to_ids.has(gt)){nt=gt;break}--dt}if(nt===null){ve=!0;break}st.push(nt),je=dt}ve?B.push(this.unk_token):B.push(...st)}return B}}class J extends pe{constructor(P,B){super(P);const ne=P.vocab.length;this.vocab=new Array(ne),this.scores=new Array(ne);for(let we=0;we[we,ve])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=B.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,H.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new _.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(P){const B=P.chars,ne=1;let we=0;for(;we{const xe=[...Array.from({length:"~".charCodeAt(0)-"!".charCodeAt(0)+1},(we,ve)=>ve+"!".charCodeAt(0)),...Array.from({length:"¬".charCodeAt(0)-"¡".charCodeAt(0)+1},(we,ve)=>ve+"¡".charCodeAt(0)),...Array.from({length:"ÿ".charCodeAt(0)-"®".charCodeAt(0)+1},(we,ve)=>ve+"®".charCodeAt(0))],P=xe.slice();let B=0;for(let we=0;we<256;++we)xe.includes(we)||(xe.push(we),P.push(256+B),B+=1);const ne=P.map(we=>String.fromCharCode(we));return Object.fromEntries(xe.map((we,ve)=>[we,ne[ve]]))})(),de=(0,T.reverseDictionary)(fe);class Te extends pe{constructor(P){super(P),this.tokens_to_ids=z(P.vocab),this.unk_token_id=this.tokens_to_ids.get(P.unk_token),this.unk_token=P.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[ne,we]of this.tokens_to_ids)this.vocab[we]=ne;const B=Array.isArray(P.merges[0]);this.merges=B?P.merges:P.merges.map(ne=>ne.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((ne,we)=>[JSON.stringify(ne),we])),this.end_of_word_suffix=P.end_of_word_suffix,this.continuing_subword_suffix=P.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 _.LRUCache(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(P){if(P.length===0)return[];const B=this.cache.get(P);if(B!==void 0)return B;const ne=Array.from(P);this.end_of_word_suffix&&(ne[ne.length-1]+=this.end_of_word_suffix);let we=[];if(ne.length>1){const ve=new _.PriorityQueue((dt,nt)=>dt.score`<0x${st.toString(16).toUpperCase().padStart(2,"0")}>`);je.every(st=>this.tokens_to_ids.has(st))?B.push(...je):B.push(this.unk_token)}else B.push(this.unk_token)}return B}}class Pe extends pe{constructor(P,B){super(P),this.tokens_to_ids=z(B.target_lang?P.vocab[B.target_lang]:P.vocab),this.bos_token=B.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=B.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=B.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=B.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[ne,we]of this.tokens_to_ids)this.vocab[we]=ne}encode(P){return P}}class be extends w.Callable{constructor(P){super(),this.config=P}static fromConfig(P){if(P===null)return null;switch(P.type){case"BertNormalizer":return new We(P);case"Precompiled":return new Ls(P);case"Sequence":return new wt(P);case"Replace":return new He(P);case"NFC":return new he(P);case"NFD":return new K(P);case"NFKC":return new ce(P);case"NFKD":return new ye(P);case"Strip":return new Fe(P);case"StripAccents":return new Xe(P);case"Lowercase":return new Qe(P);case"Prepend":return new Ye(P);default:throw new Error(`Unknown Normalizer type: ${P.type}`)}}normalize(P){throw Error("normalize should be implemented in subclass.")}_call(P){return this.normalize(P)}}class He extends be{normalize(P){const B=U(this.config.pattern);return B===null?P:P.replaceAll(B,this.config.content)}}class Oe extends be{constructor(){super(...arguments);ie(this,"form")}normalize(B){return B=B.normalize(this.form),B}}class he extends Oe{constructor(){super(...arguments);ie(this,"form","NFC")}}class K extends Oe{constructor(){super(...arguments);ie(this,"form","NFD")}}class ce extends Oe{constructor(){super(...arguments);ie(this,"form","NFKC")}}class ye extends Oe{constructor(){super(...arguments);ie(this,"form","NFKD")}}class Fe extends be{normalize(P){return this.config.strip_left&&this.config.strip_right?P=P.trim():(this.config.strip_left&&(P=P.trimStart()),this.config.strip_right&&(P=P.trimEnd())),P}}class Xe extends be{normalize(P){return P=j(P),P}}class Qe extends be{normalize(P){return P=P.toLowerCase(),P}}class Ye extends be{normalize(P){return P=this.config.prepend+P,P}}class wt extends be{constructor(P){super(P),this.normalizers=P.normalizers.map(B=>be.fromConfig(B))}normalize(P){return this.normalizers.reduce((B,ne)=>ne.normalize(B),P)}}class We extends be{_tokenize_chinese_chars(P){const B=[];for(let ne=0;nethis.pre_tokenize_text(ne,B)):this.pre_tokenize_text(P,B)).flat()}_call(P,B){return this.pre_tokenize(P,B)}}class Ee extends le{constructor(P){super(),this.pattern=new RegExp(`[^\\s${E}]+|[${E}]`,"gu")}pre_tokenize_text(P,B){return P.trim().match(this.pattern)||[]}}class X extends le{constructor(P){super(),this.config=P,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=fe,this.text_encoder=new TextEncoder}pre_tokenize_text(P,B){return this.add_prefix_space&&!P.startsWith(" ")&&(P=" "+P),(this.use_regex?P.match(this.pattern)||[]:[P]).map(we=>Array.from(this.text_encoder.encode(we),ve=>this.byte_encoder[ve]).join(""))}}class ke extends le{constructor(P){super(),this.config=P,this.pattern=U(this.config.pattern,this.config.invert)}pre_tokenize_text(P,B){var ne;return this.pattern===null?[]:this.config.invert?P.match(this.pattern)||[]:((ne=this.config.behavior)==null?void 0:ne.toLowerCase())==="removed"?P.split(this.pattern).filter(we=>we):h(P,this.pattern)}}class Ne extends le{constructor(P){super(),this.config=P,this.pattern=new RegExp(`[^${E}]+|[${E}]+`,"gu")}pre_tokenize_text(P,B){return P.match(this.pattern)||[]}}class Ve extends le{constructor(P){super(),this.config=P;const B=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(B,"gu")}pre_tokenize_text(P,B){return P.match(this.pattern)||[]}}class De extends w.Callable{constructor(P){super(),this.config=P}static fromConfig(P){if(P===null)return null;switch(P.type){case"TemplateProcessing":return new qe(P);case"ByteLevel":return new et(P);case"RobertaProcessing":return new Ae(P);case"BertProcessing":return new Ke(P);case"Sequence":return new ut(P);default:throw new Error(`Unknown PostProcessor type: ${P.type}`)}}post_process(P,...B){throw Error("post_process should be implemented in subclass.")}_call(P,...B){return this.post_process(P,...B)}}class Ke extends De{constructor(P){super(P),this.cls=P.cls[0],this.sep=P.sep[0]}post_process(P,B=null,{add_special_tokens:ne=!0}={}){ne&&(P=(0,T.mergeArrays)([this.cls],P,[this.sep]));let we=new Array(P.length).fill(0);if(B!==null){const ve=ne&&this instanceof Ae?[this.sep]:[],je=ne?[this.sep]:[];P=(0,T.mergeArrays)(P,ve,B,je),we=(0,T.mergeArrays)(we,new Array(B.length+ve.length+je.length).fill(1))}return{tokens:P,token_type_ids:we}}}class Ae extends Ke{}class qe extends De{constructor(P){super(P),this.single=P.single,this.pair=P.pair}post_process(P,B=null,{add_special_tokens:ne=!0}={}){const we=B===null?this.single:this.pair;let ve=[],je=[];for(const st of we)"SpecialToken"in st?ne&&(ve.push(st.SpecialToken.id),je.push(st.SpecialToken.type_id)):"Sequence"in st&&(st.Sequence.id==="A"?(ve=(0,T.mergeArrays)(ve,P),je=(0,T.mergeArrays)(je,new Array(P.length).fill(st.Sequence.type_id))):st.Sequence.id==="B"&&(ve=(0,T.mergeArrays)(ve,B),je=(0,T.mergeArrays)(je,new Array(B.length).fill(st.Sequence.type_id))));return{tokens:ve,token_type_ids:je}}}class et extends De{post_process(P,B=null){return B&&(P=(0,T.mergeArrays)(P,B)),{tokens:P}}}class ut extends De{constructor(P){super(P),this.processors=P.processors.map(B=>De.fromConfig(B))}post_process(P,B=null,ne={}){let we;for(const ve of this.processors)if(ve instanceof et)P=ve.post_process(P).tokens,B&&(B=ve.post_process(B).tokens);else{const je=ve.post_process(P,B,ne);P=je.tokens,we=je.token_type_ids}return{tokens:P,token_type_ids:we}}}class Re extends w.Callable{constructor(P){super(),this.config=P,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=P.trim_offsets}static fromConfig(P){if(P===null)return null;switch(P.type){case"WordPiece":return new ct(P);case"Metaspace":return new ds(P);case"ByteLevel":return new ht(P);case"Replace":return new Mt(P);case"ByteFallback":return new lt(P);case"Fuse":return new pt(P);case"Strip":return new yt(P);case"Sequence":return new Wt(P);case"CTC":return new vt(P);case"BPEDecoder":return new Qt(P);default:throw new Error(`Unknown Decoder type: ${P.type}`)}}_call(P){return this.decode(P)}decode(P){return this.decode_chain(P).join("")}decode_chain(P){throw Error("`decode_chain` should be implemented in subclass.")}}class Mt extends Re{decode_chain(P){const B=U(this.config.pattern);return B===null?P:P.map(ne=>ne.replaceAll(B,this.config.content))}}class lt extends Re{constructor(P){super(P),this.text_decoder=new TextDecoder}decode_chain(P){const B=[];let ne=[];for(const we of P){let ve=null;if(we.length===6&&we.startsWith("<0x")&&we.endsWith(">")){const je=parseInt(we.slice(3,5),16);isNaN(je)||(ve=je)}if(ve!==null)ne.push(ve);else{if(ne.length>0){const je=this.text_decoder.decode(Uint8Array.from(ne));B.push(je),ne=[]}B.push(we)}}if(ne.length>0){const we=this.text_decoder.decode(Uint8Array.from(ne));B.push(we),ne=[]}return B}}class pt extends Re{decode_chain(P){return[P.join("")]}}class yt extends Re{constructor(P){super(P),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(P){return P.map(B=>{let ne=0;for(let ve=0;ve(ne!==0&&(B.startsWith(this.config.prefix)?B=B.replace(this.config.prefix,""):B=" "+B),this.cleanup&&(B=ge(B)),B))}}class ht extends Re{constructor(P){super(P),this.byte_decoder=de,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(P){const B=P.join(""),ne=new Uint8Array([...B].map(ve=>this.byte_decoder[ve]));return this.text_decoder.decode(ne)}decode_chain(P){const B=[];let ne=[];for(const we of P)this.added_tokens.find(ve=>ve.content===we)!==void 0?(ne.length>0&&(B.push(this.convert_tokens_to_string(ne)),ne=[]),B.push(we)):ne.push(we);return ne.length>0&&B.push(this.convert_tokens_to_string(ne)),B}}class vt extends Re{constructor(P){super(P),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(P){if(P.length===0)return"";const B=[P[0]];for(let ve=1;veve!==this.pad_token).join("");return this.cleanup&&(we=ge(we).replaceAll(this.word_delimiter_token," ").trim()),we}decode_chain(P){return[this.convert_tokens_to_string(P)]}}class Wt extends Re{constructor(P){super(P),this.decoders=P.decoders.map(B=>Re.fromConfig(B))}decode_chain(P){return this.decoders.reduce((B,ne)=>ne.decode_chain(B),P)}}class Qt extends Re{constructor(P){super(P),this.suffix=this.config.suffix}decode_chain(P){return P.map((B,ne)=>B.replaceAll(this.suffix,ne===P.length-1?"":" "))}}class jt extends Re{decode_chain(P){let B="";for(let ne=1;nene.normalize("NFKC")).join("~"):P=P.normalize("NFKC"),P}}class Js extends le{constructor(P){super(),this.tokenizers=P.pretokenizers.map(B=>le.fromConfig(B))}pre_tokenize_text(P,B){return this.tokenizers.reduce((ne,we)=>we.pre_tokenize(ne,B),[P])}}class is extends le{constructor(P){super()}pre_tokenize_text(P,B){return P.match(/\w+|[^\w\s]+/g)||[]}}class Ts extends le{constructor(P){super()}pre_tokenize_text(P,B){return S(P)}}class Sr extends le{constructor(P){super(),this.config=P,this.pattern=U(this.config.pattern),this.content=this.config.content}pre_tokenize_text(P,B){return this.pattern===null?[P]:[P.replaceAll(this.pattern,this.config.content)]}}const Gr=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function kr(xe,P,B,ne){for(const we of Object.keys(xe)){const ve=P-xe[we].length,je=B(we),st=new Array(ve).fill(je);xe[we]=ne==="right"?(0,T.mergeArrays)(xe[we],st):(0,T.mergeArrays)(st,xe[we])}}function Kr(xe,P){for(const B of Object.keys(xe))xe[B].length=P}class At extends w.Callable{constructor(B,ne){super();ie(this,"return_token_type_ids",!1);ie(this,"padding_side","right");this.config=ne,this.normalizer=be.fromConfig(B.normalizer),this.pre_tokenizer=le.fromConfig(B.pre_tokenizer),this.model=pe.fromConfig(B.model,ne),this.post_processor=De.fromConfig(B.post_processor),this.decoder=Re.fromConfig(B.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const we of B.added_tokens){const ve=new q(we);this.added_tokens.push(ve),this.model.tokens_to_ids.set(ve.content,ve.id),this.model.vocab[ve.id]=ve.content,ve.special&&(this.special_tokens.push(ve.content),this.all_special_ids.push(ve.id))}if(this.additional_special_tokens=ne.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 _.DictionarySplitter(this.added_tokens.map(we=>we.content)),this.added_tokens_map=new Map(this.added_tokens.map(we=>[we.content,we])),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=ne.model_max_length,this.remove_space=ne.remove_space,this.clean_up_tokenization_spaces=ne.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=ne.do_lowercase_and_remove_accent??!1,ne.padding_side&&(this.padding_side=ne.padding_side),this.add_bos_token=ne.add_bos_token,this.add_eos_token=ne.add_eos_token,this.legacy=!1,this.chat_template=ne.chat_template??null,Array.isArray(this.chat_template)){const we=Object.create(null);for(const{name:ve,template:je}of this.chat_template){if(typeof ve!="string"||typeof je!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');we[ve]=je}this.chat_template=we}this._compiled_template_cache=new Map}getToken(...B){for(const ne of B){const we=this.config[ne];if(we)if(typeof we=="object"){if(we.__type==="AddedToken")return we.content;throw Error(`Unknown token: ${we}`)}else return we}return null}static async from_pretrained(B,{progress_callback:ne=null,config:we=null,cache_dir:ve=null,local_files_only:je=!1,revision:st="main",legacy:dt=null}={}){const nt=await b(B,{progress_callback:ne,config:we,cache_dir:ve,local_files_only:je,revision:st,legacy:dt});return new this(...nt)}_call(B,{text_pair:ne=null,add_special_tokens:we=!0,padding:ve=!1,truncation:je=null,max_length:st=null,return_tensor:dt=!0,return_token_type_ids:nt=null}={}){const gt=Array.isArray(B);let Ot;if(gt){if(B.length===0)throw Error("text array must be non-empty");if(ne!==null){if(Array.isArray(ne)){if(B.length!==ne.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");Ot=B.map((es,us)=>this._encode_plus(es,{text_pair:ne[us],add_special_tokens:we,return_token_type_ids:nt}))}else Ot=B.map(es=>this._encode_plus(es,{add_special_tokens:we,return_token_type_ids:nt}))}else{if(B==null)throw Error("text may not be null or undefined");if(Array.isArray(ne))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");Ot=[this._encode_plus(B,{text_pair:ne,add_special_tokens:we,return_token_type_ids:nt})]}if(st===null?st=this.model_max_length:je===null&&(ve===!0?(console.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),st=this.model_max_length):ve===!1&&(console.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),je=!0)),ve===!0&&(st=Math.min((0,H.max)(Ot.map(es=>es.input_ids.length))[0],st??1/0)),st=Math.min(st,this.model_max_length??1/0),ve||je)for(let es=0;esst?je&&Kr(Ot[es],st):ve&&kr(Ot[es],st,us=>us==="input_ids"?this.pad_token_id:0,this.padding_side));const Kt={};if(dt){if(!(ve&&je)&&Ot.some(us=>{var rs;for(const ps of Object.keys(us))if(us[ps].length!==((rs=Ot[0][ps])==null?void 0:rs.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 es=[Ot.length,Ot[0].input_ids.length];for(const us of Object.keys(Ot[0]))Kt[us]=new $.Tensor("int64",BigInt64Array.from(Ot.flatMap(rs=>rs[us]).map(BigInt)),es)}else{for(const es of Object.keys(Ot[0]))Kt[es]=Ot.map(us=>us[es]);if(!gt)for(const es of Object.keys(Kt))Kt[es]=Kt[es][0]}return Kt}_encode_text(B){if(B===null)return null;const ne=this.added_tokens_splitter.split(B);for(let ve=0;ve0&&(ne[ve-1]=ne[ve-1].trimEnd()),je.rstrip&&ve{if(ve.length===0)return[];if(this.added_tokens_map.has(ve))return[ve];if(this.remove_space===!0&&(ve=ve.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(ve=G(ve)),this.normalizer!==null&&(ve=this.normalizer(ve)),ve.length===0)return[];const st=this.pre_tokenizer!==null?this.pre_tokenizer(ve,{section_index:je}):[ve];return this.model(st)})}_encode_plus(B,{text_pair:ne=null,add_special_tokens:we=!0,return_token_type_ids:ve=null}={}){const{tokens:je,token_type_ids:st}=this._tokenize_helper(B,{pair:ne,add_special_tokens:we}),dt=this.model.convert_tokens_to_ids(je),nt={input_ids:dt,attention_mask:new Array(dt.length).fill(1)};return(ve??this.return_token_type_ids)&&st&&(nt.token_type_ids=st),nt}_tokenize_helper(B,{pair:ne=null,add_special_tokens:we=!1}={}){const ve=this._encode_text(B),je=this._encode_text(ne);return this.post_processor?this.post_processor(ve,je,{add_special_tokens:we}):{tokens:(0,T.mergeArrays)(ve??[],je??[])}}tokenize(B,{pair:ne=null,add_special_tokens:we=!1}={}){return this._tokenize_helper(B,{pair:ne,add_special_tokens:we}).tokens}encode(B,{text_pair:ne=null,add_special_tokens:we=!0,return_token_type_ids:ve=null}={}){return this._encode_plus(B,{text_pair:ne,add_special_tokens:we,return_token_type_ids:ve}).input_ids}batch_decode(B,ne={}){return B instanceof $.Tensor&&(B=B.tolist()),B.map(we=>this.decode(we,ne))}decode(B,ne={}){if(B instanceof $.Tensor&&(B=Q(B)),!Array.isArray(B)||B.length===0||!(0,T.isIntegralNumber)(B[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(B,ne)}decode_single(B,{skip_special_tokens:ne=!1,clean_up_tokenization_spaces:we=null}){let ve=this.model.convert_ids_to_tokens(B);ne&&(ve=ve.filter(st=>!this.special_tokens.includes(st)));let je=this.decoder?this.decoder(ve):ve.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(je=je.replaceAll(this.decoder.end_of_word_suffix," "),ne&&(je=je.trim())),(we??this.clean_up_tokenization_spaces)&&(je=ge(je)),je}get_chat_template({chat_template:B=null,tools:ne=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const we=this.chat_template;if(B!==null&&Object.hasOwn(we,B))B=we[B];else if(B===null)if(ne!==null&&"tool_use"in we)B=we.tool_use;else if("default"in we)B=we.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(we).sort()}.`)}else if(B===null)if(this.chat_template)B=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 B}apply_chat_template(B,{tools:ne=null,documents:we=null,chat_template:ve=null,add_generation_prompt:je=!1,tokenize:st=!0,padding:dt=!1,truncation:nt=!1,max_length:gt=null,return_tensor:Ot=!0,return_dict:Kt=!1,tokenizer_kwargs:es={},...us}={}){if(ve=this.get_chat_template({chat_template:ve,tools:ne}),typeof ve!="string")throw Error(`chat_template must be a string, but got ${typeof ve}`);let rs=this._compiled_template_cache.get(ve);rs===void 0&&(rs=new I.Template(ve),this._compiled_template_cache.set(ve,rs));const ps=Object.create(null);for(const As of Gr){const hr=this.getToken(As);hr&&(ps[As]=hr)}const Is=rs.render({messages:B,add_generation_prompt:je,tools:ne,documents:we,...ps,...us});if(st){const As=this._call(Is,{add_special_tokens:!1,padding:dt,truncation:nt,max_length:gt,return_tensor:Ot,...es});return Kt?As:As.input_ids}return Is}}class Ir extends At{constructor(){super(...arguments);ie(this,"return_token_type_ids",!0)}}class wr extends At{constructor(){super(...arguments);ie(this,"return_token_type_ids",!0)}}class Vt extends At{constructor(){super(...arguments);ie(this,"return_token_type_ids",!0)}}class dr extends At{constructor(){super(...arguments);ie(this,"return_token_type_ids",!0)}}class y extends At{constructor(){super(...arguments);ie(this,"return_token_type_ids",!0)}}class te extends At{constructor(){super(...arguments);ie(this,"return_token_type_ids",!0)}}class N extends At{constructor(){super(...arguments);ie(this,"return_token_type_ids",!0)}}class Z extends At{constructor(){super(...arguments);ie(this,"return_token_type_ids",!0)}}class ue extends At{constructor(){super(...arguments);ie(this,"return_token_type_ids",!0)}}class Se extends At{}class ze extends At{}class _t extends At{constructor(B,ne){super(B,ne);ie(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 $t extends At{constructor(){super(...arguments);ie(this,"return_token_type_ids",!0)}}class kt extends At{}class mt extends At{}class bt extends At{}class Yt extends At{constructor(P,B){super(P,B),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(ne=>this.languageRegex.test(ne)),this.lang_to_token=ne=>ne}_build_translation_inputs(P,B,ne){return ur(this,P,B,ne)}}class ss extends Yt{}class Ns extends At{}class Hs extends At{}const Es="▁";class ms extends At{constructor(B,ne){super(B,ne);ie(this,"padding_side","left");this.legacy=ne.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new bs({replacement:Es,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(B){if(B===null)return null;if(this.legacy||B.length===0)return super._encode_text(B);let ne=super._encode_text(Es+B.replaceAll(Es," "));return ne.length>1&&ne[0]===Es&&this.special_tokens.includes(ne[1])&&(ne=ne.slice(1)),ne}}class Mr extends At{}class qs extends At{}class Ar extends At{}class Vs extends At{}class zs extends At{}class Us extends At{}class yr extends At{}class Ps extends At{}class Ys extends At{}function ur(xe,P,B,ne){if(!("language_codes"in xe)||!Array.isArray(xe.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in xe)||!(xe.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in xe)||typeof xe.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const we=ne.src_lang,ve=ne.tgt_lang;if(!xe.language_codes.includes(ve))throw new Error(`Target language code "${ve}" is not valid. Must be one of: {${xe.language_codes.join(", ")}}`);if(we!==void 0){if(!xe.language_codes.includes(we))throw new Error(`Source language code "${we}" is not valid. Must be one of: {${xe.language_codes.join(", ")}}`);for(const je of xe.post_processor.config.single)if("SpecialToken"in je&&xe.languageRegex.test(je.SpecialToken.id)){je.SpecialToken.id=xe.lang_to_token(we);break}}return ne.forced_bos_token_id=xe.model.convert_tokens_to_ids([xe.lang_to_token(ve)])[0],xe._call(P,B)}class br extends At{constructor(P,B){super(P,B),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(ne=>this.languageRegex.test(ne)),this.lang_to_token=ne=>ne}_build_translation_inputs(P,B,ne){return ur(this,P,B,ne)}}class It extends At{constructor(P,B){super(P,B),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(ne=>this.languageRegex.test(ne)).map(ne=>ne.slice(2,-2)),this.lang_to_token=ne=>`__${ne}__`}_build_translation_inputs(P,B,ne){return ur(this,P,B,ne)}}class pr extends At{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(P,{return_timestamps:B=!1,return_language:ne=!1,time_precision:we=null,force_full_sequences:ve=!0}={}){if(we===null)throw Error("Must specify time_precision");let je=null;const st=B==="word";function dt(){return{language:je,timestamp:[null,null],text:""}}const nt=[];let gt=dt(),Ot=0;const Kt=this.timestamp_begin,us=Kt+1500;let rs=[],ps=[],Is=!1,As=null;const hr=new Set(this.all_special_ids);for(const os of P){const fs=os.tokens,Rs=st?os.token_timestamps:null;let Gs=null,or=Kt;if("stride"in os){const[ys,hs,gs]=os.stride;if(Ot-=hs,As=ys-gs,hs&&(or=hs/we+Kt),gs)for(let Lt=fs.length-1;Lt>=0;--Lt){const Ht=Number(fs[Lt]);if(Ht>=Kt){if(Gs!==null&&(Ht-Kt)*we=Kt&&hs<=us){const gs=(hs-Kt)*we+Ot,Lt=(0,H.round)(gs,2);if(Gs!==null&&hs>=Gs)Is=!0;else if(Is||rs.length>0&&hs0?(rs.push(vs),st&&ps.push(ar)):rs.every(ys=>ys.length===0)&&(gt=dt(),rs=[],vs=[],ps=[],ar=[])}if(rs.length>0){if(ve&&B)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[os,fs]=this.findLongestCommonSequence(rs,ps),Rs=this.decode(os);gt.text=Rs,st&&(gt.words=this.collateWordTimestamps(os,fs,je)),nt.push(gt)}let Cs=Object.create(null);const er=nt.map(os=>os.text).join("");if(B||ne){for(let os=0;os0;let st=je?[]:null,dt=je?B[0]:null;for(let nt=1;nths===or[gs]&&dt[er+gs]<=B[nt][Rs+gs]).length:vs=fs.filter((hs,gs)=>hs===or[gs]).length;const ar=Cs/1e4,ys=vs/Cs+ar;vs>1&&ys>Ot&&(Ot=ys,Kt=[er,os,Rs,Gs])}const[us,rs,ps,Is]=Kt,As=Math.floor((rs+us)/2),hr=Math.floor((Is+ps)/2);ve.push(...ne.slice(0,As)),ne=gt.slice(hr),we=ne.length,je&&(st.push(...dt.slice(0,As)),dt=B[nt].slice(hr))}return ve.push(...ne),je?(st.push(...dt),[ve,st]):[ve,[]]}collateWordTimestamps(P,B,ne){const[we,ve,je]=this.combineTokensIntoWords(P,ne),st=[];for(let dt=0;dt=we){const st=((je-we)*ne).toFixed(2);ve.push(`<|${st}|>`),ve.push([])}else ve[ve.length-1].push(je);return ve=ve.map(je=>typeof je=="string"?je:super.decode(je,B)),ve.join("")}splitTokensOnUnicode(P){const B=this.decode(P,{decode_with_timestamps:!0}),ne="�",we=[],ve=[],je=[];let st=[],dt=[],nt=0;for(let gt=0;gt=this.model.tokens_to_ids.get("<|endoftext|>"),us=gt.startsWith(" "),rs=gt.trim(),ps=dt.test(rs);if(es||us||ps||ve.length===0)ve.push(gt),je.push(Ot),st.push(Kt);else{const Is=ve.length-1;ve[Is]+=gt,je[Is].push(...Ot),st[Is].push(...Kt)}}return[ve,je,st]}mergePunctuations(P,B,ne,we,ve){const je=structuredClone(P),st=structuredClone(B),dt=structuredClone(ne);let nt=je.length-2,gt=je.length-1;for(;nt>=0;)je[nt].startsWith(" ")&&we.includes(je[nt].trim())?(je[gt]=je[nt]+je[gt],st[gt]=(0,T.mergeArrays)(st[nt],st[gt]),dt[gt]=(0,T.mergeArrays)(dt[nt],dt[gt]),je[nt]="",st[nt]=[],dt[nt]=[]):gt=nt,--nt;for(nt=0,gt=1;gtOt),st.filter(Ot=>Ot.length>0),dt.filter(Ot=>Ot.length>0)]}}class Zs extends At{}class Fr extends At{}class Bs extends At{}class Ze extends At{constructor(P,B){super(P,B),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(ne=>this.languageRegex.test(ne)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(P){if(P===null)return null;const[B,...ne]=P.trim().split(this.languageRegex);if(ne.length===0)return super._encode_text(B);if(ne.length===2){const[we,ve]=ne;return this.supported_language_codes.includes(we)||console.warn(`Unsupported language code "${we}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,T.mergeArrays)([we],super._encode_text(ve))}}}class tt extends At{}class ft extends At{}class ns extends At{}class Ut extends At{}class ks extends At{}class Dr extends At{constructor(P,B){super(P,B),this.decoder=new jt({})}}class Ws extends At{}class Le extends At{}class Or extends At{}class rn{static async from_pretrained(P,{progress_callback:B=null,config:ne=null,cache_dir:we=null,local_files_only:ve=!1,revision:je="main",legacy:st=null}={}){var Kt;const[dt,nt]=await b(P,{progress_callback:B,config:ne,cache_dir:we,local_files_only:ve,revision:je,legacy:st}),gt=((Kt=nt.tokenizer_class)==null?void 0:Kt.replace(/Fast$/,""))??"PreTrainedTokenizer";let Ot=this.TOKENIZER_CLASS_MAPPING[gt];return Ot||(console.warn(`Unknown tokenizer class "${gt}", attempting to construct from base class.`),Ot=At),new Ot(dt,nt)}}ie(rn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:kt,DistilBertTokenizer:Se,CamembertTokenizer:ze,DebertaTokenizer:y,DebertaV2Tokenizer:te,BertTokenizer:Ir,HerbertTokenizer:N,ConvBertTokenizer:Z,RoFormerTokenizer:ue,XLMTokenizer:_t,ElectraTokenizer:$t,MobileBertTokenizer:Vt,SqueezeBertTokenizer:dr,AlbertTokenizer:wr,GPT2Tokenizer:mt,BartTokenizer:bt,MBartTokenizer:Yt,MBart50Tokenizer:ss,RobertaTokenizer:Ns,WhisperTokenizer:pr,CodeGenTokenizer:Zs,CLIPTokenizer:Fr,SiglipTokenizer:Bs,MarianTokenizer:Ze,BloomTokenizer:Hs,NllbTokenizer:br,M2M100Tokenizer:It,LlamaTokenizer:ms,CodeLlamaTokenizer:Mr,XLMRobertaTokenizer:qs,MPNetTokenizer:Ar,FalconTokenizer:Vs,GPTNeoXTokenizer:zs,EsmTokenizer:Us,Wav2Vec2CTCTokenizer:tt,BlenderbotTokenizer:ft,BlenderbotSmallTokenizer:ns,SpeechT5Tokenizer:Ut,NougatTokenizer:ks,VitsTokenizer:Dr,Qwen2Tokenizer:yr,GemmaTokenizer:Ps,Grok1Tokenizer:Ys,CohereTokenizer:Ws,MgpstrTokenizer:Le,Ernie4_5_Tokenizer:Or,PreTrainedTokenizer:At})},"./src/utils/audio.js":(ae,m,r)=>{r.r(m),r.d(m,{RawAudio:()=>me,hamming:()=>h,hanning:()=>b,mel_filter_bank:()=>Y,read_audio:()=>I,spectrogram:()=>C,window_function:()=>re});var w=r("./src/utils/hub.js"),T=r("./src/utils/maths.js"),L=r("./src/utils/core.js"),H=r("./src/env.js"),$=r("./src/utils/tensor.js"),_=r("?7992");async function I(J,fe){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 de=await(await(0,w.getFile)(J)).arrayBuffer(),Te=new AudioContext({sampleRate:fe});typeof fe>"u"&&console.warn(`No sampling rate provided, using default of ${Te.sampleRate}Hz.`);const Pe=await Te.decodeAudioData(de);let be;if(Pe.numberOfChannels===2){const He=Math.sqrt(2),Oe=Pe.getChannelData(0),he=Pe.getChannelData(1);be=new Float32Array(Oe.length);for(let K=0;K2595*Math.log10(1+J/700),kaldi:J=>1127*Math.log(1+J/700),slaney:(J,fe=1e3,de=15,Te=27/Math.log(6.4))=>J>=fe?de+Math.log(J/fe)*Te:3*J/200};function z(J,fe="htk"){const de=U[fe];if(!de)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof J=="number"?de(J):J.map(Te=>de(Te))}const Q={htk:J=>700*(10**(J/2595)-1),kaldi:J=>700*(Math.exp(J/1127)-1),slaney:(J,fe=1e3,de=15,Te=Math.log(6.4)/27)=>J>=de?fe*Math.exp(Te*(J-de)):200*J/3};function ge(J,fe="htk"){const de=Q[fe];if(!de)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof J=="number"?de(J):J.map(Te=>de(Te))}function j(J,fe){const de=Float64Array.from({length:fe.length-1},(He,Oe)=>fe[Oe+1]-fe[Oe]),Te=Array.from({length:J.length},()=>new Array(fe.length));for(let He=0;Henew Array(J.length));for(let He=0;HeJ+Te*be)}function Y(J,fe,de,Te,Pe,be=null,He="htk",Oe=!1){if(be!==null&&be!=="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(de>Te)throw new Error(`Require min_frequency: ${de} <= max_frequency: ${Te}`);const he=z(de,He),K=z(Te,He),ce=G(he,K,fe+2);let ye=ge(ce,He),Fe;if(Oe){const Qe=Pe/((J-1)*2);Fe=z(Float64Array.from({length:J},(Ye,wt)=>wt*Qe),He),ye=ce}else Fe=G(0,Math.floor(Pe/2),J);const Xe=j(Fe,ye);if(be!==null&&be==="slaney")for(let Qe=0;QePe)throw Error(`frame_length (${de}) may not be larger than fft_length (${Pe})`);if(Ne!==de)throw new Error(`Length of the window (${Ne}) must equal frame_length (${de})`);if(Te<=0)throw new Error("hop_length must be greater than zero");if(be===null&&ye!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!ce)throw new Error("`preemphasis_htk_flavor=false` is not currently supported.");if(He){if(Oe!=="reflect")throw new Error(`pad_mode="${Oe}" not implemented yet.`);const yt=Math.floor((Pe-1)/2)+1;J=O(J,yt,yt)}let Ve=Math.floor(1+Math.floor((J.length-de)/Te));le!==null&&VeVe?X&&(Ae=Ee):Ae=Ke=Ee);const qe=new T.FFT(Pe),et=new Float64Array(Pe),ut=new Float64Array(qe.outputBufferSize),Re=new Float32Array(De*Ae);for(let yt=0;yt=1;--vt)et[vt]-=K*et[vt-1];et[0]*=1-K}for(let vt=0;vtMath.pow(Oe,.85));break;default:throw new Error(`Unknown window type ${fe}.`)}if(de&&(He=He.subarray(0,J)),Te===null)return He;if(J>Te)throw new Error(`Length of the window (${J}) may not be larger than frame_length (${Te})`);return He}function q(J,fe){let de=44;const Te=new ArrayBuffer(de+J.length*4),Pe=new DataView(Te);pe(Pe,0,"RIFF"),Pe.setUint32(4,36+J.length*4,!0),pe(Pe,8,"WAVE"),pe(Pe,12,"fmt "),Pe.setUint32(16,16,!0),Pe.setUint16(20,3,!0),Pe.setUint16(22,1,!0),Pe.setUint32(24,fe,!0),Pe.setUint32(28,fe*4,!0),Pe.setUint16(32,4,!0),Pe.setUint16(34,32,!0),pe(Pe,36,"data"),Pe.setUint32(40,J.length*4,!0);for(let be=0;be{let be=await Pe.arrayBuffer();_.writeFileSync(Te,Buffer.from(be))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await de(fe,this.toBlob())}}},"./src/utils/constants.js":(ae,m,r)=>{r.r(m),r.d(m,{CHAT_TEMPLATE_NAME:()=>_,CONFIG_NAME:()=>T,FEATURE_EXTRACTOR_NAME:()=>L,GENERATION_CONFIG_NAME:()=>I,GITHUB_ISSUE_URL:()=>w,IMAGE_PROCESSOR_NAME:()=>H,PROCESSOR_NAME:()=>$});const w="https://github.com/huggingface/transformers.js/issues/new/choose",T="config.json",L="preprocessor_config.json",H=L,$="processor_config.json",_="chat_template.jinja",I="generation_config.json"},"./src/utils/core.js":(ae,m,r)=>{r.r(m),r.d(m,{calculateDimensions:()=>I,calculateReflectOffset:()=>U,count:()=>j,dispatchCallback:()=>w,escapeRegExp:()=>L,isIntegralNumber:()=>$,isNullishDimension:()=>_,isTypedArray:()=>H,len:()=>ge,mergeArrays:()=>b,pick:()=>Q,pop:()=>D,product:()=>h,reverseDictionary:()=>T,saveBlob:()=>z});function w(G,Y){G&&G(Y)}function T(G){return Object.fromEntries(Object.entries(G).map(([Y,O])=>[O,Y]))}function L(G){return G.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function H(G){var Y,O,S;return((S=(O=(Y=G==null?void 0:G.prototype)==null?void 0:Y.__proto__)==null?void 0:O.constructor)==null?void 0:S.name)==="TypedArray"}function $(G){return Number.isInteger(G)||typeof G=="bigint"}function _(G){return G==null||G===-1}function I(G){const Y=[];let O=G;for(;Array.isArray(O);)Y.push(O.length),O=O[0];return Y}function D(G,Y,O=void 0){const S=G[Y];if(S!==void 0)return delete G[Y],S;if(O===void 0)throw Error(`Key ${Y} does not exist in object.`);return O}function b(...G){return Array.prototype.concat.apply([],G)}function h(...G){return G.reduce((Y,O)=>Y.flatMap(S=>O.map(E=>[S,E])))}function U(G,Y){return Math.abs((G+Y)%(2*Y)-Y)}function z(G,Y){const O=URL.createObjectURL(Y),S=document.createElement("a");S.href=O,S.download=G,S.click(),S.remove(),URL.revokeObjectURL(O)}function Q(G,Y){return Object.assign({},...Y.map(O=>{if(G[O]!==void 0)return{[O]:G[O]}}))}function ge(G){let Y=0;for(const O of G)++Y;return Y}function j(G,Y){let O=0;for(const S of G)S===Y&&++O;return O}},"./src/utils/data-structures.js":(ae,m,r)=>{r.r(m),r.d(m,{CharTrie:()=>T,DictionarySplitter:()=>_,LRUCache:()=>I,PriorityQueue:()=>w,TokenLattice:()=>H});class w{constructor(b=(U,z)=>U>z,h=1/0){this._heap=[],this._comparator=b,this._maxSize=h}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...b){return this.extend(b)}extend(b){for(const h of b)if(this.size0&&this._swap(0,h),this._heap.pop(),this._siftDown(),b}replace(b){const h=this.peek();return this._heap[0]=b,this._siftDown(),h}_parent(b){return(b+1>>>1)-1}_left(b){return(b<<1)+1}_right(b){return b+1<<1}_greater(b,h){return this._comparator(this._heap[b],this._heap[h])}_swap(b,h){const U=this._heap[b];this._heap[b]=this._heap[h],this._heap[h]=U}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(b){for(;b>0&&this._greater(b,this._parent(b));)this._swap(b,this._parent(b)),b=this._parent(b)}_siftDown(){let b=0;for(;this._left(b)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const z=new $(this.bosTokenId,0,0,0,0),Q=new $(this.eosTokenId,1,this.len,0,0);this.nodes.push(z.clone()),this.nodes.push(Q.clone()),this.beginNodes[this.len].push(Q),this.endNodes[0].push(z)}insert(b,h,U,z){const Q=this.nodes.length,ge=new $(z,Q,b,h,U);this.beginNodes[b].push(ge),this.endNodes[b+h].push(ge),this.nodes.push(ge)}viterbi(){const b=this.len;let h=0;for(;h<=b;){if(this.beginNodes[h].length==0)return[];for(let j of this.beginNodes[h]){j.prev=null;let G=0,Y=null;for(let O of this.endNodes[h]){const S=O.backtraceScore+j.score;(Y===null||S>G)&&(Y=O.clone(),G=S)}if(Y!==null)j.prev=Y,j.backtraceScore=G;else return[]}++h}const U=[],Q=this.beginNodes[b][0].prev;if(Q===null)return[];let ge=Q.clone();for(;ge.prev!==null;)U.push(ge.clone()),ge=ge.clone().prev.clone();return U.reverse(),U}piece(b){return this.chars.slice(b.pos,b.pos+b.length).join("")}tokens(){return this.viterbi().map(h=>this.piece(h))}tokenIds(){return this.viterbi().map(h=>h.tokenId)}}class ${constructor(b,h,U,z,Q){this.tokenId=b,this.nodeId=h,this.pos=U,this.length=z,this.score=Q,this.prev=null,this.backtraceScore=0}clone(){const b=new $(this.tokenId,this.nodeId,this.pos,this.length,this.score);return b.prev=this.prev,b.backtraceScore=this.backtraceScore,b}}class _{constructor(b){this.trie=this._buildTrie(b)}_buildTrie(b){var U;const h=Object.create(null);for(const z of b){let Q=h;for(let ge=0;gez&&h.push(b.slice(z,Q)),h.push(j),Q+=j.length,z=Q):++Q}return zthis.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}}},"./src/utils/devices.js":(ae,m,r)=>{r.r(m),r.d(m,{DEVICE_TYPES:()=>w});const w=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":(ae,m,r)=>{r.r(m),r.d(m,{DATA_TYPES:()=>H,DEFAULT_DEVICE_DTYPE_MAPPING:()=>$,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>_,isWebGpuFp16Supported:()=>L});var w=r("./src/env.js"),T=r("./src/utils/devices.js");const L=function(){let I;return async function(){if(I===void 0)if(!w.apis.IS_WEBGPU_AVAILABLE)I=!1;else try{I=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{I=!1}return I}}(),H=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),$=Object.freeze({[T.DEVICE_TYPES.wasm]:H.q8}),_=Object.freeze({[H.fp32]:"",[H.fp16]:"_fp16",[H.int8]:"_int8",[H.uint8]:"_uint8",[H.q8]:"_quantized",[H.q4]:"_q4",[H.q4f16]:"_q4f16",[H.bnb4]:"_bnb4"})},"./src/utils/generic.js":(ae,m,r)=>{r.r(m),r.d(m,{Callable:()=>w});const w=class{constructor(){let T=function(...L){return T._call(...L)};return Object.setPrototypeOf(T,new.target.prototype)}_call(...T){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(ae,m,r)=>{r.r(m),r.d(m,{MAX_EXTERNAL_DATA_CHUNKS:()=>$,getFile:()=>U,getModelFile:()=>G,getModelJSON:()=>O,getModelText:()=>Y});var w=r("?7992"),T=r("?5af5"),L=r("./src/env.js"),H=r("./src/utils/core.js");const $=100,_={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 I{constructor(C){if(this.filePath=C,this.headers=new Headers,this.exists=w.existsSync(C),this.exists){this.status=200,this.statusText="OK";let re=w.statSync(C);this.headers.set("content-length",re.size.toString()),this.updateContentType();const q=w.createReadStream(C);this.body=new ReadableStream({start(pe){q.on("data",me=>pe.enqueue(me)),q.on("end",()=>pe.close()),q.on("error",me=>pe.error(me))},cancel(){q.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const C=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",_[C]??"application/octet-stream")}clone(){let C=new I(this.filePath);return C.exists=this.exists,C.status=this.status,C.statusText=this.statusText,C.headers=new Headers(this.headers),C}async arrayBuffer(){return(await w.promises.readFile(this.filePath)).buffer}async blob(){const C=await w.promises.readFile(this.filePath);return new Blob([C],{type:this.headers.get("content-type")})}async text(){return await w.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function D(x,C=null,re=null){let q;try{q=new URL(x)}catch{return!1}return!(C&&!C.includes(q.protocol)||re&&!re.includes(q.hostname))}const b=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function h(x){return!(!b.test(x)||x.includes("..")||x.includes("--")||x.endsWith(".git")||x.endsWith(".ipynb"))}async function U(x){var C,re,q,pe;if(L.env.useFS&&!D(x,["http:","https:","blob:"]))return new I(x instanceof URL?x.protocol==="file:"?x.pathname:x.toString():x);if(typeof process<"u"&&((C=process==null?void 0:process.release)==null?void 0:C.name)==="node"){const me=!!((re=process.env)!=null&&re.TESTING_REMOTELY),J=L.env.version,fe=new Headers;if(fe.set("User-Agent",`transformers.js/${J}; is_ci/${me};`),D(x,["http:","https:"],["huggingface.co","hf.co"])){const Te=((q=process.env)==null?void 0:q.HF_TOKEN)??((pe=process.env)==null?void 0:pe.HF_ACCESS_TOKEN);Te&&fe.set("Authorization",`Bearer ${Te}`)}return fetch(x,{headers:fe})}else return fetch(x)}const z={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 Q(x,C,re){if(!re)return null;const q=z[x]??`Error (${x}) occurred while trying to load file`;throw Error(`${q}: "${C}".`)}class ge{constructor(C){this.path=C}async match(C){let re=T.join(this.path,C),q=new I(re);if(q.exists)return q}async put(C,re,q=void 0){let pe=T.join(this.path,C);try{const me=re.headers.get("Content-Length"),J=parseInt(me??"0");let fe=0;await w.promises.mkdir(T.dirname(pe),{recursive:!0});const de=w.createWriteStream(pe),Te=re.body.getReader();for(;;){const{done:Pe,value:be}=await Te.read();if(Pe)break;await new Promise((Oe,he)=>{de.write(be,K=>{if(K){he(K);return}Oe()})}),fe+=be.length;const He=J?fe/J*100:0;q==null||q({progress:He,loaded:fe,total:J})}de.close()}catch(me){try{await w.promises.unlink(pe)}catch{}throw me}}}async function j(x,...C){for(let re of C)try{let q=await x.match(re);if(q)return q}catch{continue}}async function G(x,C,re=!0,q={},pe=!1){if(!L.env.allowLocalModels){if(q.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(!L.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,H.dispatchCallback)(q.progress_callback,{status:"initiate",name:x,file:C});let me;if(!me&&L.env.useCustomCache){if(!L.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!L.env.customCache.match||!L.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");me=L.env.customCache}if(!me&&L.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{me=await caches.open("transformers-cache")}catch(Fe){console.warn("An error occurred while opening the browser cache:",Fe)}}if(!me&&L.env.useFSCache){if(!L.apis.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");me=new ge(q.cache_dir??L.env.cacheDir)}const J=q.revision??"main",fe=E(x,C),de=h(x),Te=de?E(L.env.localModelPath,fe):fe,Pe=E(L.env.remoteHost,L.env.remotePathTemplate.replaceAll("{model}",x).replaceAll("{revision}",encodeURIComponent(J)),C);let be;const He=me instanceof ge?J==="main"?fe:E(x,J,C):Pe;let Oe=!1,he;me&&(he=await j(me,Te,He));const K=he!==void 0;if(he===void 0){if(L.env.allowLocalModels)if(D(fe,["http:","https:"])){if(q.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${fe}.`);if(!L.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${fe}.`)}else try{he=await U(Te),be=Te}catch(Xe){console.warn(`Unable to load from local path "${Te}": "${Xe}"`)}if(he===void 0||he.status===404){if(q.local_files_only||!L.env.allowRemoteModels){if(re)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${Te}".`);return null}if(!de)throw Error(`Local file missing at "${Te}" and download aborted due to invalid model ID "${x}".`);if(he=await U(Pe),he.status!==200)return Q(he.status,Pe,re);be=He}Oe=me&&typeof Response<"u"&&he instanceof Response&&he.status===200}(0,H.dispatchCallback)(q.progress_callback,{status:"download",name:x,file:C});let ce;if(!(L.apis.IS_NODE_ENV&&pe)){let Fe;q.progress_callback?K&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(Fe=new Uint8Array(await he.arrayBuffer()),(0,H.dispatchCallback)(q.progress_callback,{status:"progress",name:x,file:C,progress:100,loaded:Fe.length,total:Fe.length})):Fe=await S(he,Xe=>{(0,H.dispatchCallback)(q.progress_callback,{status:"progress",name:x,file:C,...Xe})}):Fe=new Uint8Array(await he.arrayBuffer()),ce=Fe}if(Oe&&be&&await me.match(be)===void 0&&(ce?await me.put(be,new Response(ce,{headers:he.headers})).catch(Fe=>{console.warn(`Unable to add response to browser cache: ${Fe}.`)}):await me.put(be,he,q.progress_callback)),(0,H.dispatchCallback)(q.progress_callback,{status:"done",name:x,file:C}),ce){if(!L.apis.IS_NODE_ENV&&pe)throw new Error("Cannot return path in a browser environment.");return ce}if(he instanceof I)return he.filePath;const ye=await(me==null?void 0:me.match(be));if(ye instanceof I)return ye.filePath;if(ye instanceof Response)return new Uint8Array(await ye.arrayBuffer());if(typeof ye=="string")return ye;throw new Error("Unable to get model file path or buffer.")}async function Y(x,C,re=!0,q={}){const pe=await G(x,C,re,q,!1);return pe===null?null:new TextDecoder("utf-8").decode(pe)}async function O(x,C,re=!0,q={}){const pe=await Y(x,C,re,q);return pe===null?{}:JSON.parse(pe)}async function S(x,C){const re=x.headers.get("Content-Length");re===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let q=parseInt(re??"0"),pe=new Uint8Array(q),me=0;const J=x.body.getReader();async function fe(){const{done:de,value:Te}=await J.read();if(de)return;const Pe=me+Te.length;if(Pe>q){q=Pe;const He=new Uint8Array(q);He.set(pe),pe=He}pe.set(Te,me),me=Pe;const be=me/q*100;return C({progress:be,loaded:me,total:q}),fe()}return await fe(),pe}function E(...x){return x=x.map((C,re)=>(re&&(C=C.replace(new RegExp("^/"),"")),re!==x.length-1&&(C=C.replace(new RegExp("/$"),"")),C)),x.join("/")}},"./src/utils/image.js":(ae,m,r)=>{r.r(m),r.d(m,{RawImage:()=>z,load_image:()=>Q});var w=r("./src/utils/core.js"),T=r("./src/utils/hub.js"),L=r("./src/env.js"),H=r("./src/utils/tensor.js"),$=r("?2b25");let _,I,D;const b=L.apis.IS_BROWSER_ENV||L.apis.IS_WEBWORKER_ENV;if(b)_=(ge,j)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(ge,j)},D=self.createImageBitmap,I=self.ImageData;else if($)D=async ge=>{const G=(await ge.metadata()).channels,{data:Y,info:O}=await ge.rotate().raw().toBuffer({resolveWithObject:!0}),S=new z(new Uint8ClampedArray(Y),O.width,O.height,O.channels);return G!==void 0&&G!==O.channels&&S.convert(G),S};else throw new Error("Unable to load image processing library.");const h={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},U=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class z{constructor(j,G,Y,O){this.data=j,this.width=G,this.height=Y,this.channels=O}get size(){return[this.width,this.height]}static async read(j){if(j instanceof z)return j;if(typeof j=="string"||j instanceof URL)return await this.fromURL(j);if(j instanceof Blob)return await this.fromBlob(j);if(typeof HTMLCanvasElement<"u"&&j instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&j instanceof OffscreenCanvas)return this.fromCanvas(j);throw new Error(`Unsupported input type: ${typeof j}`)}static fromCanvas(j){if(!b)throw new Error("fromCanvas() is only supported in browser environments.");const Y=j.getContext("2d").getImageData(0,0,j.width,j.height).data;return new z(Y,j.width,j.height,4)}static async fromURL(j){const G=await(0,T.getFile)(j);if(G.status!==200)throw new Error(`Unable to read image from "${j}" (${G.status} ${G.statusText})`);const Y=await G.blob();return this.fromBlob(Y)}static async fromBlob(j){if(b){const G=await D(j),Y=_(G.width,G.height).getContext("2d");return Y.drawImage(G,0,0),new this(Y.getImageData(0,0,G.width,G.height).data,G.width,G.height,4)}else{const G=$(await j.arrayBuffer());return await D(G)}}static fromTensor(j,G="CHW"){if(j.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${j.dims.length} dimensions.`);if(G==="CHW")j=j.transpose(1,2,0);else if(G!=="HWC")throw new Error(`Unsupported channel format: ${G}`);if(!(j.data instanceof Uint8ClampedArray||j.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${j.type}`);switch(j.dims[2]){case 1:case 2:case 3:case 4:return new z(j.data,j.dims[1],j.dims[0],j.dims[2]);default:throw new Error(`Unsupported number of channels: ${j.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const j=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let G=0,Y=0;G=0?C=Y:q=-Y,O>=0?re=O:pe=-O,x.drawImage(E,C,re,j,G,q,pe,j,G),new z(x.getImageData(0,0,j,G).data,j,G,4).convert(S)}else{let S=this.toSharp();if(Y>=0&&O>=0)S=S.extract({left:Math.floor(Y),top:Math.floor(O),width:j,height:G});else if(Y<=0&&O<=0){const E=Math.floor(-O),x=Math.floor(-Y);S=S.extend({top:E,left:x,right:j-this.width-x,bottom:G-this.height-E})}else{let E=[0,0],x=0;O<0?(E[0]=Math.floor(-O),E[1]=G-this.height-E[0]):x=Math.floor(O);let C=[0,0],re=0;Y<0?(C[0]=Math.floor(-Y),C[1]=j-this.width-C[0]):re=Math.floor(Y),S=S.extend({top:E[0],bottom:E[1],left:C[0],right:C[1]}).extract({left:re,top:x,width:j,height:G})}return await D(S)}}async toBlob(j="image/png",G=1){if(!b)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:j,quality:G})}toTensor(j="CHW"){let G=new H.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(j!=="HWC")if(j==="CHW")G=G.permute(2,0,1);else throw new Error(`Unsupported channel format: ${j}`);return G}toCanvas(){if(!b)throw new Error("toCanvas() is only supported in browser environments.");const j=this.clone().rgba(),G=_(j.width,j.height),Y=new I(j.data,j.width,j.height);return G.getContext("2d").putImageData(Y,0,0),G}split(){const{data:j,width:G,height:Y,channels:O}=this,S=j.constructor,E=j.length/O,x=Array.from({length:O},()=>new S(E));for(let C=0;Cnew z(C,G,Y,1))}_update(j,G,Y,O=null){return this.data=j,this.width=G,this.height=Y,O!==null&&(this.channels=O),this}clone(){return new z(this.data.slice(),this.width,this.height,this.channels)}convert(j){if(this.channels===j)return this;switch(j){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(j){if(b){if(L.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const G=j.split(".").pop().toLowerCase(),Y=U.get(G)??"image/png",O=await this.toBlob(Y);(0,w.saveBlob)(j,O)}else{if(L.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(j);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(b)throw new Error("toSharp() is only supported in server-side environments.");return $(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const Q=z.read.bind(z)},"./src/utils/maths.js":(ae,m,r)=>{r.r(m),r.d(m,{FFT:()=>Q,bankers_round:()=>G,cos_sim:()=>_,dot:()=>$,dynamic_time_warping:()=>Y,interpolate_data:()=>w,log_softmax:()=>H,magnitude:()=>I,max:()=>b,medianFilter:()=>ge,min:()=>D,permute_data:()=>T,round:()=>j,softmax:()=>L});function w(O,[S,E,x],[C,re],q="bilinear",pe=!1){const me=re/x,J=C/E,fe=new O.constructor(C*re*S),de=E*x,Te=C*re;for(let Pe=0;Pe=0;--pe)C[pe]=me,x[pe]=S[E[pe]],me*=x[pe];const re=E.map((pe,me)=>C[E.indexOf(me)]),q=new O.constructor(O.length);for(let pe=0;pe=0;--J)me+=fe%S[J]*re[J],fe=Math.floor(fe/S[J]);q[me]=O[pe]}return[q,x]}function L(O){const S=b(O)[0],E=O.map(re=>Math.exp(re-S)),x=E.reduce((re,q)=>re+q,0);return E.map(re=>re/x)}function H(O){const S=b(O)[0];let E=0;for(let re=0;rere-S-x)}function $(O,S){let E=0;for(let x=0;xS+E*E,0))}function D(O){if(O.length===0)throw Error("Array must not be empty");let S=O[0],E=0;for(let x=1;xS&&(S=O[x],E=x);return[S,E]}function h(O){return O>0&&(O&O-1)===0}class U{constructor(S){if(this.size=S|0,this.size<=1||!h(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=S<<1,this.table=new Float64Array(this.size*2);for(let x=0;xx;x<<=1)++E;this._width=E%2===0?E-1:E,this._bitrev=new Int32Array(1<>>C&3)<>>1);for(let C=0;C>>1]=S[C];return x}toComplexArray(S,E){const x=E||this.createComplexArray();for(let C=0;C>>1],x[C+1]=0;return x}transform(S,E){if(S===E)throw new Error("Input and output buffers must be different");this._transform4(S,E,1)}realTransform(S,E){if(S===E)throw new Error("Input and output buffers must be different");this._realTransform4(S,E,1)}inverseTransform(S,E){if(S===E)throw new Error("Input and output buffers must be different");this._transform4(S,E,-1);for(let x=0;x>=2;q>=2;q>>=2){pe=C/q<<1;const Te=pe>>>2;for(me=0;me>>1,q>>>1)}else for(me=0,J=0;me>>1,q>>>1,x)}const de=this.table;for(q>>=2;q>=2;q>>=2){pe=C/q<<1;const Pe=pe>>>1,be=Pe>>>1,He=be>>>1;for(me=0;me>>1;for(let Pe=2;Pe>1;++fe){const de=(fe+1-S)**2/2,Te=Math.sqrt(me**2+J**2)**de,Pe=de*Math.atan2(J,me),be=2*fe;re[be]=Te*Math.cos(Pe),re[be+1]=Te*Math.sin(Pe),q[be]=re[be],q[be+1]=-re[be+1]}this._slicedChirpBuffer=re.subarray(E,x),this._f=new U(C>>1),this._f.transform(this._chirpBuffer,q)}_transform(S,E,x){const C=this._buffer1,re=this._buffer2,q=this._outBuffer1,pe=this._outBuffer2,me=this._chirpBuffer,J=this._slicedChirpBuffer,fe=this._a;if(x)for(let de=0;de>1,be=E[Pe];C[de]=be*J[de],C[Te]=be*J[Te]}else for(let de=0;de=O.length&&(me=2*(O.length-1)-me),x[q++]=O[me]}x.sort(),E[re]=x[C]}return E}function j(O,S){const E=Math.pow(10,S);return Math.round(O*E)/E}function G(O){const S=Math.round(O);return Math.abs(O)%1===.5?S%2===0?S:S-1:S}function Y(O){const S=O.length,E=O[0].length,x=[S+1,E+1],C=Array.from({length:x[0]},()=>Array(x[1]).fill(1/0));C[0][0]=0;const re=Array.from({length:x[0]},()=>Array(x[1]).fill(-1));for(let fe=1;fe0||pe>0;)switch(me.push(q-1),J.push(pe-1),re[q][pe]){case 0:--q,--pe;break;case 1:--q;break;case 2:--pe;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${q}, ${pe}]. Please file a bug report.`)}return me.reverse(),J.reverse(),[me,J]}},"./src/utils/tensor.js":(ae,m,r)=>{r.r(m),r.d(m,{DataTypeMap:()=>H,Tensor:()=>$,cat:()=>E,full:()=>J,full_like:()=>fe,interpolate:()=>D,interpolate_4d:()=>b,layer_norm:()=>G,matmul:()=>h,mean:()=>q,mean_pooling:()=>j,ones:()=>de,ones_like:()=>Te,permute:()=>I,quantize_embeddings:()=>Oe,rand:()=>He,rfft:()=>U,slice:()=>ge,stack:()=>x,std_mean:()=>re,topk:()=>z,zeros:()=>Pe,zeros_like:()=>be});var w=r("./src/utils/maths.js"),T=r("./src/backends/onnx.js"),L=r("./src/ops/registry.js");const H=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 ${constructor(...K){ie(this,"ort_tensor");return(0,T.isONNXTensor)(K[0])?this.ort_tensor=K[0]:this.ort_tensor=new T.Tensor(K[0],K[1],K[2]),new Proxy(this,{get:(ce,ye)=>{if(typeof ye=="string"){let Fe=Number(ye);if(Number.isInteger(Fe))return ce._getitem(Fe)}return ce[ye]},set:(ce,ye,Fe)=>ce[ye]=Fe})}get dims(){return this.ort_tensor.dims}set dims(K){this.ort_tensor.dims=K}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[K,...ce]=this.dims;if(ce.length>0){const ye=ce.reduce((Fe,Xe)=>Fe*Xe);for(let Fe=0;Fe0){const Fe=ye.reduce((Xe,Qe)=>Xe*Qe);return this._subarray(K,Fe,ye)}else return new $(this.type,[this.data[K]],ye)}indexOf(K){const ce=this.data;for(let ye=0;yeke)throw new Error(`Invalid slice: ${Ee}`);const Ne=[Math.max(X,0),Math.min(ke,this.dims[le])];ye.push(Ne),ce.push(Ne[1]-Ne[0])}else throw new Error(`Invalid slice: ${Ee}`)}const Fe=ye.map(([le,Ee])=>Ee-le),Xe=Fe.reduce((le,Ee)=>le*Ee),Qe=this.data,Ye=new Qe.constructor(Xe),wt=this.stride();let We=!0;for(let le=1;le=0;--X){const Ne=Fe[X];Ee+=(ke%Ne+ye[X][0])*wt[X],ke=Math.floor(ke/Ne)}Ye[le]=Qe[Ee]}return new $(this.type,Ye,ce)}permute(...K){return I(this,K)}transpose(...K){return this.permute(...K)}sum(K=null,ce=!1){return this.norm(1,K,ce)}norm(K="fro",ce=null,ye=!1){if(K==="fro")K=2;else if(typeof K=="string")throw Error(`Unsupported norm: ${K}`);const Fe=this.data,Xe=(We,le)=>We+le**K;if(ce===null){const We=Fe.reduce(Xe,0)**(1/K);return new $(this.type,[We],[])}const[Qe,Ye,wt]=C(Xe,this,ce,ye);if(K!==1)for(let We=0;We=0;--wt){const Ee=this.dims[wt];if(wt!==ce){const X=We%Ee;Ye+=X*le,le*=this.dims[wt]}We=Math.floor(We/Ee)}Fe[Qe]/=Xe[Ye]}return this}normalize(K=2,ce=1){return this.clone().normalize_(K,ce)}stride(){return pe(this.dims)}squeeze(K=null){return new $(this.type,this.data,Y(this.dims,K))}squeeze_(K=null){return this.dims=Y(this.dims,K),this}unsqueeze(K=null){return new $(this.type,this.data,O(this.dims,K))}unsqueeze_(K=null){return this.dims=O(this.dims,K),this}flatten_(K=0,ce=-1){ce=(ce+this.dims.length)%this.dims.length;let ye=this.dims.slice(0,K),Fe=this.dims.slice(K,ce+1),Xe=this.dims.slice(ce+1);return this.dims=[...ye,Fe.reduce((Qe,Ye)=>Qe*Ye,1),...Xe],this}flatten(K=0,ce=-1){return this.clone().flatten_(K,ce)}view(...K){let ce=-1;for(let Fe=0;FeYe!==ce?Xe*Qe:Xe,1);K[ce]=ye.length/Fe}return new $(this.type,ye,K)}neg_(){const K=this.data;for(let ce=0;ceK?1:0;return new $("bool",ce,this.dims)}lt(K){const ce=new Uint8Array(this.data.length),ye=this.data;for(let Fe=0;FeMath.min(Qe,Ye),this,K,ce,1/0);return new $(ye,Fe,Xe)}max(K=null,ce=!1){if(K===null){const Qe=(0,w.max)(this.data)[0];return new $(this.type,[Qe],[])}const[ye,Fe,Xe]=C((Qe,Ye)=>Math.max(Qe,Ye),this,K,ce,-1/0);return new $(ye,Fe,Xe)}argmin(K=null,ce=!1){if(K!==null)throw new Error("`dim !== null` not yet implemented.");const ye=(0,w.min)(this.data)[1];return new $("int64",[BigInt(ye)],[])}argmax(K=null,ce=!1){if(K!==null)throw new Error("`dim !== null` not yet implemented.");const ye=(0,w.max)(this.data)[1];return new $("int64",[BigInt(ye)],[])}to(K){if(this.type===K)return this;if(!H.hasOwnProperty(K))throw new Error(`Unsupported type: ${K}`);let ce;const ye=["int64","uint64"].includes(this.type),Fe=["int64","uint64"].includes(K);return ye&&!Fe?ce=Number:!ye&&Fe&&(ce=BigInt),new $(K,H[K].from(this.data,ce),this.dims)}}function _(he,K){const ce=he.length,ye=K.reduce((Xe,Qe)=>Xe*Qe);if(ce!==ye)throw Error(`cannot reshape array of size ${ce} into shape (${K})`);let Fe=he;for(let Xe=K.length-1;Xe>=0;Xe--)Fe=Fe.reduce((Qe,Ye)=>{let wt=Qe[Qe.length-1];return wt.lengthnew $("int64",he,[he.length]);async function ge(he,K,ce,ye,Fe){return await(await L.TensorOpRegistry.slice)({x:he,s:Q(K),e:Q(ce),a:Q(ye),t:Q(Fe??new Array(ye.length).fill(1))})}function j(he,K){const ce=he.data,ye=K.data,Fe=[he.dims[0],he.dims[2]],Xe=new ce.constructor(Fe[0]*Fe[1]),[Qe,Ye,wt]=he.dims;let We=0;for(let le=0;lece!==1):typeof K=="number"?he[K]===1&&he.splice(K,1):Array.isArray(K)&&(he=he.filter((ce,ye)=>ce!==1||!K.includes(ye))),he}function O(he,K){return K=S(K,he.length+1),he=he.slice(),he.splice(K,0,1),he}function S(he,K,ce=null,ye=!0){if(he<-K||he>=K){if(ye)throw new Error(`IndexError: index ${he} is out of bounds for dimension${ce===null?"":" "+ce} with size ${K}`);return he<-K?0:K}return he<0&&(he=(he%K+K)%K),he}function E(he,K=0){K=S(K,he[0].dims.length);const ce=he[0].dims.slice();ce[K]=he.reduce((Qe,Ye)=>Qe+Ye.dims[K],0);const ye=ce.reduce((Qe,Ye)=>Qe*Ye,1),Fe=new he[0].data.constructor(ye),Xe=he[0].type;if(K===0){let Qe=0;for(const Ye of he){const wt=Ye.data;Fe.set(wt,Qe),Qe+=wt.length}}else{let Qe=0;for(let Ye=0;Ye=0;--X){const Ve=We[X];let De=ke%Ve;X===K&&(De+=Qe),Ee+=De*Ne,Ne*=ce[X],ke=Math.floor(ke/Ve)}Fe[Ee]=wt[le]}Qe+=We[K]}}return new $(Xe,Fe,ce)}function x(he,K=0){return E(he.map(ce=>ce.unsqueeze(K)),K)}function C(he,K,ce=null,ye=!1,Fe=null){const Xe=K.data,Qe=K.dims;ce=S(ce,Qe.length);const Ye=Qe.slice();Ye[ce]=1;const wt=new Xe.constructor(Xe.length/Qe[ce]);Fe!==null&&wt.fill(Fe);for(let We=0;We=0;--Ee){const Ne=Qe[Ee];if(Ee!==ce){const Ve=X%Ne;le+=Ve*ke,ke*=Ye[Ee]}X=Math.floor(X/Ne)}wt[le]=he(wt[le],Xe[We],We,le)}return ye||Ye.splice(ce,1),[K.type,wt,Ye]}function re(he,K=null,ce=1,ye=!1){const Fe=he.data,Xe=he.dims;if(K===null){const ke=Fe.reduce((Ke,Ae)=>Ke+Ae,0)/Fe.length,Ne=Math.sqrt(Fe.reduce((Ke,Ae)=>Ke+(Ae-ke)**2,0)/(Fe.length-ce)),Ve=new $(he.type,[ke],[]);return[new $(he.type,[Ne],[]),Ve]}K=S(K,Xe.length);const Qe=q(he,K,ye),Ye=Qe.data,[wt,We,le]=C((X,ke,Ne,Ve)=>X+(ke-Ye[Ve])**2,he,K,ye);for(let X=0;XWe+le,0);return new $(he.type,[wt/Fe.length],[])}K=S(K,ye.length);const[Xe,Qe,Ye]=C((wt,We)=>wt+We,he,K,ce);if(ye[K]!==1)for(let wt=0;wt=0;--ce)K[ce]=ye,ye*=he[ce];return K}function me(he,K,ce,ye){const Fe=he.reduce((Xe,Qe)=>Xe*Qe,1);return new $(ce,new ye(Fe).fill(K),he)}function J(he,K){let ce,ye;if(typeof K=="number")ce="float32",ye=Float32Array;else if(typeof K=="bigint")ce="int64",ye=BigInt64Array;else if(typeof K=="boolean")ce="bool",ye=Uint8Array;else throw new Error(`Unsupported data type: ${typeof K}`);return me(he,K,ce,ye)}function fe(he,K){return J(he.dims,K)}function de(he){return me(he,1n,"int64",BigInt64Array)}function Te(he){return de(he.dims)}function Pe(he){return me(he,0n,"int64",BigInt64Array)}function be(he){return Pe(he.dims)}function He(he){const K=he.reduce((ce,ye)=>ce*ye,1);return new $("float32",Float32Array.from({length:K},()=>Math.random()),he)}function Oe(he,K){if(he.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(he.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(K))throw new Error("The precision must be either 'binary' or 'ubinary'");const ce=K==="binary",ye=ce?"int8":"uint8",Fe=ce?Int8Array:Uint8Array,Xe=he.data,Qe=new Fe(Xe.length/8);for(let Ye=0;Ye0?1:0,We=Math.floor(Ye/8),le=Ye%8;Qe[We]|=wt<<7-le,ce&&le===0&&(Qe[We]-=128)}return new $(ye,Qe,[he.dims[0],he.dims[1]/8])}},"./src/utils/video.js":(ae,m,r)=>{r.r(m),r.d(m,{RawVideo:()=>H,RawVideoFrame:()=>L,load_video:()=>$});var w=r("./src/utils/image.js"),T=r("./src/env.js");class L{constructor(I,D){this.image=I,this.timestamp=D}}class H{constructor(I,D){I.length>0&&I[0]instanceof w.RawImage&&(I=I.map((b,h)=>new L(b,(h+1)/(I.length+1)*D))),this.frames=I,this.duration=D}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 $(_,{num_frames:I=null,fps:D=null}={}){if(!T.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(I==null&&D==null)throw new Error("Either num_frames or fps must be provided.");const b=[],h=document.createElement("video");if(h.crossOrigin="anonymous",h.muted=!0,typeof _=="string")h.src=_;else if(_ instanceof Blob)h.src=URL.createObjectURL(_);else if(_ instanceof HTMLVideoElement)h.src=_.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(Y=>h.onloadedmetadata=Y),h.seekable.start(0)===h.seekable.end(0)){const O=await(await fetch(h.src)).blob();h.src=URL.createObjectURL(O),await new Promise(S=>h.onloadedmetadata=S)}const U=h.duration;let z,Q;I!=null?(z=I,Q=I===1?0:U/(I-1)):(Q=1/D,z=Math.floor(U/Q));let ge=[];for(let Y=0;Y{h.onseeked=x}),G.drawImage(h,0,0,j.width,j.height);const O=G.getImageData(0,0,j.width,j.height),S=new w.RawImage(O.data,j.width,j.height,4),E=new L(S,Y);b.push(E)}return h.remove(),new H(b,U)}}},zp={};function ts(ae){var m=zp[ae];if(m!==void 0)return m.exports;var r=zp[ae]={exports:{}};return ah[ae](r,r.exports,ts),r.exports}(()=>{var ae=Object.getPrototypeOf?r=>Object.getPrototypeOf(r):r=>r.__proto__,m;ts.t=function(r,w){if(w&1&&(r=this(r)),w&8||typeof r=="object"&&r&&(w&4&&r.__esModule||w&16&&typeof r.then=="function"))return r;var T=Object.create(null);ts.r(T);var L={};m=m||[null,ae({}),ae([]),ae(ae)];for(var H=w&2&&r;typeof H=="object"&&!~m.indexOf(H);H=ae(H))Object.getOwnPropertyNames(H).forEach($=>L[$]=()=>r[$]);return L.default=()=>r,ts.d(T,L),T}})(),ts.d=(ae,m)=>{for(var r in m)ts.o(m,r)&&!ts.o(ae,r)&&Object.defineProperty(ae,r,{enumerable:!0,get:m[r]})},ts.o=(ae,m)=>Object.prototype.hasOwnProperty.call(ae,m),ts.r=ae=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(ae,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(ae,"__esModule",{value:!0})};var l={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/ts.r(l),ts.d(l,{ASTFeatureExtractor:()=>b.ASTFeatureExtractor,ASTForAudioClassification:()=>r.ASTForAudioClassification,ASTModel:()=>r.ASTModel,ASTPreTrainedModel:()=>r.ASTPreTrainedModel,AlbertForMaskedLM:()=>r.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>r.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>r.AlbertForSequenceClassification,AlbertModel:()=>r.AlbertModel,AlbertPreTrainedModel:()=>r.AlbertPreTrainedModel,AlbertTokenizer:()=>w.AlbertTokenizer,ArceeForCausalLM:()=>r.ArceeForCausalLM,ArceeModel:()=>r.ArceeModel,ArceePreTrainedModel:()=>r.ArceePreTrainedModel,AudioClassificationPipeline:()=>m.AudioClassificationPipeline,AutoConfig:()=>T.AutoConfig,AutoFeatureExtractor:()=>h.AutoFeatureExtractor,AutoImageProcessor:()=>Q.AutoImageProcessor,AutoModel:()=>r.AutoModel,AutoModelForAudioClassification:()=>r.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>r.AutoModelForAudioFrameClassification,AutoModelForAudioTextToText:()=>r.AutoModelForAudioTextToText,AutoModelForCTC:()=>r.AutoModelForCTC,AutoModelForCausalLM:()=>r.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>r.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>r.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>r.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>r.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>r.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>r.AutoModelForImageSegmentation,AutoModelForImageTextToText:()=>r.AutoModelForImageTextToText,AutoModelForImageToImage:()=>r.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>r.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>r.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>r.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>r.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>r.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>r.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>r.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>r.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>r.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>r.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>r.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>r.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>r.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>r.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>r.AutoModelForVision2Seq,AutoModelForXVector:()=>r.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>r.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>G.AutoProcessor,AutoTokenizer:()=>w.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>m.AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline:()=>m.BackgroundRemovalPipeline,BartForConditionalGeneration:()=>r.BartForConditionalGeneration,BartForSequenceClassification:()=>r.BartForSequenceClassification,BartModel:()=>r.BartModel,BartPretrainedModel:()=>r.BartPretrainedModel,BartTokenizer:()=>w.BartTokenizer,BaseModelOutput:()=>r.BaseModelOutput,BaseStreamer:()=>Y.BaseStreamer,BeitFeatureExtractor:()=>z.BeitFeatureExtractor,BeitForImageClassification:()=>r.BeitForImageClassification,BeitModel:()=>r.BeitModel,BeitPreTrainedModel:()=>r.BeitPreTrainedModel,BertForMaskedLM:()=>r.BertForMaskedLM,BertForQuestionAnswering:()=>r.BertForQuestionAnswering,BertForSequenceClassification:()=>r.BertForSequenceClassification,BertForTokenClassification:()=>r.BertForTokenClassification,BertModel:()=>r.BertModel,BertPreTrainedModel:()=>r.BertPreTrainedModel,BertTokenizer:()=>w.BertTokenizer,BitImageProcessor:()=>z.BitImageProcessor,BlenderbotForConditionalGeneration:()=>r.BlenderbotForConditionalGeneration,BlenderbotModel:()=>r.BlenderbotModel,BlenderbotPreTrainedModel:()=>r.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>r.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>r.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>r.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>w.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>w.BlenderbotTokenizer,BloomForCausalLM:()=>r.BloomForCausalLM,BloomModel:()=>r.BloomModel,BloomPreTrainedModel:()=>r.BloomPreTrainedModel,BloomTokenizer:()=>w.BloomTokenizer,CLIPFeatureExtractor:()=>z.CLIPFeatureExtractor,CLIPImageProcessor:()=>z.CLIPImageProcessor,CLIPModel:()=>r.CLIPModel,CLIPPreTrainedModel:()=>r.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>r.CLIPSegForImageSegmentation,CLIPSegModel:()=>r.CLIPSegModel,CLIPSegPreTrainedModel:()=>r.CLIPSegPreTrainedModel,CLIPTextModel:()=>r.CLIPTextModel,CLIPTextModelWithProjection:()=>r.CLIPTextModelWithProjection,CLIPTokenizer:()=>w.CLIPTokenizer,CLIPVisionModel:()=>r.CLIPVisionModel,CLIPVisionModelWithProjection:()=>r.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>r.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>r.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>r.CamembertForSequenceClassification,CamembertForTokenClassification:()=>r.CamembertForTokenClassification,CamembertModel:()=>r.CamembertModel,CamembertPreTrainedModel:()=>r.CamembertPreTrainedModel,CamembertTokenizer:()=>w.CamembertTokenizer,CausalLMOutput:()=>r.CausalLMOutput,CausalLMOutputWithPast:()=>r.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>z.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>r.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>r.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>r.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>b.ClapFeatureExtractor,ClapModel:()=>r.ClapModel,ClapPreTrainedModel:()=>r.ClapPreTrainedModel,ClapTextModelWithProjection:()=>r.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>S.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>r.CodeGenForCausalLM,CodeGenModel:()=>r.CodeGenModel,CodeGenPreTrainedModel:()=>r.CodeGenPreTrainedModel,CodeGenTokenizer:()=>w.CodeGenTokenizer,CodeLlamaTokenizer:()=>w.CodeLlamaTokenizer,CohereForCausalLM:()=>r.CohereForCausalLM,CohereModel:()=>r.CohereModel,CoherePreTrainedModel:()=>r.CoherePreTrainedModel,CohereTokenizer:()=>w.CohereTokenizer,ConvBertForMaskedLM:()=>r.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>r.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>r.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>r.ConvBertForTokenClassification,ConvBertModel:()=>r.ConvBertModel,ConvBertPreTrainedModel:()=>r.ConvBertPreTrainedModel,ConvBertTokenizer:()=>w.ConvBertTokenizer,ConvNextFeatureExtractor:()=>z.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>r.ConvNextForImageClassification,ConvNextImageProcessor:()=>z.ConvNextImageProcessor,ConvNextModel:()=>r.ConvNextModel,ConvNextPreTrainedModel:()=>r.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>r.ConvNextV2ForImageClassification,ConvNextV2Model:()=>r.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>r.ConvNextV2PreTrainedModel,DFineForObjectDetection:()=>r.DFineForObjectDetection,DFineModel:()=>r.DFineModel,DFinePreTrainedModel:()=>r.DFinePreTrainedModel,DINOv3ConvNextModel:()=>r.DINOv3ConvNextModel,DINOv3ConvNextPreTrainedModel:()=>r.DINOv3ConvNextPreTrainedModel,DINOv3ViTImageProcessor:()=>z.DINOv3ViTImageProcessor,DINOv3ViTModel:()=>r.DINOv3ViTModel,DINOv3ViTPreTrainedModel:()=>r.DINOv3ViTPreTrainedModel,DPTFeatureExtractor:()=>z.DPTFeatureExtractor,DPTForDepthEstimation:()=>r.DPTForDepthEstimation,DPTImageProcessor:()=>z.DPTImageProcessor,DPTModel:()=>r.DPTModel,DPTPreTrainedModel:()=>r.DPTPreTrainedModel,DacDecoderModel:()=>r.DacDecoderModel,DacDecoderOutput:()=>r.DacDecoderOutput,DacEncoderModel:()=>r.DacEncoderModel,DacEncoderOutput:()=>r.DacEncoderOutput,DacFeatureExtractor:()=>b.DacFeatureExtractor,DacModel:()=>r.DacModel,DacPreTrainedModel:()=>r.DacPreTrainedModel,DataTypeMap:()=>_.DataTypeMap,DebertaForMaskedLM:()=>r.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>r.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>r.DebertaForSequenceClassification,DebertaForTokenClassification:()=>r.DebertaForTokenClassification,DebertaModel:()=>r.DebertaModel,DebertaPreTrainedModel:()=>r.DebertaPreTrainedModel,DebertaTokenizer:()=>w.DebertaTokenizer,DebertaV2ForMaskedLM:()=>r.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>r.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>r.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>r.DebertaV2ForTokenClassification,DebertaV2Model:()=>r.DebertaV2Model,DebertaV2PreTrainedModel:()=>r.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>w.DebertaV2Tokenizer,DecisionTransformerModel:()=>r.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>r.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>z.DeiTFeatureExtractor,DeiTForImageClassification:()=>r.DeiTForImageClassification,DeiTImageProcessor:()=>z.DeiTImageProcessor,DeiTModel:()=>r.DeiTModel,DeiTPreTrainedModel:()=>r.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>r.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>r.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>m.DepthEstimationPipeline,DepthProForDepthEstimation:()=>r.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>r.DepthProPreTrainedModel,DetrFeatureExtractor:()=>z.DetrFeatureExtractor,DetrForObjectDetection:()=>r.DetrForObjectDetection,DetrForSegmentation:()=>r.DetrForSegmentation,DetrImageProcessor:()=>z.DetrImageProcessor,DetrModel:()=>r.DetrModel,DetrObjectDetectionOutput:()=>r.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>r.DetrPreTrainedModel,DetrSegmentationOutput:()=>r.DetrSegmentationOutput,Dinov2ForImageClassification:()=>r.Dinov2ForImageClassification,Dinov2Model:()=>r.Dinov2Model,Dinov2PreTrainedModel:()=>r.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>r.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>r.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>r.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>r.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>r.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>r.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>r.DistilBertForTokenClassification,DistilBertModel:()=>r.DistilBertModel,DistilBertPreTrainedModel:()=>r.DistilBertPreTrainedModel,DistilBertTokenizer:()=>w.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>m.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>z.DonutFeatureExtractor,DonutImageProcessor:()=>z.DonutImageProcessor,DonutSwinModel:()=>r.DonutSwinModel,DonutSwinPreTrainedModel:()=>r.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>r.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>z.EfficientNetImageProcessor,EfficientNetModel:()=>r.EfficientNetModel,EfficientNetPreTrainedModel:()=>r.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>r.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>r.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>r.ElectraForSequenceClassification,ElectraForTokenClassification:()=>r.ElectraForTokenClassification,ElectraModel:()=>r.ElectraModel,ElectraPreTrainedModel:()=>r.ElectraPreTrainedModel,ElectraTokenizer:()=>w.ElectraTokenizer,EncodecFeatureExtractor:()=>b.EncodecFeatureExtractor,EosTokenCriteria:()=>O.EosTokenCriteria,Ernie4_5_ForCausalLM:()=>r.Ernie4_5_ForCausalLM,Ernie4_5_Model:()=>r.Ernie4_5_Model,Ernie4_5_PretrainedModel:()=>r.Ernie4_5_PretrainedModel,Ernie4_5_Tokenizer:()=>w.Ernie4_5_Tokenizer,EsmForMaskedLM:()=>r.EsmForMaskedLM,EsmForSequenceClassification:()=>r.EsmForSequenceClassification,EsmForTokenClassification:()=>r.EsmForTokenClassification,EsmModel:()=>r.EsmModel,EsmPreTrainedModel:()=>r.EsmPreTrainedModel,EsmTokenizer:()=>w.EsmTokenizer,ExaoneForCausalLM:()=>r.ExaoneForCausalLM,ExaoneModel:()=>r.ExaoneModel,ExaonePreTrainedModel:()=>r.ExaonePreTrainedModel,FFT:()=>I.FFT,FalconForCausalLM:()=>r.FalconForCausalLM,FalconModel:()=>r.FalconModel,FalconPreTrainedModel:()=>r.FalconPreTrainedModel,FalconTokenizer:()=>w.FalconTokenizer,FastViTForImageClassification:()=>r.FastViTForImageClassification,FastViTModel:()=>r.FastViTModel,FastViTPreTrainedModel:()=>r.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>m.FeatureExtractionPipeline,FeatureExtractor:()=>D.FeatureExtractor,FillMaskPipeline:()=>m.FillMaskPipeline,Florence2ForConditionalGeneration:()=>r.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>r.Florence2PreTrainedModel,Florence2Processor:()=>j.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>S.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>S.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>z.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>r.GLPNForDepthEstimation,GLPNModel:()=>r.GLPNModel,GLPNPreTrainedModel:()=>r.GLPNPreTrainedModel,GPT2LMHeadModel:()=>r.GPT2LMHeadModel,GPT2Model:()=>r.GPT2Model,GPT2PreTrainedModel:()=>r.GPT2PreTrainedModel,GPT2Tokenizer:()=>w.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>r.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>r.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>r.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>r.GPTJForCausalLM,GPTJModel:()=>r.GPTJModel,GPTJPreTrainedModel:()=>r.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>r.GPTNeoForCausalLM,GPTNeoModel:()=>r.GPTNeoModel,GPTNeoPreTrainedModel:()=>r.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>r.GPTNeoXForCausalLM,GPTNeoXModel:()=>r.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>r.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>w.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>r.Gemma2ForCausalLM,Gemma2Model:()=>r.Gemma2Model,Gemma2PreTrainedModel:()=>r.Gemma2PreTrainedModel,Gemma3ForCausalLM:()=>r.Gemma3ForCausalLM,Gemma3Model:()=>r.Gemma3Model,Gemma3PreTrainedModel:()=>r.Gemma3PreTrainedModel,Gemma3nAudioFeatureExtractor:()=>b.Gemma3nAudioFeatureExtractor,Gemma3nForConditionalGeneration:()=>r.Gemma3nForConditionalGeneration,Gemma3nPreTrainedModel:()=>r.Gemma3nPreTrainedModel,Gemma3nProcessor:()=>j.Gemma3nProcessor,GemmaForCausalLM:()=>r.GemmaForCausalLM,GemmaModel:()=>r.GemmaModel,GemmaPreTrainedModel:()=>r.GemmaPreTrainedModel,GemmaTokenizer:()=>w.GemmaTokenizer,GlmForCausalLM:()=>r.GlmForCausalLM,GlmModel:()=>r.GlmModel,GlmPreTrainedModel:()=>r.GlmPreTrainedModel,GraniteForCausalLM:()=>r.GraniteForCausalLM,GraniteModel:()=>r.GraniteModel,GranitePreTrainedModel:()=>r.GranitePreTrainedModel,Grok1Tokenizer:()=>w.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>r.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>z.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>r.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>j.GroundingDinoProcessor,GroupViTModel:()=>r.GroupViTModel,GroupViTPreTrainedModel:()=>r.GroupViTPreTrainedModel,HeliumForCausalLM:()=>r.HeliumForCausalLM,HeliumModel:()=>r.HeliumModel,HeliumPreTrainedModel:()=>r.HeliumPreTrainedModel,HerbertTokenizer:()=>w.HerbertTokenizer,HieraForImageClassification:()=>r.HieraForImageClassification,HieraModel:()=>r.HieraModel,HieraPreTrainedModel:()=>r.HieraPreTrainedModel,HubertForCTC:()=>r.HubertForCTC,HubertForSequenceClassification:()=>r.HubertForSequenceClassification,HubertModel:()=>r.HubertModel,HubertPreTrainedModel:()=>r.HubertPreTrainedModel,IJepaForImageClassification:()=>r.IJepaForImageClassification,IJepaModel:()=>r.IJepaModel,IJepaPreTrainedModel:()=>r.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>r.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>z.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>r.Idefics3PreTrainedModel,Idefics3Processor:()=>j.Idefics3Processor,ImageClassificationPipeline:()=>m.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>m.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>b.ImageFeatureExtractor,ImageMattingOutput:()=>r.ImageMattingOutput,ImageProcessor:()=>U.ImageProcessor,ImageSegmentationPipeline:()=>m.ImageSegmentationPipeline,ImageToImagePipeline:()=>m.ImageToImagePipeline,ImageToTextPipeline:()=>m.ImageToTextPipeline,InterruptableStoppingCriteria:()=>O.InterruptableStoppingCriteria,JAISLMHeadModel:()=>r.JAISLMHeadModel,JAISModel:()=>r.JAISModel,JAISPreTrainedModel:()=>r.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>z.JinaCLIPImageProcessor,JinaCLIPModel:()=>r.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>r.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>j.JinaCLIPProcessor,JinaCLIPTextModel:()=>r.JinaCLIPTextModel,JinaCLIPVisionModel:()=>r.JinaCLIPVisionModel,Lfm2ForCausalLM:()=>r.Lfm2ForCausalLM,Lfm2Model:()=>r.Lfm2Model,Lfm2PreTrainedModel:()=>r.Lfm2PreTrainedModel,LiteWhisperForConditionalGeneration:()=>r.LiteWhisperForConditionalGeneration,LlamaForCausalLM:()=>r.LlamaForCausalLM,LlamaModel:()=>r.LlamaModel,LlamaPreTrainedModel:()=>r.LlamaPreTrainedModel,LlamaTokenizer:()=>w.LlamaTokenizer,LlavaForConditionalGeneration:()=>r.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>r.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>z.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>r.LlavaPreTrainedModel,LlavaProcessor:()=>j.LlavaProcessor,LlavaQwen2ForCausalLM:()=>r.LlavaQwen2ForCausalLM,LogitsProcessor:()=>S.LogitsProcessor,LogitsProcessorList:()=>S.LogitsProcessorList,LogitsWarper:()=>S.LogitsWarper,LongT5ForConditionalGeneration:()=>r.LongT5ForConditionalGeneration,LongT5Model:()=>r.LongT5Model,LongT5PreTrainedModel:()=>r.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>r.M2M100ForConditionalGeneration,M2M100Model:()=>r.M2M100Model,M2M100PreTrainedModel:()=>r.M2M100PreTrainedModel,M2M100Tokenizer:()=>w.M2M100Tokenizer,MBart50Tokenizer:()=>w.MBart50Tokenizer,MBartForCausalLM:()=>r.MBartForCausalLM,MBartForConditionalGeneration:()=>r.MBartForConditionalGeneration,MBartForSequenceClassification:()=>r.MBartForSequenceClassification,MBartModel:()=>r.MBartModel,MBartPreTrainedModel:()=>r.MBartPreTrainedModel,MBartTokenizer:()=>w.MBartTokenizer,MPNetForMaskedLM:()=>r.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>r.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>r.MPNetForSequenceClassification,MPNetForTokenClassification:()=>r.MPNetForTokenClassification,MPNetModel:()=>r.MPNetModel,MPNetPreTrainedModel:()=>r.MPNetPreTrainedModel,MPNetTokenizer:()=>w.MPNetTokenizer,MT5ForConditionalGeneration:()=>r.MT5ForConditionalGeneration,MT5Model:()=>r.MT5Model,MT5PreTrainedModel:()=>r.MT5PreTrainedModel,MarianMTModel:()=>r.MarianMTModel,MarianModel:()=>r.MarianModel,MarianPreTrainedModel:()=>r.MarianPreTrainedModel,MarianTokenizer:()=>w.MarianTokenizer,Mask2FormerImageProcessor:()=>z.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>z.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>r.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>z.MaskFormerImageProcessor,MaskFormerModel:()=>r.MaskFormerModel,MaskFormerPreTrainedModel:()=>r.MaskFormerPreTrainedModel,MaskedLMOutput:()=>r.MaskedLMOutput,MaxLengthCriteria:()=>O.MaxLengthCriteria,Metric3DForDepthEstimation:()=>r.Metric3DForDepthEstimation,Metric3DPreTrainedModel:()=>r.Metric3DPreTrainedModel,Metric3Dv2ForDepthEstimation:()=>r.Metric3Dv2ForDepthEstimation,Metric3Dv2PreTrainedModel:()=>r.Metric3Dv2PreTrainedModel,MgpstrForSceneTextRecognition:()=>r.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>r.MgpstrModelOutput,MgpstrPreTrainedModel:()=>r.MgpstrPreTrainedModel,MgpstrProcessor:()=>j.MgpstrProcessor,MgpstrTokenizer:()=>w.MgpstrTokenizer,MimiDecoderModel:()=>r.MimiDecoderModel,MimiDecoderOutput:()=>r.MimiDecoderOutput,MimiEncoderModel:()=>r.MimiEncoderModel,MimiEncoderOutput:()=>r.MimiEncoderOutput,MimiModel:()=>r.MimiModel,MimiPreTrainedModel:()=>r.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>S.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>S.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>r.MistralForCausalLM,MistralModel:()=>r.MistralModel,MistralPreTrainedModel:()=>r.MistralPreTrainedModel,MobileBertForMaskedLM:()=>r.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>r.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>r.MobileBertForSequenceClassification,MobileBertModel:()=>r.MobileBertModel,MobileBertPreTrainedModel:()=>r.MobileBertPreTrainedModel,MobileBertTokenizer:()=>w.MobileBertTokenizer,MobileLLMForCausalLM:()=>r.MobileLLMForCausalLM,MobileLLMModel:()=>r.MobileLLMModel,MobileLLMPreTrainedModel:()=>r.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>z.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>r.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>r.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>z.MobileNetV1ImageProcessor,MobileNetV1Model:()=>r.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>r.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>z.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>r.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>r.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>z.MobileNetV2ImageProcessor,MobileNetV2Model:()=>r.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>r.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>z.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>r.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>r.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>z.MobileNetV3ImageProcessor,MobileNetV3Model:()=>r.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>r.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>z.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>r.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>r.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>z.MobileNetV4ImageProcessor,MobileNetV4Model:()=>r.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>r.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>z.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>r.MobileViTForImageClassification,MobileViTImageProcessor:()=>z.MobileViTImageProcessor,MobileViTModel:()=>r.MobileViTModel,MobileViTPreTrainedModel:()=>r.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>r.MobileViTV2ForImageClassification,MobileViTV2Model:()=>r.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>r.MobileViTV2PreTrainedModel,ModelOutput:()=>r.ModelOutput,ModernBertDecoderForCausalLM:()=>r.ModernBertDecoderForCausalLM,ModernBertDecoderModel:()=>r.ModernBertDecoderModel,ModernBertDecoderPreTrainedModel:()=>r.ModernBertDecoderPreTrainedModel,ModernBertForMaskedLM:()=>r.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>r.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>r.ModernBertForTokenClassification,ModernBertModel:()=>r.ModernBertModel,ModernBertPreTrainedModel:()=>r.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>r.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>b.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>r.MoonshineForConditionalGeneration,MoonshineModel:()=>r.MoonshineModel,MoonshinePreTrainedModel:()=>r.MoonshinePreTrainedModel,MoonshineProcessor:()=>j.MoonshineProcessor,MptForCausalLM:()=>r.MptForCausalLM,MptModel:()=>r.MptModel,MptPreTrainedModel:()=>r.MptPreTrainedModel,MultiModalityCausalLM:()=>r.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>r.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>r.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>r.MusicgenForConditionalGeneration,MusicgenModel:()=>r.MusicgenModel,MusicgenPreTrainedModel:()=>r.MusicgenPreTrainedModel,NeoBertForMaskedLM:()=>r.NeoBertForMaskedLM,NeoBertForQuestionAnswering:()=>r.NeoBertForQuestionAnswering,NeoBertForSequenceClassification:()=>r.NeoBertForSequenceClassification,NeoBertForTokenClassification:()=>r.NeoBertForTokenClassification,NeoBertModel:()=>r.NeoBertModel,NeoBertPreTrainedModel:()=>r.NeoBertPreTrainedModel,NllbTokenizer:()=>w.NllbTokenizer,NoBadWordsLogitsProcessor:()=>S.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>S.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>r.NomicBertModel,NomicBertPreTrainedModel:()=>r.NomicBertPreTrainedModel,NougatImageProcessor:()=>z.NougatImageProcessor,NougatTokenizer:()=>w.NougatTokenizer,OPTForCausalLM:()=>r.OPTForCausalLM,OPTModel:()=>r.OPTModel,OPTPreTrainedModel:()=>r.OPTPreTrainedModel,ObjectDetectionPipeline:()=>m.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>r.Olmo2ForCausalLM,Olmo2Model:()=>r.Olmo2Model,Olmo2PreTrainedModel:()=>r.Olmo2PreTrainedModel,OlmoForCausalLM:()=>r.OlmoForCausalLM,OlmoModel:()=>r.OlmoModel,OlmoPreTrainedModel:()=>r.OlmoPreTrainedModel,OpenELMForCausalLM:()=>r.OpenELMForCausalLM,OpenELMModel:()=>r.OpenELMModel,OpenELMPreTrainedModel:()=>r.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>z.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>r.OwlViTForObjectDetection,OwlViTImageProcessor:()=>z.OwlViTImageProcessor,OwlViTModel:()=>r.OwlViTModel,OwlViTPreTrainedModel:()=>r.OwlViTPreTrainedModel,OwlViTProcessor:()=>j.OwlViTProcessor,Owlv2ForObjectDetection:()=>r.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>z.Owlv2ImageProcessor,Owlv2Model:()=>r.Owlv2Model,Owlv2PreTrainedModel:()=>r.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>r.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>r.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>j.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>r.PatchTSMixerForPrediction,PatchTSMixerModel:()=>r.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>r.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>r.PatchTSTForPrediction,PatchTSTModel:()=>r.PatchTSTModel,PatchTSTPreTrainedModel:()=>r.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>r.Phi3ForCausalLM,Phi3Model:()=>r.Phi3Model,Phi3PreTrainedModel:()=>r.Phi3PreTrainedModel,Phi3VForCausalLM:()=>r.Phi3VForCausalLM,Phi3VImageProcessor:()=>z.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>r.Phi3VPreTrainedModel,Phi3VProcessor:()=>j.Phi3VProcessor,PhiForCausalLM:()=>r.PhiForCausalLM,PhiModel:()=>r.PhiModel,PhiPreTrainedModel:()=>r.PhiPreTrainedModel,Pipeline:()=>m.Pipeline,PreTrainedModel:()=>r.PreTrainedModel,PreTrainedTokenizer:()=>w.PreTrainedTokenizer,PretrainedConfig:()=>T.PretrainedConfig,PretrainedMixin:()=>r.PretrainedMixin,Processor:()=>ge.Processor,PvtForImageClassification:()=>r.PvtForImageClassification,PvtImageProcessor:()=>z.PvtImageProcessor,PvtModel:()=>r.PvtModel,PvtPreTrainedModel:()=>r.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>b.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>r.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>r.PyAnnoteModel,PyAnnotePreTrainedModel:()=>r.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>j.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>r.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>m.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>r.Qwen2ForCausalLM,Qwen2Model:()=>r.Qwen2Model,Qwen2PreTrainedModel:()=>r.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>w.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>r.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>z.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>r.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>j.Qwen2VLProcessor,Qwen3ForCausalLM:()=>r.Qwen3ForCausalLM,Qwen3Model:()=>r.Qwen3Model,Qwen3PreTrainedModel:()=>r.Qwen3PreTrainedModel,RFDetrForObjectDetection:()=>r.RFDetrForObjectDetection,RFDetrModel:()=>r.RFDetrModel,RFDetrObjectDetectionOutput:()=>r.RFDetrObjectDetectionOutput,RFDetrPreTrainedModel:()=>r.RFDetrPreTrainedModel,RTDetrForObjectDetection:()=>r.RTDetrForObjectDetection,RTDetrImageProcessor:()=>z.RTDetrImageProcessor,RTDetrModel:()=>r.RTDetrModel,RTDetrObjectDetectionOutput:()=>r.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>r.RTDetrPreTrainedModel,RTDetrV2ForObjectDetection:()=>r.RTDetrV2ForObjectDetection,RTDetrV2Model:()=>r.RTDetrV2Model,RTDetrV2ObjectDetectionOutput:()=>r.RTDetrV2ObjectDetectionOutput,RTDetrV2PreTrainedModel:()=>r.RTDetrV2PreTrainedModel,RawAudio:()=>L.RawAudio,RawImage:()=>H.RawImage,RawVideo:()=>$.RawVideo,RawVideoFrame:()=>$.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>S.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>r.ResNetForImageClassification,ResNetModel:()=>r.ResNetModel,ResNetPreTrainedModel:()=>r.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>r.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>r.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>r.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>r.RoFormerForTokenClassification,RoFormerModel:()=>r.RoFormerModel,RoFormerPreTrainedModel:()=>r.RoFormerPreTrainedModel,RoFormerTokenizer:()=>w.RoFormerTokenizer,RobertaForMaskedLM:()=>r.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>r.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>r.RobertaForSequenceClassification,RobertaForTokenClassification:()=>r.RobertaForTokenClassification,RobertaModel:()=>r.RobertaModel,RobertaPreTrainedModel:()=>r.RobertaPreTrainedModel,RobertaTokenizer:()=>w.RobertaTokenizer,SamImageProcessor:()=>z.SamImageProcessor,SamImageSegmentationOutput:()=>r.SamImageSegmentationOutput,SamModel:()=>r.SamModel,SamPreTrainedModel:()=>r.SamPreTrainedModel,SamProcessor:()=>j.SamProcessor,SapiensForDepthEstimation:()=>r.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>r.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>r.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>r.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>b.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>z.SegformerFeatureExtractor,SegformerForImageClassification:()=>r.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>r.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>z.SegformerImageProcessor,SegformerModel:()=>r.SegformerModel,SegformerPreTrainedModel:()=>r.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>r.Seq2SeqLMOutput,SequenceClassifierOutput:()=>r.SequenceClassifierOutput,SiglipImageProcessor:()=>z.SiglipImageProcessor,SiglipModel:()=>r.SiglipModel,SiglipPreTrainedModel:()=>r.SiglipPreTrainedModel,SiglipTextModel:()=>r.SiglipTextModel,SiglipTokenizer:()=>w.SiglipTokenizer,SiglipVisionModel:()=>r.SiglipVisionModel,SmolLM3ForCausalLM:()=>r.SmolLM3ForCausalLM,SmolLM3Model:()=>r.SmolLM3Model,SmolLM3PreTrainedModel:()=>r.SmolLM3PreTrainedModel,SmolVLMForConditionalGeneration:()=>r.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>z.SmolVLMImageProcessor,SmolVLMProcessor:()=>j.SmolVLMProcessor,SnacDecoderModel:()=>r.SnacDecoderModel,SnacEncoderModel:()=>r.SnacEncoderModel,SnacFeatureExtractor:()=>b.SnacFeatureExtractor,SnacModel:()=>r.SnacModel,SnacPreTrainedModel:()=>r.SnacPreTrainedModel,SpeechT5FeatureExtractor:()=>b.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>r.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>r.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>r.SpeechT5HifiGan,SpeechT5Model:()=>r.SpeechT5Model,SpeechT5PreTrainedModel:()=>r.SpeechT5PreTrainedModel,SpeechT5Processor:()=>j.SpeechT5Processor,SpeechT5Tokenizer:()=>w.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>r.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>r.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>r.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>r.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>r.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>w.SqueezeBertTokenizer,StableLmForCausalLM:()=>r.StableLmForCausalLM,StableLmModel:()=>r.StableLmModel,StableLmPreTrainedModel:()=>r.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>r.Starcoder2ForCausalLM,Starcoder2Model:()=>r.Starcoder2Model,Starcoder2PreTrainedModel:()=>r.Starcoder2PreTrainedModel,StoppingCriteria:()=>O.StoppingCriteria,StoppingCriteriaList:()=>O.StoppingCriteriaList,StyleTextToSpeech2Model:()=>r.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>r.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>m.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>S.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>r.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>z.Swin2SRImageProcessor,Swin2SRModel:()=>r.Swin2SRModel,Swin2SRPreTrainedModel:()=>r.Swin2SRPreTrainedModel,SwinForImageClassification:()=>r.SwinForImageClassification,SwinForSemanticSegmentation:()=>r.SwinForSemanticSegmentation,SwinModel:()=>r.SwinModel,SwinPreTrainedModel:()=>r.SwinPreTrainedModel,T5ForConditionalGeneration:()=>r.T5ForConditionalGeneration,T5Model:()=>r.T5Model,T5PreTrainedModel:()=>r.T5PreTrainedModel,T5Tokenizer:()=>w.T5Tokenizer,TableTransformerForObjectDetection:()=>r.TableTransformerForObjectDetection,TableTransformerModel:()=>r.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>r.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>r.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>S.TemperatureLogitsWarper,Tensor:()=>_.Tensor,Text2TextGenerationPipeline:()=>m.Text2TextGenerationPipeline,TextClassificationPipeline:()=>m.TextClassificationPipeline,TextGenerationPipeline:()=>m.TextGenerationPipeline,TextStreamer:()=>Y.TextStreamer,TextToAudioPipeline:()=>m.TextToAudioPipeline,TokenClassificationPipeline:()=>m.TokenClassificationPipeline,TokenClassifierOutput:()=>r.TokenClassifierOutput,TokenizerModel:()=>w.TokenizerModel,TopKLogitsWarper:()=>S.TopKLogitsWarper,TopPLogitsWarper:()=>S.TopPLogitsWarper,TrOCRForCausalLM:()=>r.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>r.TrOCRPreTrainedModel,TranslationPipeline:()=>m.TranslationPipeline,UltravoxModel:()=>r.UltravoxModel,UltravoxPreTrainedModel:()=>r.UltravoxPreTrainedModel,UltravoxProcessor:()=>j.UltravoxProcessor,UniSpeechForCTC:()=>r.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>r.UniSpeechForSequenceClassification,UniSpeechModel:()=>r.UniSpeechModel,UniSpeechPreTrainedModel:()=>r.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>r.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>r.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>r.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>r.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>r.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>j.VLChatProcessor,VLMImageProcessor:()=>z.VLMImageProcessor,ViTFeatureExtractor:()=>z.ViTFeatureExtractor,ViTForImageClassification:()=>r.ViTForImageClassification,ViTImageProcessor:()=>z.ViTImageProcessor,ViTMAEModel:()=>r.ViTMAEModel,ViTMAEPreTrainedModel:()=>r.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>r.ViTMSNForImageClassification,ViTMSNModel:()=>r.ViTMSNModel,ViTMSNPreTrainedModel:()=>r.ViTMSNPreTrainedModel,ViTModel:()=>r.ViTModel,ViTPreTrainedModel:()=>r.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>r.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>r.VitMatteForImageMatting,VitMatteImageProcessor:()=>z.VitMatteImageProcessor,VitMattePreTrainedModel:()=>r.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>r.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>z.VitPoseImageProcessor,VitPosePreTrainedModel:()=>r.VitPosePreTrainedModel,VitsModel:()=>r.VitsModel,VitsModelOutput:()=>r.VitsModelOutput,VitsPreTrainedModel:()=>r.VitsPreTrainedModel,VitsTokenizer:()=>w.VitsTokenizer,VoxtralForConditionalGeneration:()=>r.VoxtralForConditionalGeneration,VoxtralProcessor:()=>j.VoxtralProcessor,Wav2Vec2BertForCTC:()=>r.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>r.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>r.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>r.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>w.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>b.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>r.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>r.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>r.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>r.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>r.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>j.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>j.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>r.WavLMForAudioFrameClassification,WavLMForCTC:()=>r.WavLMForCTC,WavLMForSequenceClassification:()=>r.WavLMForSequenceClassification,WavLMForXVector:()=>r.WavLMForXVector,WavLMModel:()=>r.WavLMModel,WavLMPreTrainedModel:()=>r.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>b.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>r.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>r.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>b.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>r.WhisperForConditionalGeneration,WhisperModel:()=>r.WhisperModel,WhisperPreTrainedModel:()=>r.WhisperPreTrainedModel,WhisperProcessor:()=>j.WhisperProcessor,WhisperTextStreamer:()=>Y.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>S.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>w.WhisperTokenizer,XLMForQuestionAnswering:()=>r.XLMForQuestionAnswering,XLMForSequenceClassification:()=>r.XLMForSequenceClassification,XLMForTokenClassification:()=>r.XLMForTokenClassification,XLMModel:()=>r.XLMModel,XLMPreTrainedModel:()=>r.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>r.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>r.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>r.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>r.XLMRobertaForTokenClassification,XLMRobertaModel:()=>r.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>r.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>w.XLMRobertaTokenizer,XLMTokenizer:()=>w.XLMTokenizer,XLMWithLMHeadModel:()=>r.XLMWithLMHeadModel,XVectorOutput:()=>r.XVectorOutput,YolosFeatureExtractor:()=>z.YolosFeatureExtractor,YolosForObjectDetection:()=>r.YolosForObjectDetection,YolosImageProcessor:()=>z.YolosImageProcessor,YolosModel:()=>r.YolosModel,YolosObjectDetectionOutput:()=>r.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>r.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>m.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>m.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>m.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>m.ZeroShotObjectDetectionPipeline,bankers_round:()=>I.bankers_round,cat:()=>_.cat,cos_sim:()=>I.cos_sim,dot:()=>I.dot,dynamic_time_warping:()=>I.dynamic_time_warping,env:()=>ae.env,full:()=>_.full,full_like:()=>_.full_like,getCacheShapes:()=>T.getCacheShapes,hamming:()=>L.hamming,hanning:()=>L.hanning,interpolate:()=>_.interpolate,interpolate_4d:()=>_.interpolate_4d,interpolate_data:()=>I.interpolate_data,is_chinese_char:()=>w.is_chinese_char,layer_norm:()=>_.layer_norm,load_image:()=>H.load_image,load_video:()=>$.load_video,log_softmax:()=>I.log_softmax,magnitude:()=>I.magnitude,matmul:()=>_.matmul,max:()=>I.max,mean:()=>_.mean,mean_pooling:()=>_.mean_pooling,medianFilter:()=>I.medianFilter,mel_filter_bank:()=>L.mel_filter_bank,min:()=>I.min,ones:()=>_.ones,ones_like:()=>_.ones_like,permute:()=>_.permute,permute_data:()=>I.permute_data,pipeline:()=>m.pipeline,quantize_embeddings:()=>_.quantize_embeddings,rand:()=>_.rand,read_audio:()=>L.read_audio,rfft:()=>_.rfft,round:()=>I.round,slice:()=>_.slice,softmax:()=>I.softmax,spectrogram:()=>L.spectrogram,stack:()=>_.stack,std_mean:()=>_.std_mean,topk:()=>_.topk,window_function:()=>L.window_function,zeros:()=>_.zeros,zeros_like:()=>_.zeros_like});var ae=ts("./src/env.js"),m=ts("./src/pipelines.js"),r=ts("./src/models.js"),w=ts("./src/tokenizers.js"),T=ts("./src/configs.js"),L=ts("./src/utils/audio.js"),H=ts("./src/utils/image.js"),$=ts("./src/utils/video.js"),_=ts("./src/utils/tensor.js"),I=ts("./src/utils/maths.js"),D=ts("./src/base/feature_extraction_utils.js"),b=ts("./src/models/feature_extractors.js"),h=ts("./src/models/auto/feature_extraction_auto.js"),U=ts("./src/base/image_processors_utils.js"),z=ts("./src/models/image_processors.js"),Q=ts("./src/models/auto/image_processing_auto.js"),ge=ts("./src/base/processing_utils.js"),j=ts("./src/models/processors.js"),G=ts("./src/models/auto/processing_auto.js"),Y=ts("./src/generation/streamers.js"),O=ts("./src/generation/stopping_criteria.js"),S=ts("./src/generation/logits_process.js")})(),l.ASTFeatureExtractor,l.ASTForAudioClassification,l.ASTModel,l.ASTPreTrainedModel,l.AlbertForMaskedLM,l.AlbertForQuestionAnswering,l.AlbertForSequenceClassification,l.AlbertModel,l.AlbertPreTrainedModel,l.AlbertTokenizer,l.ArceeForCausalLM,l.ArceeModel,l.ArceePreTrainedModel,l.AudioClassificationPipeline,l.AutoConfig,l.AutoFeatureExtractor,l.AutoImageProcessor,l.AutoModel,l.AutoModelForAudioClassification,l.AutoModelForAudioFrameClassification,l.AutoModelForAudioTextToText,l.AutoModelForCTC,l.AutoModelForCausalLM,l.AutoModelForDepthEstimation,l.AutoModelForDocumentQuestionAnswering,l.AutoModelForImageClassification,l.AutoModelForImageFeatureExtraction,l.AutoModelForImageMatting,l.AutoModelForImageSegmentation,l.AutoModelForImageTextToText,l.AutoModelForImageToImage,l.AutoModelForMaskGeneration,l.AutoModelForMaskedLM,l.AutoModelForNormalEstimation,l.AutoModelForObjectDetection,l.AutoModelForPoseEstimation,l.AutoModelForQuestionAnswering,l.AutoModelForSemanticSegmentation,l.AutoModelForSeq2SeqLM,l.AutoModelForSequenceClassification,l.AutoModelForSpeechSeq2Seq,l.AutoModelForTextToSpectrogram,l.AutoModelForTextToWaveform,l.AutoModelForTokenClassification,l.AutoModelForUniversalSegmentation,l.AutoModelForVision2Seq,l.AutoModelForXVector,l.AutoModelForZeroShotObjectDetection,l.AutoProcessor;var lh=l.AutoTokenizer;l.AutomaticSpeechRecognitionPipeline,l.BackgroundRemovalPipeline,l.BartForConditionalGeneration,l.BartForSequenceClassification,l.BartModel,l.BartPretrainedModel,l.BartTokenizer,l.BaseModelOutput,l.BaseStreamer,l.BeitFeatureExtractor,l.BeitForImageClassification,l.BeitModel,l.BeitPreTrainedModel,l.BertForMaskedLM,l.BertForQuestionAnswering,l.BertForSequenceClassification,l.BertForTokenClassification,l.BertModel,l.BertPreTrainedModel,l.BertTokenizer,l.BitImageProcessor,l.BlenderbotForConditionalGeneration,l.BlenderbotModel,l.BlenderbotPreTrainedModel,l.BlenderbotSmallForConditionalGeneration,l.BlenderbotSmallModel,l.BlenderbotSmallPreTrainedModel,l.BlenderbotSmallTokenizer,l.BlenderbotTokenizer,l.BloomForCausalLM,l.BloomModel,l.BloomPreTrainedModel,l.BloomTokenizer,l.CLIPFeatureExtractor,l.CLIPImageProcessor,l.CLIPModel,l.CLIPPreTrainedModel,l.CLIPSegForImageSegmentation,l.CLIPSegModel,l.CLIPSegPreTrainedModel,l.CLIPTextModel,l.CLIPTextModelWithProjection,l.CLIPTokenizer,l.CLIPVisionModel,l.CLIPVisionModelWithProjection,l.CamembertForMaskedLM,l.CamembertForQuestionAnswering,l.CamembertForSequenceClassification,l.CamembertForTokenClassification,l.CamembertModel,l.CamembertPreTrainedModel,l.CamembertTokenizer,l.CausalLMOutput,l.CausalLMOutputWithPast,l.ChineseCLIPFeatureExtractor,l.ChineseCLIPModel,l.ChineseCLIPPreTrainedModel,l.ClapAudioModelWithProjection,l.ClapFeatureExtractor,l.ClapModel,l.ClapPreTrainedModel,l.ClapTextModelWithProjection,l.ClassifierFreeGuidanceLogitsProcessor,l.CodeGenForCausalLM,l.CodeGenModel,l.CodeGenPreTrainedModel,l.CodeGenTokenizer,l.CodeLlamaTokenizer,l.CohereForCausalLM,l.CohereModel,l.CoherePreTrainedModel,l.CohereTokenizer,l.ConvBertForMaskedLM,l.ConvBertForQuestionAnswering,l.ConvBertForSequenceClassification,l.ConvBertForTokenClassification,l.ConvBertModel,l.ConvBertPreTrainedModel,l.ConvBertTokenizer,l.ConvNextFeatureExtractor,l.ConvNextForImageClassification,l.ConvNextImageProcessor,l.ConvNextModel,l.ConvNextPreTrainedModel,l.ConvNextV2ForImageClassification,l.ConvNextV2Model,l.ConvNextV2PreTrainedModel,l.DFineForObjectDetection,l.DFineModel,l.DFinePreTrainedModel,l.DINOv3ConvNextModel,l.DINOv3ConvNextPreTrainedModel,l.DINOv3ViTImageProcessor,l.DINOv3ViTModel,l.DINOv3ViTPreTrainedModel,l.DPTFeatureExtractor,l.DPTForDepthEstimation,l.DPTImageProcessor,l.DPTModel,l.DPTPreTrainedModel,l.DacDecoderModel,l.DacDecoderOutput,l.DacEncoderModel,l.DacEncoderOutput,l.DacFeatureExtractor,l.DacModel,l.DacPreTrainedModel,l.DataTypeMap,l.DebertaForMaskedLM,l.DebertaForQuestionAnswering,l.DebertaForSequenceClassification,l.DebertaForTokenClassification,l.DebertaModel,l.DebertaPreTrainedModel,l.DebertaTokenizer,l.DebertaV2ForMaskedLM,l.DebertaV2ForQuestionAnswering,l.DebertaV2ForSequenceClassification,l.DebertaV2ForTokenClassification,l.DebertaV2Model,l.DebertaV2PreTrainedModel,l.DebertaV2Tokenizer,l.DecisionTransformerModel,l.DecisionTransformerPreTrainedModel,l.DeiTFeatureExtractor,l.DeiTForImageClassification,l.DeiTImageProcessor,l.DeiTModel,l.DeiTPreTrainedModel,l.DepthAnythingForDepthEstimation,l.DepthAnythingPreTrainedModel,l.DepthEstimationPipeline,l.DepthProForDepthEstimation,l.DepthProPreTrainedModel,l.DetrFeatureExtractor,l.DetrForObjectDetection,l.DetrForSegmentation,l.DetrImageProcessor,l.DetrModel,l.DetrObjectDetectionOutput,l.DetrPreTrainedModel,l.DetrSegmentationOutput,l.Dinov2ForImageClassification,l.Dinov2Model,l.Dinov2PreTrainedModel,l.Dinov2WithRegistersForImageClassification,l.Dinov2WithRegistersModel,l.Dinov2WithRegistersPreTrainedModel,l.DistilBertForMaskedLM,l.DistilBertForQuestionAnswering,l.DistilBertForSequenceClassification,l.DistilBertForTokenClassification,l.DistilBertModel,l.DistilBertPreTrainedModel,l.DistilBertTokenizer,l.DocumentQuestionAnsweringPipeline,l.DonutFeatureExtractor,l.DonutImageProcessor,l.DonutSwinModel,l.DonutSwinPreTrainedModel,l.EfficientNetForImageClassification,l.EfficientNetImageProcessor,l.EfficientNetModel,l.EfficientNetPreTrainedModel,l.ElectraForMaskedLM,l.ElectraForQuestionAnswering,l.ElectraForSequenceClassification,l.ElectraForTokenClassification,l.ElectraModel,l.ElectraPreTrainedModel,l.ElectraTokenizer,l.EncodecFeatureExtractor,l.EosTokenCriteria,l.Ernie4_5_ForCausalLM,l.Ernie4_5_Model,l.Ernie4_5_PretrainedModel,l.Ernie4_5_Tokenizer,l.EsmForMaskedLM,l.EsmForSequenceClassification,l.EsmForTokenClassification,l.EsmModel,l.EsmPreTrainedModel,l.EsmTokenizer,l.ExaoneForCausalLM,l.ExaoneModel,l.ExaonePreTrainedModel,l.FFT,l.FalconForCausalLM,l.FalconModel,l.FalconPreTrainedModel,l.FalconTokenizer,l.FastViTForImageClassification,l.FastViTModel,l.FastViTPreTrainedModel,l.FeatureExtractionPipeline,l.FeatureExtractor,l.FillMaskPipeline,l.Florence2ForConditionalGeneration,l.Florence2PreTrainedModel,l.Florence2Processor,l.ForcedBOSTokenLogitsProcessor,l.ForcedEOSTokenLogitsProcessor,l.GLPNFeatureExtractor,l.GLPNForDepthEstimation,l.GLPNModel,l.GLPNPreTrainedModel,l.GPT2LMHeadModel,l.GPT2Model,l.GPT2PreTrainedModel,l.GPT2Tokenizer,l.GPTBigCodeForCausalLM,l.GPTBigCodeModel,l.GPTBigCodePreTrainedModel,l.GPTJForCausalLM,l.GPTJModel,l.GPTJPreTrainedModel,l.GPTNeoForCausalLM,l.GPTNeoModel,l.GPTNeoPreTrainedModel,l.GPTNeoXForCausalLM,l.GPTNeoXModel,l.GPTNeoXPreTrainedModel,l.GPTNeoXTokenizer,l.Gemma2ForCausalLM,l.Gemma2Model,l.Gemma2PreTrainedModel,l.Gemma3ForCausalLM,l.Gemma3Model,l.Gemma3PreTrainedModel,l.Gemma3nAudioFeatureExtractor,l.Gemma3nForConditionalGeneration,l.Gemma3nPreTrainedModel,l.Gemma3nProcessor,l.GemmaForCausalLM,l.GemmaModel,l.GemmaPreTrainedModel,l.GemmaTokenizer,l.GlmForCausalLM,l.GlmModel,l.GlmPreTrainedModel,l.GraniteForCausalLM,l.GraniteModel,l.GranitePreTrainedModel,l.Grok1Tokenizer,l.GroundingDinoForObjectDetection,l.GroundingDinoImageProcessor,l.GroundingDinoPreTrainedModel,l.GroundingDinoProcessor,l.GroupViTModel,l.GroupViTPreTrainedModel,l.HeliumForCausalLM,l.HeliumModel,l.HeliumPreTrainedModel,l.HerbertTokenizer,l.HieraForImageClassification,l.HieraModel,l.HieraPreTrainedModel,l.HubertForCTC,l.HubertForSequenceClassification,l.HubertModel,l.HubertPreTrainedModel,l.IJepaForImageClassification,l.IJepaModel,l.IJepaPreTrainedModel,l.Idefics3ForConditionalGeneration,l.Idefics3ImageProcessor,l.Idefics3PreTrainedModel,l.Idefics3Processor,l.ImageClassificationPipeline,l.ImageFeatureExtractionPipeline,l.ImageFeatureExtractor,l.ImageMattingOutput,l.ImageProcessor,l.ImageSegmentationPipeline,l.ImageToImagePipeline,l.ImageToTextPipeline,l.InterruptableStoppingCriteria,l.JAISLMHeadModel,l.JAISModel,l.JAISPreTrainedModel,l.JinaCLIPImageProcessor,l.JinaCLIPModel,l.JinaCLIPPreTrainedModel,l.JinaCLIPProcessor,l.JinaCLIPTextModel,l.JinaCLIPVisionModel,l.Lfm2ForCausalLM,l.Lfm2Model,l.Lfm2PreTrainedModel,l.LiteWhisperForConditionalGeneration,l.LlamaForCausalLM,l.LlamaModel,l.LlamaPreTrainedModel,l.LlamaTokenizer,l.LlavaForConditionalGeneration,l.LlavaOnevisionForConditionalGeneration,l.LlavaOnevisionImageProcessor,l.LlavaPreTrainedModel,l.LlavaProcessor,l.LlavaQwen2ForCausalLM,l.LogitsProcessor,l.LogitsProcessorList,l.LogitsWarper,l.LongT5ForConditionalGeneration,l.LongT5Model,l.LongT5PreTrainedModel,l.M2M100ForConditionalGeneration,l.M2M100Model,l.M2M100PreTrainedModel,l.M2M100Tokenizer,l.MBart50Tokenizer,l.MBartForCausalLM,l.MBartForConditionalGeneration,l.MBartForSequenceClassification,l.MBartModel,l.MBartPreTrainedModel,l.MBartTokenizer,l.MPNetForMaskedLM,l.MPNetForQuestionAnswering,l.MPNetForSequenceClassification,l.MPNetForTokenClassification,l.MPNetModel,l.MPNetPreTrainedModel,l.MPNetTokenizer,l.MT5ForConditionalGeneration,l.MT5Model,l.MT5PreTrainedModel,l.MarianMTModel,l.MarianModel,l.MarianPreTrainedModel,l.MarianTokenizer,l.Mask2FormerImageProcessor,l.MaskFormerFeatureExtractor,l.MaskFormerForInstanceSegmentation,l.MaskFormerImageProcessor,l.MaskFormerModel,l.MaskFormerPreTrainedModel,l.MaskedLMOutput,l.MaxLengthCriteria,l.Metric3DForDepthEstimation,l.Metric3DPreTrainedModel,l.Metric3Dv2ForDepthEstimation,l.Metric3Dv2PreTrainedModel,l.MgpstrForSceneTextRecognition,l.MgpstrModelOutput,l.MgpstrPreTrainedModel,l.MgpstrProcessor,l.MgpstrTokenizer,l.MimiDecoderModel,l.MimiDecoderOutput,l.MimiEncoderModel,l.MimiEncoderOutput,l.MimiModel,l.MimiPreTrainedModel,l.MinLengthLogitsProcessor,l.MinNewTokensLengthLogitsProcessor,l.MistralForCausalLM,l.MistralModel,l.MistralPreTrainedModel,l.MobileBertForMaskedLM,l.MobileBertForQuestionAnswering,l.MobileBertForSequenceClassification,l.MobileBertModel,l.MobileBertPreTrainedModel,l.MobileBertTokenizer,l.MobileLLMForCausalLM,l.MobileLLMModel,l.MobileLLMPreTrainedModel,l.MobileNetV1FeatureExtractor,l.MobileNetV1ForImageClassification,l.MobileNetV1ForSemanticSegmentation,l.MobileNetV1ImageProcessor,l.MobileNetV1Model,l.MobileNetV1PreTrainedModel,l.MobileNetV2FeatureExtractor,l.MobileNetV2ForImageClassification,l.MobileNetV2ForSemanticSegmentation,l.MobileNetV2ImageProcessor,l.MobileNetV2Model,l.MobileNetV2PreTrainedModel,l.MobileNetV3FeatureExtractor,l.MobileNetV3ForImageClassification,l.MobileNetV3ForSemanticSegmentation,l.MobileNetV3ImageProcessor,l.MobileNetV3Model,l.MobileNetV3PreTrainedModel,l.MobileNetV4FeatureExtractor,l.MobileNetV4ForImageClassification,l.MobileNetV4ForSemanticSegmentation,l.MobileNetV4ImageProcessor,l.MobileNetV4Model,l.MobileNetV4PreTrainedModel,l.MobileViTFeatureExtractor,l.MobileViTForImageClassification,l.MobileViTImageProcessor,l.MobileViTModel,l.MobileViTPreTrainedModel,l.MobileViTV2ForImageClassification,l.MobileViTV2Model,l.MobileViTV2PreTrainedModel,l.ModelOutput,l.ModernBertDecoderForCausalLM,l.ModernBertDecoderModel,l.ModernBertDecoderPreTrainedModel,l.ModernBertForMaskedLM,l.ModernBertForSequenceClassification,l.ModernBertForTokenClassification,l.ModernBertModel,l.ModernBertPreTrainedModel,l.Moondream1ForConditionalGeneration,l.MoonshineFeatureExtractor,l.MoonshineForConditionalGeneration,l.MoonshineModel,l.MoonshinePreTrainedModel,l.MoonshineProcessor,l.MptForCausalLM,l.MptModel,l.MptPreTrainedModel,l.MultiModalityCausalLM,l.MultiModalityPreTrainedModel,l.MusicgenForCausalLM,l.MusicgenForConditionalGeneration,l.MusicgenModel,l.MusicgenPreTrainedModel,l.NeoBertForMaskedLM,l.NeoBertForQuestionAnswering,l.NeoBertForSequenceClassification,l.NeoBertForTokenClassification,l.NeoBertModel,l.NeoBertPreTrainedModel,l.NllbTokenizer,l.NoBadWordsLogitsProcessor,l.NoRepeatNGramLogitsProcessor,l.NomicBertModel,l.NomicBertPreTrainedModel,l.NougatImageProcessor,l.NougatTokenizer,l.OPTForCausalLM,l.OPTModel,l.OPTPreTrainedModel,l.ObjectDetectionPipeline,l.Olmo2ForCausalLM,l.Olmo2Model,l.Olmo2PreTrainedModel,l.OlmoForCausalLM,l.OlmoModel,l.OlmoPreTrainedModel,l.OpenELMForCausalLM,l.OpenELMModel,l.OpenELMPreTrainedModel,l.OwlViTFeatureExtractor,l.OwlViTForObjectDetection,l.OwlViTImageProcessor,l.OwlViTModel,l.OwlViTPreTrainedModel,l.OwlViTProcessor,l.Owlv2ForObjectDetection,l.Owlv2ImageProcessor,l.Owlv2Model,l.Owlv2PreTrainedModel,l.PaliGemmaForConditionalGeneration,l.PaliGemmaPreTrainedModel,l.PaliGemmaProcessor,l.PatchTSMixerForPrediction,l.PatchTSMixerModel,l.PatchTSMixerPreTrainedModel,l.PatchTSTForPrediction,l.PatchTSTModel,l.PatchTSTPreTrainedModel,l.Phi3ForCausalLM,l.Phi3Model,l.Phi3PreTrainedModel,l.Phi3VForCausalLM,l.Phi3VImageProcessor,l.Phi3VPreTrainedModel,l.Phi3VProcessor,l.PhiForCausalLM,l.PhiModel,l.PhiPreTrainedModel,l.Pipeline,l.PreTrainedModel,l.PreTrainedTokenizer,l.PretrainedConfig,l.PretrainedMixin,l.Processor,l.PvtForImageClassification,l.PvtImageProcessor,l.PvtModel,l.PvtPreTrainedModel,l.PyAnnoteFeatureExtractor,l.PyAnnoteForAudioFrameClassification,l.PyAnnoteModel,l.PyAnnotePreTrainedModel,l.PyAnnoteProcessor,l.QuestionAnsweringModelOutput,l.QuestionAnsweringPipeline,l.Qwen2ForCausalLM,l.Qwen2Model,l.Qwen2PreTrainedModel,l.Qwen2Tokenizer,l.Qwen2VLForConditionalGeneration,l.Qwen2VLImageProcessor,l.Qwen2VLPreTrainedModel,l.Qwen2VLProcessor,l.Qwen3ForCausalLM,l.Qwen3Model,l.Qwen3PreTrainedModel,l.RFDetrForObjectDetection,l.RFDetrModel,l.RFDetrObjectDetectionOutput,l.RFDetrPreTrainedModel,l.RTDetrForObjectDetection,l.RTDetrImageProcessor,l.RTDetrModel,l.RTDetrObjectDetectionOutput,l.RTDetrPreTrainedModel,l.RTDetrV2ForObjectDetection,l.RTDetrV2Model,l.RTDetrV2ObjectDetectionOutput,l.RTDetrV2PreTrainedModel,l.RawAudio,l.RawImage,l.RawVideo,l.RawVideoFrame,l.RepetitionPenaltyLogitsProcessor,l.ResNetForImageClassification,l.ResNetModel,l.ResNetPreTrainedModel,l.RoFormerForMaskedLM,l.RoFormerForQuestionAnswering,l.RoFormerForSequenceClassification,l.RoFormerForTokenClassification,l.RoFormerModel,l.RoFormerPreTrainedModel,l.RoFormerTokenizer,l.RobertaForMaskedLM,l.RobertaForQuestionAnswering,l.RobertaForSequenceClassification,l.RobertaForTokenClassification,l.RobertaModel,l.RobertaPreTrainedModel,l.RobertaTokenizer,l.SamImageProcessor,l.SamImageSegmentationOutput,l.SamModel,l.SamPreTrainedModel,l.SamProcessor,l.SapiensForDepthEstimation,l.SapiensForNormalEstimation,l.SapiensForSemanticSegmentation,l.SapiensPreTrainedModel,l.SeamlessM4TFeatureExtractor,l.SegformerFeatureExtractor,l.SegformerForImageClassification,l.SegformerForSemanticSegmentation,l.SegformerImageProcessor,l.SegformerModel,l.SegformerPreTrainedModel,l.Seq2SeqLMOutput,l.SequenceClassifierOutput,l.SiglipImageProcessor,l.SiglipModel,l.SiglipPreTrainedModel,l.SiglipTextModel,l.SiglipTokenizer,l.SiglipVisionModel,l.SmolLM3ForCausalLM,l.SmolLM3Model,l.SmolLM3PreTrainedModel,l.SmolVLMForConditionalGeneration,l.SmolVLMImageProcessor,l.SmolVLMProcessor,l.SnacDecoderModel,l.SnacEncoderModel,l.SnacFeatureExtractor,l.SnacModel,l.SnacPreTrainedModel,l.SpeechT5FeatureExtractor,l.SpeechT5ForSpeechToText,l.SpeechT5ForTextToSpeech,l.SpeechT5HifiGan,l.SpeechT5Model,l.SpeechT5PreTrainedModel,l.SpeechT5Processor,l.SpeechT5Tokenizer,l.SqueezeBertForMaskedLM,l.SqueezeBertForQuestionAnswering,l.SqueezeBertForSequenceClassification,l.SqueezeBertModel,l.SqueezeBertPreTrainedModel,l.SqueezeBertTokenizer,l.StableLmForCausalLM,l.StableLmModel,l.StableLmPreTrainedModel,l.Starcoder2ForCausalLM,l.Starcoder2Model,l.Starcoder2PreTrainedModel,l.StoppingCriteria,l.StoppingCriteriaList,l.StyleTextToSpeech2Model,l.StyleTextToSpeech2PreTrainedModel,l.SummarizationPipeline,l.SuppressTokensAtBeginLogitsProcessor,l.Swin2SRForImageSuperResolution,l.Swin2SRImageProcessor,l.Swin2SRModel,l.Swin2SRPreTrainedModel,l.SwinForImageClassification,l.SwinForSemanticSegmentation,l.SwinModel,l.SwinPreTrainedModel,l.T5ForConditionalGeneration,l.T5Model,l.T5PreTrainedModel,l.T5Tokenizer,l.TableTransformerForObjectDetection,l.TableTransformerModel,l.TableTransformerObjectDetectionOutput,l.TableTransformerPreTrainedModel,l.TemperatureLogitsWarper,l.Tensor,l.Text2TextGenerationPipeline,l.TextClassificationPipeline,l.TextGenerationPipeline,l.TextStreamer,l.TextToAudioPipeline,l.TokenClassificationPipeline,l.TokenClassifierOutput,l.TokenizerModel,l.TopKLogitsWarper,l.TopPLogitsWarper,l.TrOCRForCausalLM,l.TrOCRPreTrainedModel,l.TranslationPipeline,l.UltravoxModel,l.UltravoxPreTrainedModel,l.UltravoxProcessor,l.UniSpeechForCTC,l.UniSpeechForSequenceClassification,l.UniSpeechModel,l.UniSpeechPreTrainedModel,l.UniSpeechSatForAudioFrameClassification,l.UniSpeechSatForCTC,l.UniSpeechSatForSequenceClassification,l.UniSpeechSatModel,l.UniSpeechSatPreTrainedModel,l.VLChatProcessor,l.VLMImageProcessor,l.ViTFeatureExtractor,l.ViTForImageClassification,l.ViTImageProcessor,l.ViTMAEModel,l.ViTMAEPreTrainedModel,l.ViTMSNForImageClassification,l.ViTMSNModel,l.ViTMSNPreTrainedModel,l.ViTModel,l.ViTPreTrainedModel,l.VisionEncoderDecoderModel,l.VitMatteForImageMatting,l.VitMatteImageProcessor,l.VitMattePreTrainedModel,l.VitPoseForPoseEstimation,l.VitPoseImageProcessor,l.VitPosePreTrainedModel,l.VitsModel,l.VitsModelOutput,l.VitsPreTrainedModel,l.VitsTokenizer,l.VoxtralForConditionalGeneration,l.VoxtralProcessor,l.Wav2Vec2BertForCTC,l.Wav2Vec2BertForSequenceClassification,l.Wav2Vec2BertModel,l.Wav2Vec2BertPreTrainedModel,l.Wav2Vec2CTCTokenizer,l.Wav2Vec2FeatureExtractor,l.Wav2Vec2ForAudioFrameClassification,l.Wav2Vec2ForCTC,l.Wav2Vec2ForSequenceClassification,l.Wav2Vec2Model,l.Wav2Vec2PreTrainedModel,l.Wav2Vec2Processor,l.Wav2Vec2ProcessorWithLM,l.WavLMForAudioFrameClassification,l.WavLMForCTC,l.WavLMForSequenceClassification,l.WavLMForXVector,l.WavLMModel,l.WavLMPreTrainedModel,l.WeSpeakerFeatureExtractor,l.WeSpeakerResNetModel,l.WeSpeakerResNetPreTrainedModel,l.WhisperFeatureExtractor,l.WhisperForConditionalGeneration,l.WhisperModel,l.WhisperPreTrainedModel,l.WhisperProcessor,l.WhisperTextStreamer,l.WhisperTimeStampLogitsProcessor,l.WhisperTokenizer,l.XLMForQuestionAnswering,l.XLMForSequenceClassification,l.XLMForTokenClassification,l.XLMModel,l.XLMPreTrainedModel,l.XLMRobertaForMaskedLM,l.XLMRobertaForQuestionAnswering,l.XLMRobertaForSequenceClassification,l.XLMRobertaForTokenClassification,l.XLMRobertaModel,l.XLMRobertaPreTrainedModel,l.XLMRobertaTokenizer,l.XLMTokenizer,l.XLMWithLMHeadModel,l.XVectorOutput,l.YolosFeatureExtractor,l.YolosForObjectDetection,l.YolosImageProcessor,l.YolosModel,l.YolosObjectDetectionOutput,l.YolosPreTrainedModel,l.ZeroShotAudioClassificationPipeline,l.ZeroShotClassificationPipeline,l.ZeroShotImageClassificationPipeline,l.ZeroShotObjectDetectionPipeline,l.bankers_round,l.cat,l.cos_sim,l.dot,l.dynamic_time_warping;var ch=l.env;l.full,l.full_like,l.getCacheShapes,l.hamming,l.hanning,l.interpolate,l.interpolate_4d,l.interpolate_data,l.is_chinese_char,l.layer_norm,l.load_image,l.load_video,l.log_softmax,l.magnitude,l.matmul,l.max,l.mean,l.mean_pooling,l.medianFilter,l.mel_filter_bank,l.min,l.ones,l.ones_like,l.permute,l.permute_data,l.pipeline,l.quantize_embeddings,l.rand,l.read_audio,l.rfft,l.round,l.slice,l.softmax,l.spectrogram,l.stack,l.std_mean,l.topk,l.window_function,l.zeros,l.zeros_like,ch.allowLocalModels=!1;const Bp=new Map;self.addEventListener("message",async ae=>{let m=Bp.get(ae.data.model_id);m||(m=lh.from_pretrained(ae.data.model_id),Bp.set(ae.data.model_id,new Promise(I=>{m.then(D=>{switch(D.constructor.name){case"LlamaTokenizer":case"Grok1Tokenizer":D.decoder.decoders.pop();break;case"T5Tokenizer":D.decoder.addPrefixSpace=!1;break}I(D)})})));const r=await m,w=ae.data.text,T=performance.now(),L=r.encode(w),H=performance.now();console.log("[INFO]",`Tokenized ${w.length} characters in ${(H-T).toFixed(2)}ms`);let $=L.map(I=>r.decode([I])),_=[];switch(r.constructor.name){case"BertTokenizer":_=$.map((I,D)=>D===0||I.startsWith("##")?0:8),$=$.map(I=>I.replace("##",""));break;case"T5Tokenizer":$.length>0&&$.length!==" "&&($[0]=$[0].replace(/^ /,""));break}self.postMessage({token_ids:L,decoded:$,margins:_})})})();