diff --git "a/assets/worker-CUJZWIcI.js" "b/assets/worker-CUJZWIcI.js" new file mode 100644--- /dev/null +++ "b/assets/worker-CUJZWIcI.js" @@ -0,0 +1,2846 @@ +var Gb=Object.defineProperty;var Kb=(e,r,t)=>r in e?Gb(e,r,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[r]=t;var re=(e,r,t)=>Kb(e,typeof r!="symbol"?r+"":r,t);const ed=new Map,Sn=[],Hb=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){const s=ed.get(e);if(s===void 0)ed.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){const i=Sn.indexOf(e);i!==-1&&Sn.splice(i,1);for(let n=0;n{const r=ed.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{const t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},Rw=async e=>{const r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?Sn:t;let i;const n=[],o=new Set;for(const l of s){const d=await qb(l);typeof d=="string"?n.push({name:l,err:d}):(i||(i=d),i===d&&o.add(l))}if(!i)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(const{name:l,err:d}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${d}`);const a=r.filter(l=>o.has(typeof l=="string"?l:l.name));return[i,new Proxy(e,{get:(l,d)=>d==="executionProviders"?a:Reflect.get(l,d)})]},Qb="1.20.1";let rf="warning";const ws={wasm:{},webgl:{},webgpu:{},versions:{common:Qb},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}`);rf=e}},get logLevel(){return rf}};Object.defineProperty(ws,"logLevel",{enumerable:!0});const Xb=ws,Jb=(e,r)=>{const t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];const s=t.getContext("2d");if(s!=null){let i,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[3]):(i=e.dims[3],n=e.dims[2]);const o=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm;let l,d;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?d=[0,0,0,0]:typeof a.bias=="number"?d=[a.bias,a.bias,a.bias,a.bias]:(d=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(d[3]=a.bias[3]));const p=n*i;let u=0,h=p,w=p*2,_=-1;o==="RGBA"?(u=0,h=p,w=p*2,_=p*3):o==="RGB"?(u=0,h=p,w=p*2):o==="RBG"&&(u=0,w=p,h=p*2);for(let P=0;P{const t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d");let s;if(t!=null){let i,n,o;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[1],o=e.dims[3]):(i=e.dims[3],n=e.dims[2],o=e.dims[1]);const a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm;let d,p;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean=="number"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));const u=n*i;if(r!==void 0&&(r.format!==void 0&&o===4&&r.format!=="RGBA"||o===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");const h=4;let w=0,_=1,P=2,A=3,v=0,y=u,S=u*2,x=-1;a==="RGBA"?(v=0,y=u,S=u*2,x=u*3):a==="RGB"?(v=0,y=u,S=u*2):a==="RBG"&&(v=0,S=u,y=u*2),s=t.createImageData(i,n);for(let g=0;g{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");const{height:t,width:s}=r,i=r.norm??{mean:255,bias:0};let n,o;typeof i.mean=="number"?n=[i.mean,i.mean,i.mean,i.mean]:n=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?o=[i.bias,i.bias,i.bias,i.bias]:o=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];const a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",d=t*s,p=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3);let u=4,h=0,w=1,_=2,P=3,A=0,v=d,y=d*2,S=-1;a==="RGB"&&(u=3,h=0,w=1,_=2,P=-1),l==="RGBA"?S=d*3:l==="RBG"?(A=0,y=d,v=d*2):l==="BGR"&&(y=0,v=d,A=d*2);for(let g=0;g{const t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string";let o,a=r??{};const l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},d=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){const p=l();p.width=e.width,p.height=e.height;const u=d(p);if(u!=null){let h=e.height,w=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(h=r.resizedHeight,w=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=h,a.width=w}else a.tensorFormat="RGBA",a.height=h,a.width=w;u.drawImage(e,0,0),o=u.getImageData(0,0,w,h).data}else throw new Error("Can not access image data")}else if(s){let p,u;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,u=r.resizedWidth):(p=e.height,u=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=u,r!==void 0){const h=l();h.width=u,h.height=p;const w=d(h);if(w!=null)w.putImageData(e,0,0),o=w.getImageData(0,0,u,p).data;else throw new Error("Can not access image data")}else o=e.data}else if(i){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");const p=l();p.width=e.width,p.height=e.height;const u=d(p);if(u!=null){const h=e.height,w=e.width;return u.drawImage(e,0,0,w,h),o=u.getImageData(0,0,w,h).data,a.height=h,a.width=w,Qd(o,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,u)=>{const h=l(),w=d(h);if(!e||!w)return u();const _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{h.width=_.width,h.height=_.height,w.drawImage(_,0,0,h.width,h.height);const P=w.getImageData(0,0,h.width,h.height);a.height=h.height,a.width=h.width,p(Qd(P.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return Qd(o,a);throw new Error("Input data provided is not supported - aborted tensor creation")},ev=(e,r)=>{const{width:t,height:s,download:i,dispose:n}=r,o=[1,s,t,4];return new Jr({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:n})},tv=(e,r)=>{const{dataType:t,dims:s,download:i,dispose:n}=r;return new Jr({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:i,dispose:n})},rv=(e,r)=>{const{dataType:t,dims:s,download:i,dispose:n}=r;return new Jr({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:i,dispose:n})},sv=(e,r,t)=>new Jr({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]}),vi=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),td=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);let sf=!1;const nv=()=>{if(!sf){sf=!0;const e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=typeof Float16Array<"u"&&Float16Array.from;e&&(vi.set("int64",BigInt64Array),td.set(BigInt64Array,"int64")),r&&(vi.set("uint64",BigUint64Array),td.set(BigUint64Array,"uint64")),t?(vi.set("float16",Float16Array),td.set(Float16Array,"float16")):vi.set("float16",Uint16Array)}},iv=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Jr(e.type,e.data,r);case"cpu-pinned":return new Jr({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Jr({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Jr({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Jr({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}};let Jr=class{constructor(r,t,s){nv();let i,n;if(typeof r=="object"&&"location"in r)switch(this.dataLocation=r.location,i=r.type,n=r.dims,r.location){case"cpu-pinned":{const a=vi.get(i);if(!a)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(r.data instanceof a))throw new TypeError(`buffer should be of type ${a.name}`);this.cpuData=r.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=r.texture,this.downloader=r.download,this.disposer=r.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=r.gpuBuffer,this.downloader=r.download,this.disposer=r.dispose;break}case"ml-tensor":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint64"&&i!=="int8"&&i!=="uint8"&&i!=="bool")throw new TypeError(`unsupported type "${i}" to create tensor from MLTensor`);this.mlTensorData=r.mlTensor,this.downloader=r.download,this.disposer=r.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,l;if(typeof r=="string")if(i=r,l=s,r==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");a=t}else{const d=vi.get(r);if(d===void 0)throw new TypeError(`Unsupported tensor type: ${r}.`);if(Array.isArray(t)){if(r==="float16"&&d===Uint16Array||r==="uint4"||r==="int4")throw new TypeError(`Creating a ${r} tensor from number array is not supported. Please use ${d.name} as data.`);r==="uint64"||r==="int64"?a=d.from(t,BigInt):a=d.from(t)}else if(t instanceof d)a=t;else if(t instanceof Uint8ClampedArray)if(r==="uint8")a=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else throw new TypeError(`A ${i} tensor's data must be type of ${d}`)}else if(l=t,Array.isArray(r)){if(r.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");const d=typeof r[0];if(d==="string")i="string",a=r;else if(d==="boolean")i="bool",a=Uint8Array.from(r);else throw new TypeError(`Invalid element type of data array: ${d}.`)}else if(r instanceof Uint8ClampedArray)i="uint8",a=Uint8Array.from(r);else{const d=td.get(r.constructor);if(d===void 0)throw new TypeError(`Unsupported type for tensor data: ${r.constructor}.`);i=d,a=r}if(l===void 0)l=[a.length];else if(!Array.isArray(l))throw new TypeError("A tensor's dims must be a number array");n=l,this.cpuData=a,this.dataLocation="cpu"}const o=iv(n);if(this.cpuData&&o!==this.cpuData.length&&!((i==="uint4"||i==="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=i,this.dims=n,this.size=o}static async fromImage(r,t){return Zb(r,t)}static fromTexture(r,t){return ev(r,t)}static fromGpuBuffer(r,t){return tv(r,t)}static fromMLTensor(r,t){return rv(r,t)}static fromPinnedBuffer(r,t,s){return sv(r,t,s)}toDataURL(r){return Jb(this,r)}toImageData(r){return Yb(this,r)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(r){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;const t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,r&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(r){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return ov(this,r)}};const _s=Jr,Nw=(e,r)=>{(typeof ws.trace>"u"?!ws.wasm.trace:!ws.trace)||console.timeStamp(`${e}::ORT::${r}`)},jw=(e,r)=>{var i;const t=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[];let s=!1;for(let n=0;n{(typeof ws.trace>"u"?!ws.wasm.trace:!ws.trace)||jw("BEGIN",e)},Kc=e=>{(typeof ws.trace>"u"?!ws.wasm.trace:!ws.trace)||jw("END",e)};let av=class Uw{constructor(r){this.handler=r}async run(r,t,s){Gc();const i={};let n={};if(typeof r!="object"||r===null||r instanceof _s||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof _s)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(const d of t){if(typeof d!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(d)===-1)throw new RangeError(`'fetches' contains invalid output name: ${d}.`);i[d]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let d=!1;const p=Object.getOwnPropertyNames(t);for(const u of this.outputNames)if(p.indexOf(u)!==-1){const h=t[u];(h===null||h instanceof _s)&&(d=!0,o=!1,i[u]=h)}if(d){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const d of this.inputNames)if(typeof r[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(o)for(const d of this.outputNames)i[d]=null;const a=await this.handler.run(r,i,n),l={};for(const d in a)if(Object.hasOwnProperty.call(a,d)){const p=a[d];p instanceof _s?l[d]=p:l[d]=new _s(p.type,p.data,p.dims)}return Kc(),l}async release(){return this.handler.dispose()}static async create(r,t,s,i){Gc();let n,o={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)o=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)o=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){const p=r;let u=0,h=r.byteLength;if(typeof t=="object"&&t!==null)o=t;else if(typeof t=="number"){if(u=t,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(h=r.byteLength-u,typeof s=="number"){if(h=s,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||u+h>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-u}].`);if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,u,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");const[a,l]=await Rw(o),d=await a.createInferenceSessionHandler(n,l);return Kc(),new Uw(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}};const lv=av,dv="Training backend could not be resolved. Make sure you're using the correct configuration & WebAssembly files.";let cv=class Vw{constructor(r,t,s){this.handler=r,this.hasOptimizerModel=t,this.hasEvalModel=s}get trainingInputNames(){return this.handler.inputNames}get trainingOutputNames(){return this.handler.outputNames}get evalInputNames(){if(this.hasEvalModel)return this.handler.evalInputNames;throw new Error("This training session has no evalModel loaded.")}get evalOutputNames(){if(this.hasEvalModel)return this.handler.evalOutputNames;throw new Error("This training session has no evalModel loaded.")}static async create(r,t){const s=r.evalModel||"",i=r.optimizerModel||"",n=t||{},[o,a]=await Rw(n);if(o.createTrainingSessionHandler){const l=await o.createTrainingSessionHandler(r.checkpointState,r.trainModel,s,i,a);return new Vw(l,!!r.optimizerModel,!!r.evalModel)}else throw new Error(dv)}typeNarrowingForRunStep(r,t,s,i,n){const o={};let a={};if(typeof s!="object"||s===null||s instanceof _s||Array.isArray(s))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let l=!0;if(typeof i=="object"){if(i===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(i instanceof _s)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(i)){if(i.length===0)throw new TypeError("'fetches' cannot be an empty array.");l=!1;for(const d of i){if(typeof d!="string")throw new TypeError("'fetches' must be a string array or an object.");if(t.indexOf(d)===-1)throw new RangeError(`'fetches' contains invalid output name: ${d}.`);o[d]=null}if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else{let d=!1;const p=Object.getOwnPropertyNames(i);for(const u of t)if(p.indexOf(u)!==-1){const h=i[u];(h===null||h instanceof _s)&&(d=!0,l=!1,o[u]=h)}if(d){if(typeof n=="object"&&n!==null)a=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else a=i}}else if(typeof i<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(const d of r)if(typeof s[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(l)for(const d of t)o[d]=null;return[o,a]}convertHandlerReturnTypeToMapOfTensors(r){const t={};for(const s in r)if(Object.hasOwnProperty.call(r,s)){const i=r[s];i instanceof _s?t[s]=i:t[s]=new _s(i.type,i.data,i.dims)}return t}async lazyResetGrad(){await this.handler.lazyResetGrad()}async runTrainStep(r,t,s){const[i,n]=this.typeNarrowingForRunStep(this.trainingInputNames,this.trainingOutputNames,r,t,s),o=await this.handler.runTrainStep(r,i,n);return this.convertHandlerReturnTypeToMapOfTensors(o)}async runOptimizerStep(r){if(this.hasOptimizerModel)await this.handler.runOptimizerStep(r||{});else throw new Error("This TrainingSession has no OptimizerModel loaded.")}async runEvalStep(r,t,s){if(this.hasEvalModel){const[i,n]=this.typeNarrowingForRunStep(this.evalInputNames,this.evalOutputNames,r,t,s),o=await this.handler.runEvalStep(r,i,n);return this.convertHandlerReturnTypeToMapOfTensors(o)}else throw new Error("This TrainingSession has no EvalModel loaded.")}async getParametersSize(r=!0){return this.handler.getParametersSize(r)}async loadParametersBuffer(r,t=!0){const s=await this.getParametersSize(t);if(r.length!==4*s)throw new Error("Size of the buffer passed into loadParametersBuffer must match the number of parameters in the model. Please use getParametersSize method to check.");return this.handler.loadParametersBuffer(r,t)}async getContiguousParameters(r=!0){return this.handler.getContiguousParameters(r)}async release(){return this.handler.dispose()}};const uv=cv;var pv=Object.freeze({__proto__:null,InferenceSession:lv,TRACE:Nw,TRACE_FUNC_BEGIN:Gc,TRACE_FUNC_END:Kc,Tensor:_s,TrainingSession:uv,env:Xb,registerBackend:Hb});/*! + * ONNX Runtime Web v1.22.0-dev.20250306-ccf8fdd9ea + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + */var cu=Object.defineProperty,hv=Object.getOwnPropertyDescriptor,mv=Object.getOwnPropertyNames,fv=Object.prototype.hasOwnProperty,_v=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),je=(e,r)=>()=>(e&&(r=e(e=0)),r),_a=(e,r)=>{for(var t in r)cu(e,t,{get:r[t],enumerable:!0})},gv=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of mv(r))!fv.call(e,i)&&i!==t&&cu(e,i,{get:()=>r[i],enumerable:!(s=hv(r,i))||s.enumerable});return e},nd=e=>gv(cu({},"__esModule",{value:!0}),e),Jo,an,An,nf,Ww,Gw=je(()=>{Jo=new Map,an=[],An=(e,r,t)=>{if(r&&typeof r.init=="function"&&typeof r.createInferenceSessionHandler=="function"){let s=Jo.get(e);if(s===void 0)Jo.set(e,{backend:r,priority:t});else{if(s.priority>t)return;if(s.priority===t&&s.backend!==r)throw new Error(`cannot register backend "${e}" using priority ${t}`)}if(t>=0){let i=an.indexOf(e);i!==-1&&an.splice(i,1);for(let n=0;n{let r=Jo.get(e);if(!r)return"backend not found.";if(r.initialized)return r.backend;if(r.aborted)return r.error;{let t=!!r.initPromise;try{return t||(r.initPromise=r.backend.init(e)),await r.initPromise,r.initialized=!0,r.backend}catch(s){return t||(r.error=`${s}`,r.aborted=!0),r.error}finally{delete r.initPromise}}},Ww=async e=>{let r=e.executionProviders||[],t=r.map(l=>typeof l=="string"?l:l.name),s=t.length===0?an:t,i,n=[],o=new Set;for(let l of s){let d=await nf(l);typeof d=="string"?n.push({name:l,err:d}):(i||(i=d),i===d&&o.add(l))}if(!i)throw new Error(`no available backend found. ERR: ${n.map(l=>`[${l.name}] ${l.err}`).join(", ")}`);for(let{name:l,err:d}of n)t.includes(l)&&console.warn(`removing requested execution provider "${l}" from session options because it is not available: ${d}`);let a=r.filter(l=>o.has(typeof l=="string"?l:l.name));return[i,new Proxy(e,{get:(l,d)=>d==="executionProviders"?a:Reflect.get(l,d)})]}}),wv=je(()=>{Gw()}),Kw,yv=je(()=>{Kw="1.22.0-dev.20250306-aafa8d170a"}),Xd,Xr,Hw=je(()=>{yv(),Xd="warning",Xr={wasm:{},webgl:{},webgpu:{},versions:{common:Kw},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}`);Xd=e}},get logLevel(){return Xd}},Object.defineProperty(Xr,"logLevel",{enumerable:!0})}),Kt,Mv=je(()=>{Hw(),Kt=Xr}),qw,Qw,bv=je(()=>{qw=(e,r)=>{let t=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);t.width=e.dims[3],t.height=e.dims[2];let s=t.getContext("2d");if(s!=null){let i,n;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[3]):(i=e.dims[3],n=e.dims[2]);let o=(r==null?void 0:r.format)!==void 0?r.format:"RGB",a=r==null?void 0:r.norm,l,d;a===void 0||a.mean===void 0?l=[255,255,255,255]:typeof a.mean=="number"?l=[a.mean,a.mean,a.mean,a.mean]:(l=[a.mean[0],a.mean[1],a.mean[2],0],a.mean[3]!==void 0&&(l[3]=a.mean[3])),a===void 0||a.bias===void 0?d=[0,0,0,0]:typeof a.bias=="number"?d=[a.bias,a.bias,a.bias,a.bias]:(d=[a.bias[0],a.bias[1],a.bias[2],0],a.bias[3]!==void 0&&(d[3]=a.bias[3]));let p=n*i,u=0,h=p,w=p*2,_=-1;o==="RGBA"?(u=0,h=p,w=p*2,_=p*3):o==="RGB"?(u=0,h=p,w=p*2):o==="RBG"&&(u=0,w=p,h=p*2);for(let P=0;P{let t=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),s;if(t!=null){let i,n,o;(r==null?void 0:r.tensorLayout)!==void 0&&r.tensorLayout==="NHWC"?(i=e.dims[2],n=e.dims[1],o=e.dims[3]):(i=e.dims[3],n=e.dims[2],o=e.dims[1]);let a=r!==void 0&&r.format!==void 0?r.format:"RGB",l=r==null?void 0:r.norm,d,p;l===void 0||l.mean===void 0?d=[255,255,255,255]:typeof l.mean=="number"?d=[l.mean,l.mean,l.mean,l.mean]:(d=[l.mean[0],l.mean[1],l.mean[2],255],l.mean[3]!==void 0&&(d[3]=l.mean[3])),l===void 0||l.bias===void 0?p=[0,0,0,0]:typeof l.bias=="number"?p=[l.bias,l.bias,l.bias,l.bias]:(p=[l.bias[0],l.bias[1],l.bias[2],0],l.bias[3]!==void 0&&(p[3]=l.bias[3]));let u=n*i;if(r!==void 0&&(r.format!==void 0&&o===4&&r.format!=="RGBA"||o===3&&r.format!=="RGB"&&r.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let h=4,w=0,_=1,P=2,A=3,v=0,y=u,S=u*2,x=-1;a==="RGBA"?(v=0,y=u,S=u*2,x=u*3):a==="RGB"?(v=0,y=u,S=u*2):a==="RBG"&&(v=0,S=u,y=u*2),s=t.createImageData(i,n);for(let g=0;g{uu(),Nl=(e,r)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(r.height===void 0||r.width===void 0)throw new Error("Image height and width must be defined");if(r.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:t,width:s}=r,i=r.norm??{mean:255,bias:0},n,o;typeof i.mean=="number"?n=[i.mean,i.mean,i.mean,i.mean]:n=[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],typeof i.bias=="number"?o=[i.bias,i.bias,i.bias,i.bias]:o=[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let a=r.format!==void 0?r.format:"RGBA",l=r.tensorFormat!==void 0&&r.tensorFormat!==void 0?r.tensorFormat:"RGB",d=t*s,p=l==="RGBA"?new Float32Array(d*4):new Float32Array(d*3),u=4,h=0,w=1,_=2,P=3,A=0,v=d,y=d*2,S=-1;a==="RGB"&&(u=3,h=0,w=1,_=2,P=-1),l==="RGBA"?S=d*3:l==="RBG"?(A=0,y=d,v=d*2):l==="BGR"&&(y=0,v=d,A=d*2);for(let x=0;x{let t=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,s=typeof ImageData<"u"&&e instanceof ImageData,i=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,n=typeof e=="string",o,a=r??{},l=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},d=p=>typeof HTMLCanvasElement<"u"&&p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?p.getContext("2d"):null;if(t){let p=l();p.width=e.width,p.height=e.height;let u=d(p);if(u!=null){let h=e.height,w=e.width;if(r!==void 0&&r.resizedHeight!==void 0&&r.resizedWidth!==void 0&&(h=r.resizedHeight,w=r.resizedWidth),r!==void 0){if(a=r,r.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");a.tensorFormat="RGBA",a.height=h,a.width=w}else a.tensorFormat="RGBA",a.height=h,a.width=w;u.drawImage(e,0,0),o=u.getImageData(0,0,w,h).data}else throw new Error("Can not access image data")}else if(s){let p,u;if(r!==void 0&&r.resizedWidth!==void 0&&r.resizedHeight!==void 0?(p=r.resizedHeight,u=r.resizedWidth):(p=e.height,u=e.width),r!==void 0&&(a=r),a.format="RGBA",a.height=p,a.width=u,r!==void 0){let h=l();h.width=u,h.height=p;let w=d(h);if(w!=null)w.putImageData(e,0,0),o=w.getImageData(0,0,u,p).data;else throw new Error("Can not access image data")}else o=e.data}else if(i){if(r===void 0)throw new Error("Please provide image config with format for Imagebitmap");let p=l();p.width=e.width,p.height=e.height;let u=d(p);if(u!=null){let h=e.height,w=e.width;return u.drawImage(e,0,0,w,h),o=u.getImageData(0,0,w,h).data,a.height=h,a.width=w,Nl(o,a)}else throw new Error("Can not access image data")}else{if(n)return new Promise((p,u)=>{let h=l(),w=d(h);if(!e||!w)return u();let _=new Image;_.crossOrigin="Anonymous",_.src=e,_.onload=()=>{h.width=_.width,h.height=_.height,w.drawImage(_,0,0,h.width,h.height);let P=w.getImageData(0,0,h.width,h.height);a.height=h.height,a.width=h.width,p(Nl(P.data,a))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(o!==void 0)return Nl(o,a);throw new Error("Input data provided is not supported - aborted tensor creation")},Jw=(e,r)=>{let{width:t,height:s,download:i,dispose:n}=r,o=[1,s,t,4];return new Ur({location:"texture",type:"float32",texture:e,dims:o,download:i,dispose:n})},Yw=(e,r)=>{let{dataType:t,dims:s,download:i,dispose:n}=r;return new Ur({location:"gpu-buffer",type:t??"float32",gpuBuffer:e,dims:s,download:i,dispose:n})},Zw=(e,r)=>{let{dataType:t,dims:s,download:i,dispose:n}=r;return new Ur({location:"ml-tensor",type:t??"float32",mlTensor:e,dims:s,download:i,dispose:n})},ey=(e,r,t)=>new Ur({location:"cpu-pinned",type:e,data:r,dims:t??[r.length]})}),$n,oa,Jd,ty,xv=je(()=>{$n=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),oa=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Jd=!1,ty=()=>{if(!Jd){Jd=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,r=typeof BigUint64Array<"u"&&BigUint64Array.from,t=globalThis.Float16Array,s=typeof t<"u"&&t.from;e&&($n.set("int64",BigInt64Array),oa.set(BigInt64Array,"int64")),r&&($n.set("uint64",BigUint64Array),oa.set(BigUint64Array,"uint64")),s?($n.set("float16",t),oa.set(t,"float16")):$n.set("float16",Uint16Array)}}}),ry,sy,Tv=je(()=>{uu(),ry=e=>{let r=1;for(let t=0;t{switch(e.location){case"cpu":return new Ur(e.type,e.data,r);case"cpu-pinned":return new Ur({location:"cpu-pinned",data:e.data,type:e.type,dims:r});case"texture":return new Ur({location:"texture",texture:e.texture,type:e.type,dims:r});case"gpu-buffer":return new Ur({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:r});case"ml-tensor":return new Ur({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:r});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),Ur,uu=je(()=>{bv(),vv(),xv(),Tv(),Ur=class{constructor(e,r,t){ty();let s,i;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,s=e.type,i=e.dims,e.location){case"cpu-pinned":{let o=$n.get(s);if(!o)throw new TypeError(`unsupported type "${s}" to create tensor from pinned buffer`);if(!(e.data instanceof o))throw new TypeError(`buffer should be of type ${o.name}`);this.cpuData=e.data;break}case"texture":{if(s!=="float32")throw new TypeError(`unsupported type "${s}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(s!=="float32"&&s!=="float16"&&s!=="int32"&&s!=="int64"&&s!=="uint32"&&s!=="uint64"&&s!=="int8"&&s!=="uint8"&&s!=="bool"&&s!=="uint4"&&s!=="int4")throw new TypeError(`unsupported type "${s}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let o,a;if(typeof e=="string")if(s=e,a=t,e==="string"){if(!Array.isArray(r))throw new TypeError("A string tensor's data must be a string array.");o=r}else{let l=$n.get(e);if(l===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(r)){if(e==="float16"&&l===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${l.name} as data.`);e==="uint64"||e==="int64"?o=l.from(r,BigInt):o=l.from(r)}else if(r instanceof l)o=r;else if(r instanceof Uint8ClampedArray)if(e==="uint8")o=Uint8Array.from(r);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&r instanceof Uint16Array&&l!==Uint16Array)o=new globalThis.Float16Array(r.buffer,r.byteOffset,r.length);else throw new TypeError(`A ${s} tensor's data must be type of ${l}`)}else if(a=r,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let l=typeof e[0];if(l==="string")s="string",o=e;else if(l==="boolean")s="bool",o=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${l}.`)}else if(e instanceof Uint8ClampedArray)s="uint8",o=Uint8Array.from(e);else{let l=oa.get(e.constructor);if(l===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);s=l,o=e}if(a===void 0)a=[o.length];else if(!Array.isArray(a))throw new TypeError("A tensor's dims must be a number array");i=a,this.cpuData=o,this.dataLocation="cpu"}let n=ry(i);if(this.cpuData&&n!==this.cpuData.length&&!((s==="uint4"||s==="int4")&&Math.ceil(n/2)===this.cpuData.length))throw new Error(`Tensor's size(${n}) does not match data length(${this.cpuData.length}).`);this.type=s,this.dims=i,this.size=n}static async fromImage(e,r){return Xw(e,r)}static fromTexture(e,r){return Jw(e,r)}static fromGpuBuffer(e,r){return Yw(e,r)}static fromMLTensor(e,r){return Zw(e,r)}static fromPinnedBuffer(e,r,t){return ey(e,r,t)}toDataURL(e){return qw(this,e)}toImageData(e){return Qw(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let r=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=r,e&&this.disposer&&(this.disposer(),this.disposer=void 0),r}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return sy(this,e)}}}),gs,ny=je(()=>{uu(),gs=Ur}),ma,Yd,ys,Yr,iy=je(()=>{Hw(),ma=(e,r)=>{(typeof Xr.trace>"u"?!Xr.wasm.trace:!Xr.trace)||console.timeStamp(`${e}::ORT::${r}`)},Yd=(e,r)=>{var i;let t=((i=new Error().stack)==null?void 0:i.split(/\r\n|\r|\n/g))||[],s=!1;for(let n=0;n{(typeof Xr.trace>"u"?!Xr.wasm.trace:!Xr.trace)||Yd("BEGIN",e)},Yr=e=>{(typeof Xr.trace>"u"?!Xr.wasm.trace:!Xr.trace)||Yd("END",e)}}),oy,Ev=je(()=>{Gw(),ny(),iy(),oy=class ay{constructor(r){this.handler=r}async run(r,t,s){ys();let i={},n={};if(typeof r!="object"||r===null||r instanceof gs||Array.isArray(r))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let o=!0;if(typeof t=="object"){if(t===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(t instanceof gs)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(t)){if(t.length===0)throw new TypeError("'fetches' cannot be an empty array.");o=!1;for(let d of t){if(typeof d!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(d)===-1)throw new RangeError(`'fetches' contains invalid output name: ${d}.`);i[d]=null}if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else{let d=!1,p=Object.getOwnPropertyNames(t);for(let u of this.outputNames)if(p.indexOf(u)!==-1){let h=t[u];(h===null||h instanceof gs)&&(d=!0,o=!1,i[u]=h)}if(d){if(typeof s=="object"&&s!==null)n=s;else if(typeof s<"u")throw new TypeError("'options' must be an object.")}else n=t}}else if(typeof t<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let d of this.inputNames)if(typeof r[d]>"u")throw new Error(`input '${d}' is missing in 'feeds'.`);if(o)for(let d of this.outputNames)i[d]=null;let a=await this.handler.run(r,i,n),l={};for(let d in a)if(Object.hasOwnProperty.call(a,d)){let p=a[d];p instanceof gs?l[d]=p:l[d]=new gs(p.type,p.data,p.dims)}return Yr(),l}async release(){return this.handler.dispose()}static async create(r,t,s,i){ys();let n,o={};if(typeof r=="string"){if(n=r,typeof t=="object"&&t!==null)o=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof Uint8Array){if(n=r,typeof t=="object"&&t!==null)o=t;else if(typeof t<"u")throw new TypeError("'options' must be an object.")}else if(r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer){let p=r,u=0,h=r.byteLength;if(typeof t=="object"&&t!==null)o=t;else if(typeof t=="number"){if(u=t,!Number.isSafeInteger(u))throw new RangeError("'byteOffset' must be an integer.");if(u<0||u>=p.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${p.byteLength}).`);if(h=r.byteLength-u,typeof s=="number"){if(h=s,!Number.isSafeInteger(h))throw new RangeError("'byteLength' must be an integer.");if(h<=0||u+h>p.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${p.byteLength-u}].`);if(typeof i=="object"&&i!==null)o=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else if(typeof s<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof t<"u")throw new TypeError("'options' must be an object.");n=new Uint8Array(p,u,h)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[a,l]=await Ww(o),d=await a.createInferenceSessionHandler(n,l);return Yr(),new ay(d)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}}),pu,Pv=je(()=>{Ev(),pu=oy}),Cv=je(()=>{}),Sv=je(()=>{}),$v=je(()=>{}),kv=je(()=>{}),ly={};_a(ly,{InferenceSession:()=>pu,TRACE:()=>ma,TRACE_FUNC_BEGIN:()=>ys,TRACE_FUNC_END:()=>Yr,Tensor:()=>gs,env:()=>Kt,registerBackend:()=>An});var Ms=je(()=>{wv(),Mv(),Pv(),ny(),Cv(),Sv(),iy(),$v(),kv()}),hu=je(()=>{}),dy={};_a(dy,{default:()=>cy});var Zd,ec,cy,Iv=je(()=>{var e;hb(),Ln(),mu(),Zd="ort-wasm-proxy-worker",ec=((e=globalThis.self)==null?void 0:e.name)===Zd,ec&&(self.onmessage=r=>{let{type:t,in:s}=r.data;try{switch(t){case"init-wasm":fu(s.wasm).then(()=>{Fu(s).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:n}=s;Ou(n,i).then(()=>{postMessage({type:t})},o=>{postMessage({type:t,err:o})});break}case"copy-from":{let{buffer:i}=s,n=cd(i);postMessage({type:t,out:n});break}case"create":{let{model:i,options:n}=s;Du(i,n).then(o=>{postMessage({type:t,out:o})},o=>{postMessage({type:t,err:o})});break}case"release":Lu(s),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:n,inputs:o,outputIndices:a,options:l}=s;zu(i,n,o,a,new Array(a.length).fill(null),l).then(d=>{d.some(p=>p[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:d},Ru([...o,...d]))},d=>{postMessage({type:t,err:d})});break}case"end-profiling":Bu(s),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),cy=ec?null:r=>new Worker(r??jr,{type:"module",name:Zd})}),uy={};_a(uy,{default:()=>py});var tc,rc,py,of,Av=je(()=>{var e,r;rc=(tc=import.meta.url,async function(t={}){var Qo;var s,i,n=t,o=new Promise((c,m)=>{s=c,i=m}),a=typeof window=="object",l=typeof WorkerGlobalScope<"u",d=l&&((Qo=self.name)==null?void 0:Qo.startsWith("em-pthread"));n.mountExternalData=(c,m)=>{c.startsWith("./")&&(c=c.substring(2)),(n.Bd||(n.Bd=new Map)).set(c,m)},n.unmountExternalData=()=>{delete n.Bd};var p=globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let u=()=>{let c=(b,C,I)=>(...W)=>{let se=Rt,ye=C==null?void 0:C();W=b(...W);let Te=C==null?void 0:C();return ye!==Te&&(b=Te,I(ye),C=I=null),Rt!=se?new Promise((ze,Ye)=>{Ys={resolve:ze,reject:Ye}}):W},m=b=>async(...C)=>{var I;try{if(n.Cd)throw Error("Session already started");let W=n.Cd={be:C[0],errors:[]},se=await b(...C);if(n.Cd!==W)throw Error("Session mismatch");(I=n.Dd)==null||I.flush();let ye=W.errors;if(0ze),0n._OrtCreateSession,b=>n._OrtCreateSession=b),n._OrtRun=m(c(n._OrtRun,()=>n._OrtRun,b=>n._OrtRun=b)),n._OrtRunWithBinding=m(c(n._OrtRunWithBinding,()=>n._OrtRunWithBinding,b=>n._OrtRunWithBinding=b)),n._OrtBindInput=c(n._OrtBindInput,()=>n._OrtBindInput,b=>n._OrtBindInput=b),u=void 0};n.jsepInit=(c,m)=>{if(u==null||u(),c==="webgpu"){[n.Dd,n.Rd,n.Vd,n.Hd,n.Ud,n.hc,n.Wd,n.Zd,n.Sd,n.Td,n.Xd]=m;let b=n.Dd;n.jsepRegisterBuffer=(C,I,W,se)=>b.registerBuffer(C,I,W,se),n.jsepGetBuffer=C=>b.getBuffer(C),n.jsepCreateDownloader=(C,I,W)=>b.createDownloader(C,I,W),n.jsepOnCreateSession=C=>{b.onCreateSession(C)},n.jsepOnReleaseSession=C=>{b.onReleaseSession(C)},n.jsepOnRunStart=C=>b.onRunStart(C),n.$d=(C,I)=>{b.upload(C,I)}}else if(c==="webnn"){[n.Dd,n.Yd,n.Id,n.jsepEnsureTensor,n.Jd,n.jsepDownloadTensor]=m,n.jsepReleaseTensorId=n.Id,n.jsepUploadTensor=n.Jd;let b=n.Dd;n.jsepOnRunStart=C=>b.onRunStart(C),n.jsepOnRunEnd=b.onRunEnd.bind(b),n.jsepRegisterMLContext=(C,I)=>{b.registerMLContext(C,I)},n.jsepOnReleaseSession=C=>{b.onReleaseSession(C)},n.jsepCreateMLTensorDownloader=(C,I)=>b.createMLTensorDownloader(C,I),n.jsepRegisterMLTensor=(C,I,W,se)=>b.registerMLTensor(C,I,W,se),n.jsepCreateMLContext=C=>b.createMLContext(C),n.jsepRegisterMLConstant=(C,I,W,se,ye)=>b.registerMLConstant(C,I,W,se,ye,n.Bd),n.jsepRegisterGraphInput=b.registerGraphInput.bind(b),n.jsepIsGraphInput=b.isGraphInput.bind(b),n.jsepCreateTemporaryTensor=b.createTemporaryTensor.bind(b)}};var h,w,_=Object.assign({},n),P=(c,m)=>{throw m},A="";(a||l)&&(l?A=self.location.href:typeof document<"u"&&document.currentScript&&(A=document.currentScript.src),tc&&(A=tc),A=A.startsWith("blob:")?"":A.slice(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1),l&&(w=c=>{var m=new XMLHttpRequest;return m.open("GET",c,!1),m.responseType="arraybuffer",m.send(null),new Uint8Array(m.response)}),h=async c=>{if(ge(c))return new Promise((b,C)=>{var I=new XMLHttpRequest;I.open("GET",c,!0),I.responseType="arraybuffer",I.onload=()=>{I.status==200||I.status==0&&I.response?b(I.response):C(I.status)},I.onerror=C,I.send(null)});var m=await fetch(c,{credentials:"same-origin"});if(m.ok)return m.arrayBuffer();throw Error(m.status+" : "+m.url)});var v=console.log.bind(console),y=console.error.bind(console),S=v,x=y;Object.assign(n,_),_=null;var g,M,E,k,B,R,J,q,V,Y,H,Q,ie,le=n.wasmBinary,ae=!1,ge=c=>c.startsWith("file://");function N(){return g.buffer!=k.buffer&&K(),k}function O(){return g.buffer!=k.buffer&&K(),B}function G(){return g.buffer!=k.buffer&&K(),R}function ne(){return g.buffer!=k.buffer&&K(),J}function X(){return g.buffer!=k.buffer&&K(),q}function we(){return g.buffer!=k.buffer&&K(),V}function fe(){return g.buffer!=k.buffer&&K(),Y}function ke(){return g.buffer!=k.buffer&&K(),ie}if(d){let c=function(m){try{var b=m.data,C=b.yd;if(C==="load"){let I=[];self.onmessage=W=>I.push(W),self.startWorker=()=>{postMessage({yd:"loaded"});for(let W of I)c(W);self.onmessage=c};for(let W of b.Od)n[W]&&!n[W].proxy||(n[W]=(...se)=>{postMessage({yd:"callHandler",Nd:W,args:se})},W=="print"&&(S=n[W]),W=="printErr"&&(x=n[W]));g=b.he,K(),He(b.ie)}else if(C==="run"){$s(b.xd),Qn(b.xd,0,0,1,0,0),jt(),At(b.xd),Me||(qn(),Me=!0);try{Fr(b.de,b.Fd)}catch(I){if(I!="unwind")throw I}}else b.target!=="setimmediate"&&(C==="checkMailbox"?Me&&Ut():C&&(x(`worker: received unknown command ${C}`),x(b)))}catch(I){throw Qi(),I}};var He,Me=!1;x=function(...m){m=m.join(" "),console.error(m)},self.alert=function(...m){postMessage({yd:"alert",text:m.join(" "),fe:yn()})},self.onunhandledrejection=m=>{throw m.reason||m},self.onmessage=c}function K(){var c=g.buffer;n.HEAP8=k=new Int8Array(c),n.HEAP16=R=new Int16Array(c),n.HEAPU8=B=new Uint8Array(c),n.HEAPU16=J=new Uint16Array(c),n.HEAP32=q=new Int32Array(c),n.HEAPU32=V=new Uint32Array(c),n.HEAPF32=Y=new Float32Array(c),n.HEAPF64=ie=new Float64Array(c),n.HEAP64=H=new BigInt64Array(c),n.HEAPU64=Q=new BigUint64Array(c)}function U(){d?startWorker(n):Oe.Bb()}d||(g=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),K());var pe,Pe=0,Ee=null;function Fe(){if(--Pe==0&&Ee){var c=Ee;Ee=null,c()}}function Ie(c){throw x(c="Aborted("+c+")"),ae=!0,c=new WebAssembly.RuntimeError(c+". Build with -sASSERTIONS for more info."),i(c),c}function Le(){return{a:{Ta:D,Va:Ve,W:ks,la:dt,b:bs,u:vs,R:xs,Za:Is,d:hr,pb:et,g:Br,T:Sr,Ga:rs,lb:ns,nb:is,Ha:Gr,Ea:Ts,wb:Ws,Da:Gs,pa:Ks,mb:Hs,jb:os,Fa:qs,kb:Qs,Ma:Es,za:pn,eb:hn,cb:Ps,ya:ue,V:F,N:j,db:te,ma:pt,fb:Ct,zb:$t,hb:br,qb:qr,ab:vr,Aa:as,yb:At,Ja:Wt,S:Qr,Wa:ls,$:wa,H:ya,E:ba,l:Hr,F:ki,B:Ta,X:Ii,J:Ea,v:Ai,O:md,D:Pa,t:Fi,A:Ca,z:Rn,w:Sa,r:$a,tb:ka,ub:Ia,vb:Nn,rb:jn,sb:zi,bb:Bi,Oa:fd,La:_d,y:Fa,ja:Oa,Ba:Da,Ka:Aa,qa:La,Ia:za,ib:Wn,U:zs,fa:Ba,Sa:Ra,gb:Na,Qa:Ni,Pa:ja,Ab:Ui,Ca:Kn,ob:Ue,aa:Vi,oa:Wi,xb:Hn,na:Gi,$a:al,ia:fl,sa:Ho,ga:jo,da:ul,ua:gl,p:nl,e:Ka,c:Ga,ea:_i,f:Ha,n:Qa,k:Ro,Y:Xa,ka:rl,j:il,wa:dl,Ra:qo,ca:hl,Ua:Ml,P:cl,K:Ya,_:Go,Q:ol,Z:Ko,x:Ja,m:Lo,va:pl,i:Wa,h:zo,ra:yl,ta:wl,o:qa,q:Za,s:el,I:tl,C:No,L:sl,xa:ll,_a:Uo,G:ml,Ya:Vo,ba:_l,M:Bo,Xa:Wo,ha:Ki,a:g,Na:Re}}}var Ne={1320978:()=>typeof wasmOffsetConverter<"u",1321035:(c,m,b,C,I)=>{if(n===void 0||!n.Bd)return 1;if((c=zt(Number(c>>>0))).startsWith("./")&&(c=c.substring(2)),!(c=n.Bd.get(c)))return 2;if(m=Number(m>>>0),b=Number(b>>>0),C=Number(C>>>0),m+b>c.byteLength)return 3;try{let W=c.subarray(m,m+b);switch(I){case 0:O().set(W,C>>>0);break;case 1:n.$d(C,W);break;default:return 4}return 0}catch{return 4}},1321750:(c,m,b)=>{n.Jd(c,O().subarray(m>>>0,m+b>>>0))},1321813:()=>n.Yd(),1321854:c=>{n.Id(c)},1321890:()=>{n.Sd()},1321921:()=>{n.Td()},1321950:()=>{n.Xd()},1321975:c=>n.Rd(c),1322008:c=>n.Vd(c),1322040:(c,m,b)=>{n.Hd(Number(c),Number(m),Number(b),!0)},1322103:(c,m,b)=>{n.Hd(Number(c),Number(m),Number(b))},1322160:c=>{n.hc("Abs",c,void 0)},1322211:c=>{n.hc("Neg",c,void 0)},1322262:c=>{n.hc("Floor",c,void 0)},1322315:c=>{n.hc("Ceil",c,void 0)},1322367:c=>{n.hc("Reciprocal",c,void 0)},1322425:c=>{n.hc("Sqrt",c,void 0)},1322477:c=>{n.hc("Exp",c,void 0)},1322528:c=>{n.hc("Erf",c,void 0)},1322579:c=>{n.hc("Sigmoid",c,void 0)},1322634:(c,m,b)=>{n.hc("HardSigmoid",c,{alpha:m,beta:b})},1322713:c=>{n.hc("Log",c,void 0)},1322764:c=>{n.hc("Sin",c,void 0)},1322815:c=>{n.hc("Cos",c,void 0)},1322866:c=>{n.hc("Tan",c,void 0)},1322917:c=>{n.hc("Asin",c,void 0)},1322969:c=>{n.hc("Acos",c,void 0)},1323021:c=>{n.hc("Atan",c,void 0)},1323073:c=>{n.hc("Sinh",c,void 0)},1323125:c=>{n.hc("Cosh",c,void 0)},1323177:c=>{n.hc("Asinh",c,void 0)},1323230:c=>{n.hc("Acosh",c,void 0)},1323283:c=>{n.hc("Atanh",c,void 0)},1323336:c=>{n.hc("Tanh",c,void 0)},1323388:c=>{n.hc("Not",c,void 0)},1323439:(c,m,b)=>{n.hc("Clip",c,{min:m,max:b})},1323508:c=>{n.hc("Clip",c,void 0)},1323560:(c,m)=>{n.hc("Elu",c,{alpha:m})},1323618:c=>{n.hc("Gelu",c,void 0)},1323670:c=>{n.hc("Relu",c,void 0)},1323722:(c,m)=>{n.hc("LeakyRelu",c,{alpha:m})},1323786:(c,m)=>{n.hc("ThresholdedRelu",c,{alpha:m})},1323856:(c,m)=>{n.hc("Cast",c,{to:m})},1323914:c=>{n.hc("Add",c,void 0)},1323965:c=>{n.hc("Sub",c,void 0)},1324016:c=>{n.hc("Mul",c,void 0)},1324067:c=>{n.hc("Div",c,void 0)},1324118:c=>{n.hc("Pow",c,void 0)},1324169:c=>{n.hc("Equal",c,void 0)},1324222:c=>{n.hc("Greater",c,void 0)},1324277:c=>{n.hc("GreaterOrEqual",c,void 0)},1324339:c=>{n.hc("Less",c,void 0)},1324391:c=>{n.hc("LessOrEqual",c,void 0)},1324450:(c,m,b,C,I)=>{n.hc("ReduceMean",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1324625:(c,m,b,C,I)=>{n.hc("ReduceMax",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1324799:(c,m,b,C,I)=>{n.hc("ReduceMin",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1324973:(c,m,b,C,I)=>{n.hc("ReduceProd",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325148:(c,m,b,C,I)=>{n.hc("ReduceSum",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325322:(c,m,b,C,I)=>{n.hc("ReduceL1",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325495:(c,m,b,C,I)=>{n.hc("ReduceL2",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325668:(c,m,b,C,I)=>{n.hc("ReduceLogSum",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1325845:(c,m,b,C,I)=>{n.hc("ReduceSumSquare",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1326025:(c,m,b,C,I)=>{n.hc("ReduceLogSumExp",c,{keepDims:!!m,noopWithEmptyAxes:!!b,axes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1326205:c=>{n.hc("Where",c,void 0)},1326258:(c,m,b)=>{n.hc("Transpose",c,{perm:m?Array.from(X().subarray(Number(m)>>>0,Number(b)>>>0)):[]})},1326382:(c,m,b,C)=>{n.hc("DepthToSpace",c,{blocksize:m,mode:zt(b),format:C?"NHWC":"NCHW"})},1326515:(c,m,b,C)=>{n.hc("DepthToSpace",c,{blocksize:m,mode:zt(b),format:C?"NHWC":"NCHW"})},1326648:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt,Ir)=>{n.hc("ConvTranspose",c,{format:Te?"NHWC":"NCHW",autoPad:m,dilations:[b],group:C,kernelShape:[I],pads:[W,se],strides:[ye],wIsConst:()=>!!N()[ze>>>0],outputPadding:Ye?Array.from(X().subarray(Number(Ye)>>>0,Number(ot)>>>0)):[],outputShape:gt?Array.from(X().subarray(Number(gt)>>>0,Number(Bt)>>>0)):[],activation:zt(Ir)})},1327081:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>{n.hc("ConvTranspose",c,{format:ye?"NHWC":"NCHW",autoPad:m,dilations:Array.from(X().subarray(Number(b)>>>0,2+(Number(b)>>>0)>>>0)),group:C,kernelShape:Array.from(X().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),pads:Array.from(X().subarray(Number(W)>>>0,4+(Number(W)>>>0)>>>0)),strides:Array.from(X().subarray(Number(se)>>>0,2+(Number(se)>>>0)>>>0)),wIsConst:()=>!!N()[Te>>>0],outputPadding:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],outputShape:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[],activation:zt(Bt)})},1327742:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt,Ir)=>{n.hc("ConvTranspose",c,{format:Te?"NHWC":"NCHW",autoPad:m,dilations:[b],group:C,kernelShape:[I],pads:[W,se],strides:[ye],wIsConst:()=>!!N()[ze>>>0],outputPadding:Ye?Array.from(X().subarray(Number(Ye)>>>0,Number(ot)>>>0)):[],outputShape:gt?Array.from(X().subarray(Number(gt)>>>0,Number(Bt)>>>0)):[],activation:zt(Ir)})},1328175:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>{n.hc("ConvTranspose",c,{format:ye?"NHWC":"NCHW",autoPad:m,dilations:Array.from(X().subarray(Number(b)>>>0,2+(Number(b)>>>0)>>>0)),group:C,kernelShape:Array.from(X().subarray(Number(I)>>>0,2+(Number(I)>>>0)>>>0)),pads:Array.from(X().subarray(Number(W)>>>0,4+(Number(W)>>>0)>>>0)),strides:Array.from(X().subarray(Number(se)>>>0,2+(Number(se)>>>0)>>>0)),wIsConst:()=>!!N()[Te>>>0],outputPadding:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],outputShape:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[],activation:zt(Bt)})},1328836:(c,m)=>{n.hc("GlobalAveragePool",c,{format:m?"NHWC":"NCHW"})},1328927:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>{n.hc("AveragePool",c,{format:Bt?"NHWC":"NCHW",auto_pad:m,ceil_mode:b,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],kernel_shape:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Te)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[]})},1329406:(c,m)=>{n.hc("GlobalAveragePool",c,{format:m?"NHWC":"NCHW"})},1329497:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>{n.hc("AveragePool",c,{format:Bt?"NHWC":"NCHW",auto_pad:m,ceil_mode:b,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],kernel_shape:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Te)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[]})},1329976:(c,m)=>{n.hc("GlobalMaxPool",c,{format:m?"NHWC":"NCHW"})},1330063:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>{n.hc("MaxPool",c,{format:Bt?"NHWC":"NCHW",auto_pad:m,ceil_mode:b,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],kernel_shape:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Te)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[]})},1330538:(c,m)=>{n.hc("GlobalMaxPool",c,{format:m?"NHWC":"NCHW"})},1330625:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>{n.hc("MaxPool",c,{format:Bt?"NHWC":"NCHW",auto_pad:m,ceil_mode:b,count_include_pad:C,storage_order:I,dilations:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],kernel_shape:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Te)>>>0)):[],pads:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],strides:ot?Array.from(X().subarray(Number(ot)>>>0,Number(gt)>>>0)):[]})},1331100:(c,m,b,C,I)=>{n.hc("Gemm",c,{alpha:m,beta:b,transA:C,transB:I})},1331204:c=>{n.hc("MatMul",c,void 0)},1331258:(c,m,b,C)=>{n.hc("ArgMax",c,{keepDims:!!m,selectLastIndex:!!b,axis:C})},1331366:(c,m,b,C)=>{n.hc("ArgMin",c,{keepDims:!!m,selectLastIndex:!!b,axis:C})},1331474:(c,m)=>{n.hc("Softmax",c,{axis:m})},1331537:(c,m)=>{n.hc("Concat",c,{axis:m})},1331597:(c,m,b,C,I)=>{n.hc("Split",c,{axis:m,numOutputs:b,splitSizes:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1331753:c=>{n.hc("Expand",c,void 0)},1331807:(c,m)=>{n.hc("Gather",c,{axis:Number(m)})},1331878:(c,m)=>{n.hc("GatherElements",c,{axis:Number(m)})},1331957:(c,m)=>{n.hc("GatherND",c,{batch_dims:Number(m)})},1332036:(c,m,b,C,I,W,se,ye,Te,ze,Ye)=>{n.hc("Resize",c,{antialias:m,axes:b?Array.from(X().subarray(Number(b)>>>0,Number(C)>>>0)):[],coordinateTransformMode:zt(I),cubicCoeffA:W,excludeOutside:se,extrapolationValue:ye,keepAspectRatioPolicy:zt(Te),mode:zt(ze),nearestMode:zt(Ye)})},1332398:(c,m,b,C,I,W,se)=>{n.hc("Slice",c,{starts:m?Array.from(X().subarray(Number(m)>>>0,Number(b)>>>0)):[],ends:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[],axes:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[]})},1332662:c=>{n.hc("Tile",c,void 0)},1332714:(c,m,b)=>{n.hc("InstanceNormalization",c,{epsilon:m,format:b?"NHWC":"NCHW"})},1332828:(c,m,b)=>{n.hc("InstanceNormalization",c,{epsilon:m,format:b?"NHWC":"NCHW"})},1332942:c=>{n.hc("Range",c,void 0)},1332995:(c,m)=>{n.hc("Einsum",c,{equation:zt(m)})},1333076:(c,m,b,C,I)=>{n.hc("Pad",c,{mode:m,value:b,pads:C?Array.from(X().subarray(Number(C)>>>0,Number(I)>>>0)):[]})},1333219:(c,m,b,C,I,W)=>{n.hc("BatchNormalization",c,{epsilon:m,momentum:b,spatial:!!I,trainingMode:!!C,format:W?"NHWC":"NCHW"})},1333388:(c,m,b,C,I,W)=>{n.hc("BatchNormalization",c,{epsilon:m,momentum:b,spatial:!!I,trainingMode:!!C,format:W?"NHWC":"NCHW"})},1333557:(c,m,b)=>{n.hc("CumSum",c,{exclusive:Number(m),reverse:Number(b)})},1333654:(c,m,b)=>{n.hc("DequantizeLinear",c,{axis:m,blockSize:b})},1333744:(c,m,b,C,I)=>{n.hc("GridSample",c,{align_corners:m,mode:zt(b),padding_mode:zt(C),format:I?"NHWC":"NCHW"})},1333914:(c,m,b,C,I)=>{n.hc("GridSample",c,{align_corners:m,mode:zt(b),padding_mode:zt(C),format:I?"NHWC":"NCHW"})},1334084:(c,m)=>{n.hc("ScatterND",c,{reduction:zt(m)})},1334169:(c,m,b,C,I,W,se,ye,Te)=>{n.hc("Attention",c,{numHeads:m,isUnidirectional:b,maskFilterValue:C,scale:I,doRotary:W,qkvHiddenSizes:se?Array.from(X().subarray(Number(ye)>>>0,Number(ye)+se>>>0)):[],pastPresentShareBuffer:!!Te})},1334441:c=>{n.hc("BiasAdd",c,void 0)},1334496:c=>{n.hc("BiasSplitGelu",c,void 0)},1334557:c=>{n.hc("FastGelu",c,void 0)},1334613:(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt,Ir,rn)=>{n.hc("Conv",c,{format:ot?"NHWC":"NCHW",auto_pad:m,dilations:b?Array.from(X().subarray(Number(b)>>>0,Number(C)>>>0)):[],group:I,kernel_shape:W?Array.from(X().subarray(Number(W)>>>0,Number(se)>>>0)):[],pads:ye?Array.from(X().subarray(Number(ye)>>>0,Number(Te)>>>0)):[],strides:ze?Array.from(X().subarray(Number(ze)>>>0,Number(Ye)>>>0)):[],w_is_const:()=>!!N()[Number(gt)>>>0],activation:zt(Bt),activation_params:Ir?Array.from(fe().subarray(Number(Ir)>>>0,Number(rn)>>>0)):[]})},1335197:c=>{n.hc("Gelu",c,void 0)},1335249:(c,m,b,C,I,W,se,ye,Te)=>{n.hc("GroupQueryAttention",c,{numHeads:m,kvNumHeads:b,scale:C,softcap:I,doRotary:W,rotaryInterleaved:se,smoothSoftmax:ye,localWindowSize:Te})},1335466:(c,m,b,C)=>{n.hc("LayerNormalization",c,{axis:m,epsilon:b,simplified:!!C})},1335577:(c,m,b,C)=>{n.hc("LayerNormalization",c,{axis:m,epsilon:b,simplified:!!C})},1335688:(c,m,b,C,I,W)=>{n.hc("MatMulNBits",c,{k:m,n:b,accuracyLevel:C,bits:I,blockSize:W})},1335815:(c,m,b,C,I,W)=>{n.hc("MultiHeadAttention",c,{numHeads:m,isUnidirectional:b,maskFilterValue:C,scale:I,doRotary:W})},1335974:(c,m)=>{n.hc("QuickGelu",c,{alpha:m})},1336038:(c,m,b,C,I)=>{n.hc("RotaryEmbedding",c,{interleaved:!!m,numHeads:b,rotaryEmbeddingDim:C,scale:I})},1336177:(c,m,b)=>{n.hc("SkipLayerNormalization",c,{epsilon:m,simplified:!!b})},1336279:(c,m,b)=>{n.hc("SkipLayerNormalization",c,{epsilon:m,simplified:!!b})},1336381:(c,m,b,C)=>{n.hc("GatherBlockQuantized",c,{gatherAxis:m,quantizeAxis:b,blockSize:C})},1336502:c=>{n.Wd(c)},1336536:(c,m)=>n.Zd(Number(c),Number(m),n.Cd.be,n.Cd.errors)};function Ve(c,m,b){return Si(async()=>{await n.Ud(Number(c),Number(m),Number(b))})}function D(){return typeof wasmOffsetConverter<"u"}class Z{constructor(m){re(this,"name","ExitStatus");this.message=`Program terminated with exit(${m})`,this.status=m}}var z=c=>{c.terminate(),c.onmessage=()=>{}},ee=[],ce=c=>{Qe.length==0&&(Zr(),ar(Qe[0]));var m=Qe.pop();if(!m)return 6;Xe.push(m),vt[c.xd]=m,m.xd=c.xd;var b={yd:"run",de:c.ce,Fd:c.Fd,xd:c.xd};return m.postMessage(b,c.Ld),0},be=0,ve=(c,m,...b)=>{for(var C=2*b.length,I=ft(),W=Mn(8*C),se=W>>>3,ye=0;ye>>0]=Te)}return c=Xn(c,0,C,W,m),ht(I),c};function Re(c){if(d)return ve(0,1,c);if(E=c,!(0{if(E=c,d)throw Ae(c),"unwind";Re(c)},Qe=[],Xe=[],ct=[],vt={},nr=c=>{var m=c.xd;delete vt[m],Qe.push(c),Xe.splice(Xe.indexOf(c),1),c.xd=0,Xi(m)};function jt(){ct.forEach(c=>c())}var ar=c=>new Promise(m=>{c.onmessage=I=>{var W=(I=I.data).yd;if(I.Ed&&I.Ed!=yn()){var se=vt[I.Ed];se?se.postMessage(I,I.Ld):x(`Internal error! Worker sent a message "${W}" to target pthread ${I.Ed}, but that thread no longer exists!`)}else W==="checkMailbox"?Ut():W==="spawnThread"?ce(I):W==="cleanupThread"?nr(vt[I.ee]):W==="loaded"?(c.loaded=!0,m(c)):W==="alert"?alert(`Thread ${I.fe}: ${I.text}`):I.target==="setimmediate"?c.postMessage(I):W==="callHandler"?n[I.Nd](...I.args):W&&x(`worker sent an unknown command ${W}`)},c.onerror=I=>{throw x(`worker sent an error! ${I.filename}:${I.lineno}: ${I.message}`),I};var b,C=[];for(b of[])n.propertyIsEnumerable(b)&&C.push(b);c.postMessage({yd:"load",Od:C,he:g,ie:M})});function Zr(){var c=new Worker((()=>{let m=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new m("ort.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Qe.push(c)}var $s=c=>{K();var m=we()[c+52>>>2>>>0];c=we()[c+56>>>2>>>0],Yi(m,m-c),ht(m)},Fr=(c,m)=>{be=0,c=ti(c,m),0>>=0);if(N()[m.wd+12>>>0]==0){var b=1;N()[m.wd+12>>>0]=b}return b=0,N()[m.wd+13>>>0]=b,es.push(m),Zn(c),to(c)}var zr=0,dt=()=>{_t(0,0);var c=es.pop();Zi(c.Gd),zr=0};class Wr{constructor(m){this.Gd=m,this.wd=m-24}}function Br(c){throw zr||(zr=c>>>0),zr}var ts=c=>{var m=zr;if(!m)return Bs(0),0;var b=new Wr(m);we()[b.wd+16>>>2>>>0]=m;var C=we()[b.wd+4>>>2>>>0];if(!C)return Bs(0),m;for(var I of c){if(I===0||I===C)break;if(eo(I,C,b.wd+16))return Bs(I),m}return Bs(C),m};function bs(){return ts([])}function vs(c){return ts([c>>>0])}function xs(c,m){return ts([c>>>0,m>>>0])}var Is=()=>{var c=es.pop();c||Ie("no exception to throw");var m=c.Gd;if(N()[c.wd+13>>>0]==0){es.push(c);var b=1;N()[c.wd+13>>>0]=b,b=0,N()[c.wd+12>>>0]=b}throw zr=m};function hr(c,m,b){var C=new Wr(c>>>=0);throw m>>>=0,b>>>=0,we()[C.wd+16>>>2>>>0]=0,we()[C.wd+4>>>2>>>0]=m,we()[C.wd+8>>>2>>>0]=b,zr=c}function Be(c,m,b,C){return d?ve(2,1,c,m,b,C):et(c,m,b,C)}function et(c,m,b,C){if(c>>>=0,b>>>=0,C>>>=0,p===void 0)return 6;var I=[];return d&&I.length===0?Be(c,m>>>=0,b,C):(c={ce:b,xd:c,Fd:C,Ld:I},d?(c.yd="spawnThread",postMessage(c,I),0):ce(c))}var it=typeof TextDecoder<"u"?new TextDecoder:void 0,rr=(c,m=0,b=NaN)=>{var C=(m>>>=0)+b;for(b=m;c[b]&&!(b>=C);)++b;if(16(I=(240&I)==224?(15&I)<<12|W<<6|se:(7&I)<<18|W<<12|se<<6|63&c[m++])?C+=String.fromCharCode(I):(I-=65536,C+=String.fromCharCode(55296|I>>10,56320|1023&I))}}else C+=String.fromCharCode(I)}return C},zt=(c,m)=>(c>>>=0)?rr(O(),c,m):"";function Sr(c,m,b){return d?ve(3,1,c,m,b):0}function rs(c,m){if(d)return ve(4,1,c,m)}var ss=c=>{for(var m=0,b=0;b=C?m++:2047>=C?m+=2:55296<=C&&57343>=C?(m+=4,++b):m+=3}return m},Tr=(c,m,b)=>{var C=O();if(m>>>=0,0=se&&(se=65536+((1023&se)<<10)|1023&c.charCodeAt(++W)),127>=se){if(m>=b)break;C[m++>>>0]=se}else{if(2047>=se){if(m+1>=b)break;C[m++>>>0]=192|se>>6}else{if(65535>=se){if(m+2>=b)break;C[m++>>>0]=224|se>>12}else{if(m+3>=b)break;C[m++>>>0]=240|se>>18,C[m++>>>0]=128|se>>12&63}C[m++>>>0]=128|se>>6&63}C[m++>>>0]=128|63&se}}C[m>>>0]=0,c=m-I}else c=0;return c};function ns(c,m){if(d)return ve(5,1,c,m)}function is(c,m,b){if(d)return ve(6,1,c,m,b)}function Gr(c,m,b){return d?ve(7,1,c,m,b):0}function Ts(c,m){if(d)return ve(8,1,c,m)}function Ws(c,m,b){if(d)return ve(9,1,c,m,b)}function Gs(c,m,b,C){if(d)return ve(10,1,c,m,b,C)}function Ks(c,m,b,C){if(d)return ve(11,1,c,m,b,C)}function Hs(c,m,b,C){if(d)return ve(12,1,c,m,b,C)}function os(c){if(d)return ve(13,1,c)}function qs(c,m){if(d)return ve(14,1,c,m)}function Qs(c,m,b){if(d)return ve(15,1,c,m,b)}var Xs,Or,Es=()=>Ie(""),Mr=c=>{for(var m="";O()[c>>>0];)m+=Xs[O()[c++>>>0]];return m},As={},Fs={};function $r(c,m,b={}){return function(C,I,W={}){var se=I.name;if(!C)throw new Or(`type "${se}" must have a positive integer typeid pointer`);if(Fs.hasOwnProperty(C)){if(W.Pd)return;throw new Or(`Cannot register type '${se}' twice`)}Fs[C]=I,As.hasOwnProperty(C)&&(I=As[C],delete As[C],I.forEach(ye=>ye()))}(c,m,b)}var Kr=(c,m,b)=>{switch(m){case 1:return b?C=>N()[C>>>0]:C=>O()[C>>>0];case 2:return b?C=>G()[C>>>1>>>0]:C=>ne()[C>>>1>>>0];case 4:return b?C=>X()[C>>>2>>>0]:C=>we()[C>>>2>>>0];case 8:return b?C=>H[C>>>3]:C=>Q[C>>>3];default:throw new TypeError(`invalid integer width (${m}): ${c}`)}};function pn(c,m,b){b>>>=0,$r(c>>>=0,{name:m=Mr(m>>>0),fromWireType:C=>C,toWireType:function(C,I){if(typeof I!="bigint"&&typeof I!="number")throw I=I===null?"null":(C=typeof I)=="object"||C==="array"||C==="function"?I.toString():""+I,new TypeError(`Cannot convert "${I}" to ${this.name}`);return typeof I=="number"&&(I=BigInt(I)),I},zd:Dr,readValueFromPointer:Kr(m,b,m.indexOf("u")==-1),Ad:null})}var Dr=8;function hn(c,m,b,C){$r(c>>>=0,{name:m=Mr(m>>>0),fromWireType:function(I){return!!I},toWireType:function(I,W){return W?b:C},zd:Dr,readValueFromPointer:function(I){return this.fromWireType(O()[I>>>0])},Ad:null})}var Os=[],kr=[];function Hr(c){9<(c>>>=0)&&--kr[c+1]==0&&(kr[c]=void 0,Os.push(c))}var lr=c=>{if(!c)throw new Or("Cannot use deleted val. handle = "+c);return kr[c]},mr=c=>{switch(c){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let m=Os.pop()||kr.length;return kr[m]=c,kr[m+1]=1,m}};function Ds(c){return this.fromWireType(we()[c>>>2>>>0])}var mn={name:"emscripten::val",fromWireType:c=>{var m=lr(c);return Hr(c),m},toWireType:(c,m)=>mr(m),zd:Dr,readValueFromPointer:Ds,Ad:null};function Ps(c){return $r(c>>>0,mn)}var fn=(c,m)=>{switch(m){case 4:return function(b){return this.fromWireType(fe()[b>>>2>>>0])};case 8:return function(b){return this.fromWireType(ke()[b>>>3>>>0])};default:throw new TypeError(`invalid float width (${m}): ${c}`)}};function ue(c,m,b){b>>>=0,$r(c>>>=0,{name:m=Mr(m>>>0),fromWireType:C=>C,toWireType:(C,I)=>I,zd:Dr,readValueFromPointer:fn(m,b),Ad:null})}function F(c,m,b,C,I){if(c>>>=0,b>>>=0,m=Mr(m>>>0),I===-1&&(I=4294967295),I=ye=>ye,C===0){var W=32-8*b;I=ye=>ye<>>W}var se=m.includes("unsigned")?function(ye,Te){return Te>>>0}:function(ye,Te){return Te};$r(c,{name:m,fromWireType:I,toWireType:se,zd:Dr,readValueFromPointer:Kr(m,b,C!==0),Ad:null})}function j(c,m,b){function C(W){var se=we()[W>>>2>>>0];return W=we()[W+4>>>2>>>0],new I(N().buffer,W,se)}var I=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][m];$r(c>>>=0,{name:b=Mr(b>>>0),fromWireType:C,zd:Dr,readValueFromPointer:C},{Pd:!0})}function te(c,m){$r(c>>>=0,{name:m=Mr(m>>>0),fromWireType:function(b){for(var C,I=we()[b>>>2>>>0],W=b+4,se=W,ye=0;ye<=I;++ye){var Te=W+ye;ye!=I&&O()[Te>>>0]!=0||(se=zt(se,Te-se),C===void 0?C=se:(C+="\0",C+=se),se=Te+1)}return Rr(b),C},toWireType:function(b,C){C instanceof ArrayBuffer&&(C=new Uint8Array(C));var I=typeof C=="string";if(!(I||C instanceof Uint8Array||C instanceof Uint8ClampedArray||C instanceof Int8Array))throw new Or("Cannot pass non-string to std::string");var W=I?ss(C):C.length,se=tn(4+W+1),ye=se+4;if(we()[se>>>2>>>0]=W,I)Tr(C,ye,W+1);else if(I)for(I=0;I>>0]=Te}else for(I=0;I>>0]=C[I];return b!==null&&b.push(Rr,se),se},zd:Dr,readValueFromPointer:Ds,Ad(b){Rr(b)}})}var de=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,he=(c,m)=>{for(var b=c>>1,C=b+m/2;!(b>=C)&&ne()[b>>>0];)++b;if(32<(b<<=1)-c&&de)return de.decode(O().slice(c,b));for(b="",C=0;!(C>=m/2);++C){var I=G()[c+2*C>>>1>>>0];if(I==0)break;b+=String.fromCharCode(I)}return b},Ce=(c,m,b)=>{if(b??(b=2147483647),2>b)return 0;var C=m;b=(b-=2)<2*c.length?b/2:c.length;for(var I=0;I>>1>>>0]=W,m+=2}return G()[m>>>1>>>0]=0,m-C},We=c=>2*c.length,qe=(c,m)=>{for(var b=0,C="";!(b>=m/4);){var I=X()[c+4*b>>>2>>>0];if(I==0)break;++b,65536<=I?(I-=65536,C+=String.fromCharCode(55296|I>>10,56320|1023&I)):C+=String.fromCharCode(I)}return C},Ke=(c,m,b)=>{if(m>>>=0,b??(b=2147483647),4>b)return 0;var C=m;b=C+b-4;for(var I=0;I=W&&(W=65536+((1023&W)<<10)|1023&c.charCodeAt(++I)),X()[m>>>2>>>0]=W,(m+=4)+4>b)break}return X()[m>>>2>>>0]=0,m-C},Ze=c=>{for(var m=0,b=0;b=C&&++b,m+=4}return m};function pt(c,m,b){if(c>>>=0,m>>>=0,b=Mr(b>>>=0),m===2)var C=he,I=Ce,W=We,se=ye=>ne()[ye>>>1>>>0];else m===4&&(C=qe,I=Ke,W=Ze,se=ye=>we()[ye>>>2>>>0]);$r(c,{name:b,fromWireType:ye=>{for(var Te,ze=we()[ye>>>2>>>0],Ye=ye+4,ot=0;ot<=ze;++ot){var gt=ye+4+ot*m;ot!=ze&&se(gt)!=0||(Ye=C(Ye,gt-Ye),Te===void 0?Te=Ye:(Te+="\0",Te+=Ye),Ye=gt+m)}return Rr(ye),Te},toWireType:(ye,Te)=>{if(typeof Te!="string")throw new Or(`Cannot pass non-string to C++ string type ${b}`);var ze=W(Te),Ye=tn(4+ze+m);return we()[Ye>>>2>>>0]=ze/m,I(Te,Ye+4,ze+m),ye!==null&&ye.push(Rr,Ye),Ye},zd:Dr,readValueFromPointer:Ds,Ad(ye){Rr(ye)}})}function Ct(c,m){$r(c>>>=0,{Qd:!0,name:m=Mr(m>>>0),zd:0,fromWireType:()=>{},toWireType:()=>{}})}function $t(c){Qn(c>>>0,!l,1,!a,131072,!1),jt()}var Vt=c=>{if(!ae)try{if(c(),!(0>>=0,typeof Atomics.ge=="function"&&(Atomics.ge(X(),c>>>2,c).value.then(Ut),c+=128,Atomics.store(X(),c>>>2,1))}var Ut=()=>{var c=yn();c&&(At(c),Vt(Ji))};function br(c,m){(c>>>=0)==m>>>0?setTimeout(Ut):d?postMessage({Ed:c,yd:"checkMailbox"}):(c=vt[c])&&c.postMessage({yd:"checkMailbox"})}var fr=[];function qr(c,m,b,C,I){for(m>>>=0,C/=2,fr.length=C,b=I>>>0>>>3,I=0;I>>0];return(m?Ne[m]:Va[c])(...fr)}var vr=()=>{be=0};function as(c){c>>>=0,d?postMessage({yd:"cleanupThread",ee:c}):nr(vt[c])}function Wt(c){}var Yt=(c,m)=>{var b=Fs[c];if(b===void 0)throw c=qi(c),b=Mr(c),Rr(c),new Or(`${m} has unknown type ${b}`);return b},_r=(c,m,b)=>{var C=[];return c=c.toWireType(C,b),C.length&&(we()[m>>>2>>>0]=mr(C)),c};function Qr(c,m,b){return m>>>=0,b>>>=0,c=lr(c>>>0),m=Yt(m,"emval::as"),_r(m,b,c)}function ls(c,m){return m>>>=0,c=lr(c>>>0),(m=Yt(m,"emval::as")).toWireType(null,c)}var Ht=c=>{try{c()}catch(m){Ie(m)}},dr=0,Rt=null,Xt=0,qt=[],Zt={},ir={},Js=0,Ys=null,ga=[];function Si(c){return function(m){if(!ae){if(dr===0){var b=!1,C=!1;m((I=0)=>{if(!ae&&(Xt=I,b=!0,C)){dr=2,Ht(()=>Oo(Rt)),typeof MainLoop<"u"&&MainLoop.Md&&MainLoop.resume(),I=!1;try{var W=function(){var Te=X()[Rt+8>>>2>>>0];return Te=Oe[ir[Te]],--be,Te()}()}catch(Te){W=Te,I=!0}var se=!1;if(!Rt){var ye=Ys;ye&&(Ys=null,(I?ye.reject:ye.resolve)(W),se=!0)}if(I&&!se)throw W}}),C=!0,b||(dr=1,Rt=function(){var I=tn(65548),W=I+12;we()[I>>>2>>>0]=W,we()[I+4>>>2>>>0]=W+65536,W=qt[0];var se=Zt[W];return se===void 0&&(se=Js++,Zt[W]=se,ir[se]=W),W=se,X()[I+8>>>2>>>0]=W,I}(),typeof MainLoop<"u"&&MainLoop.Md&&MainLoop.pause(),Ht(()=>Fo(Rt)))}else dr===2?(dr=0,Ht(Do),Rr(Rt),Rt=null,ga.forEach(Vt)):Ie(`invalid state: ${dr}`);return Xt}}(m=>{c().then(m)})}function wa(c){return c>>>=0,Si(async()=>{var m=await lr(c);return mr(m)})}var ds=[];function ya(c,m,b,C){return b>>>=0,C>>>=0,(c=ds[c>>>0])(null,m=lr(m>>>0),b,C)}var Ma={},_n=c=>{var m=Ma[c];return m===void 0?Mr(c):m};function ba(c,m,b,C,I){return b>>>=0,C>>>=0,I>>>=0,(c=ds[c>>>0])(m=lr(m>>>0),m[b=_n(b)],C,I)}var $i=()=>typeof globalThis=="object"?globalThis:Function("return this")();function ki(c){return(c>>>=0)==0?mr($i()):(c=_n(c),mr($i()[c]))}var va=c=>{var m=ds.length;return ds.push(c),m},xa=(c,m)=>{for(var b=Array(c),C=0;C>>2>>>0],"parameter "+C);return b},Bn=(c,m)=>Object.defineProperty(m,"name",{value:c});function Ta(c,m,b){var C=(m=xa(c,m>>>0)).shift();c--;var I=`return function (obj, func, destructorsRef, args) { +`,W=0,se=[];b===0&&se.push("obj");for(var ye=["retType"],Te=[C],ze=0;zeYe.name).join(", ")}) => ${C.name}>`,va(Bn(b,c))}function Ii(c){return c=_n(c>>>0),mr(n[c])}function Ea(c,m){return m>>>=0,c=lr(c>>>0),m=lr(m),mr(c[m])}function Ai(c){9<(c>>>=0)&&(kr[c+1]+=1)}function md(){return mr([])}function Pa(c){c=lr(c>>>0);for(var m=Array(c.length),b=0;b>>0))}function Ca(){return mr({})}function Rn(c){for(var m=lr(c>>>=0);m.length;){var b=m.pop();m.pop()(b)}Hr(c)}function Sa(c,m,b){m>>>=0,b>>>=0,c=lr(c>>>0),m=lr(m),b=lr(b),c[m]=b}function $a(c,m){return m>>>=0,c=(c=Yt(c>>>0,"_emval_take_value")).readValueFromPointer(m),mr(c)}function ka(c,m){c=-9007199254740992>c||9007199254740992>>=0,c=new Date(1e3*c),X()[m>>>2>>>0]=c.getUTCSeconds(),X()[m+4>>>2>>>0]=c.getUTCMinutes(),X()[m+8>>>2>>>0]=c.getUTCHours(),X()[m+12>>>2>>>0]=c.getUTCDate(),X()[m+16>>>2>>>0]=c.getUTCMonth(),X()[m+20>>>2>>>0]=c.getUTCFullYear()-1900,X()[m+24>>>2>>>0]=c.getUTCDay(),c=(c.getTime()-Date.UTC(c.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,X()[m+28>>>2>>>0]=c}var Oi=c=>c%4==0&&(c%100!=0||c%400==0),Di=[0,31,60,91,121,152,182,213,244,274,305,335],Li=[0,31,59,90,120,151,181,212,243,273,304,334];function Ia(c,m){c=-9007199254740992>c||9007199254740992>>=0,c=new Date(1e3*c),X()[m>>>2>>>0]=c.getSeconds(),X()[m+4>>>2>>>0]=c.getMinutes(),X()[m+8>>>2>>>0]=c.getHours(),X()[m+12>>>2>>>0]=c.getDate(),X()[m+16>>>2>>>0]=c.getMonth(),X()[m+20>>>2>>>0]=c.getFullYear()-1900,X()[m+24>>>2>>>0]=c.getDay();var b=(Oi(c.getFullYear())?Di:Li)[c.getMonth()]+c.getDate()-1|0;X()[m+28>>>2>>>0]=b,X()[m+36>>>2>>>0]=-60*c.getTimezoneOffset(),b=new Date(c.getFullYear(),6,1).getTimezoneOffset();var C=new Date(c.getFullYear(),0,1).getTimezoneOffset();c=0|(b!=C&&c.getTimezoneOffset()==Math.min(C,b)),X()[m+32>>>2>>>0]=c}function Nn(c){c>>>=0;var m=new Date(X()[c+20>>>2>>>0]+1900,X()[c+16>>>2>>>0],X()[c+12>>>2>>>0],X()[c+8>>>2>>>0],X()[c+4>>>2>>>0],X()[c>>>2>>>0],0),b=X()[c+32>>>2>>>0],C=m.getTimezoneOffset(),I=new Date(m.getFullYear(),6,1).getTimezoneOffset(),W=new Date(m.getFullYear(),0,1).getTimezoneOffset(),se=Math.min(W,I);return 0>b?X()[c+32>>>2>>>0]=+(I!=W&&se==C):0>>2>>>0]=m.getDay(),b=(Oi(m.getFullYear())?Di:Li)[m.getMonth()]+m.getDate()-1|0,X()[c+28>>>2>>>0]=b,X()[c>>>2>>>0]=m.getSeconds(),X()[c+4>>>2>>>0]=m.getMinutes(),X()[c+8>>>2>>>0]=m.getHours(),X()[c+12>>>2>>>0]=m.getDate(),X()[c+16>>>2>>>0]=m.getMonth(),X()[c+20>>>2>>>0]=m.getYear(),c=m.getTime(),BigInt(isNaN(c)?-1:c/1e3)}function jn(c,m,b,C,I,W,se){return d?ve(16,1,c,m,b,C,I,W,se):-52}function zi(c,m,b,C,I,W){if(d)return ve(17,1,c,m,b,C,I,W)}var Ls={},zs=()=>performance.timeOrigin+performance.now();function Bi(c,m){if(d)return ve(18,1,c,m);if(Ls[c]&&(clearTimeout(Ls[c].id),delete Ls[c]),!m)return 0;var b=setTimeout(()=>{delete Ls[c],Vt(()=>Yn(c,performance.timeOrigin+performance.now()))},m);return Ls[c]={id:b,ke:m},0}function fd(c,m,b,C){c>>>=0,m>>>=0,b>>>=0,C>>>=0;var I=new Date().getFullYear(),W=new Date(I,0,1).getTimezoneOffset();I=new Date(I,6,1).getTimezoneOffset();var se=Math.max(W,I);we()[c>>>2>>>0]=60*se,X()[m>>>2>>>0]=+(W!=I),c=(m=ye=>{var Te=Math.abs(ye);return`UTC${0<=ye?"-":"+"}${String(Math.floor(Te/60)).padStart(2,"0")}${String(Te%60).padStart(2,"0")}`})(W),m=m(I),IDate.now();function _d(c,m,b){return 0<=c&&3>=c?(c===0?c=Date.now():c=performance.timeOrigin+performance.now(),H[b>>>0>>>3]=BigInt(Math.round(1e6*c)),0):28}var Un=[],Vn=(c,m)=>{Un.length=0;for(var b;b=O()[c++>>>0];){var C=b!=105;m+=(C&=b!=112)&&m%8?4:0,Un.push(b==112?we()[m>>>2>>>0]:b==106?H[m>>>3]:b==105?X()[m>>>2>>>0]:ke()[m>>>3>>>0]),m+=C?8:4}return Un};function Fa(c,m,b){return c>>>=0,m=Vn(m>>>0,b>>>0),Ne[c](...m)}function Oa(c,m,b){return c>>>=0,m=Vn(m>>>0,b>>>0),Ne[c](...m)}var Da=()=>{};function La(c,m){return x(zt(c>>>0,m>>>0))}var za=()=>{throw be+=1,"unwind"};function Wn(){return 4294901760}var Ba=()=>navigator.hardwareConcurrency;function Ra(){return Ie("Cannot use emscripten_pc_get_function without -sUSE_OFFSET_CONVERTER"),0}function Na(c){c>>>=0;var m=O().length;if(c<=m||4294901760=b;b*=2){var C=m*(1+.2/b);C=Math.min(C,c+100663296);e:{C=(Math.min(4294901760,65536*Math.ceil(Math.max(c,C)/65536))-g.buffer.byteLength+65535)/65536|0;try{g.grow(C),K();var I=1;break e}catch{}I=void 0}if(I)return!0}return!1}var Zs=()=>(Ie("Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER"),0),en={},Ri=c=>{c.forEach(m=>{Zs()})};function Ni(){var c=Error().stack.toString().split(` +`);return c[0]=="Error"&&c.shift(),Ri(c),en.Kd=Zs(),en.ae=c,en.Kd}function ja(c,m,b){if(c>>>=0,m>>>=0,en.Kd==c)var C=en.ae;else(C=Error().stack.toString().split(` +`))[0]=="Error"&&C.shift(),Ri(C);for(var I=3;C[I]&&Zs()!=c;)++I;for(c=0;c>>2>>>0]=Zs();return c}var Gn,gn={},ji=()=>{if(!Gn){var c,m={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:"./this.program"};for(c in gn)gn[c]===void 0?delete m[c]:m[c]=gn[c];var b=[];for(c in m)b.push(`${c}=${m[c]}`);Gn=b}return Gn};function Ui(c,m){if(d)return ve(19,1,c,m);c>>>=0,m>>>=0;var b=0;return ji().forEach((C,I)=>{var W=m+b;for(I=we()[c+4*I>>>2>>>0]=W,W=0;W>>0]=C.charCodeAt(W);N()[I>>>0]=0,b+=C.length+1}),0}function Kn(c,m){if(d)return ve(20,1,c,m);c>>>=0,m>>>=0;var b=ji();we()[c>>>2>>>0]=b.length;var C=0;return b.forEach(I=>C+=I.length+1),we()[m>>>2>>>0]=C,0}function Vi(c){return d?ve(21,1,c):52}function Wi(c,m,b,C){return d?ve(22,1,c,m,b,C):52}function Hn(c,m,b,C){return d?ve(23,1,c,m,b,C):70}var Ua=[null,[],[]];function Gi(c,m,b,C){if(d)return ve(24,1,c,m,b,C);m>>>=0,b>>>=0,C>>>=0;for(var I=0,W=0;W>>2>>>0],ye=we()[m+4>>>2>>>0];m+=8;for(var Te=0;Te>>0],Ye=Ua[c];ze===0||ze===10?((c===1?S:x)(rr(Ye)),Ye.length=0):Ye.push(ze)}I+=ye}return we()[C>>>2>>>0]=I,0}function Ki(c){return c>>>0}d||function(){for(var c=n.numThreads-1;c--;)Zr();ee.unshift(()=>{Pe++,function(m){d?m():Promise.all(Qe.map(ar)).then(m)}(()=>Fe())})}();for(var Hi=Array(256),wn=0;256>wn;++wn)Hi[wn]=String.fromCharCode(wn);Xs=Hi,Or=n.BindingError=class extends Error{constructor(c){super(c),this.name="BindingError"}},n.InternalError=class extends Error{constructor(c){super(c),this.name="InternalError"}},kr.push(0,1,void 0,1,null,1,!0,1,!1,1),n.count_emval_handles=()=>kr.length/2-5-Os.length;var Oe,Va=[Re,Ae,Be,Sr,rs,ns,is,Gr,Ts,Ws,Gs,Ks,Hs,os,qs,Qs,jn,zi,Bi,Ui,Kn,Vi,Wi,Hn,Gi];(async function(){function c(C,I){return Oe=C.exports,Oe=function(){var W=Oe,se={};for(let[ye,Te]of Object.entries(W))se[ye]=typeof Te=="function"?(...ze)=>{qt.push(ye);try{return Te(...ze)}finally{ae||(qt.pop(),Rt&&dr===1&&qt.length===0&&(dr=0,be+=1,Ht(fi),typeof Fibers<"u"&&Fibers.le()))}}:Te;return se}(),Oe=function(){var W=Oe,se=Te=>ze=>Te(ze)>>>0,ye=Te=>()=>Te()>>>0;return(W=Object.assign({},W)).Cb=se(W.Cb),W.fc=ye(W.fc),W.ic=se(W.ic),W.vc=se(W.vc),W.wc=ye(W.wc),W.Ac=se(W.Ac),W}(),ct.push(Oe.jc),M=I,Fe(),Oe}Pe++;var m=Le();if(n.instantiateWasm)return new Promise(C=>{n.instantiateWasm(m,(I,W)=>{c(I,W),C(I.exports)})});if(d)return new Promise(C=>{He=I=>{var W=new WebAssembly.Instance(I,Le());C(c(W,I))}});pe??(pe=n.locateFile?n.locateFile?n.locateFile("ort-wasm-simd-threaded.jsep.wasm",A):A+"ort-wasm-simd-threaded.jsep.wasm":new URL("/assets/ort-wasm-simd-threaded.jsep-BAR87mbD.wasm",import.meta.url).href);try{var b=await async function(C){var I=pe;if(!le&&typeof WebAssembly.instantiateStreaming=="function"&&!ge(I))try{var W=fetch(I,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(W,C)}catch(se){x(`wasm streaming compile failed: ${se}`),x("falling back to ArrayBuffer instantiation")}return async function(se,ye){try{var Te=await async function(ze){if(!le)try{var Ye=await h(ze);return new Uint8Array(Ye)}catch{}if(ze==pe&&le)ze=new Uint8Array(le);else{if(!w)throw"both async and sync fetching of the wasm failed";ze=w(ze)}return ze}(se);return await WebAssembly.instantiate(Te,ye)}catch(ze){x(`failed to asynchronously prepare wasm: ${ze}`),Ie(ze)}}(I,C)}(m);return c(b.instance,b.module)}catch(C){return i(C),Promise.reject(C)}})();var qi=c=>(qi=Oe.Cb)(c),qn=()=>(qn=Oe.Db)();n._OrtInit=(c,m)=>(n._OrtInit=Oe.Eb)(c,m),n._OrtGetLastError=(c,m)=>(n._OrtGetLastError=Oe.Fb)(c,m),n._OrtCreateSessionOptions=(c,m,b,C,I,W,se,ye,Te,ze)=>(n._OrtCreateSessionOptions=Oe.Gb)(c,m,b,C,I,W,se,ye,Te,ze),n._OrtAppendExecutionProvider=(c,m)=>(n._OrtAppendExecutionProvider=Oe.Hb)(c,m),n._OrtAddFreeDimensionOverride=(c,m,b)=>(n._OrtAddFreeDimensionOverride=Oe.Ib)(c,m,b),n._OrtAddSessionConfigEntry=(c,m,b)=>(n._OrtAddSessionConfigEntry=Oe.Jb)(c,m,b),n._OrtReleaseSessionOptions=c=>(n._OrtReleaseSessionOptions=Oe.Kb)(c),n._OrtCreateSession=(c,m,b)=>(n._OrtCreateSession=Oe.Lb)(c,m,b),n._OrtReleaseSession=c=>(n._OrtReleaseSession=Oe.Mb)(c),n._OrtGetInputOutputCount=(c,m,b)=>(n._OrtGetInputOutputCount=Oe.Nb)(c,m,b),n._OrtGetInputName=(c,m)=>(n._OrtGetInputName=Oe.Ob)(c,m),n._OrtGetOutputName=(c,m)=>(n._OrtGetOutputName=Oe.Pb)(c,m),n._OrtFree=c=>(n._OrtFree=Oe.Qb)(c),n._OrtCreateTensor=(c,m,b,C,I,W)=>(n._OrtCreateTensor=Oe.Rb)(c,m,b,C,I,W),n._OrtGetTensorData=(c,m,b,C,I)=>(n._OrtGetTensorData=Oe.Sb)(c,m,b,C,I),n._OrtReleaseTensor=c=>(n._OrtReleaseTensor=Oe.Tb)(c),n._OrtCreateRunOptions=(c,m,b,C)=>(n._OrtCreateRunOptions=Oe.Ub)(c,m,b,C),n._OrtAddRunConfigEntry=(c,m,b)=>(n._OrtAddRunConfigEntry=Oe.Vb)(c,m,b),n._OrtReleaseRunOptions=c=>(n._OrtReleaseRunOptions=Oe.Wb)(c),n._OrtCreateBinding=c=>(n._OrtCreateBinding=Oe.Xb)(c),n._OrtBindInput=(c,m,b)=>(n._OrtBindInput=Oe.Yb)(c,m,b),n._OrtBindOutput=(c,m,b,C)=>(n._OrtBindOutput=Oe.Zb)(c,m,b,C),n._OrtClearBoundOutputs=c=>(n._OrtClearBoundOutputs=Oe._b)(c),n._OrtReleaseBinding=c=>(n._OrtReleaseBinding=Oe.$b)(c),n._OrtRunWithBinding=(c,m,b,C,I)=>(n._OrtRunWithBinding=Oe.ac)(c,m,b,C,I),n._OrtRun=(c,m,b,C,I,W,se,ye)=>(n._OrtRun=Oe.bc)(c,m,b,C,I,W,se,ye),n._OrtEndProfiling=c=>(n._OrtEndProfiling=Oe.cc)(c),n._JsepOutput=(c,m,b)=>(n._JsepOutput=Oe.dc)(c,m,b),n._JsepGetNodeName=c=>(n._JsepGetNodeName=Oe.ec)(c);var yn=()=>(yn=Oe.fc)(),Rr=n._free=c=>(Rr=n._free=Oe.gc)(c),tn=n._malloc=c=>(tn=n._malloc=Oe.ic)(c),Qn=(c,m,b,C,I,W)=>(Qn=Oe.kc)(c,m,b,C,I,W),Qi=()=>(Qi=Oe.lc)(),Xn=(c,m,b,C,I)=>(Xn=Oe.mc)(c,m,b,C,I),Xi=c=>(Xi=Oe.nc)(c),Jn=c=>(Jn=Oe.oc)(c),Yn=(c,m)=>(Yn=Oe.pc)(c,m),Ji=()=>(Ji=Oe.qc)(),_t=(c,m)=>(_t=Oe.rc)(c,m),Bs=c=>(Bs=Oe.sc)(c),Yi=(c,m)=>(Yi=Oe.tc)(c,m),ht=c=>(ht=Oe.uc)(c),Mn=c=>(Mn=Oe.vc)(c),ft=()=>(ft=Oe.wc)(),Zi=c=>(Zi=Oe.xc)(c),Zn=c=>(Zn=Oe.yc)(c),eo=(c,m,b)=>(eo=Oe.zc)(c,m,b),to=c=>(to=Oe.Ac)(c),ei=n.dynCall_iii=(c,m,b)=>(ei=n.dynCall_iii=Oe.Bc)(c,m,b),ro=n.dynCall_vi=(c,m)=>(ro=n.dynCall_vi=Oe.Cc)(c,m),ti=n.dynCall_ii=(c,m)=>(ti=n.dynCall_ii=Oe.Dc)(c,m),ri=n.dynCall_vii=(c,m,b)=>(ri=n.dynCall_vii=Oe.Ec)(c,m,b),so=n.dynCall_iiii=(c,m,b,C)=>(so=n.dynCall_iiii=Oe.Fc)(c,m,b,C),no=n.dynCall_viii=(c,m,b,C)=>(no=n.dynCall_viii=Oe.Gc)(c,m,b,C),si=n.dynCall_iiiii=(c,m,b,C,I)=>(si=n.dynCall_iiiii=Oe.Hc)(c,m,b,C,I),io=n.dynCall_viiii=(c,m,b,C,I)=>(io=n.dynCall_viiii=Oe.Ic)(c,m,b,C,I),oo=n.dynCall_viiiiii=(c,m,b,C,I,W,se)=>(oo=n.dynCall_viiiiii=Oe.Jc)(c,m,b,C,I,W,se),ni=n.dynCall_viiiiiii=(c,m,b,C,I,W,se,ye)=>(ni=n.dynCall_viiiiiii=Oe.Kc)(c,m,b,C,I,W,se,ye),ao=n.dynCall_ji=(c,m)=>(ao=n.dynCall_ji=Oe.Lc)(c,m),lo=n.dynCall_v=c=>(lo=n.dynCall_v=Oe.Mc)(c),ii=n.dynCall_viiiii=(c,m,b,C,I,W)=>(ii=n.dynCall_viiiii=Oe.Nc)(c,m,b,C,I,W),co=n.dynCall_i=c=>(co=n.dynCall_i=Oe.Oc)(c),uo=n.dynCall_fii=(c,m,b)=>(uo=n.dynCall_fii=Oe.Pc)(c,m,b),oi=n.dynCall_viiiiiiii=(c,m,b,C,I,W,se,ye,Te)=>(oi=n.dynCall_viiiiiiii=Oe.Qc)(c,m,b,C,I,W,se,ye,Te),po=n.dynCall_viiiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze,Ye)=>(po=n.dynCall_viiiiiiiiii=Oe.Rc)(c,m,b,C,I,W,se,ye,Te,ze,Ye),ho=n.dynCall_jiii=(c,m,b,C)=>(ho=n.dynCall_jiii=Oe.Sc)(c,m,b,C),ai=n.dynCall_dii=(c,m,b)=>(ai=n.dynCall_dii=Oe.Tc)(c,m,b),mo=n.dynCall_viiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze)=>(mo=n.dynCall_viiiiiiiii=Oe.Uc)(c,m,b,C,I,W,se,ye,Te,ze),fo=n.dynCall_viiiiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot)=>(fo=n.dynCall_viiiiiiiiiii=Oe.Vc)(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot),_o=n.dynCall_iiiiii=(c,m,b,C,I,W)=>(_o=n.dynCall_iiiiii=Oe.Wc)(c,m,b,C,I,W),go=n.dynCall_iij=(c,m,b)=>(go=n.dynCall_iij=Oe.Xc)(c,m,b),li=n.dynCall_iiiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze)=>(li=n.dynCall_iiiiiiiiii=Oe.Yc)(c,m,b,C,I,W,se,ye,Te,ze),wo=n.dynCall_iiiiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze,Ye)=>(wo=n.dynCall_iiiiiiiiiii=Oe.Zc)(c,m,b,C,I,W,se,ye,Te,ze,Ye),yo=n.dynCall_vij=(c,m,b)=>(yo=n.dynCall_vij=Oe._c)(c,m,b),di=n.dynCall_iiif=(c,m,b,C)=>(di=n.dynCall_iiif=Oe.$c)(c,m,b,C),Mo=n.dynCall_iiij=(c,m,b,C)=>(Mo=n.dynCall_iiij=Oe.ad)(c,m,b,C),bo=n.dynCall_fiii=(c,m,b,C)=>(bo=n.dynCall_fiii=Oe.bd)(c,m,b,C),ci=n.dynCall_viiiiiiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)=>(ci=n.dynCall_viiiiiiiiiiiii=Oe.cd)(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt),vo=n.dynCall_vjiii=(c,m,b,C,I)=>(vo=n.dynCall_vjiii=Oe.dd)(c,m,b,C,I),xo=n.dynCall_vif=(c,m,b)=>(xo=n.dynCall_vif=Oe.ed)(c,m,b),ui=n.dynCall_iiiiiii=(c,m,b,C,I,W,se)=>(ui=n.dynCall_iiiiiii=Oe.fd)(c,m,b,C,I,W,se),To=n.dynCall_iiiij=(c,m,b,C,I)=>(To=n.dynCall_iiiij=Oe.gd)(c,m,b,C,I),Eo=n.dynCall_iiiiiiii=(c,m,b,C,I,W,se,ye)=>(Eo=n.dynCall_iiiiiiii=Oe.hd)(c,m,b,C,I,W,se,ye),pi=n.dynCall_viiiiiiiiiiii=(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt)=>(pi=n.dynCall_viiiiiiiiiiii=Oe.id)(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt),Po=n.dynCall_diii=(c,m,b,C)=>(Po=n.dynCall_diii=Oe.jd)(c,m,b,C),Co=n.dynCall_jiiii=(c,m,b,C,I)=>(Co=n.dynCall_jiiii=Oe.kd)(c,m,b,C,I),hi=n.dynCall_viiij=(c,m,b,C,I)=>(hi=n.dynCall_viiij=Oe.ld)(c,m,b,C,I),So=n.dynCall_fiiii=(c,m,b,C,I)=>(So=n.dynCall_fiiii=Oe.md)(c,m,b,C,I),$o=n.dynCall_viiif=(c,m,b,C,I)=>($o=n.dynCall_viiif=Oe.nd)(c,m,b,C,I),mi=n.dynCall_diiii=(c,m,b,C,I)=>(mi=n.dynCall_diiii=Oe.od)(c,m,b,C,I),ko=n.dynCall_viiid=(c,m,b,C,I)=>(ko=n.dynCall_viiid=Oe.pd)(c,m,b,C,I),Io=n.dynCall_iiiijii=(c,m,b,C,I,W,se)=>(Io=n.dynCall_iiiijii=Oe.qd)(c,m,b,C,I,W,se),Ao=n.dynCall_iiiiiij=(c,m,b,C,I,W,se)=>(Ao=n.dynCall_iiiiiij=Oe.rd)(c,m,b,C,I,W,se),Fo=c=>(Fo=Oe.sd)(c),fi=()=>(fi=Oe.td)(),Oo=c=>(Oo=Oe.ud)(c),Do=()=>(Do=Oe.vd)();function Wa(c,m,b){var C=ft();try{ri(c,m,b)}catch(I){if(ht(C),I!==I+0)throw I;_t(1,0)}}function Ga(c,m,b){var C=ft();try{return ei(c,m,b)}catch(I){if(ht(C),I!==I+0)throw I;_t(1,0)}}function Lo(c,m){var b=ft();try{ro(c,m)}catch(C){if(ht(b),C!==C+0)throw C;_t(1,0)}}function Ka(c,m){var b=ft();try{return ti(c,m)}catch(C){if(ht(b),C!==C+0)throw C;_t(1,0)}}function Ha(c,m,b,C){var I=ft();try{return so(c,m,b,C)}catch(W){if(ht(I),W!==W+0)throw W;_t(1,0)}}function qa(c,m,b,C,I){var W=ft();try{io(c,m,b,C,I)}catch(se){if(ht(W),se!==se+0)throw se;_t(1,0)}}function Qa(c,m,b,C,I){var W=ft();try{return si(c,m,b,C,I)}catch(se){if(ht(W),se!==se+0)throw se;_t(1,0)}}function zo(c,m,b,C){var I=ft();try{no(c,m,b,C)}catch(W){if(ht(I),W!==W+0)throw W;_t(1,0)}}function Xa(c,m,b,C,I,W,se){var ye=ft();try{return ui(c,m,b,C,I,W,se)}catch(Te){if(ht(ye),Te!==Te+0)throw Te;_t(1,0)}}function Ja(c){var m=ft();try{lo(c)}catch(b){if(ht(m),b!==b+0)throw b;_t(1,0)}}function Ya(c,m,b){var C=ft();try{return go(c,m,b)}catch(I){if(ht(C),I!==I+0)throw I;_t(1,0)}}function Za(c,m,b,C,I,W){var se=ft();try{ii(c,m,b,C,I,W)}catch(ye){if(ht(se),ye!==ye+0)throw ye;_t(1,0)}}function Bo(c,m,b){var C=ft();try{yo(c,m,b)}catch(I){if(ht(C),I!==I+0)throw I;_t(1,0)}}function el(c,m,b,C,I,W,se){var ye=ft();try{oo(c,m,b,C,I,W,se)}catch(Te){if(ht(ye),Te!==Te+0)throw Te;_t(1,0)}}function tl(c,m,b,C,I,W,se,ye){var Te=ft();try{ni(c,m,b,C,I,W,se,ye)}catch(ze){if(ht(Te),ze!==ze+0)throw ze;_t(1,0)}}function Ro(c,m,b,C,I,W){var se=ft();try{return _o(c,m,b,C,I,W)}catch(ye){if(ht(se),ye!==ye+0)throw ye;_t(1,0)}}function rl(c,m,b,C,I,W,se,ye){var Te=ft();try{return Eo(c,m,b,C,I,W,se,ye)}catch(ze){if(ht(Te),ze!==ze+0)throw ze;_t(1,0)}}function sl(c,m,b,C,I,W,se,ye,Te,ze){var Ye=ft();try{mo(c,m,b,C,I,W,se,ye,Te,ze)}catch(ot){if(ht(Ye),ot!==ot+0)throw ot;_t(1,0)}}function No(c,m,b,C,I,W,se,ye,Te){var ze=ft();try{oi(c,m,b,C,I,W,se,ye,Te)}catch(Ye){if(ht(ze),Ye!==Ye+0)throw Ye;_t(1,0)}}function nl(c){var m=ft();try{return co(c)}catch(b){if(ht(m),b!==b+0)throw b;_t(1,0)}}function il(c,m,b,C,I,W,se,ye,Te,ze){var Ye=ft();try{return li(c,m,b,C,I,W,se,ye,Te,ze)}catch(ot){if(ht(Ye),ot!==ot+0)throw ot;_t(1,0)}}function jo(c,m,b){var C=ft();try{return uo(c,m,b)}catch(I){if(ht(C),I!==I+0)throw I;_t(1,0)}}function ol(c,m,b,C){var I=ft();try{return ho(c,m,b,C)}catch(W){if(ht(I),W!==W+0)throw W;return _t(1,0),0n}}function al(c,m,b){var C=ft();try{return ai(c,m,b)}catch(I){if(ht(C),I!==I+0)throw I;_t(1,0)}}function Uo(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot){var gt=ft();try{fo(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot)}catch(Bt){if(ht(gt),Bt!==Bt+0)throw Bt;_t(1,0)}}function ll(c,m,b,C,I,W,se,ye,Te,ze,Ye){var ot=ft();try{po(c,m,b,C,I,W,se,ye,Te,ze,Ye)}catch(gt){if(ht(ot),gt!==gt+0)throw gt;_t(1,0)}}function dl(c,m,b,C,I,W,se,ye,Te,ze,Ye){var ot=ft();try{return wo(c,m,b,C,I,W,se,ye,Te,ze,Ye)}catch(gt){if(ht(ot),gt!==gt+0)throw gt;_t(1,0)}}function _i(c,m,b,C){var I=ft();try{return di(c,m,b,C)}catch(W){if(ht(I),W!==W+0)throw W;_t(1,0)}}function cl(c,m,b,C){var I=ft();try{return Mo(c,m,b,C)}catch(W){if(ht(I),W!==W+0)throw W;_t(1,0)}}function ul(c,m,b,C){var I=ft();try{return bo(c,m,b,C)}catch(W){if(ht(I),W!==W+0)throw W;_t(1,0)}}function Vo(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt){var Ir=ft();try{ci(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt,Bt)}catch(rn){if(ht(Ir),rn!==rn+0)throw rn;_t(1,0)}}function Wo(c,m,b,C,I){var W=ft();try{vo(c,m,b,C,I)}catch(se){if(ht(W),se!==se+0)throw se;_t(1,0)}}function pl(c,m,b){var C=ft();try{xo(c,m,b)}catch(I){if(ht(C),I!==I+0)throw I;_t(1,0)}}function Go(c,m){var b=ft();try{return ao(c,m)}catch(C){if(ht(b),C!==C+0)throw C;return _t(1,0),0n}}function hl(c,m,b,C,I){var W=ft();try{return To(c,m,b,C,I)}catch(se){if(ht(W),se!==se+0)throw se;_t(1,0)}}function ml(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt){var Bt=ft();try{pi(c,m,b,C,I,W,se,ye,Te,ze,Ye,ot,gt)}catch(Ir){if(ht(Bt),Ir!==Ir+0)throw Ir;_t(1,0)}}function fl(c,m,b,C){var I=ft();try{return Po(c,m,b,C)}catch(W){if(ht(I),W!==W+0)throw W;_t(1,0)}}function Ko(c,m,b,C,I){var W=ft();try{return Co(c,m,b,C,I)}catch(se){if(ht(W),se!==se+0)throw se;return _t(1,0),0n}}function _l(c,m,b,C,I){var W=ft();try{hi(c,m,b,C,I)}catch(se){if(ht(W),se!==se+0)throw se;_t(1,0)}}function gl(c,m,b,C,I){var W=ft();try{return So(c,m,b,C,I)}catch(se){if(ht(W),se!==se+0)throw se;_t(1,0)}}function wl(c,m,b,C,I){var W=ft();try{$o(c,m,b,C,I)}catch(se){if(ht(W),se!==se+0)throw se;_t(1,0)}}function Ho(c,m,b,C,I){var W=ft();try{return mi(c,m,b,C,I)}catch(se){if(ht(W),se!==se+0)throw se;_t(1,0)}}function yl(c,m,b,C,I){var W=ft();try{ko(c,m,b,C,I)}catch(se){if(ht(W),se!==se+0)throw se;_t(1,0)}}function Ml(c,m,b,C,I,W,se){var ye=ft();try{return Io(c,m,b,C,I,W,se)}catch(Te){if(ht(ye),Te!==Te+0)throw Te;_t(1,0)}}function qo(c,m,b,C,I,W,se){var ye=ft();try{return Ao(c,m,b,C,I,W,se)}catch(Te){if(ht(ye),Te!==Te+0)throw Te;_t(1,0)}}return n.stackSave=()=>ft(),n.stackRestore=c=>ht(c),n.stackAlloc=c=>Mn(c),n.setValue=function(c,m,b="i8"){switch(b.endsWith("*")&&(b="*"),b){case"i1":case"i8":N()[c>>>0]=m;break;case"i16":G()[c>>>1>>>0]=m;break;case"i32":X()[c>>>2>>>0]=m;break;case"i64":H[c>>>3]=BigInt(m);break;case"float":fe()[c>>>2>>>0]=m;break;case"double":ke()[c>>>3>>>0]=m;break;case"*":we()[c>>>2>>>0]=m;break;default:Ie(`invalid type for setValue: ${b}`)}},n.getValue=function(c,m="i8"){switch(m.endsWith("*")&&(m="*"),m){case"i1":case"i8":return N()[c>>>0];case"i16":return G()[c>>>1>>>0];case"i32":return X()[c>>>2>>>0];case"i64":return H[c>>>3];case"float":return fe()[c>>>2>>>0];case"double":return ke()[c>>>3>>>0];case"*":return we()[c>>>2>>>0];default:Ie(`invalid type for getValue: ${m}`)}},n.UTF8ToString=zt,n.stringToUTF8=Tr,n.lengthBytesUTF8=ss,function c(){if(0{hu(),sc=typeof location>"u"?void 0:location.origin,Hc=import.meta.url>"file:"&&import.meta.url<"file;",af=()=>{{if(Hc){let e=URL;return new URL(new e("ort.bundle.min.mjs",import.meta.url).href,sc).href}return import.meta.url}},jr=af(),hy=()=>{if(jr&&!jr.startsWith("blob:"))return jr.substring(0,jr.lastIndexOf("/")+1)},jl=(e,r)=>{try{let t=r??jr;return(t?new URL(e,t):new URL(e)).origin===sc}catch{return!1}},lf=(e,r)=>{let t=r??jr;try{return(t?new URL(e,t):new URL(e)).href}catch{return}},df=(e,r)=>`${r??"./"}${e}`,nc=async e=>{let r=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(r)},cf=async e=>(await import(e)).default,ic=(Iv(),nd(dy)).default,my=async()=>{if(!jr)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(jl(jr))return[void 0,ic()];let e=await nc(jr);return[e,ic(e)]},oc=(Av(),nd(uy)).default,fy=async(e,r,t)=>{if(!e&&!r&&oc&&jr&&jl(jr))return[void 0,oc];{let s="ort-wasm-simd-threaded.jsep.mjs",i=e??lf(s,r),n=t&&i&&!jl(i,r),o=n?await nc(i):i??df(s,r);return[n?o:void 0,await cf(o)]}}}),ac,Ul,Yo,lc,uf,pf,fu,ur,Ln=je(()=>{mu(),Ul=!1,Yo=!1,lc=!1,uf=()=>{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}},pf=()=>{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}},fu=async e=>{if(Ul)return Promise.resolve();if(Yo)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(lc)throw new Error("previous call to 'initializeWebAssembly()' failed.");Yo=!0;let r=e.initTimeout,t=e.numThreads;if(!pf())throw new Error("WebAssembly SIMD is not supported in the current environment.");let s=uf();t>1&&!s&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+t+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=t=1);let i=e.wasmPaths,n=typeof i=="string"?i:void 0,o=i==null?void 0:i.mjs,a=(o==null?void 0:o.href)??o,l=i==null?void 0:i.wasm,d=(l==null?void 0:l.href)??l,p=e.wasmBinary,[u,h]=await fy(a,n,t>1),w=!1,_=[];if(r>0&&_.push(new Promise(P=>{setTimeout(()=>{w=!0,P()},r)})),_.push(new Promise((P,A)=>{let v={numThreads:t};if(p)v.wasmBinary=p;else if(d||n)v.locateFile=y=>d??n+y;else if(a&&a.indexOf("blob:")!==0)v.locateFile=y=>new URL(y,a).href;else if(u){let y=hy();y&&(v.locateFile=S=>y+S)}h(v).then(y=>{Yo=!1,Ul=!0,ac=y,P(),u&&URL.revokeObjectURL(u)},y=>{Yo=!1,lc=!0,A(y)})})),await Promise.race(_),w)throw new Error(`WebAssembly backend initializing failed due to timeout: ${r}ms`)},ur=()=>{if(Ul&&ac)return ac;throw new Error("WebAssembly is not initialized yet.")}}),xr,id,Ot,_u=je(()=>{Ln(),xr=(e,r)=>{let t=ur(),s=t.lengthBytesUTF8(e)+1,i=t._malloc(s);return t.stringToUTF8(e,i,s),r.push(i),i},id=(e,r,t,s)=>{if(typeof e=="object"&&e!==null){if(t.has(e))throw new Error("Circular reference in options");t.add(e)}Object.entries(e).forEach(([i,n])=>{let o=r?r+i:i;if(typeof n=="object")id(n,o+".",t,s);else if(typeof n=="string"||typeof n=="number")s(o,n.toString());else if(typeof n=="boolean")s(o,n?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof n}`)})},Ot=e=>{let r=ur(),t=r.stackSave();try{let s=r.PTR_SIZE,i=r.stackAlloc(2*s);r._OrtGetLastError(i,i+s);let n=Number(r.getValue(i,s===4?"i32":"i64")),o=r.getValue(i+s,"*"),a=o?r.UTF8ToString(o):"";throw new Error(`${e} ERROR_CODE: ${n}, ERROR_MESSAGE: ${a}`)}finally{r.stackRestore(t)}}}),_y,Fv=je(()=>{Ln(),_u(),_y=e=>{let r=ur(),t=0,s=[],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 n=0;return(e==null?void 0:e.tag)!==void 0&&(n=xr(e.tag,s)),t=r._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,n),t===0&&Ot("Can't create run options."),(e==null?void 0:e.extra)!==void 0&&id(e.extra,"",new WeakSet,(o,a)=>{let l=xr(o,s),d=xr(a,s);r._OrtAddRunConfigEntry(t,l,d)!==0&&Ot(`Can't set a run config entry: ${o} - ${a}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseRunOptions(t),s.forEach(o=>r._free(o)),n}}}),hf,mf,ff,_f,gy,Ov=je(()=>{Ln(),_u(),hf=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}`)}},mf=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},ff=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let r=e.extra.session;r.use_ort_model_bytes_directly||(r.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(t=>(typeof t=="string"?t:t.name)==="webgpu")&&(e.enableMemPattern=!1)},_f=(e,r,t)=>{for(let s of r){let i=typeof s=="string"?s:s.name;switch(i){case"webnn":if(i="WEBNN",typeof s!="string"){let o=s==null?void 0:s.deviceType;if(o){let a=xr("deviceType",t),l=xr(o,t);ur()._OrtAddSessionConfigEntry(e,a,l)!==0&&Ot(`Can't set a session config entry: 'deviceType' - ${o}.`)}}break;case"webgpu":if(i="JS",typeof s!="string"){let o=s;if(o!=null&&o.preferredLayout){if(o.preferredLayout!=="NCHW"&&o.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${o.preferredLayout}`);let a=xr("preferredLayout",t),l=xr(o.preferredLayout,t);ur()._OrtAddSessionConfigEntry(e,a,l)!==0&&Ot(`Can't set a session config entry: 'preferredLayout' - ${o.preferredLayout}.`)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${i}`)}let n=xr(i,t);ur()._OrtAppendExecutionProvider(e,n)!==0&&Ot(`Can't append execution provider: ${i}.`)}},gy=e=>{let r=ur(),t=0,s=[],i=e||{};ff(i);try{let n=hf(i.graphOptimizationLevel??"all"),o=mf(i.executionMode??"sequential"),a=typeof i.logId=="string"?xr(i.logId,s):0,l=i.logSeverityLevel??2;if(!Number.isInteger(l)||l<0||l>4)throw new Error(`log serverity level is not valid: ${l}`);let d=i.logVerbosityLevel??0;if(!Number.isInteger(d)||d<0||d>4)throw new Error(`log verbosity level is not valid: ${d}`);let p=typeof i.optimizedModelFilePath=="string"?xr(i.optimizedModelFilePath,s):0;if(t=r._OrtCreateSessionOptions(n,!!i.enableCpuMemArena,!!i.enableMemPattern,o,!!i.enableProfiling,0,a,l,d,p),t===0&&Ot("Can't create session options."),i.executionProviders&&_f(t,i.executionProviders,s),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);let u=xr("enableGraphCapture",s),h=xr(i.enableGraphCapture.toString(),s);r._OrtAddSessionConfigEntry(t,u,h)!==0&&Ot(`Can't set a session config entry: 'enableGraphCapture' - ${i.enableGraphCapture}.`)}if(i.freeDimensionOverrides)for(let[u,h]of Object.entries(i.freeDimensionOverrides)){if(typeof u!="string")throw new Error(`free dimension override name must be a string: ${u}`);if(typeof h!="number"||!Number.isInteger(h)||h<0)throw new Error(`free dimension override value must be a non-negative integer: ${h}`);let w=xr(u,s);r._OrtAddFreeDimensionOverride(t,w,h)!==0&&Ot(`Can't set a free dimension override: ${u} - ${h}.`)}return i.extra!==void 0&&id(i.extra,"",new WeakSet,(u,h)=>{let w=xr(u,s),_=xr(h,s);r._OrtAddSessionConfigEntry(t,w,_)!==0&&Ot(`Can't set a session config entry: ${u} - ${h}.`)}),[t,s]}catch(n){throw t!==0&&r._OrtReleaseSessionOptions(t)!==0&&Ot("Can't release session options."),s.forEach(o=>r._free(o)),n}}}),bi,kn,In,gu,od,wu,yu,qc,mt=je(()=>{bi=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}`)}},kn=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}`)}},In=(e,r)=>{let t=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],s=typeof r=="number"?r:r.reduce((i,n)=>i*n,1);return t>0?Math.ceil(s*t):void 0},gu=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}`)}},od=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}`)}},wu=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",yu=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",qc=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}`)}}}),Mu,wy=je(()=>{hu(),Mu=async e=>{if(typeof e=="string"){let r=await fetch(e);if(!r.ok)throw new Error(`failed to load external data file: ${e}`);let t=r.headers.get("Content-Length"),s=t?parseInt(t,10):0;if(s<1073741824)return new Uint8Array(await r.arrayBuffer());{if(!r.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let i=r.body.getReader(),n;try{n=new ArrayBuffer(s)}catch(a){if(a instanceof RangeError){let l=Math.ceil(s/65536);n=new WebAssembly.Memory({initial:l,maximum:l}).buffer}else throw a}let o=0;for(;;){let{done:a,value:l}=await i.read();if(a)break;let d=l.byteLength;new Uint8Array(n,o,d).set(l),o+=d}return new Uint8Array(n,0,s)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),gf,wf,yf,Mf,bu,bf,St,Vs=je(()=>{mt(),gf=["V","I","W","E","F"],wf=(e,r)=>{console.log(`[${gf[e]},${new Date().toISOString()}]${r}`)},bu=(e,r)=>{yf=e,Mf=r},bf=(e,r)=>{let t=od(e),s=od(yf);t>=s&&wf(t,typeof r=="function"?r():r)},St=(...e)=>{Mf&&bf(...e)}}),vu,yy=je(()=>{mt(),vu=(e,r)=>new(gu(r))(e)}),xu=je(()=>{}),dc,Vl,Wl,vf,xf,cc,Qc,Tf,My,Dv=je(()=>{Vs(),xu(),dc=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]]),Vl=[],Wl=e=>Math.ceil(Number(e)/16)*16,vf=e=>{for(let r=0;rxf++,Qc=async(e,r,t,s)=>{let i=Wl(t),n=e.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let o=e.getCommandEncoder();e.endComputePass(),o.copyBufferToBuffer(r,0,n,0,i),e.flush(),await n.mapAsync(GPUMapMode.READ);let a=n.getMappedRange();if(s){let l=s();return l.set(new Uint8Array(a,0,t)),l}else return new Uint8Array(a.slice(0,t))}finally{n.destroy()}},Tf=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[r]of dc)Vl.push(r),this.freeBuffers.set(r,[]),this.freeUniformBuffers.set(r,[]);this.sessionCount=0}upload(e,r){let t=r.buffer,s=r.byteOffset,i=r.byteLength,n=Wl(i),o=this.storageCache.get(e);if(!o)throw new Error("gpu data for uploading does not exist");if(Number(o.originalSize)!==i)throw new Error(`inconsistent data size. gpu data size=${o.originalSize}, data size=${i}`);let a=this.backend.device.createBuffer({mappedAtCreation:!0,size:n,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),l=a.getMappedRange();new Uint8Array(l).set(new Uint8Array(t,s,i)),a.unmap();let d=this.backend.device.createCommandEncoder();d.copyBufferToBuffer(a,0,o.gpuData.buffer,0,n),this.backend.device.queue.submit([d.finish()]),a.destroy(),St("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,r){let t=this.storageCache.get(e);if(!t)throw new Error("source gpu data for memcpy does not exist");let s=this.storageCache.get(r);if(!s)throw new Error("destination gpu data for memcpy does not exist");if(t.originalSize!==s.originalSize)throw new Error("inconsistent source and destination gpu data size");let i=Wl(t.originalSize),n=this.backend.getCommandEncoder();this.backend.endComputePass(),n.copyBufferToBuffer(t.gpuData.buffer,0,s.gpuData.buffer,0,i)}registerExternalBuffer(e,r,t){let s;if(t){if(s=t[0],e===t[1])return St("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, buffer is the same, skip.`),s;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`)}else s=cc();return this.storageCache.set(s,{gpuData:{id:s,type:0,buffer:e},originalSize:r}),St("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${r}) => id=${s}, registered.`),s}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),St("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,r=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let t=vf(e),s,i=(r&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,n=(r&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(i||n){let a=(i?this.freeBuffers:this.freeUniformBuffers).get(t);a?a.length>0?s=a.pop():s=this.backend.device.createBuffer({size:t,usage:r}):s=this.backend.device.createBuffer({size:t,usage:r})}else s=this.backend.device.createBuffer({size:t,usage:r});let o={id:cc(),type:0,buffer:s};return this.storageCache.set(o.id,{gpuData:o,originalSize:Number(e)}),St("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${o.id}`),o}get(e){var r;return(r=this.storageCache.get(e))==null?void 0:r.gpuData}release(e){let r=typeof e=="bigint"?Number(e):e,t=this.storageCache.get(r);if(!t){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return St("verbose",()=>`[WebGPU] GpuDataManager.release(id=${r}), gpuDataId=${t.gpuData.id}`),this.storageCache.delete(r),this.buffersPending.push(t.gpuData.buffer),t.originalSize}async download(e,r){let t=this.storageCache.get(Number(e));if(!t)throw new Error("data does not exist");await Qc(this.backend,t.gpuData.buffer,t.originalSize,r)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let r=dc.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let t=this.freeBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let t=this.freeUniformBuffers.get(e.size)||[];r===void 0||t.length>=r?e.destroy():t.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let r of this.buffersPending)e.push(r);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(r=>{r.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let r=this.capturedPendingBuffers.get(e);r&&(r.forEach(t=>{t.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(St("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(t=>{t.gpuData.buffer.destroy()}),this.storageCache=new Map)}},My=(...e)=>new Tf(...e)}),Ef,Lt,tr=je(()=>{Ef=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 Ef(e)}),Pf,Ei,xe,ad,by,vy,xy,Mt=je(()=>{Pf=class{static calcMatMulShape(e,r){return e[1]!==r[0]?void 0:[e[0],r[1]]}},Ei=class{static calcShape(e,r,t=!1){let s=e.length,i=r.length;if(s===0)return r;if(i===0)return e;let n=Math.max(e.length,r.length),o=new Array(n);if(t){if(s<2||i<2)return;let a=Pf.calcMatMulShape([e[s-2],e[s-1]],[r[i-2],r[i-1]]);if(a===void 0)return;[o[n-2],o[n-1]]=a}for(let a=t?3:1;a<=n;a++){let l=s-a<0?1:e[s-a],d=i-a<0?1:r[i-a];if(l!==d&&l>1&&d>1)return;let p=Math.max(l,d);if(l&&d)o[n-a]=Math.max(l,d);else{if(p>1)return;o[n-a]=0}}return o}static isValidBroadcast(e,r){let t=e.length,s=r.length;if(t>s)return!1;for(let i=1;i<=t;i++)if(e[t-i]!==1&&e[t-i]!==r[s-i])return!1;return!0}},xe=class rd{static size(r){return rd.getSizeFromDimensionRange(r,0,r.length)}static convertShape(r,t=4){let s=r.length;if(s===0)return[];let i=new Array(s),n=s-1;for(;n>=0;){if(r[n]%t===0){i[n]=r[n]/t;break}if(t%r[n]!==0)throw new Error("cannot convert shape");i[n]=1,t/=r[n],n--}for(n--;n>=0;n--)i[n]=r[n];return i}static sizeFromDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeFromDimension as Tensor has ${r.length} dimensions.`);return rd.getSizeFromDimensionRange(r,t,r.length)}static sizeToDimension(r,t){if(t<0||t>r.length)throw new Error(`invalid dimension of ${t} for sizeToDimension as Tensor has ${r.length} dimensions.`);return rd.getSizeFromDimensionRange(r,0,t)}static getSizeFromDimensionRange(r,t,s){let i=1;for(let n=t;n=0;--i)s[i]=s[i+1]*r[i+1];return s}static normalizeAxis(r,t){if(r<-t&&r>=t)throw new Error("unsupported axis for this operation.");return r<0?r+t:r}static normalizeAxes(r,t){return r.map(s=>this.normalizeAxis(s,t??r.length))}static sortBasedOnPerm(r,t){return t?t.map(s=>r[s]):r.slice().reverse()}static padShape(r,t){let s=r.length;return r.map((i,n)=>i+t[n]+t[n+s])}static areEqual(r,t){return r.length!==t.length?!1:r.every((s,i)=>s===t[i])}},ad=class aa{static adjustPoolAttributes(r,t,s,i,n,o){if(!r&&s.length!==t.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(r)for(let a=0;a=s.length?s.push(t[a+2]):s[a]=t[a+2];for(let a=0;a=s[a]||o[a+s.length]>=s[a])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(r,t,s,i,n,o,a){if(a){if(n.length!==2*(r.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(t.length!==r.length-2)throw new Error("length of strides should be the length of data dimensions");if(i.length!==r.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let l=0;l{mt(),Mt(),Pi=64,Gl=(e,r)=>{if(r===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return r>1?`vec${r}`:"f16";case 1:return r>1?`vec${r}`:"f32";case 6:return r>1?`vec${r}`:"i32";case 12:return r>1?`vec${r}`:"u32";case 7:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(r>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(r!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},pr=(e,r=1)=>{let t=Gl(e,r);return typeof t=="string"?t:t[0]},Cr=(e,r=1)=>{let t=Gl(e,r);return typeof t=="string"?t:t[1]},nt=(...e)=>{let r=[];return e.forEach(t=>{t.length!==0&&r.push({type:12,data:t},{type:12,data:xe.computeStrides(t)})}),r},Jt=e=>e%4===0?4:e%2===0?2:1,Xc=(e="f32",r,t="0")=>!r||r===1?`${e}(${t})`:`vec${r}<${e}>(${t})`,xi=(e,r,t)=>e==="f32"?t:r===1?`f32(${t})`:`vec${r}(${t})`,cn=(e,r)=>r===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:r===2?`(${e}.x + ${e}.y)`:r===3?`(${e}.x + ${e}.y + ${e}.z)`:e,rt=(e,r,t,s)=>e.startsWith("uniforms.")&&t>4?typeof r=="string"?s==="f16"?`${e}[(${r}) / 8][(${r}) % 8 / 4][(${r}) % 8 % 4]`:`${e}[(${r}) / 4][(${r}) % 4]`:s==="f16"?`${e}[${Math.floor(r/8)}][${Math.floor(r%8/4)}][${r%8%4}]`:`${e}[${Math.floor(r/4)}][${r%4}]`:t>1?`${e}[${r}]`:e,Zo=(e,r,t,s,i)=>{let n=typeof t=="number",o=n?t:t.length,a=[...new Array(o).keys()],l=o<2?"u32":o<=4?`vec${o}`:`array`,d=Gl(r,i),p=typeof d=="string"?d:d[1],u=typeof d=="string"?d:d[0],h={indices:l,value:p,storage:u,tensor:r},w=N=>typeof N=="string"?N:`${N}u`,_={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},P=n?"uniforms.":"",A=`${P}${e}_shape`,v=`${P}${e}_strides`,y="";for(let N=0;N ${h.indices} { + var indices: ${h.indices}; + var current = offset; + ${y} + return indices; + }`,x=N=>(_.offsetToIndices=!0,o<2?N:`o2i_${e}(${N})`),g=[];if(o>=2)for(let N=o-1;N>=0;N--)g.push(`${rt(v,N,o)} * (indices[${N}])`);let M=o<2?"":` + fn i2o_${e}(indices: ${h.indices}) -> u32 { + return ${g.join("+")}; + }`,E=N=>(_.indicesToOffset=!0,o<2?N:`i2o_${e}(${N})`),k=(...N)=>o===0?"0u":`${h.indices}(${N.map(w).join(",")})`,B=(N,O)=>o<2?`${N}`:`${rt(N,O,o)}`,R=(N,O,G)=>o<2?`${N}=${G};`:`${rt(N,O,o)}=${G};`,J={},q=(N,O)=>{_.broadcastedIndicesToOffset=!0;let G=`${O.name}broadcastedIndicesTo${e}Offset`;if(G in J)return`${G}(${N})`;let ne=[];for(let X=o-1;X>=0;X--){let we=O.indicesGet("outputIndices",X+O.rank-o);ne.push(`${B(v,X)} * (${we} % ${B(A,X)})`)}return J[G]=`fn ${G}(outputIndices: ${O.type.indices}) -> u32 { + return ${ne.length>0?ne.join("+"):"0u"}; + }`,`${G}(${N})`},V=(N,O)=>(()=>{if(h.storage===h.value)return`${e}[${N}]=${O};`;if(h.storage==="vec2"&&h.value==="i32")return`${e}[${N}]=vec2(u32(${O}), select(0u, 0xFFFFFFFFu, ${O} < 0));`;if(h.storage==="vec2"&&h.value==="u32")return`${e}[${N}]=vec2(u32(${O}), 0u);`;if(h.storage==="u32"&&h.value==="vec4")return`${e}[${N}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${O}));`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),Y=N=>(()=>{if(h.storage===h.value)return`${e}[${N}]`;if(h.storage==="vec2"&&h.value==="i32")return`i32(${e}[${N}].x)`;if(h.storage==="vec2"&&h.value==="u32")return`u32(${e}[${N}].x)`;if(h.storage==="u32"&&h.value==="vec4")return`vec4(bool(${e}[${N}] & 0xFFu), bool(${e}[${N}] & 0xFF00u), bool(${e}[${N}] & 0xFF0000u), bool(${e}[${N}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${h.storage} and value type ${h.value} yet`)})(),H=o<2?"":` + fn get_${e}ByIndices(indices: ${h.indices}) -> ${p} { + return ${Y(`i2o_${e}(indices)`)}; + }`,Q=o<2?"":(()=>{let N=a.map(G=>`d${G}: u32`).join(", "),O=a.map(G=>`d${G}`).join(", ");return` + fn get_${e}(${N}) -> ${p} { + return get_${e}ByIndices(${k(O)}); + }`})(),ie=(...N)=>{if(N.length!==o)throw new Error(`indices length must be ${o}`);let O=N.map(w).join(",");return o===0?Y("0u"):o===1?Y(O[0]):(_.get=!0,_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}(${O})`)},le=N=>o<2?Y(N):(_.getByIndices=!0,_.indicesToOffset=!0,`get_${e}ByIndices(${N})`),ae=o<2?"":` + fn set_${e}ByIndices(indices: ${h.indices}, value: ${p}) { + ${V(`i2o_${e}(indices)`,"value")} + }`,ge=o<2?"":(()=>{let N=a.map(G=>`d${G}: u32`).join(", "),O=a.map(G=>`d${G}`).join(", ");return` + fn set_${e}(${N}, value: ${p}) { + set_${e}ByIndices(${k(O)}, value); + }`})();return{impl:()=>{let N=[],O=!1;return _.offsetToIndices&&(N.push(S),O=!0),_.indicesToOffset&&(N.push(M),O=!0),_.broadcastedIndicesToOffset&&(Object.values(J).forEach(G=>N.push(G)),O=!0),_.set&&(N.push(ge),O=!0),_.setByIndices&&(N.push(ae),O=!0),_.get&&(N.push(Q),O=!0),_.getByIndices&&(N.push(H),O=!0),!n&&O&&N.unshift(`const ${A} = ${h.indices}(${t.join(",")});`,`const ${v} = ${h.indices}(${xe.computeStrides(t).join(",")});`),N.join(` +`)},type:h,offsetToIndices:x,indicesToOffset:E,broadcastedIndicesToOffset:q,indices:k,indicesGet:B,indicesSet:R,set:(...N)=>{if(N.length!==o+1)throw new Error(`indices length must be ${o}`);let O=N[o];if(typeof O!="string")throw new Error("value must be string");let G=N.slice(0,o).map(w).join(",");return o===0?V("0u",O):o===1?V(G[0],O):(_.set=!0,_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}(${G}, ${O})`)},setByOffset:V,setByIndices:(N,O)=>o<2?V(N,O):(_.setByIndices=!0,_.indicesToOffset=!0,`set_${e}ByIndices(${N}, ${O});`),get:ie,getByOffset:Y,getByIndices:le,usage:s,name:e,strides:v,shape:A,rank:o}},$e=(e,r,t,s=1)=>Zo(e,r,t,"input",s),tt=(e,r,t,s=1)=>Zo(e,r,t,"output",s),Ty=(e,r,t)=>Zo(e,r,t,"atomicOutput",1),Tu=(e,r,t,s=1)=>Zo(e,r,t,"internal",s),Cf=class{constructor(e,r){this.normalizedDispatchGroup=e,this.limits=r,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=Pi){let r=typeof e=="number"?e:e[0],t=typeof e=="number"?1:e[1],s=typeof e=="number"?1:e[2];if(r>this.limits.maxComputeWorkgroupSizeX||t>this.limits.maxComputeWorkgroupSizeY||s>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(r*t*s>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${r}, ${t}, ${s}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let i=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,n=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`,o=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 * ${r*t*s}u + local_idx;`;return`@compute @workgroup_size(${r}, ${t}, ${s}) + fn main(${n}) { + ${o} + `}appendVariableUniforms(e){e.rank!==0&&(e.shape.startsWith("uniforms.")&&this.uniforms.push({name:e.shape.replace("uniforms.",""),type:"u32",length:e.rank}),e.strides.startsWith("uniforms.")&&this.uniforms.push({name:e.strides.replace("uniforms.",""),type:"u32",length:e.rank}))}declareVariable(e,r){if(e.usage==="internal")throw new Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(e),this.appendVariableUniforms(e);let t=e.usage==="input"?"read":"read_write",s=e.usage==="atomicOutput"?"atomic":e.type.storage;return`@group(0) @binding(${r}) var ${e.name}: array<${s}>;`}declareVariables(...e){return e.map(r=>this.declareVariable(r,this.variableIndex++)).join(` +`)}registerInternalVariable(e){if(e.usage!=="internal")throw new Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(e),this.appendVariableUniforms(e)}registerInternalVariables(...e){return e.forEach(r=>this.registerInternalVariable(r)),this}registerUniform(e,r,t=1){return this.uniforms.push({name:e,type:r,length:t}),this}registerUniforms(e){return this.uniforms=this.uniforms.concat(e),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let e=[];for(let{name:r,type:t,length:s}of this.uniforms)if(s&&s>4)t==="f16"?e.push(`@align(16) ${r}:array, ${Math.ceil(s/8)}>`):e.push(`${r}:array, ${Math.ceil(s/4)}>`);else{let i=s==null||s===1?t:`vec${s}<${t}>`;e.push(`${r}:${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=r=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(r)];return this.uniforms.map(r=>[e(r.type),r.length??1])}},Ey=(e,r)=>new Cf(e,r)}),Sf,uc,$f,kf,If,Af,Vr,Py,Cy,un=je(()=>{mt(),Mt(),tr(),xt(),Sf=(e,r)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(r.length!==0&&r.length!==e[0].dims.length)throw new Error(`perm size ${r.length} does not match input rank ${e[0].dims.length}`)},uc=(e,r)=>r.length!==0?r:[...new Array(e).keys()].reverse(),$f=(e,r)=>xe.sortBasedOnPerm(e,uc(e.length,r)),kf=(e,r,t,s)=>{let i=`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`;for(let n=0;n{let t=[],s=[];for(let i=0;i{let t=0;for(let s=0;s{let t=e.dataType,s=e.dims.length,i=uc(s,r),n=$f(e.dims,i),o=e.dims,a=n,l=s<2||Af(i,e.dims),d;if(l)return d=_=>{let P=$e("input",t,o,4),A=tt("output",t,a,4);return` + ${_.registerUniform("output_size","u32").declareVariables(P,A)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + output[global_idx] = input[global_idx]; + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let _=xe.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64/4)},programUniforms:[{type:12,data:Math.ceil(_/4)}]}},getShaderSource:d};let{newShape:p,newPerm:u}=If(e.dims,i),h=xe.areEqual(u,[2,3,1]),w=xe.areEqual(u,[3,1,2]);if(p.length===2||h||w){o=h?[p[0],p[1]*p[2]]:w?[p[0]*p[1],p[2]]:p,a=[o[1],o[0]];let _=16;return d=P=>{let A=$e("a",t,o.length),v=tt("output",t,a.length);return` + ${P.registerUniform("output_size","u32").declareVariables(A,v)} + var tile : array, ${_}>; + ${P.mainStart([_,_,1])} + let stride = (uniforms.output_shape[1] - 1) / ${_} + 1; + let workgroup_id_x = workgroup_index % stride; + let workgroup_id_y = workgroup_index / stride; + let input_col = workgroup_id_y * ${_}u + local_id.x; + let input_row = workgroup_id_x * ${_}u + local_id.y; + if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) { + tile[local_id.y][local_id.x] = ${A.getByIndices(`${A.type.indices}(input_row, input_col)`)}; + } + workgroupBarrier(); + + let output_col = workgroup_id_x * ${_}u + local_id.x; + let output_row = workgroup_id_y * ${_}u + local_id.y; + if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) { + ${v.setByIndices(`${v.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")} + } + }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let P=xe.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(a[1]/_),y:Math.ceil(a[0]/_)},programUniforms:[{type:12,data:P},...nt(o,a)]}},getShaderSource:d}}return d=_=>{let P=$e("a",t,o.length),A=tt("output",t,a.length);return` + ${_.registerUniform("output_size","u32").declareVariables(P,A)} + + ${kf(i,s,P,A)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${A.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${A.setByOffset("global_idx",P.getByIndices("aIndices"))} + }`},{name:"Transpose",shaderCache:{hint:`${r}`,inputDependencies:["rank"]},getRunData:()=>{let _=xe.size(n);return{outputs:[{dims:n,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...nt(o,a)]}},getShaderSource:d}},Py=(e,r)=>{Sf(e.inputs,r.perm),e.compute(Vr(e.inputs[0],r.perm))},Cy=e=>Lt({perm:e.perm})}),Ff,Of,Df,Lf,zf,Bf,Rf,Nf,jf,Uf,us,Sy,$y,ky,Iy,Ay,Fy,Oy,Dy,Ly,zy,Lv=je(()=>{mt(),Mt(),xt(),Eu(),un(),Ff={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"},Of={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"},Df={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Lf={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},zf=(e,r)=>{let t=[];for(let s=r-e;s{let t=[],s=e.length;for(let n=0;ne[n]);return[t,i]},Rf=(e,r)=>{let t=e.length+r.length,s=[],i=0;for(let n=0;n{for(let t=0;t{let t=[];if(!Nf(e,r)){for(let s=0;st.push(s))}return t},Uf=(e,r,t,s,i,n,o)=>{let a=t[0].dims,l=xe.size(n),d=xe.size(o),p=$e("_A",t[0].dataType,a),u=tt("output",i,n),h=64;l===1&&(h=256);let w=` + var aBestValues : array; + `,_=P=>` + ${P.registerUniform("reduceSize","u32").declareVariables(p,u)} + ${w} + fn DIV_CEIL(a : u32, b : u32) -> u32 { + return ((a - 1u) / b + 1u); + } + ${P.mainStart(h)} + + let outputIndex = global_idx / ${h}; + let offset = outputIndex * uniforms.reduceSize; + + var bestValue = f32(${Df[s]}); + let Length = uniforms.reduceSize; + for (var k = local_idx; k < Length; k = k + ${h}) { + let candidate = f32(${p.getByOffset("offset + k")}); + bestValue = ${Ff[s]}; + } + aBestValues[local_idx] = bestValue; + workgroupBarrier(); + + var reduceSize = min(Length, ${h}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 = ${Of[s]}; + aBestValues[local_idx] = bestValue; + } + reduceSize = interval; + workgroupBarrier(); + } + + if (local_idx == 0u) { + ${u.setByOffset("outputIndex",`${s==="mean"?`${u.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${u.type.storage}(${Lf[s]})`}`)}; + } + }`;return{name:e,shaderCache:{hint:`${r};${h}`,inputDependencies:["type"]},getShaderSource:_,getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:l},programUniforms:[{type:12,data:d}]})}},us=(e,r,t,s)=>{let i=e.inputs.length===1?t:Jc(e.inputs,t),n=i.axes;n.length===0&&!i.noopWithEmptyAxes&&(n=e.inputs[0].dims.map((w,_)=>_));let o=xe.normalizeAxes(n,e.inputs[0].dims.length),a=o,l=e.inputs[0],d=jf(a,e.inputs[0].dims.length);d.length>0&&(l=e.compute(Vr(e.inputs[0],d),{inputs:[0],outputs:[-1]})[0],a=zf(a.length,l.dims.length));let[p,u]=Bf(l.dims,a),h=p;i.keepDims&&(h=Rf(p,o)),e.compute(Uf(r,i.cacheKey,[l],s,e.inputs[0].dataType,h,u),{inputs:[l]})},Sy=(e,r)=>{us(e,"ReduceMeanShared",r,"mean")},$y=(e,r)=>{us(e,"ReduceL1Shared",r,"l1")},ky=(e,r)=>{us(e,"ReduceL2Shared",r,"l2")},Iy=(e,r)=>{us(e,"ReduceLogSumExpShared",r,"logSumExp")},Ay=(e,r)=>{us(e,"ReduceMaxShared",r,"max")},Fy=(e,r)=>{us(e,"ReduceMinShared",r,"min")},Oy=(e,r)=>{us(e,"ReduceProdShared",r,"prod")},Dy=(e,r)=>{us(e,"ReduceSumShared",r,"sum")},Ly=(e,r)=>{us(e,"ReduceSumSquareShared",r,"sumSquare")},zy=(e,r)=>{us(e,"ReduceLogSumShared",r,"logSum")}}),ps,Vf,ld,Jc,hs,Wf,Gf,Kf,Hf,qf,Qf,Xf,Jf,Yf,Zf,ms,By,Ry,Ny,jy,Uy,Vy,Wy,Gy,Ky,Hy,Eu=je(()=>{mt(),Mt(),tr(),xt(),Lv(),ps=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.")},Vf=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],ld=(e,r,t,s,i,n,o=!1,a=!1)=>{let l=[],d=t[0].dims,p=d.length,u=xe.normalizeAxes(i,p),h=!a&&u.length===0;d.forEach((P,A)=>{h||u.indexOf(A)>=0?o&&l.push(1):l.push(P)});let w=l.length,_=xe.size(l);return{name:e,shaderCache:r,getShaderSource:P=>{let A=[],v=$e("_A",t[0].dataType,p),y=tt("output",n,w),S=s(v,y,u),x=S[2];for(let g=0,M=0;g=0?(o&&M++,x=`for(var j${g}: u32 = 0; j${g} < ${d[g]}; j${g}++) { + ${S[2].includes("last_index")?`let last_index = j${g};`:""} + ${v.indicesSet("input_indices",g,`j${g}`)} + ${x} + }`):(A.push(`${v.indicesSet("input_indices",g,y.indicesGet("output_indices",M))};`),M++);return` + + ${P.registerUniform("output_size","u32").declareVariables(v,y)} + + ${P.mainStart()} + ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var input_indices: ${v.type.indices}; + let output_indices = ${y.offsetToIndices("global_idx")}; + + ${A.join(` +`)} + ${S[0]} // init ops for reduce max/min + ${S[1]} + ${x} + ${S[3]} + ${S.length===4?y.setByOffset("global_idx","value"):S.slice(4).join(` +`)} + }`},getRunData:()=>({outputs:[{dims:l,dataType:n}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:[{type:12,data:_},...nt(d,l)]})}},Jc=(e,r)=>{let t=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(s=>t.push(Number(s))),Lt({axes:t,keepDims:r.keepDims,noopWithEmptyAxes:r.noopWithEmptyAxes})},hs=(e,r,t,s)=>{let i=e.inputs,n=i.length===1?t:Jc(i,t);e.compute(ld(r,{hint:n.cacheKey,inputDependencies:["rank"]},[i[0]],n.noopWithEmptyAxes&&n.axes.length===0?Vf:s,n.axes,i[0].dataType,n.keepDims,n.noopWithEmptyAxes),{inputs:[0]})},Wf=(e,r)=>{ps(e.inputs),hs(e,"ReduceLogSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,"value = log(value);"])},Gf=(e,r)=>{ps(e.inputs),hs(e,"ReduceL1",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += abs(${t.getByIndices("input_indices")});`,""])},Kf=(e,r)=>{ps(e.inputs),hs(e,"ReduceL2",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},Hf=(e,r)=>{ps(e.inputs),hs(e,"ReduceLogSumExp",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += exp(${t.getByIndices("input_indices")});`,"value = log(value);"])},qf=(e,r)=>{ps(e.inputs),hs(e,"ReduceMax",r,(t,s,i)=>{let n=[];for(let o=0;o=0||i.length===0)&&n.push(t.indicesSet("input_indices",o,0));return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = max(value, ${t.getByIndices("input_indices")});`,""]})},Qf=(e,r)=>{ps(e.inputs),hs(e,"ReduceMean",r,(t,s,i)=>{let n=1;for(let o=0;o=0||i.length===0)&&(n*=e.inputs[0].dims[o]);return["var sum = f32(0);","",`sum += f32(${t.getByIndices("input_indices")});`,`let value = ${s.type.value}(sum / ${n});`]})},Xf=(e,r)=>{ps(e.inputs),hs(e,"ReduceMin",r,(t,s,i)=>{let n=[];for(let o=0;o=0||i.length===0)&&n.push(`input_indices[${o}] = 0;`);return[`${n.join(` +`)}`,`var value = ${t.getByIndices("input_indices")};`,`value = min(value, ${t.getByIndices("input_indices")});`,""]})},Jf=(e,r)=>{ps(e.inputs),hs(e,"ReduceProd",r,(t,s)=>[`var value = ${s.type.storage}(1);`,"",`value *= ${t.getByIndices("input_indices")};`,""])},Yf=(e,r)=>{ps(e.inputs),hs(e,"ReduceSum",r,(t,s)=>[`var value = ${s.type.storage}(0);`,"",`value += ${t.getByIndices("input_indices")};`,""])},Zf=(e,r)=>{ps(e.inputs),hs(e,"ReduceSumSquare",r,(t,s)=>[`var t = ${s.type.value}(0); var value = ${s.type.value}(0);`,"",`t = ${t.getByIndices("input_indices")}; value += t * t;`,""])},ms=(e,r,t)=>{if(r.length===0)return t;let s=1,i=1;for(let n=0;n1024},By=(e,r)=>{ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Qf(e,r):Sy(e,r)},Ry=(e,r)=>{ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Gf(e,r):$y(e,r)},Ny=(e,r)=>{ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Kf(e,r):ky(e,r)},jy=(e,r)=>{ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Hf(e,r):Iy(e,r)},Uy=(e,r)=>{ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?qf(e,r):Ay(e,r)},Vy=(e,r)=>{ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Xf(e,r):Fy(e,r)},Wy=(e,r)=>{ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Jf(e,r):Oy(e,r)},Gy=(e,r)=>{ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Yf(e,r):Dy(e,r)},Ky=(e,r)=>{ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Zf(e,r):Ly(e,r)},Hy=(e,r)=>{ms(e.inputs[0].dims,r.axes,r.noopWithEmptyAxes)?Wf(e,r):zy(e,r)}}),pc,qy,Qy,Yc,zv=je(()=>{mt(),tr(),Eu(),pc=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.")},qy=(e,r)=>{pc(e.inputs);let t=(s,i,n)=>{let o=[];for(let a=0;a=0||n.length===0)&&o.push(`input_indices[${a}] = 0;`);return[`${o.join(` +`)}`,`var value = ${s.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?"<=":"<"} value) { + value = ${s.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(ld("ArgMin",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Qy=(e,r)=>{pc(e.inputs);let t=(s,i,n)=>{let o=[];for(let a=0;a=0||n.length===0)&&o.push(`input_indices[${a}] = 0;`);return[`${o.join(` +`)}`,`var value = ${s.getByIndices("input_indices")}; +var best_index : i32 = 0;`,`if (${s.getByIndices("input_indices")} ${r.selectLastIndex>0?">=":">"} value) { + value = ${s.getByIndices("input_indices")}; + best_index = i32(last_index); + }`,"",i.setByOffset("global_idx","best_index")]};e.compute(ld("argMax",{hint:r.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],t,[r.axis],7,r.keepDims),{inputs:[0]})},Yc=e=>Lt(e)}),e_,Kl,t_,r_,s_,fa,n_,Xy,Pu=je(()=>{mt(),Mt(),xu(),xt(),e_=(e,r)=>{let t=e[0],s=e[1],i=e[2],n=e[3],o=e[4],a=e[5];if(o&&a)throw new Error("Attention cannot have both past and attention_bias");if(t.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let l=t.dims[0],d=t.dims[1],p=t.dims[2];if(i.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(s.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(s.dims[0]!==p)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(i.dims[0]!==s.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let u=i.dims[0]/3,h=u,w=h;if(r.qkvHiddenSizes.length>0){if(r.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let S of r.qkvHiddenSizes)if(S%r.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");u=r.qkvHiddenSizes[0],h=r.qkvHiddenSizes[1],w=r.qkvHiddenSizes[2]}let _=d;if(u!==h)throw new Error("qkv_hidden_sizes first element should be same as the second");if(i.dims[0]!==u+h+w)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let P=0;if(o){if(h!==w)throw new Error('Input "past" expect k_hidden_size == v_hidden_size');if(o.dims.length!==5)throw new Error('Input "past" must have 5 dimensions');if(o.dims[0]!==2)throw new Error('Input "past" first dimension must be 2');if(o.dims[1]!==l)throw new Error('Input "past" second dimension must be batch_size');if(o.dims[2]!==r.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(o.dims[4]!==h/r.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');r.pastPresentShareBuffer||(P=o.dims[3])}let A=_+P,v=-1,y=0;if(n)throw new Error("Mask not supported");if(o)throw new Error("past is not supported");if(a){if(a.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(a.dims[0]!==l||a.dims[1]!==r.numHeads||a.dims[2]!==d||a.dims[3]!==A)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:l,sequenceLength:d,pastSequenceLength:P,kvSequenceLength:_,totalSequenceLength:A,maxSequenceLength:v,inputHiddenSize:p,hiddenSize:u,vHiddenSize:w,headSize:Math.floor(u/r.numHeads),vHeadSize:Math.floor(w/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:y,scale:r.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Kl=(e,r,t)=>r&&e?` + let total_sequence_length_input = u32(${r.getByOffset("0")}); + let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); + let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; + let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input; + total_sequence_length = u32(${e==null?void 0:e.getByOffset("batchIdx")}) + 1; + var past_sequence_length: u32 = 0; + if (is_first_prompt == false) { + past_sequence_length = total_sequence_length - sequence_length; + } + `:` + ${t?"let past_sequence_length = uniforms.past_sequence_length":""}; + let present_sequence_length = total_sequence_length; + `,t_=(e,r,t,s,i,n,o,a)=>{let l=Jt(o?1:n),d=64,p=n/l;p{let y=tt("x",e.dataType,e.dims,l),S=[y],x=o?$e("seq_lens",o.dataType,o.dims):void 0;x&&S.push(x);let g=a?$e("total_sequence_length_input",a.dataType,a.dims):void 0;g&&S.push(g);let M=Cr(e.dataType),E=[{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; + ${v.registerUniforms(E).declareVariables(...S)} + ${v.mainStart([d,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; + ${Kl(x,g,!1)} + let local_offset = local_idx * uniforms.elements_per_thread; + let offset = (global_idx / ${d}) * uniforms.total_sequence_length + local_offset; + let seq_causal_length = ${o?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; + var thread_max_vector = ${_}(-3.402823e+38f); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + thread_max_vector = max(${_}(x[offset + i]), thread_max_vector); + } + thread_max[local_idx] = ${(()=>{switch(l){case 1:return"thread_max_vector";case 2:return"max(thread_max_vector.x, thread_max_vector.y)";case 4:return"max(max(thread_max_vector.x, thread_max_vector.y), max(thread_max_vector.z, thread_max_vector.w))";default:throw new Error(`Unsupported components: ${l}`)}})()}; + workgroupBarrier(); + + var max_value = f32(-3.402823e+38f); + for (var i = 0u; i < ${d}; i++) { + max_value = max(thread_max[i], max_value); + } + + var sum_vector = ${_}(0); + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + sum_vector += exp(${_}(x[offset + i]) - max_value); + } + thread_sum[local_idx] = ${(()=>{switch(l){case 1:return"sum_vector";case 2:return"sum_vector.x + sum_vector.y";case 4:return"sum_vector.x + sum_vector.y + sum_vector.z + sum_vector.w";default:throw new Error(`Unsupported components: ${l}`)}})()}; + workgroupBarrier(); + + var sum: f32 = 0; + for (var i = 0u; i < ${d}; 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] = ${y.type.value}(${M}(1.0) / ${M}(seq_causal_length)); + } + } else { + for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) { + var f32input = ${_}(x[offset + i]); + x[offset + i] = ${y.type.value}(exp(f32input - max_value) / sum); + } + } + ${o?` + 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] = ${y.type.value}(${M}(0)); + }`:""}; + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${d};${w};${l}`,inputDependencies:P},getShaderSource:A,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:i,z:r*t},programUniforms:h})}},r_=(e,r,t,s,i,n,o,a,l)=>{let d=o+n.kvSequenceLength,p=[n.batchSize,n.numHeads,n.sequenceLength,d],u=e>1&&s,h=n.kvNumHeads?n.kvNumHeads:n.numHeads,w=u?[n.batchSize,h,d,n.headSize]:void 0,_=n.nReps?n.nReps:1,P=n.scale===0?1/Math.sqrt(n.headSize):n.scale,A=Jt(n.headSize),v=n.headSize/A,y=12,S={x:Math.ceil(d/y),y:Math.ceil(n.sequenceLength/y),z:n.batchSize*n.numHeads},x=[{type:12,data:n.sequenceLength},{type:12,data:v},{type:12,data:d},{type:12,data:n.numHeads},{type:12,data:n.headSize},{type:1,data:P},{type:12,data:o},{type:12,data:n.kvSequenceLength},{type:12,data:_}],g=u&&s&&xe.size(s.dims)>0,M=["type","type"];g&&M.push("type"),i&&M.push("type"),a&&M.push("type"),l&&M.push("type");let E=[{dims:p,dataType:r.dataType,gpuDataType:0}];u&&E.push({dims:w,dataType:r.dataType,gpuDataType:0});let k=B=>{let R=$e("q",r.dataType,r.dims,A),J=$e("key",t.dataType,t.dims,A),q=[R,J];if(g){let ae=$e("past_key",s.dataType,s.dims,A);q.push(ae)}i&&q.push($e("attention_bias",i.dataType,i.dims));let V=a?$e("seq_lens",a.dataType,a.dims):void 0;V&&q.push(V);let Y=l?$e("total_sequence_length_input",l.dataType,l.dims):void 0;Y&&q.push(Y);let H=tt("output",r.dataType,p),Q=[H];u&&Q.push(tt("present_key",r.dataType,w,A));let ie=Cr(1,A),le=[{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 = ${y}u; + + var tileQ: array<${R.type.storage}, ${y*y}>; + var tileK: array<${R.type.storage}, ${y*y}>; + ${B.registerUniforms(le).declareVariables(...q,...Q)} + ${B.mainStart([y,y,1])} + // x holds the N and y holds the M + let headIdx = workgroup_id.z % uniforms.num_heads; + let kvHeadIdx = ${_===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${_===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"}; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let m = workgroup_id.y * TILE_SIZE; + let n = workgroup_id.x * TILE_SIZE; + let sequence_length = uniforms.M; + var total_sequence_length = uniforms.N; + ${Kl(V,Y,!0)} + let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; + let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; + ${g&&u?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; + let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K; + ${u?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""} + var value = ${ie}(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; + ${g&&u?` + if (n + local_id.y < past_sequence_length) { + tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + } else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x]; + }`:` + if (n + local_id.y < uniforms.kv_sequence_length) { + tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x]; + }`} + ${u?`if (n + local_id.y < present_sequence_length) { + present_key[presentKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x] = tileK[idx]; + }`:""} + } + workgroupBarrier(); + + for (var k: u32 = 0u; k < TILE_SIZE && w+k < uniforms.K; k++) { + value += ${ie}(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(A){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: ${A}`)}})()}; + output[outputIdx] = ${H.type.value} (sum * uniforms.alpha) + ${i?"attention_bias[outputIdx]":"0.0"}; + } + }`};return{name:"AttentionProbs",shaderCache:{hint:`${A};${i!==void 0};${s!==void 0};${e}`,inputDependencies:M},getRunData:()=>({outputs:E,dispatchGroup:S,programUniforms:x}),getShaderSource:k}},s_=(e,r,t,s,i,n,o=void 0,a=void 0)=>{let l=n+i.kvSequenceLength,d=i.nReps?i.nReps:1,p=i.vHiddenSize*d,u=e>1&&s,h=i.kvNumHeads?i.kvNumHeads:i.numHeads,w=u?[i.batchSize,h,l,i.headSize]:void 0,_=[i.batchSize,i.sequenceLength,p],P=12,A={x:Math.ceil(i.vHeadSize/P),y:Math.ceil(i.sequenceLength/P),z:i.batchSize*i.numHeads},v=[{type:12,data:i.sequenceLength},{type:12,data:l},{type:12,data:i.vHeadSize},{type:12,data:i.numHeads},{type:12,data:i.headSize},{type:12,data:p},{type:12,data:n},{type:12,data:i.kvSequenceLength},{type:12,data:d}],y=u&&s&&xe.size(s.dims)>0,S=["type","type"];y&&S.push("type"),o&&S.push("type"),a&&S.push("type");let x=[{dims:_,dataType:r.dataType,gpuDataType:0}];u&&x.push({dims:w,dataType:r.dataType,gpuDataType:0});let g=M=>{let E=$e("probs",r.dataType,r.dims),k=$e("v",t.dataType,t.dims),B=[E,k];y&&B.push($e("past_value",s.dataType,s.dims));let R=o?$e("seq_lens",o.dataType,o.dims):void 0;o&&B.push(R);let J=a?$e("total_sequence_length_input",a.dataType,a.dims):void 0;a&&B.push(J);let q=[tt("output",r.dataType,_)];u&&q.push(tt("present_value",r.dataType,w));let V=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + const TILE_SIZE = ${P}u; + var tileQ: array<${E.type.value}, ${P*P}>; + var tileV: array<${E.type.value}, ${P*P}>; + ${M.registerUniforms(V).declareVariables(...B,...q)} + ${M.mainStart([P,P,1])} + let headIdx = workgroup_id.z % uniforms.num_heads; + let batchIdx = workgroup_id.z / uniforms.num_heads; + let kvHeadIdx = ${d===1?"headIdx":"headIdx / uniforms.n_reps"}; + let kv_num_heads = ${d===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; + ${Kl(R,J,!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 + ${y&&u?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; + let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n; + ${u?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""} + var value = ${E.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; + ${y&&u?` + if (w + local_id.y < past_sequence_length) { + tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N]; + } else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N]; + } + `:` + if (w + local_id.y < uniforms.kv_sequence_length) { + tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N]; + }`} + ${u?` + if (w + local_id.y < present_sequence_length) { + present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx]; + }`:""} + } + workgroupBarrier(); + for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) { + value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x]; + } + workgroupBarrier(); + } + + // we need to transpose output from BNSH_v to BSND_v + if (m < uniforms.M && n < uniforms.N) { + let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size + + headIdx * uniforms.N + n; + output[outputIdx] = value; + } + }`};return{name:"AttentionScore",shaderCache:{hint:`${s!==void 0};${e}`,inputDependencies:S},getRunData:()=>({outputs:x,dispatchGroup:A,programUniforms:v}),getShaderSource:g}},fa=(e,r,t,s,i,n,o,a,l,d,p=void 0,u=void 0)=>{let h=Math.min(e.outputCount,1+(o?1:0)+(a?1:0)),w=h>1?d.pastSequenceLength:0,_=w+d.kvSequenceLength,P=l&&xe.size(l.dims)>0?l:void 0,A=[r,t];h>1&&o&&xe.size(o.dims)>0&&A.push(o),P&&A.push(P),p&&A.push(p),u&&A.push(u);let v=e.compute(r_(h,r,t,o,P,d,w,p,u),{inputs:A,outputs:h>1?[-1,1]:[-1]})[0];e.compute(t_(v,d.batchSize,d.numHeads,w,d.sequenceLength,_,p,u),{inputs:p&&u?[v,p,u]:[v],outputs:[]});let y=[v,s];h>1&&a&&xe.size(a.dims)>0&&y.push(a),p&&y.push(p),u&&y.push(u),e.compute(s_(h,v,s,a,d,w,p,u),{inputs:y,outputs:h>1?[0,2]:[0]})},n_=(e,r)=>{let t=[r.batchSize,r.numHeads,r.sequenceLength,r.headSize],s=r.sequenceLength,i=r.inputHiddenSize,n=r.headSize,o=12,a={x:Math.ceil(r.headSize/o),y:Math.ceil(r.sequenceLength/o),z:r.batchSize*r.numHeads},l=[e.inputs[0],e.inputs[1],e.inputs[2]],d=[{type:12,data:s},{type:12,data:i},{type:12,data:n},{type:12,data:r.numHeads},{type:12,data:r.headSize},{type:12,data:r.hiddenSize},{type:12,data:r.hiddenSize+r.hiddenSize+r.vHiddenSize}],p=u=>{let h=tt("output_q",l[0].dataType,t),w=tt("output_k",l[0].dataType,t),_=tt("output_v",l[0].dataType,t),P=$e("input",l[0].dataType,l[0].dims),A=$e("weight",l[1].dataType,l[1].dims),v=$e("bias",l[2].dataType,l[2].dims),y=P.type.storage,S=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"hidden_size",type:"u32"},{name:"ldb",type:"u32"}];return` + const TILE_SIZE = ${o}u; + var tileInput: array<${y}, ${o*o}>; + var tileWeightQ: array<${y}, ${o*o}>; + var tileWeightK: array<${y}, ${o*o}>; + var tileWeightV: array<${y}, ${o*o}>; + ${u.registerUniforms(S).declareVariables(P,A,v,h,w,_)} + ${u.mainStart([o,o,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 = ${y}(0); + var valueK = ${y}(0); + var valueV = ${y}(0); + for (var w: u32 = 0u; w < uniforms.K; w += TILE_SIZE) { + if (m < uniforms.M && w + local_id.x < uniforms.K) { + tileInput[TILE_SIZE * local_id.y + local_id.x] = input[inputOffset + w + local_id.x]; + } + if (n < uniforms.N && w + local_id.y < uniforms.K) { + let offset = n + (w + local_id.y) * uniforms.ldb; + tileWeightQ[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetQ + offset]; + tileWeightK[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetK + offset]; + tileWeightV[TILE_SIZE * local_id.y + local_id.x] = weight[biasOffsetV + offset]; + } + workgroupBarrier(); + for (var k: u32 = 0u; k({outputs:[{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:t,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:a,programUniforms:d}),getShaderSource:p},{inputs:l,outputs:[-1,-1,-1]})},Xy=(e,r)=>{let t=e_(e.inputs,r),[s,i,n]=n_(e,t);return fa(e,s,i,n,e.inputs[4],void 0,void 0,void 0,e.inputs[5],t)}}),i_,o_,a_,Jy,Bv=je(()=>{Ms(),mt(),Mt(),tr(),xt(),i_=(e,r)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let t=(s,i,n)=>{let o=i.length;if(o!==s.length)throw new Error(`${n}: num dimensions != ${o}`);i.forEach((a,l)=>{if(a!==s[l])throw new Error(`${n}: dim[${l}] do not match`)})};if(e[0].dims.length>1){let s=r.format==="NHWC"?r.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,r.spatial?2:void 0);t(e[1].dims,s,"Invalid input scale"),t(e[2].dims,s,"Invalid input B"),t(e[3].dims,s,"Invalid input mean"),t(e[4].dims,s,"Invalid input var")}else t(e[1].dims,[1],"Invalid input scale"),t(e[2].dims,[1],"Invalid input B"),t(e[3].dims,[1],"Invalid input mean"),t(e[4].dims,[1],"Invalid input var")},o_=(e,r)=>{let{epsilon:t,spatial:s,format:i}=r,n=e[0].dims,o=s?Jt(n[n.length-1]):1,a=i==="NHWC"&&n.length>1?o:1,l=xe.size(n)/o,d=s,p=d?n.length:n,u=$e("x",e[0].dataType,e[0].dims,o),h=$e("scale",e[1].dataType,e[1].dims,a),w=$e("bias",e[2].dataType,e[2].dims,a),_=$e("inputMean",e[3].dataType,e[3].dims,a),P=$e("inputVar",e[4].dataType,e[4].dims,a),A=tt("y",e[0].dataType,p,o),v=()=>{let S="";if(s)S=`let cOffset = ${n.length===1?"0u":i==="NHWC"?`outputIndices[${n.length-1}] / ${o}`:"outputIndices[1]"};`;else if(i==="NCHW")S=` + ${A.indicesSet("outputIndices","0","0")} + let cOffset = ${A.indicesToOffset("outputIndices")};`;else{S=`var cIndices = ${h.type.indices}(0); + cIndices[0] = outputIndices[${n.length-1}];`;for(let x=1;x` + const epsilon = ${t}; + ${S.registerUniform("outputSize","u32").declareVariables(u,h,w,_,P,A)} + ${S.mainStart()} + ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${A.offsetToIndices(`global_idx * ${o}`)}; + ${v()} + let scale = ${h.getByOffset("cOffset")}; + let bias = ${w.getByOffset("cOffset")}; + let inputMean = ${_.getByOffset("cOffset")}; + let inputVar = ${P.getByOffset("cOffset")}; + let x = ${u.getByOffset("global_idx")}; + let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; + ${A.setByOffset("global_idx","value")} + }`;return{name:"BatchNormalization",shaderCache:{hint:`${r.epsilon}_${r.format}_${s}_${o}`,inputDependencies:d?["rank","type","type","type","type"]:void 0},getShaderSource:y,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d?[{type:12,data:l},...nt(n)]:[{type:12,data:l}]})}},a_=e=>Lt(e),Jy=(e,r)=>{let{inputs:t,outputCount:s}=e,i=a_({...r,outputCount:s});if(Kt.webgpu.validateInputContent&&i_(t,i),r.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(o_(t,i))}}),l_,d_,Yy,Rv=je(()=>{Mt(),xt(),l_=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")},d_=e=>{let r=e[0].dims,t=e[0].dims[2],s=xe.size(r)/4,i=e[0].dataType,n=$e("input",i,r,4),o=$e("bias",i,[t],4),a=$e("residual",i,r,4),l=tt("output",i,r,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)}}),getShaderSource:d=>` + const channels = ${t}u / 4; + ${d.declareVariables(n,o,a,l)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes(s)} + let value = ${n.getByOffset("global_idx")} + + ${o.getByOffset("global_idx % channels")} + ${a.getByOffset("global_idx")}; + ${l.setByOffset("global_idx","value")} + }`}},Yy=e=>{l_(e.inputs),e.compute(d_(e.inputs))}}),c_,It,Zy,eM,tM,rM,sM,nM,iM,oM,aM,u_,lM,dM,cM,uM,la,pM,sd,hM,mM,fM,_M,gM,wM,yM,MM,bM,vM,xM,TM,EM,PM,CM,SM,hc,$M,Zc,eu,kM,IM,AM,p_,h_,FM,Cu=je(()=>{mt(),Mt(),tr(),xt(),c_=(e,r,t,s,i,n,o)=>{let a=Math.ceil(r/4),l="";typeof i=="string"?l=`${i}(a)`:l=i("a");let d=$e("inputData",t,[a],4),p=tt("outputData",s,[a],4),u=[{name:"vec_size",type:"u32"}];return o&&u.push(...o),` + ${e.registerUniforms(u).declareVariables(d,p)} + + ${n??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + + let a = ${d.getByOffset("global_idx")}; + ${p.setByOffset("global_idx",l)} + }`},It=(e,r,t,s,i,n=e.dataType,o,a)=>{let l=[{type:12,data:Math.ceil(xe.size(e.dims)/4)}];return o&&l.push(...o),{name:r,shaderCache:{hint:i,inputDependencies:["type"]},getShaderSource:d=>c_(d,xe.size(e.dims),e.dataType,n,t,s,a),getRunData:d=>({outputs:[{dims:e.dims,dataType:n}],dispatchGroup:{x:Math.ceil(xe.size(d[0].dims)/64/4)},programUniforms:l})}},Zy=e=>{e.compute(It(e.inputs[0],"Abs","abs"))},eM=e=>{e.compute(It(e.inputs[0],"Acos","acos"))},tM=e=>{e.compute(It(e.inputs[0],"Acosh","acosh"))},rM=e=>{e.compute(It(e.inputs[0],"Asin","asin"))},sM=e=>{e.compute(It(e.inputs[0],"Asinh","asinh"))},nM=e=>{e.compute(It(e.inputs[0],"Atan","atan"))},iM=e=>{e.compute(It(e.inputs[0],"Atanh","atanh"))},oM=e=>Lt(e),aM=(e,r)=>{let t;switch(r.to){case 10:t="vec4";break;case 1:t="vec4";break;case 12:t="vec4";break;case 6:t="vec4";break;case 9:t="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${r.to}`)}e.compute(It(e.inputs[0],"Cast",t,void 0,r.cacheKey,r.to))},u_=e=>{let r,t,s=e.length>=2&&e[1].data!==0,i=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:r=s?e[1].getFloat32Array()[0]:-34028234663852886e22,t=i?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:r=s?e[1].getUint16Array()[0]:64511,t=i?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return Lt({min:r,max:t})},lM=(e,r)=>{let t=r||u_(e.inputs),s=Cr(e.inputs[0].dataType);e.compute(It(e.inputs[0],"Clip",i=>`clamp(${i}, vec4<${s}>(uniforms.min), vec4<${s}>(uniforms.max))`,void 0,t.cacheKey,void 0,[{type:e.inputs[0].dataType,data:t.min},{type:e.inputs[0].dataType,data:t.max}],[{name:"min",type:s},{name:"max",type:s}]),{inputs:[0]})},dM=e=>{e.compute(It(e.inputs[0],"Ceil","ceil"))},cM=e=>{e.compute(It(e.inputs[0],"Cos","cos"))},uM=e=>{e.compute(It(e.inputs[0],"Cosh","cosh"))},la=e=>Lt(e),pM=(e,r)=>{let t=Cr(e.inputs[0].dataType);e.compute(It(e.inputs[0],"Elu",s=>`elu_vf32(${s})`,` + const elu_alpha_ = ${t}(${r.alpha}); + + fn elu_f32(a: ${t}) -> ${t} { + return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0); + } + + fn elu_vf32(v: vec4<${t}>) -> vec4<${t}> { + return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); + }`,r.cacheKey))},sd=(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)); +}`,hM=e=>{let r=Cr(e.inputs[0].dataType);e.compute(It(e.inputs[0],"Erf",t=>`erf_vf32(${t})`,sd(r)))},mM=e=>{e.compute(It(e.inputs[0],"Exp","exp"))},fM=e=>{e.compute(It(e.inputs[0],"Floor","floor"))},_M=e=>{let r=Cr(e.inputs[0].dataType);e.compute(It(e.inputs[0],"Gelu",t=>`0.5 * ${t} * (1.0 + erf_vf32(${t} * 0.7071067811865475))`,sd(r)))},gM=(e,r)=>{let t=Cr(e.inputs[0].dataType);e.compute(It(e.inputs[0],"LeakyRelu",s=>`select(leaky_relu_alpha_ * ${s}, ${s}, ${s} >= vec4<${t}>(0.0))`,`const leaky_relu_alpha_ = ${t}(${r.alpha});`,r.cacheKey))},wM=e=>{e.compute(It(e.inputs[0],"Not",r=>`!${r}`))},yM=e=>{e.compute(It(e.inputs[0],"Neg",r=>`-${r}`))},MM=e=>{e.compute(It(e.inputs[0],"Reciprocal",r=>`1.0/${r}`))},bM=e=>{let r=Cr(e.inputs[0].dataType);e.compute(It(e.inputs[0],"Relu",t=>`select(vec4<${r}>(0.0), ${t}, ${t} > vec4<${r}>(0.0))`))},vM=e=>{e.compute(It(e.inputs[0],"Sigmoid",r=>`(1.0 / (1.0 + exp(-${r})))`))},xM=e=>Lt(e),TM=(e,r)=>{let t=Cr(e.inputs[0].dataType);e.compute(It(e.inputs[0],"HardSigmoid",s=>`max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), ${r.alpha} * ${s} + vec4<${t}>(${r.beta})))`,void 0,r.cacheKey))},EM=e=>{e.compute(It(e.inputs[0],"Sin","sin"))},PM=e=>{e.compute(It(e.inputs[0],"Sinh","sinh"))},CM=e=>{e.compute(It(e.inputs[0],"Sqrt","sqrt"))},SM=e=>{e.compute(It(e.inputs[0],"Tan","tan"))},hc=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,$M=e=>{e.compute(It(e.inputs[0],"Tanh",hc))},Zc=(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 ${hc("v")}; +} +`,eu=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,kM=e=>{let r=Cr(e.inputs[0].dataType);e.compute(It(e.inputs[0],"FastGelu",eu,Zc(r),void 0,e.inputs[0].dataType))},IM=(e,r)=>{let t=Cr(e.inputs[0].dataType);return e.compute(It(e.inputs[0],"ThresholdedRelu",s=>`select(vec4<${t}>(0.0), ${s}, ${s} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${t}>(${r.alpha});`,r.cacheKey)),0},AM=e=>{e.compute(It(e.inputs[0],"Log","log"))},p_=(e,r)=>` +const alpha = vec4<${e}>(${r}); +const one = ${e}(1.0); +const zero = ${e}(0.0); + +fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { + let v = x *alpha; + var x1 : vec4<${e}>; + for (var i = 0; i < 4; i = i + 1) { + if (v[i] >= zero) { + x1[i] = one / (one + exp(-v[i])); + } else { + x1[i] = one - one / (one + exp(v[i])); + } + } + return x * x1; +} +`,h_=e=>`quick_gelu_impl(${e})`,FM=(e,r)=>{let t=Cr(e.inputs[0].dataType);e.compute(It(e.inputs[0],"QuickGelu",h_,p_(t,r.alpha),r.cacheKey,e.inputs[0].dataType))}}),m_,f_,OM,Nv=je(()=>{Mt(),xt(),Cu(),m_=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")},f_=e=>{let r=e[0].dims.slice();r[2]=r[2]/2;let t=$e("input",e[0].dataType,e[0].dims,4),s=$e("bias",e[0].dataType,[e[0].dims[2]],4),i=tt("output",e[0].dataType,r,4),n=xe.size(r)/4,o=pr(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)}}),getShaderSource:a=>` + const M_SQRT2 = sqrt(2.0); + const halfChannels = ${e[0].dims[2]/4/2}u; + + ${a.declareVariables(t,s,i)} + + ${sd(o)} + + ${a.mainStart()} + ${a.guardAgainstOutOfBoundsWorkgroupSizes(n)} + let biasIdx = global_idx % halfChannels; + let batchIndex = global_idx / halfChannels; + let inputOffset = biasIdx + batchIndex * halfChannels * 2; + let valueLeft = input[inputOffset] + bias[biasIdx]; + let valueRight = input[inputOffset + halfChannels] + bias[biasIdx + halfChannels]; + let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); + + ${i.setByOffset("global_idx","valueLeft * geluRight")} + }`}},OM=e=>{m_(e.inputs),e.compute(f_(e.inputs))}}),__,g_,fs,DM,LM,zM,BM,RM,NM,jM,UM,VM,WM,jv=je(()=>{mt(),Mt(),xt(),__=(e,r,t,s,i,n,o,a,l,d,p,u)=>{let h,w;typeof a=="string"?h=w=(y,S)=>`${a}((${y}),(${S}))`:typeof a=="function"?h=w=a:(h=a.scalar,w=a.vector);let _=tt("outputData",p,s.length,4),P=$e("aData",l,r.length,4),A=$e("bData",d,t.length,4),v;if(i)if(n){let y=xe.size(r)===1,S=xe.size(t)===1,x=r.length>0&&r[r.length-1]%4===0,g=t.length>0&&t[t.length-1]%4===0;y||S?v=_.setByOffset("global_idx",w(y?`${P.type.value}(${P.getByOffset("0")}.x)`:P.getByOffset("global_idx"),S?`${A.type.value}(${A.getByOffset("0")}.x)`:A.getByOffset("global_idx"))):v=` + let outputIndices = ${_.offsetToIndices("global_idx * 4u")}; + let offsetA = ${P.broadcastedIndicesToOffset("outputIndices",_)}; + let offsetB = ${A.broadcastedIndicesToOffset("outputIndices",_)}; + ${_.setByOffset("global_idx",w(o||x?P.getByOffset("offsetA / 4u"):`${P.type.value}(${P.getByOffset("offsetA / 4u")}[offsetA % 4u])`,o||g?A.getByOffset("offsetB / 4u"):`${A.type.value}(${A.getByOffset("offsetB / 4u")}[offsetB % 4u])`))} + `}else v=_.setByOffset("global_idx",w(P.getByOffset("global_idx"),A.getByOffset("global_idx")));else{if(!n)throw new Error("no necessary to use scalar implementation for element-wise binary op implementation.");let y=(S,x,g="")=>{let M=`aData[indexA${x}][componentA${x}]`,E=`bData[indexB${x}][componentB${x}]`;return` + let outputIndices${x} = ${_.offsetToIndices(`global_idx * 4u + ${x}u`)}; + let offsetA${x} = ${P.broadcastedIndicesToOffset(`outputIndices${x}`,_)}; + let offsetB${x} = ${A.broadcastedIndicesToOffset(`outputIndices${x}`,_)}; + let indexA${x} = offsetA${x} / 4u; + let indexB${x} = offsetB${x} / 4u; + let componentA${x} = offsetA${x} % 4u; + let componentB${x} = offsetB${x} % 4u; + ${S}[${x}] = ${g}(${h(M,E)}); + `};p===9?v=` + var data = vec4(0); + ${y("data",0,"u32")} + ${y("data",1,"u32")} + ${y("data",2,"u32")} + ${y("data",3,"u32")} + outputData[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:v=` + ${y("outputData[global_idx]",0)} + ${y("outputData[global_idx]",1)} + ${y("outputData[global_idx]",2)} + ${y("outputData[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(P,A,_)} + + ${u??""} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${v} + }`},g_=(e,r,t,s,i,n,o=t.dataType)=>{let a=t.dims.map(P=>Number(P)??1),l=s.dims.map(P=>Number(P)??1),d=!xe.areEqual(a,l),p=a,u=xe.size(a),h=!1,w=!1,_=[d];if(d){let P=Ei.calcShape(a,l,!1);if(!P)throw new Error("Can't perform binary op on the given tensors");p=P.slice(),u=xe.size(p);let A=xe.size(a)===1,v=xe.size(l)===1,y=a.length>0&&a[a.length-1]%4===0,S=l.length>0&&l[l.length-1]%4===0;_.push(A),_.push(v),_.push(y),_.push(S);let x=1;for(let g=1;gP.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:P=>__(P,a,l,p,h,d,w,i,t.dataType,s.dataType,o,n),getRunData:()=>({outputs:[{dims:p,dataType:o}],dispatchGroup:{x:Math.ceil(u/64/4)},programUniforms:[{type:12,data:Math.ceil(xe.size(p)/4)},...nt(a,l,p)]})}},fs=(e,r,t,s,i,n)=>{e.compute(g_(r,i??"",e.inputs[0],e.inputs[1],t,s,n))},DM=e=>{fs(e,"Add",(r,t)=>`${r}+${t}`)},LM=e=>{fs(e,"Div",(r,t)=>`${r}/${t}`)},zM=e=>{fs(e,"Equal",{scalar:(r,t)=>`u32(${r}==${t})`,vector:(r,t)=>`vec4(${r}==${t})`},void 0,void 0,9)},BM=e=>{fs(e,"Mul",(r,t)=>`${r}*${t}`)},RM=e=>{let r=$e("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;fs(e,"Pow",{scalar:(t,s)=>`pow_custom(${t},${s})`,vector:(t,s)=>`pow_vector_custom(${t},${s})`},` + fn pow_custom(a : ${r}, b : ${r}) -> ${r} { + if (b == ${r}(0.0)) { + return ${r}(1.0); + } else if (a < ${r}(0.0) && f32(b) != floor(f32(b))) { + return ${r}(pow(f32(a), f32(b))); // NaN + } + return select(sign(a), ${r}(1.0), round(f32(abs(b) % ${r}(2.0))) != 1.0) * ${r}(${r==="i32"?"round":""}(pow(f32(abs(a)), f32(b)))); + } + fn pow_vector_custom(a : vec4<${r}>, b : vec4<${r}>) -> vec4<${r}> { + // TODO: implement vectorized pow + return vec4<${r}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); + } + `)},NM=e=>{fs(e,"Sub",(r,t)=>`${r}-${t}`)},jM=e=>{fs(e,"Greater",{scalar:(r,t)=>`u32(${r}>${t})`,vector:(r,t)=>`vec4(${r}>${t})`},void 0,void 0,9)},UM=e=>{fs(e,"Less",{scalar:(r,t)=>`u32(${r}<${t})`,vector:(r,t)=>`vec4(${r}<${t})`},void 0,void 0,9)},VM=e=>{fs(e,"GreaterOrEqual",{scalar:(r,t)=>`u32(${r}>=${t})`,vector:(r,t)=>`vec4(${r}>=${t})`},void 0,void 0,9)},WM=e=>{fs(e,"LessOrEqual",{scalar:(r,t)=>`u32(${r}<=${t})`,vector:(r,t)=>`vec4(${r}<=${t})`},void 0,void 0,9)}}),w_,y_,M_,b_,GM,KM,Uv=je(()=>{mt(),Mt(),tr(),xt(),w_=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");let t=0,s=e[t],i=s.dataType,n=s.dims.length;e.forEach((o,a)=>{if(a!==t){if(o.dataType!==i)throw new Error("input tensors should be one type");if(o.dims.length!==n)throw new Error("input tensors should have the same shape");o.dims.forEach((l,d)=>{if(d!==r&&l!==s.dims[d])throw new Error("non concat dimensions must match")})}})},y_=(e,r)=>` + fn calculateInputIndex(index: u32) -> u32 { + let sizeInConcatAxis = array(${r}); + for (var i: u32 = 0u; i < ${e}; i += 1u ) { + if (index < sizeInConcatAxis[i]) { + return i; + } + } + return ${e}u; + }`,M_=(e,r)=>{let t=e.length,s=[];for(let i=0;i{let i=xe.size(t),n=new Array(e.length),o=new Array(e.length),a=0,l=[],d=[],p=[{type:12,data:i}];for(let P=0;P`uniforms.sizeInConcatAxis${P}`).join(","),_=P=>` + + ${(()=>{P.registerUniform("outputSize","u32");for(let A=0;A(${w}); + ${h} -= sizeInConcatAxis[inputIndex - 1u]; + } + + ${M_(o,u)} + }`;return{name:"Concat",shaderCache:{hint:`${r}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:t,dataType:s}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p}),getShaderSource:_}},GM=(e,r)=>{let t=e.inputs,s=t[0].dims,i=xe.normalizeAxis(r.axis,s.length);w_(t,i);let n=s.slice();n[i]=t.reduce((a,l)=>a+(l.dims.length>i?l.dims[i]:0),0);let o=t.filter(a=>xe.size(a.dims)>0);e.compute(b_(o,i,n,t[0].dataType),{inputs:o})},KM=e=>Lt({axis:e.axis})}),Fn,On,Dn,Su,zn=je(()=>{mt(),Mt(),Fn=(e,r,t="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${r}(0.0));`;case"Sigmoid":return`value = (${r}(1.0) / (${r}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${r}(${t}(uniforms.clip_min)), ${r}(${t}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${r}(0.0), min(${r}(1.0), ${t}(uniforms.alpha) * value + ${t}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${t}(uniforms.alpha) * value, value, value >= ${r}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + value = sign(value) * (1.0 - e2x) / (1.0 + e2x); + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},On=(e,r)=>{e.activation==="Clip"?r.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?r.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&r.push({type:1,data:e.alpha})},Dn=(e,r)=>{e.activation==="Clip"?r.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?r.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&r.push({name:"alpha",type:"f32"})},Su=e=>{let r=(e==null?void 0:e.activation)||"";if(r==="HardSigmoid"){let[t,s]=(e==null?void 0:e.activation_params)||[.2,.5];return{activation:r,alpha:t,beta:s}}else if(r==="Clip"){let[t,s]=(e==null?void 0:e.activation_params)||[vy,xy];return{activation:r,clipMax:s,clipMin:t}}else if(r==="LeakyRelu"){let[t]=(e==null?void 0:e.activation_params)||[.01];return{activation:r,alpha:t}}return{activation:r}}}),yr,HM,$u=je(()=>{yr=(e,r)=>{switch(e){case 1:return r;case 2:return`vec2<${r}>`;case 3:return`vec3<${r}>`;case 4:return`vec4<${r}>`;default:throw new Error(`${e}-component is not supported.`)}},HM=e=>` + ${e?"value = value + getBiasByOutputCoords(coords);":""} + `}),qM,Vv=je(()=>{qM=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)); +} +`}),ca,ku,Iu=je(()=>{mt(),Mt(),xt(),zn(),ca=(e,r,t,s,i)=>{let n=s-t;return` + ${Array.from({length:t}).map((o,a)=>` + if (${rt(r.shape,a,r.rank)} != 1) { + ${r.indicesSet(e,a,rt(i,a+n,s))} + } else { + ${r.indicesSet(e,a,0)} + }`).join("")} +`},ku=(e,r,t,s,i=!1,n)=>{let o=e[0].dims,a=e[1].dims,l=o[o.length-2],d=a[a.length-1],p=o[o.length-1],u=Jt(d),h=Jt(p),w=Jt(l),_=xe.size(t)/u/w,P=e.length>2,A=s?s.slice(0,-2):t.slice(0,-2),v=[xe.size(A),l,d],y=[{type:12,data:_},{type:12,data:l},{type:12,data:d},{type:12,data:p}];On(r,y),y.push(...nt(A,o,a)),P&&y.push(...nt(e[2].dims)),y.push(...nt(v));let S=x=>{let g=Tu("batch_dims",e[0].dataType,A.length),M=$e("a",e[0].dataType,o.length,h),E=$e("b",e[1].dataType,a.length,u),k=tt("output",e[0].dataType,v.length,u),B=pr(k.type.tensor),R=Fn(r,k.type.value,B),J=[M,E],q="";if(P){let H=i?u:1;J.push($e("bias",e[2].dataType,e[2].dims.length,H)),q=`${i?`value += bias[col / ${H}];`:`value += ${k.type.value}(bias[row + i]);`}`}let V=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Dn(r,V);let Y=()=>{let H=`var a_data: ${M.type.value};`;for(let Q=0;Q; + for (var k: u32 = 0u; k < uniforms.K; k = k + ${h}) { + ${Y()} + } + for (var i = 0u; i < ${w}u; i++) { + var value = values[i]; + ${q} + ${R} + let cur_indices = ${k.type.indices}(batch, row + i, col); + let offset = ${k.indicesToOffset("cur_indices")}; + ${k.setByOffset(`offset / ${u}`,"value")}; + } + } + `};return{name:"MatMulNaive",shaderCache:{hint:`${r.activation};${u};${h};${w};${i}`,inputDependencies:P?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(_/64)},programUniforms:y}),getShaderSource:S}}}),v_,x_,tu,mc,T_,ru,E_,dd,Au=je(()=>{mt(),Mt(),xt(),zn(),Iu(),$u(),v_=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart / innerElementSize + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRow + innerRow, + kStart / innerElementSize + inputCol${r?", batchIndices":""}); + `,x_=(e,r)=>e?` + let ACached0 = mm_Asub[k * innerElementSize][localRow]; + let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; + let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; + ${r===3?"":"let ACached3 = mm_Asub[k * innerElementSize + 3][localRow];"} + for (var i = 0; i < rowPerThread; i = i + 1) { + acc[i] = BCached0 * ACached0[i] + acc[i]; + acc[i] = BCached1 * ACached1[i] + acc[i]; + acc[i] = BCached2 * ACached2[i] + acc[i]; + ${r===3?"":"acc[i] = BCached3 * ACached3[i] + acc[i];"} + }`:` + for (var i = 0; i < rowPerThread; i = i + 1) { + let ACached = mm_Asub[tileRow + i][k]; + acc[i] = BCached0 * ACached.x + acc[i]; + acc[i] = BCached1 * ACached.y + acc[i]; + acc[i] = BCached2 * ACached.z + acc[i]; + ${r===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} + }`,tu=(e,r,t="f32",s,i=!1,n=32,o=!1,a=32)=>{let l=r[1]*e[1],d=r[0]*e[0],p=i?l:n,u=i?n:l,h=p/r[0],w=n/r[1];if(!((i&&h===4&&e[1]===4||!i&&(h===3||h===4))&&p%r[0]===0&&n%r[1]===0&&e[0]===4))throw new Error(`If transposeA ${i} is true, innerElementSize ${h} and workPerThread[1] ${e[1]} must be 4. + Otherwise, innerElementSize ${h} must be 3 or 4. + tileAWidth ${p} must be divisible by workgroupSize[0]${r[0]}. tileInner ${n} must be divisible by workgroupSize[1] ${r[1]}. colPerThread ${e[0]} must be 4.`);return` +var mm_Asub: array, ${p/h}>, ${u}>; +var mm_Bsub: array, ${d/e[0]}>, ${n}>; + +const rowPerThread = ${e[1]}; +const colPerThread = ${e[0]}; +const innerElementSize = ${h}; +const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let localRow = i32(localId.y); + let tileRow = localRow * rowPerThread; + let tileCol = i32(localId.x); + + let globalRow =i32(globalId.y) * rowPerThread; + let globalCol = i32(globalId.x); + let batch = ${o?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let globalRowStart = i32(workgroupId.y) * ${l}; + + let num_tiles = ${o?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${o?`i32(globalId.z) * ${a}`:"0"}; + + var acc: array, rowPerThread>; + + // Loop over shared dimension. + let tileRowB = localRow * ${w}; + 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; + ${v_(i,s)} + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${s?", batchIndices":""}); + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + for (var k = 0; k < tileInner / innerElementSize; k = k + 1) { + let BCached0 = mm_Bsub[k * innerElementSize][tileCol]; + let BCached1 = mm_Bsub[k * innerElementSize + 1][tileCol]; + let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; + ${h===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} + + ${x_(i,h)} + } + + workgroupBarrier(); + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); + } +}`},mc=(e,r)=>e?` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + kStart + inputRow, + globalRowStart + inputCol${r?", batchIndices":""}); + `:` + mm_Asub[inputRow][inputCol] = mm_readA(batch, + globalRowStart + inputRow, + kStart + inputCol${r?", batchIndices":""}); + `,T_=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",ru=(e,r,t="f32",s,i=!1,n=32,o=!1,a=32,l=!1)=>{let d=e[1]*r[1],p=e[0]*r[0],u=i?d:n,h=i?n:d;if(!(h%r[1]===0&&u%r[0]===0&&n%r[1]===0))throw new Error(`tileAHight ${h} must be divisible by workgroupSize[1]${r[1]}, tileAWidth ${u} must be divisible by workgroupSize[0]${r[0]}, tileInner ${n} must be divisible by workgroupSize[1]${r[1]}`);let w=h/r[1],_=u/r[0],P=n/r[1],A=l?` + let localRow = i32(localId.y); + let localCol = i32(localId.x); + let globalRowStart = i32(workgroupId.y) * ${d}; + let globalColStart = i32(workgroupId.x) * ${p}; + + // Loop over shared dimension. + for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var inputRow = localRow; inputRow < ${h}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${u}; inputCol = inputCol + ${r[0]}) { + ${mc(i,s)} + } + } + // Load one tile of B into local memory. + for (var inputRow = localRow; inputRow < ${n}; inputRow = inputRow + ${r[1]}) { + for (var inputCol = localCol; inputCol < ${p}; inputCol = inputCol + ${r[0]}) { + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalColStart + inputCol${s?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${t}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][localCol + inner * ${r[0]}]; + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let ACached = ${i?`mm_Asub[k][localRow + innerRow * ${r[1]}];`:`mm_Asub[localRow + innerRow * ${r[1]}][k];`} + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + acc[innerRow][innerCol] = acc[innerRow][innerCol] + + ACached * BCached[innerCol]; + } + } + } + workgroupBarrier(); + } + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + let gRow = globalRowStart + localRow + innerRow * ${r[1]}; + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let gCol = globalColStart + localCol + innerCol * ${r[0]}; + mm_write(batch, gRow, gCol, acc[innerRow][innerCol]); + } + } + `:` +let tileRow = i32(localId.y) * rowPerThread; +let tileCol = i32(localId.x) * colPerThread; + +let globalRow = i32(globalId.y) * rowPerThread; +let globalCol = i32(globalId.x) * colPerThread; +let globalRowStart = i32(workgroupId.y) * ${d}; + +let tileRowA = i32(localId.y) * ${w}; +let tileColA = i32(localId.x) * ${_}; +let tileRowB = i32(localId.y) * ${P}; +// Loop over shared dimension. +for (var t = 0; t < num_tiles; t = t + 1) { + // Load one tile of A into local memory. + for (var innerRow = 0; innerRow < ${w}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < ${_}; innerCol = innerCol + 1) { + let inputRow = tileRowA + innerRow; + let inputCol = tileColA + innerCol; + ${mc(i,s)} + } + } + + // Load one tile of B into local memory. + for (var innerRow = 0; innerRow < ${P}; innerRow = innerRow + 1) { + for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { + let inputRow = tileRowB + innerRow; + let inputCol = tileCol + innerCol; + mm_Bsub[inputRow][inputCol] = mm_readB(batch, + kStart + inputRow, + globalCol + innerCol${s?", batchIndices":""}); + } + } + kStart = kStart + tileInner; + workgroupBarrier(); + + // Compute acc values for a single thread. + var BCached : array<${t}, colPerThread>; + for (var k = 0; k < tileInner; k = k + 1) { + for (var inner = 0; inner < colPerThread; inner = inner + 1) { + BCached[inner] = mm_Bsub[k][tileCol + inner]; + } + + for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { + ${T_(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, ${h}>; + var mm_Bsub : array, ${n}>; + const rowPerThread = ${e[1]}; + const colPerThread = ${e[0]}; + const tileInner = ${n}; + +@compute @workgroup_size(${r[0]}, ${r[1]}, ${r[2]}) +fn main(@builtin(local_invocation_id) localId : vec3, + @builtin(global_invocation_id) globalId : vec3, + @builtin(workgroup_id) workgroupId : vec3) { + let batch = ${o?"0":"i32(globalId.z)"}; + ${s?`let batchIndices = ${s.offsetToIndices("u32(batch)")};`:""} + let num_tiles = ${o?`${Math.ceil(a/n)}`:"(uniforms.dim_inner - 1) / tileInner + 1"}; + var kStart = ${o?`i32(globalId.z) * ${a}`:"0"}; + + var acc : array, rowPerThread>; + ${A} + } +`},E_=(e,r,t,s,i=!1)=>{let[n,o,a,l]=s,d=pr(s[0].type.tensor);return` + fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${yr(e,d)} { + var value = ${yr(e,d)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) + { + var aIndices: ${o.type.indices}; + ${ca("aIndices",o,o.rank-2,n.rank,"batchIndices")} + ${o.indicesSet("aIndices",o.rank-2,"u32(row)")} + ${o.indicesSet("aIndices",o.rank-1,"u32(colIn)")} + value = ${o.getByIndices("aIndices")}; + } + return value; + } + + fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${n.type.indices}) -> ${yr(e,d)} { + var value = ${yr(e,d)}(0.0); + let col = colIn * ${e}; + if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) + { + var bIndices: ${a.type.indices}; + ${ca("bIndices",a,a.rank-2,n.rank,"batchIndices")} + ${a.indicesSet("bIndices",a.rank-2,"u32(row)")} + ${a.indicesSet("bIndices",a.rank-1,"u32(colIn)")} + value = ${a.getByIndices("bIndices")}; + } + return value; + } + + fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${yr(e,d)}) { + let col = colIn * ${e}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) { + var value = valueIn; + let coords = vec3(batch, row, colIn); + ${r?`value = value + ${i?"bias[colIn]":`${yr(e,d)}(bias[row])`};`:""} + ${t} + ${l.setByIndices("vec3(coords)","value")} + } + } + `},dd=(e,r,t,s,i=!1,n)=>{let o=e[0].dims,a=e[1].dims,l=o.slice(0,-2),d=a.slice(0,-2),p=s?s.slice(0,-2):t.slice(0,-2),u=xe.size(p),h=o[o.length-2],w=o[o.length-1],_=a[a.length-1],P=w%4===0&&_%4===0,A=h<=8?[4,1,1]:[4,4,1],v=[8,8,1],y=[Math.ceil(_/v[0]/A[0]),Math.ceil(h/v[1]/A[1]),Math.ceil(u/v[2]/A[2])],S=P?4:1,x=[...l,h,w/S],g=x.length,M=[...d,w,_/S],E=M.length,k=[u,h,_/S],B=[{type:6,data:h},{type:6,data:_},{type:6,data:w}];On(r,B),B.push(...nt(p,x,M));let R=["rank","rank"],J=e.length>2;J&&(B.push(...nt(e[2].dims)),R.push("rank")),B.push(...nt(k));let q=V=>{let Y=p.length,H=Tu("batchDims",e[0].dataType,Y,1),Q=pr(e[0].dataType),ie=$e("a",e[0].dataType,g,S),le=$e("b",e[1].dataType,E,S),ae=tt("result",e[0].dataType,k.length,S),ge=[ie,le];if(J){let X=i?S:1;ge.push($e("bias",e[2].dataType,e[2].dims.length,X))}let N=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Dn(r,N);let O=pr(ae.type.tensor),G=Fn(r,ae.type.value,O),ne=E_(S,J,G,[H,ie,le,ae],i);return` + ${V.registerUniforms(N).registerInternalVariables(H).declareVariables(...ge,ae)} + ${ne} + ${P?tu(A,v,Q,H):ru(A,v,Q,H)} + `};return{name:"MatMul",shaderCache:{hint:`${A};${r.activation};${P};${i}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:n?n(t):t,dataType:e[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:B}),getShaderSource:q}}}),P_,QM,Wv=je(()=>{mt(),Vs(),xt(),zn(),$u(),Vv(),Au(),P_=(e,r,t,s,i=!1,n,o=4,a=4,l=4,d="f32")=>{let p=B=>{switch(B){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${d}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${B} is not supported.`)}},u=B=>{switch(B){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 ${B} is not supported.`)}},h=e?` + let coord = vec4(batch, xRow, xCol, xCh); + `:` + let coord = vec4(batch, xCh, xRow, xCol); + `,w=e?` + let coords = vec4( + batch, + row / outWidth, + row % outWidth, + col); + `:` + let coords = vec4( + batch, + row, + col / outWidth, + col % outWidth); + `,_=e?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",P=e?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",A=e?"row":"col",v=e?"col":"row",y=` + let inChannels = i32(uniforms.w_shape[2]); + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + let outRow = ${A} / outWidth; + let outCol = ${A} % outWidth; + + let WRow = ${v} / (i32(uniforms.w_shape[1]) * inChannels); + let WCol = ${v} / 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 = ${v} % inChannels; + var resData = ${yr(o,d)}(0.0); + // The bounds checking is always needed since we use it to pad zero for + // the 'same' padding type. + if (xRow >= 0 && xRow < ${_} && xCol >= 0 && xCol < ${P}) { + ${h} + let xIndex = getIndexFromCoords4D(coord, vec4(uniforms.x_shape)); + ${p(o)} + } + return resData;`,S=e?r&&s?` + let col = colIn * ${o}; + ${y}`:` + let col = colIn * ${o}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) { + ${y} + } + return ${yr(o,d)}(0.0);`:s&&t?` + let col = colIn * ${o}; + ${y}`:` + let col = colIn * ${o}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${y} + } + return ${yr(o,d)}(0.0);`,x=e?s&&t?u(a):` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) { + ${u(a)} + } + return ${yr(a,d)}(0.0);`:` + let col = colIn * ${a}; + if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) { + ${u(a)} + } + return ${yr(a,d)}(0.0);`,g=yr(l,d),M=yr(e?o:a,d),E=yr(e?a:o,d),k=Fn(n,g,d);return` + fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${M} { + ${e?S:x} + } + + fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${E} { + ${e?x:S} + } + + fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${g}) { + let col = colIn * ${l}; + if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) + { + var value = valueIn; + let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; + ${w} + ${HM(i)} + ${k} + setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); + } + }`},QM=(e,r,t,s,i,n,o,a,l)=>{let d=r.format==="NHWC",p=d?e[0].dims[3]:e[0].dims[1],u=t[0],h=d?t[2]:t[3],w=d?t[1]:t[2],_=d?t[3]:t[1],P=d&&(p%4===0||p%3===0)&&_%4===0,A=d?_:h*w,v=d?h*w:_,y=[8,8,1],S=s<=8?[4,1,1]:[4,4,1],x=[Math.ceil(A/y[0]/S[0]),Math.ceil(v/y[1]/S[1]),Math.ceil(u/y[2]/S[2])];St("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${x}`);let g=P?d&&p%4!==0?3:4:1,M=y[1]*S[1],E=y[0]*S[0],k=Math.max(y[0]*g,y[1]),B=s%M===0,R=i%E===0,J=n%k===0,q=P?[g,4,4]:[1,1,1],V=[{type:6,data:s},{type:6,data:i},{type:6,data:n},{type:6,data:[r.pads[0],r.pads[1]]},{type:6,data:r.strides},{type:6,data:r.dilations}];On(r,V),V.push(...nt(e[0].dims,e[1].dims));let Y=["rank","rank"];o&&(V.push(...nt(e[2].dims)),Y.push("rank")),V.push(...nt(t));let H=Q=>{let ie=[{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}];Dn(r,ie);let le=P?4:1,ae=pr(e[0].dataType),ge=` + fn setOutputAtIndex(flatIndex : i32, value : ${P?`vec4<${ae}>`:ae}) { + result[flatIndex] = ${P?`vec4<${ae}>`:ae}(value); + } + fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${P?`vec4<${ae}>`:ae}) { + let flatIndex = getOutputIndexFromCoords(vec4(d0, d1, d2, d3)); + setOutputAtIndex(flatIndex ${P?"/ 4":""}, value); + }`,N=$e("x",e[0].dataType,e[0].dims.length,g===3?1:g),O=$e("w",e[1].dataType,e[1].dims.length,le),G=[N,O],ne=tt("result",e[0].dataType,t.length,le);if(o){let X=$e("bias",e[2].dataType,e[2].dims.length,le);G.push(X),ge+=` + fn getBiasByOutputCoords(coords : vec4) -> ${P?`vec4<${ae}>`:ae} { + return bias[coords.${d?"w":"y"}${P?"/ 4":""}]; + }`}return` + ${qM("uniforms.result_strides")} + //struct Uniforms { xShape : vec4, wShape : vec4, outShape : vec4, + // outShapeStrides: vec3, filterDims : vec2, pad : vec2, stride : vec2, + // dilation : vec2, dimAOuter : i32, dimBOuter : i32, dimInner : i32 }; + ${Q.registerUniforms(ie).declareVariables(...G,ne)} + ${ge} + ${P_(d,B,R,J,o,r,q[0],q[1],q[2],ae)} + ${P?tu(S,y,ae,void 0,!d,k):ru(S,y,ae,void 0,!d,k,!1,void 0,a)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${r.cacheKey};${g};${P};${B};${R};${J};${M};${E};${k}`,inputDependencies:Y},getRunData:()=>({outputs:[{dims:l?l(t):t,dataType:e[0].dataType}],dispatchGroup:{x:x[0],y:x[1],z:x[2]},programUniforms:V}),getShaderSource:H}}}),C_,fc,ea,S_,_c,$_,XM,JM,Gv=je(()=>{mt(),Vs(),Mt(),xt(),zn(),$u(),C_=e=>{let r=1;for(let t=0;ttypeof e=="number"?[e,e,e]:e,ea=(e,r)=>r<=1?e:e+(e-1)*(r-1),S_=(e,r,t,s=1)=>{let i=ea(r,s);return Math.floor((e[0]*(t-1)-t+i)/2)},_c=(e,r,t,s,i)=>{i==null&&(i=S_(e,r[0],s[0]));let n=[0,0,0,t];for(let o=0;o<3;o++)e[o]+2*i>=r[o]&&(n[o]=Math.trunc((e[o]-r[o]+2*i)/s[o]+1));return n},$_=(e,r,t,s,i,n,o,a,l,d)=>{let p,u,h,w;if(e==="VALID"&&(e=0),typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e};let _=_c([r,t,s,1],[a,l,d],1,[i,n,o],e);u=_[0],h=_[1],w=_[2]}else if(Array.isArray(e)){if(!e.every((P,A,v)=>P===v[0]))throw Error(`Unsupported padding parameter: ${e}`);p={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let _=_c([r,t,s,1],[a,l,d],1,[i,n,o],e[0]);u=_[0],h=_[1],w=_[2]}else if(e==="SAME_UPPER"){u=Math.ceil(r/i),h=Math.ceil(t/n),w=Math.ceil(s/o);let _=(u-1)*i+a-r,P=(h-1)*n+l-t,A=(w-1)*o+d-s,v=Math.floor(_/2),y=_-v,S=Math.floor(P/2),x=P-S,g=Math.floor(A/2),M=A-g;p={top:S,bottom:x,left:g,right:M,front:v,back:y}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:u,outHeight:h,outWidth:w}},XM=(e,r,t,s,i,n=!1,o="channelsLast")=>{let a,l,d,p,u;if(o==="channelsLast")[a,l,d,p,u]=e;else if(o==="channelsFirst")[a,u,l,d,p]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,,w,_,P]=r,[A,v,y]=fc(t),[S,x,g]=fc(s),M=ea(w,S),E=ea(_,x),k=ea(P,g),{padInfo:B,outDepth:R,outHeight:J,outWidth:q}=$_(i,l,d,p,A,v,y,M,E,k),V=n?h*u:h,Y=[0,0,0,0,0];return o==="channelsFirst"?Y=[a,V,R,J,q]:o==="channelsLast"&&(Y=[a,R,J,q,V]),{batchSize:a,dataFormat:o,inDepth:l,inHeight:d,inWidth:p,inChannels:u,outDepth:R,outHeight:J,outWidth:q,outChannels:V,padInfo:B,strideDepth:A,strideHeight:v,strideWidth:y,filterDepth:w,filterHeight:_,filterWidth:P,effectiveFilterDepth:M,effectiveFilterHeight:E,effectiveFilterWidth:k,dilationDepth:S,dilationHeight:x,dilationWidth:g,inShape:e,outShape:Y,filterShape:r}},JM=(e,r,t,s,i,n)=>{let o=n==="channelsLast";o?e[0].dims[3]:e[0].dims[1];let a=[64,1,1],l={x:t.map((A,v)=>v)},d=[Math.ceil(C_(l.x.map(A=>t[A]))/a[0]),1,1];St("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${d}`);let p=1,u=xe.size(t),h=[{type:12,data:u},{type:12,data:s},{type:12,data:i},{type:12,data:r.strides},{type:12,data:r.dilations}];On(r,h),h.push(...nt(e[0].dims,e[1].dims));let w=["rank","rank"],_=e.length===3;_&&(h.push(...nt(e[2].dims)),w.push("rank")),h.push(...nt(t));let P=A=>{let v=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:s.length},{name:"pads",type:"u32",length:i.length},{name:"strides",type:"u32",length:r.strides.length},{name:"dilations",type:"u32",length:r.dilations.length}];Dn(r,v);let y=1,S=pr(e[0].dataType),x=$e("x",e[0].dataType,e[0].dims.length,p),g=$e("W",e[1].dataType,e[1].dims.length,y),M=[x,g],E=tt("result",e[0].dataType,t.length,y),k="";if(_){let J=$e("bias",e[2].dataType,e[2].dims.length,y);M.push(J),k+=` + fn getBiasByOutputCoords(coords : array) -> ${S} { + return bias[${o?rt("coords",4,5):rt("coords",1,5)}]; + }`}let B=yr(p,S),R=Fn(r,B,S);return` + ${k} + fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${x.getByIndices("aIndices")}; + } + fn getW(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { + let aIndices = array(d0, d1, d2, d3, d4); + return ${g.getByIndices("aIndices")}; + } + ${A.registerUniforms(v).declareVariables(...M,E)} + ${A.mainStart()} + ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let coords = ${E.offsetToIndices("global_idx")}; + let batch = ${rt("coords",0,x.rank)}; + let d2 = ${o?rt("coords",x.rank-1,x.rank):rt("coords",1,x.rank)}; + let xFRCCorner = vec3(${o?rt("coords",1,x.rank):rt("coords",2,x.rank)}, + ${o?rt("coords",2,x.rank):rt("coords",3,x.rank)}, + ${o?rt("coords",3,x.rank):rt("coords",4,x.rank)}) * uniforms.strides - uniforms.pads; + let xFCorner = xFRCCorner.x; + let xRCorner = xFRCCorner.y; + let xCCorner = xFRCCorner.z; + let xShapeY = ${o?rt("uniforms.x_shape",1,x.rank):rt("uniforms.x_shape",2,x.rank)}; + let xShapeZ = ${o?rt("uniforms.x_shape",2,x.rank):rt("uniforms.x_shape",3,x.rank)}; + let xShapeW = ${o?rt("uniforms.x_shape",3,x.rank):rt("uniforms.x_shape",4,x.rank)}; + let xShapeU = ${o?rt("uniforms.x_shape",4,x.rank):rt("uniforms.x_shape",1,x.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) { + ${o?`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) { + ${o?`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) { + ${o?`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) { + ${o?`let xValues = vec3( + getX(batch, xF, xR, xC, inputDepthNearestVec4), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 1), + getX(batch, xF, xR, xC, inputDepthNearestVec4 + 2)); + `:`let xValues = vec3( + getX(batch, inputDepthNearestVec4, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 1, xF, xR, xC), + getX(batch, inputDepthNearestVec4 + 2, xF, xR, xC)); + `} + let wValues = vec3( + getW(d2, inputDepthNearestVec4, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 1, wF, wR, wC), + getW(d2, inputDepthNearestVec4 + 2, wF, wR, wC)); + value += dot(xValues, wValues); + } + } + } + } + ${_?"value = value + getBiasByOutputCoords(coords)":""}; + ${R} + result[global_idx] = f32(value); + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${r.cacheKey};${o};${p};${_}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:d[0],y:d[1],z:d[2]},programUniforms:h}),getShaderSource:P}}}),YM,ZM,Kv=je(()=>{mt(),Mt(),xt(),zn(),YM=(e,r,t,s)=>{let i=e.length>2,n=i?"value += b[output_channel];":"",o=e[0].dims,a=e[1].dims,l=r.format==="NHWC",d=l?t[3]:t[1],p=d/r.group,u=l&&p>=4?Jt(d):1,h=xe.size(t)/u,w=[{type:12,data:h},{type:12,data:r.dilations},{type:12,data:[r.strides[0],r.strides[1]]},{type:12,data:[r.pads[0],r.pads[1]]},{type:12,data:p}];On(r,w),w.push(...nt(o,[a[0],a[1],a[2],a[3]/u]));let _=i?["rank","rank","rank"]:["rank","rank"];w.push(...nt([t[0],t[1],t[2],t[3]/u]));let P=A=>{let v=tt("output",e[0].dataType,t.length,u),y=pr(v.type.tensor),S=Fn(r,v.type.value,y),x=$e("x",e[0].dataType,o.length),g=$e("w",e[1].dataType,a.length,u),M=[x,g];i&&M.push($e("b",e[2].dataType,e[2].dims,u));let E=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:r.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];Dn(r,E);let k=l?` + for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { + let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; + + if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) { + continue; + } + + for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) { + let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1]; + if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) { + continue; + } + + for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) { + let input_channel = in_channel_offset + wInChannel; + let xVal = ${x.get("batch","xHeight","xWidth","input_channel")}; + let wVal = ${g.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 = ${x.get("batch","input_channel","xHeight","xWidth")}; + let wVal = ${g.get("output_channel","wInChannel","wHeight","wWidth")}; + value += xVal * wVal; + } + } + } + `;return` + ${A.registerUniforms(E).declareVariables(...M,v)} + + ${A.mainStart()} + ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let outputIndices = ${v.offsetToIndices("global_idx")}; + let batch: u32 = outputIndices[0]; + let output_channel: u32 = outputIndices[${l?3:1}]; + let xRCCorner: vec2 = vec2(outputIndices[${l?1:2}], outputIndices[${l?2:3}]) * uniforms.strides - uniforms.pads; + let group_id: u32 = output_channel * ${u} / uniforms.output_channels_per_group; + var in_channel_offset = group_id * uniforms.w_shape[${l?2:1}]; + + var value: ${v.type.value} = ${v.type.value}(0); + ${k} + ${n} + ${S} + ${v.setByOffset("global_idx","value")} + }`};return{name:"GroupedConv",shaderCache:{hint:`${r.cacheKey}_${u}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:P}},ZM=(e,r,t,s)=>{let i=e.length>2,n=Jt(t[3]),o=Jt(t[2]),a=xe.size(t)/n/o,l=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/n],d=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/n],p=[t[0],t[1],t[2],t[3]/n],u=[{type:12,data:a},{type:6,data:[r.strides[0],r.strides[1]]},{type:6,data:[r.pads[0],r.pads[1]]}];On(r,u),u.push(...nt(l,d,p));let h=(o-1)*r.strides[1]+d[1],w=_=>{let P=tt("output",e[0].dataType,p.length,n),A=pr(P.type.tensor),v=Fn(r,P.type.value,A),y=$e("x",e[0].dataType,l.length,n),S=$e("w",e[1].dataType,d.length,n),x=[y,S];i&&x.push($e("b",e[2].dataType,e[2].dims,n));let g=i?"value += b[output_channel];":"",M=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Dn(r,M),` + ${_.registerUniforms(M).declareVariables(...x,P)} + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let width0 = uniforms.output_shape[3]; + let output_channel = global_idx % width0; + var index1 = global_idx / width0; + let width1 = uniforms.output_shape[2] / ${o}u; + let col = (index1 % width1) * ${o}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<${y.type.value}, ${h}>; + var values: array<${P.type.value}, ${o}>; + 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 < ${d[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 < ${h}; i++) { + let x_width = x_corner.y + i; + if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) { + x_vals[i] = ${y.get("batch","u32(x_height)","u32(x_width)","input_channel")}; + } else { + x_vals[i] = ${y.type.value}(0); + } + } + for (var w_width: u32 = 0u; w_width < ${d[1]}; w_width++) { + let w_val = ${S.get("w_height","w_width","0","output_channel")}; + for (var i = 0u; i < ${o}u; i++) { + values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]); + } + } + } + } + + for (var i = 0u; i < ${o}u; i++) { + var value = values[i]; + ${g} + ${v} + ${P.set("batch","row","col + i","output_channel","value")}; + } + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${r.cacheKey};${n};${o};${h};${d[0]};${d[1]}`,inputDependencies:i?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:s?s(t):t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(a/64)},programUniforms:u}),getShaderSource:w}}}),k_,Hl,I_,ql,su,gc,A_,F_,nu,Hv=je(()=>{Mt(),Wv(),Gv(),Au(),Kv(),zn(),Iu(),un(),k_=(e,r,t,s,i,n)=>{let o=e[0],a=e.slice(n?1:2,n?3:4),l=a.length,d=r[0],p=r.slice(2).map((h,w)=>h+(h-1)*(t[w]-1)),u=a.map((h,w)=>h+s[w]+s[w+l]).map((h,w)=>Math.floor((h-p[w]+i[w])/i[w]));return u.splice(0,0,o),u.splice(n?3:1,0,d),u},Hl=[2,3,1,0],I_=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[1]*r.group;if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let i=e[0].dims.length-2;if(r.dilations.length!==i)throw new Error(`dilations should be ${i}D`);if(r.strides.length!==i)throw new Error(`strides should be ${i}D`);if(r.pads.length!==i*2)throw new Error(`pads should be ${i*2}D`);if(r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ql=(e,r)=>{let t=e.kernelShape.slice();t.length{let r=Su(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],i=e.dilations,n=e.group,o=e.kernel_shape,a=e.pads,l=e.strides,d=e.w_is_const();return{autoPad:s,format:t,dilations:i,group:n,kernelShape:o,pads:a,strides:l,wIsConst:d,...r,cacheKey:`${e.format};${r.activation};`}},gc=(e,r,t,s)=>{let i=t.format==="NHWC",n=k_(r[0].dims,r[1].dims,t.dilations,t.pads,t.strides,i);if(t.group!==1){let M=[r[0]];if(i){let E=e.kernelCustomData.wT??e.compute(Vr(r[1],Hl),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=E),M.push(E)}else M.push(r[1]);r.length===3&&M.push(r[2]),!e.adapterInfo.isArchitecture("ampere")&&i&&r[1].dims[0]===t.group&&r[1].dims[1]===1&&t.dilations[0]===1&&t.dilations[1]===1?e.compute(ZM(M,t,n,s),{inputs:M}):e.compute(YM(M,t,n,s),{inputs:M});return}let o=r.length===3,a=r[0].dims[i?1:2],l=r[0].dims[i?2:3],d=r[0].dims[i?3:1],p=r[1].dims[2],u=r[1].dims[3],h=n[i?1:2],w=n[i?2:3],_=n[i?3:1],P=i&&p===a&&u===l&&t.pads[0]===0&&t.pads[1]===0;if(P||p===1&&u===1&&t.dilations[0]===1&&t.dilations[1]===1&&t.strides[0]===1&&t.strides[1]===1&&t.pads[0]===0&&t.pads[1]===0){let M=n[0],E,k,B,R=[];if(i){let V=e.kernelCustomData.wT??e.compute(Vr(r[1],Hl),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];if(t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=V),P){let Y=a*l*d;E=r[0].reshape([1,M,Y]),k=V.reshape([1,Y,_]),B=[1,M,_]}else E=r[0].reshape([M,a*l,d]),k=V.reshape([1,d,_]),B=[M,h*w,_];R.push(E),R.push(k)}else E=r[0].reshape([M,d,a*l]),k=r[1].reshape([1,_,d]),B=[M,_,h*w],R.push(k),R.push(E);o&&R.push(r[2]);let J=B[2],q=R[0].dims[R[0].dims.length-1];J<8&&q<8?e.compute(ku(R,t,n,B,i,s),{inputs:R}):e.compute(dd(R,t,n,B,i,s),{inputs:R});return}let A=!0,v=e.kernelCustomData.wT??e.compute(Vr(r[1],Hl),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=v);let y=[r[0],v];o&&y.push(r[2]);let S=i?h*w:_,x=i?_:h*w,g=p*u*d;e.compute(QM(y,t,n,S,x,g,o,A,s),{inputs:y})},A_=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let i=[0,r.pads[0],0,r.pads[1]],n=[1].concat(r.strides),o=[1].concat(r.dilations),a=[1].concat(r.kernelShape),l=ql({...r,pads:i,strides:n,dilations:o,kernelShape:a},s);gc(e,s,l,d=>t?[d[0],d[2],d[3]]:[d[0],d[1],d[3]])},F_=(e,r,t)=>{let s=t.format==="NHWC"?"channelsLast":"channelsFirst",i=ql(t,r),n=t.autoPad==="NOTSET"?t.pads:t.autoPad,o=XM(r[0].dims,r[1].dims,t.strides,t.dilations,n,!1,s);e.compute(JM(r,i,o.outShape,[o.filterDepth,o.filterHeight,o.filterWidth],[o.padInfo.front,o.padInfo.top,o.padInfo.left],s))},nu=(e,r)=>{if(I_(e.inputs,r),e.inputs[0].dims.length===3)A_(e,r);else if(e.inputs[0].dims.length===5)F_(e,e.inputs,r);else{let t=ql(r,e.inputs);gc(e,e.inputs,t)}}}),e0,qv=je(()=>{mt(),Vs(),Mt(),xt(),e0=(e,r,t)=>{let s=e.length>2,i=r.outputShape,n=r.format==="NHWC",o=r.group,a=e[1].dims,l=a[2]/o,d=a[3],p=n?Jt(l):1,u=n&&d===1&&l>=4,h=u?Math.floor(l/4)*4:Math.floor(l/p)*p,w=l-h,_=n?Jt(d):1,P=n?d===1?p:_:1,A=xe.size(i)/_,v=[Math.ceil(A/64),1,1];St("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${v}`);let y=["rank","rank"],S=[r.strides[0],r.strides[1]],x=[r.kernelShape[n?1:2],r.kernelShape[n?2:3]],g=[r.dilations[0],r.dilations[1]],M=[x[0]+(r.dilations[0]<=1?0:(r.kernelShape[n?1:2]-1)*(r.dilations[0]-1)),x[1]+(r.dilations[1]<=1?0:(r.kernelShape[n?2:3]-1)*(r.dilations[1]-1))],E=[M[0]-1-Math.floor((r.pads[0]+r.pads[2])/2),M[1]-1-Math.floor((r.pads[1]+r.pads[3])/2)],k=[{type:12,data:A},{type:12,data:S},{type:12,data:x},{type:12,data:g},{type:12,data:M},{type:6,data:E},{type:12,data:h},{type:12,data:l},{type:12,data:d},...nt(e[0].dims,e[1].dims)];s&&(k.push(...nt(e[2].dims)),y.push("rank")),k.push(...nt(i));let B=R=>{let J=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:S.length},{name:"filter_dims",type:"u32",length:x.length},{name:"dilations",type:"u32",length:x.length},{name:"effective_filter_dims",type:"u32",length:M.length},{name:"pads",type:"i32",length:E.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],q=pr(e[0].dataType),V=n?1:2,Y=n?2:3,H=n?3:1,Q=$e("W",e[1].dataType,e[1].dims.length,P),ie=$e("Dy",e[0].dataType,e[0].dims.length,p),le=[ie,Q];s&&le.push($e("bias",e[2].dataType,[i[H]].length,_));let ae=tt("result",e[0].dataType,i.length,_),ge=()=>{let G="";if(u)p===4?G+=` + let xValue = ${ie.getByOffset("x_offset")}; + let wValue = ${Q.getByOffset("w_offset")}; + dotProd = dotProd + dot(xValue, wValue); + x_offset += 1u; + w_offset += 1u;`:p===2?G+=` + dotProd = dotProd + dot(vec4<${q}>(${ie.getByOffset("x_offset")}, ${ie.getByOffset("x_offset + 1u")}), vec4<${q}>(${Q.getByOffset("w_offset")}, ${Q.getByOffset("w_offset + 1u")})); + x_offset += 2u; + w_offset += 2u;`:p===1&&(G+=` + dotProd = dotProd + dot(vec4<${q}>(${ie.getByOffset("x_offset")}, ${ie.getByOffset("x_offset + 1u")}, ${ie.getByOffset("x_offset + 2u")}, ${ie.getByOffset("x_offset + 3u")}), vec4<${q}>(${Q.getByOffset("w_offset")}, ${Q.getByOffset("w_offset + 1u")}, ${Q.getByOffset("w_offset + 2u")}, ${Q.getByOffset("w_offset + 3u")})); + x_offset += 4u; + w_offset += 4u;`);else if(G+=` + let xValue = ${n?ie.getByOffset(`${ie.indicesToOffset(`${ie.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}`):ie.get("batch","inputChannel","idyR","idyC")}; + `,p===1)G+=` + let w_offset = ${Q.indicesToOffset(`${Q.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)}; + let wValue = ${Q.getByOffset(`w_offset / ${P}`)}; + dotProd = dotProd + xValue * wValue;`;else for(let ne=0;ne{if(w===0)return"";if(!u)throw new Error(`packInputAs4 ${u} is not true.`);let G="";if(p===1){G+="dotProd = dotProd";for(let ne=0;ne(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 = ${ae.type.value}(0.0); + var wR: u32 = 0; + if (uniforms.dilations.x == 1) { + // Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0 + wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner); + } + for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) { + if (wR % uniforms.dilations.x != 0) { + continue; + } + let dyR = (${q}(dyRCorner) + ${q}(wR)) / ${q}(uniforms.strides[0]); + let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; + if (dyR < 0.0 || dyR >= ${q}(uniforms.Dy_shape[${V}]) || fract(dyR) > 0.0 || + wRPerm < 0) { + continue; + } + let idyR: u32 = u32(dyR); + var wC: u32 = 0; + if (uniforms.dilations.y == 1) { + // Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0 + wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner); + } + for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) { + if (wC % uniforms.dilations.y != 0) { + continue; + } + let dyC = (${q}(dyCCorner) + ${q}(wC)) / ${q}(uniforms.strides.y); + let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; + if (dyC < 0.0 || dyC >= ${q}(uniforms.Dy_shape[${Y}]) || + fract(dyC) > 0.0 || wCPerm < 0) { + continue; + } + let idyC: u32 = u32(dyC); + var inputChannel = groupId * uniforms.input_channels_per_group; + ${u?` + var x_offset = ${ie.indicesToOffset(`${ie.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${p}; + var w_offset = ${Q.indicesToOffset(`${Q.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${P}; + `:""} + for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${u?4:p}) { + ${ge()} + inputChannel = inputChannel + ${u?4:p}; + } + ${N()} + wC = wC + uniforms.strides.y - 1; + } + wR = wR + uniforms.strides[0] - 1; + } + let value = dotProd${s?` + bias[d1 / ${_}]`:""}; + ${ae.setByOffset("global_idx","value")}; + `;return` + ${R.registerUniforms(J).declareVariables(...le,ae)} + ${R.mainStart()} + ${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${O}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${r.cacheKey};${p}${P}${_}${u}${w}`,inputDependencies:y},getRunData:()=>({dispatchGroup:{x:v[0],y:v[1],z:v[2]},outputs:[{dims:t?t(i):i,dataType:e[0].dataType}],programUniforms:k}),getShaderSource:B}}}),O_,D_,L_,wc,t0,z_,yc,B_,r0,Qv=je(()=>{qv(),zn(),un(),O_=(e,r,t,s,i,n)=>(e-1)*r+t+(s-1)*i+1-n,D_=(e,r,t,s,i)=>{let n=Math.floor(e/2);r==="SAME_UPPER"?(t[s]=n,t[i]=e-n):r==="SAME_LOWER"&&(t[s]=e-n,t[i]=n)},L_=(e,r,t,s,i,n,o,a,l,d)=>{let p=e.length-2,u=d.length===0;l.length{let t=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((u,h)=>u*h,1)===0){t.length=0;for(let u=2;uu+h,0)===0){let u=r[0].dims.length-2;l=new Array(u).fill(1)}let d=e.strides.slice();if(d.reduce((u,h)=>u+h,0)===0){let u=r[0].dims.length-2;d=new Array(u).fill(1)}L_(a,t,l,e.autoPad,e.group,i,d,s,o,n);let p=Object.assign({},e);return Object.assign(p,{kernelShape:t,pads:i,outputPadding:o,outputShape:n,dilations:l,strides:d}),p},t0=e=>{let r=Su(e),t=e.format,s=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],i=e.dilations,n=e.group,o=e.kernelShape,a=e.pads,l=e.strides,d=e.wIsConst(),p=e.outputPadding,u=e.outputShape;return{autoPad:s,format:t,dilations:i,group:n,kernelShape:o,outputPadding:p,outputShape:u,pads:a,strides:l,wIsConst:d,...r,cacheKey:`${e.format};${r.activation};`}},z_=(e,r)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let t=e[0].dims[r.format==="NHWC"?e[0].dims.length-1:1],s=e[1].dims[0];if(t!==s)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let i=e[1].dims[1]*r.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==i))throw new Error("invalid bias");let n=e[0].dims.length-2;if(r.dilations.reduce((o,a)=>o+a,0)>0&&r.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(r.strides.reduce((o,a)=>o+a,0)>0&&r.strides.length!==n)throw new Error(`strides should be ${n}D`);if(r.pads.reduce((o,a)=>o+a,0)>0&&r.pads.length!==n*2)throw new Error(`pads should be ${n*2}D`);if(r.outputPadding.length!==n&&r.outputPadding.length!==0)throw new Error(`output_padding should be ${n}D`);if(r.kernelShape.reduce((o,a)=>o+a,0)>0&&r.kernelShape.length!==0&&r.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(r.outputShape.length!==0&&r.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},yc=(e,r,t,s)=>{let i=e.kernelCustomData.wT??e.compute(Vr(r[1],[2,3,0,1]),{inputs:[1],outputs:[t.wIsConst?-2:-1]})[0];t.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=i);let n=[r[0],i];r.length===3&&n.push(r[2]),e.compute(e0(n,t,s),{inputs:n})},B_=(e,r)=>{let t=r.format==="NHWC",s=[e.inputs[0].reshape(t?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&s.push(e.inputs[2]);let i=r.kernelShape;(i.length===0||i[0]===0)&&(i=[e.inputs[1].dims[2]]);let n=r.dilations;(n.length===0||n[0]===0)&&(n=[1]);let o=r.strides;(o.length===0||o[0]===0)&&(o=[1]);let a=r.pads;a.length===0&&(a=[0,0]),a=[0,a[0],0,a[1]],o=[1].concat(o),n=[1].concat(n),i=[1].concat(i);let l=r.outputPadding;l=[0].concat(l);let d=wc({...r,pads:a,strides:o,dilations:n,kernelShape:i,outputPadding:l},s);yc(e,s,d,p=>t?[p[0],p[2],p[3]]:[p[0],p[1],p[3]])},r0=(e,r)=>{if(z_(e.inputs,r),e.inputs[0].dims.length===3)B_(e,r);else{let t=wc(r,e.inputs);yc(e,e.inputs,t)}}}),R_,s0,n0,Xv=je(()=>{mt(),Mt(),tr(),xt(),R_=(e,r,t,s)=>{let i=xe.size(r),n=r.length,o=$e("input",e,n),a=tt("output",e,n),l=t.dataType===6?t.getInt32Array()[0]:Number(t.getBigInt64Array()[0]),d=xe.normalizeAxis(l,n),p=u=>{let h=` i32(${o.indicesGet("inputIndices","uniforms.axis")}) `,w=rt("uniforms.input_shape","uniforms.axis",n),_=s.reverse?h+(s.exclusive?" + 1":""):"0",P=s.reverse?w:h+(s.exclusive?"":" + 1");return` + ${u.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(o,a)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var inputIndices = ${a.offsetToIndices("global_idx")}; + var sum = ${a.type.value}(0); + let first : i32 = ${_}; + let last : i32 = ${P}; + for (var i : i32 = first; i < last; i++) { + ${o.indicesSet("inputIndices","uniforms.axis","u32(i)")}; + sum = sum + ${o.getByIndices("inputIndices")}; + } + ${a.setByOffset("global_idx","sum")}; + }`};return{name:"CumSum",shaderCache:{hint:s.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e}],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:[{type:12,data:i},{type:12,data:d},...nt(r,r)]}),getShaderSource:p}},s0=(e,r)=>{let t=e.inputs[0].dims,s=e.inputs[0].dataType,i=e.inputs[1];e.compute(R_(s,t,i,r),{inputs:[0]})},n0=e=>{let r=e.exclusive===1,t=e.reverse===1;return Lt({exclusive:r,reverse:t})}}),N_,j_,U_,i0,o0,Jv=je(()=>{mt(),Mt(),tr(),xt(),N_=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.")},j_=(e,r,t,s)=>{let i=[];i.push(`fn perm(i: ${s.type.indices}) -> ${t.type.indices} { + var a: ${t.type.indices};`);for(let n=0;n{let t,s,i,n,o,a,l=r.format==="NHWC",d=r.blocksize,p=r.mode==="DCR";l?([t,s,i,n]=e.dims,o=p?[t,s,i,d,d,n/d**2]:[t,s,i,n/d**2,d,d],a=p?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([t,s,i,n]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],o=p?[t,d,d,n/d**2,s,i]:[t,n/d**2,d,d,s,i],a=p?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let u=e.reshape(o),h=u.dims.length,w=e.dataType,_=$e("a",w,h),P=tt("output",w,h),A=v=>` + ${v.registerUniform("output_size","u32").declareVariables(_,P)} + + ${j_(a,h,_,P)} + + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${P.offsetToIndices("global_idx")}; + let aIndices = perm(indices); + + ${P.setByOffset("global_idx",_.getByIndices("aIndices"))} + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${r.blocksize};${r.mode}`,inputDependencies:["rank"]},getRunData:v=>{let y=l?[t,s*d,i*d,n/d**2]:[t,n/d**2,s*d,i*d],S=xe.size(y),x=u.dims,g=xe.sortBasedOnPerm(x,a);return{outputs:[{dims:y,dataType:v[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:[{type:12,data:S},...nt(x,g)]}},getShaderSource:A}},i0=(e,r)=>{N_(e.inputs),e.compute(U_(e.inputs[0],r))},o0=e=>Lt({blocksize:e.blocksize,mode:e.mode,format:e.format})}),Ql,ta,Mc,V_,W_,G_,K_,bc,H_,a0,l0,Yv=je(()=>{mt(),Mt(),tr(),xt(),Ql="[a-zA-Z]|\\.\\.\\.",ta="("+Ql+")+",Mc="^"+ta+"$",V_="("+ta+",)*"+ta,W_="^"+V_+"$",G_=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,r){let t=this.symbolToIndices.get(e);t===void 0?t=[r]:t.push(r),this.symbolToIndices.set(e,t)}},K_=class{constructor(e,r){var i;this.equation=r,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[t,s]=r.includes("->")?r.split("->",2):[r,""];if(!t.match(RegExp(W_)))throw new Error("Invalid LHS term");if(t.split(",").forEach((n,o)=>{let a=e[o].dims.slice();if(!n.match(RegExp(Mc)))throw new Error("Invalid LHS term");let l=this.processTerm(n,!0,a,o);this.lhs.push(l)}),s==="")s+=[...this.symbolToInfo.entries()].filter(([n,o])=>o.count===1||n==="...").map(([n])=>n).join("");else if(!s.match(RegExp(ta)))throw new Error("Invalid RHS");(i=s.match(RegExp(Ql,"g")))==null||i.forEach(n=>{if(n==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let o=this.symbolToInfo.get(n);if(o===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(o.dimValue)}}),this.rhs=this.processTerm(s,!1,this.outputDims)}addSymbol(e,r,t){let s=this.symbolToInfo.get(e);if(s!==void 0){if(s.dimValue!==r&&s.count!==1)throw new Error("Dimension mismatch");s.count++,s.inputIndices.push(t)}else s={count:1,dimValue:r,inputIndices:[t]};this.symbolToInfo.set(e,s)}processTerm(e,r,t,s=-1){let i=t.length,n=!1,o=[],a=0;if(!e.match(RegExp(Mc))&&!r&&e!=="")throw new Error("Invalid LHS term");let l=e.match(RegExp(Ql,"g")),d=new G_(s);return l==null||l.forEach((p,u)=>{if(p==="..."){if(n)throw new Error("Only one ellipsis is allowed per input term");n=!0;let h=i-l.length+1;if(h<0)throw new Error("Ellipsis out of bounds");if(o=t.slice(a,a+h),this.hasEllipsis){if(this.ellipsisDims.length!==o.length||this.ellipsisDims.toString()!==o.toString())throw new Error("Ellipsis dimensions mismatch")}else if(r)this.hasEllipsis=!0,this.ellipsisDims=o;else throw new Error("Ellipsis must be specified in the LHS");for(let w=0;we+"_max",H_=(e,r,t,s)=>{let i=e.map(d=>d.length).map((d,p)=>$e(`input${p}`,r,d)),n=xe.size(s),o=tt("output",r,s.length),a=[...t.symbolToInfo.keys()].filter(d=>!t.rhs.symbolToIndices.has(d)),l=d=>{let p=[],u="var prod = 1.0;",h="var sum = 0.0;",w="sum += prod;",_=[],P=[],A=[],v=[],y=t.symbolToInfo.size===t.rhs.symbolToIndices.size;t.symbolToInfo.forEach((x,g)=>{var M;if(t.rhs.symbolToIndices.has(g)){let E=(M=t.rhs.symbolToIndices.get(g))==null?void 0:M[0];E!==void 0&&t.lhs.forEach((k,B)=>{if(x.inputIndices.includes(B)){let R=k.symbolToIndices.get(g);if(R===void 0)throw new Error("Invalid symbol error");R.forEach(J=>{p.push(`${i[B].indicesSet(`input${B}Indices`,J,o.indicesGet("outputIndices",E))}`)})}})}else t.lhs.forEach((E,k)=>{if(x.inputIndices.includes(k)){let B=E.symbolToIndices.get(g);if(B===void 0)throw new Error("Invalid symbol error");B.forEach(R=>{_.push(`${i[k].indicesSet(`input${k}Indices`,R,`${g}`)}`)}),v.push(`prod *= ${i[k].getByIndices(`input${k}Indices`)};`)}}),P.push(`for(var ${g}: u32 = 0; ${g} < uniforms.${bc(g)}; ${g}++) {`),A.push("}")});let S=y?[...p,`let sum = ${i.map((x,g)=>x.getByIndices(`input${g}Indices`)).join(" * ")};`]:[...p,h,...P,..._,u,...v,w,...A];return` + ${d.registerUniforms(a.map(x=>({name:`${bc(x)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...i,o)} + + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + var outputIndices = ${o.offsetToIndices("global_idx")}; + ${i.map((x,g)=>`var input${g}Indices: ${i[g].type.indices};`).join(` +`)} + ${S.join(` +`)}; + ${o.setByOffset("global_idx","sum")}; + }`};return{name:"Einsum",shaderCache:{hint:t.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let d=a.filter(u=>t.symbolToInfo.has(u)).map(u=>{var h;return{type:12,data:((h=t.symbolToInfo.get(u))==null?void 0:h.dimValue)||0}});d.push({type:12,data:n});let p=e.map((u,h)=>[...nt(u)]).reduce((u,h)=>u.concat(h),d);return p.push(...nt(s)),{outputs:[{dims:s,dataType:r}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:p}},getShaderSource:l}},a0=(e,r)=>{let t=new K_(e.inputs,r.equation),s=t.outputDims,i=e.inputs.map((n,o)=>n.dims);e.compute(H_(i,e.inputs[0].dataType,t,s))},l0=e=>{let r=e.equation.replace(/\s+/g,"");return Lt({equation:r})}}),q_,vc,Q_,X_,d0,Zv=je(()=>{mt(),Mt(),xt(),q_=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=t.length{let t=e.length-r.length,s=[];for(let i=0;ie.length>r.length?vc(e,r):vc(r,e),X_=e=>{let r=e[0].dims,t=Array.from(e[1].getBigInt64Array(),Number),s=Q_(r,t),i=e[0].dataType,n=i===9||xe.size(r)===1,o=i===9||r.length>0&&r[r.length-1]%4===0?4:1,a=n||s.length>0&&s[s.length-1]%4===0?4:1,l=Math.ceil(xe.size(s)/a),d=u=>{let h=$e("input",i,r.length,o),w=tt("output",i,s.length,a),_;if(i===9){let P=(A,v,y="")=>` + let outputIndices${v} = ${w.offsetToIndices(`outputOffset + ${v}u`)}; + let offset${v} = ${h.broadcastedIndicesToOffset(`outputIndices${v}`,w)}; + let index${v} = offset${v} / 4u; + let component${v} = offset${v} % 4u; + ${A}[${v}] = ${y}(${h.getByOffset(`index${v}`)}[component${v}]); + `;_=` + let outputOffset = global_idx * ${a}; + var data = vec4(0); + ${P("data",0,"u32")} + ${P("data",1,"u32")} + ${P("data",2,"u32")} + ${P("data",3,"u32")} + ${w.setByOffset("global_idx","data")} + }`}else _=` + let outputIndices = ${w.offsetToIndices(`global_idx * ${a}`)}; + let inputOffset = ${h.broadcastedIndicesToOffset("outputIndices",w)}; + let data = ${w.type.value}(${h.getByOffset(`inputOffset / ${o}`)}); + ${w.setByOffset("global_idx","data")} + }`;return` + ${u.registerUniform("vec_size","u32").declareVariables(h,w)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${_}`},p=[{type:12,data:l},...nt(r,s)];return{name:"Expand",shaderCache:{hint:`${s.length};${o}${a}`,inputDependencies:["rank"]},getShaderSource:d,getRunData:()=>({outputs:[{dims:s,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:p})}},d0=e=>{q_(e.inputs),e.compute(X_(e.inputs),{inputs:[0]})}}),J_,c0,ex=je(()=>{mt(),Mt(),xt(),Cu(),J_=e=>{let r=e[0].dataType,t=xe.size(e[0].dims),s=xe.size(e[1].dims),i=s%4===0,n=o=>{let a=$e("x",r,[1],4),l=$e("bias",r,[1],4),d=tt("y",r,[1],4),p=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],u=w=>` + let bias${w}_offset: u32 = (global_idx * 4 + ${w}) % uniforms.bias_size; + let bias${w} = ${l.getByOffset(`bias${w}_offset / 4`)}[bias${w}_offset % 4];`,h=i?` + let bias = ${l.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${u(0)}${u(1)}${u(2)}${u(3)} + let bias = ${a.type.value}(bias0, bias1, bias2, bias3);`;return`${o.registerUniforms(p).declareVariables(a,l,d)} + + ${Zc(Cr(r))} + + ${o.mainStart(Pi)} + ${o.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} + + let x = ${a.getByOffset("global_idx")}; + ${h} + let x_in = x + bias; + ${d.setByOffset("global_idx",eu("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${i}`,inputDependencies:["type","type"]},getShaderSource:n,getRunData:o=>({outputs:[{dims:o[0].dims,dataType:o[0].dataType}],programUniforms:[{type:12,data:Math.ceil(t/4)},{type:12,data:s}],dispatchGroup:{x:Math.ceil(t/Pi/4)}})}},c0=e=>{e.inputs.length<2||xe.size(e.inputs[1].dims)===0?kM(e):e.compute(J_(e.inputs))}}),Y_,Z_,u0,p0,tx=je(()=>{mt(),Mt(),tr(),xt(),Y_=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Z_=(e,r)=>{let t=e[0].dims,s=e[1].dims,i=t.length,n=xe.normalizeAxis(r.axis,i),o=t.slice(0);o.splice(n,1,...s);let a=t[n],l=e[0].dataType===9?4:1,d=Math.ceil(xe.size(o)/l),p=[{type:12,data:d},{type:6,data:a},{type:12,data:n},...nt(e[0].dims,e[1].dims,o)],u=h=>{let w=$e("data",e[0].dataType,e[0].dims.length,l),_=$e("inputIndices",e[1].dataType,e[1].dims.length),P=tt("output",e[0].dataType,o.length,l),A=y=>{let S=s.length,x=`var indicesIndices${y} = ${_.type.indices}(0);`;for(let g=0;g1?`indicesIndices${y}[${g}]`:`indicesIndices${y}`} = ${o.length>1?`outputIndices${y}[uniforms.axis + ${g}]`:`outputIndices${y}`};`;x+=` + var idx${y} = ${_.getByIndices(`indicesIndices${y}`)}; + if (idx${y} < 0) { + idx${y} = idx${y} + uniforms.axisDimLimit; + } + var dataIndices${y} : ${w.type.indices}; + `;for(let g=0,M=0;g1?`dataIndices${y}[${g}]`:`dataIndices${y}`} = u32(idx${y});`,M+=S):(x+=`${i>1?`dataIndices${y}[${g}]`:`dataIndices${y}`} = ${o.length>1?`outputIndices${y}[${M}]`:`outputIndices${y}`};`,M++);return x},v;if(e[0].dataType===9){let y=(S,x,g="")=>` + let outputIndices${x} = ${P.offsetToIndices(`outputOffset + ${x}u`)}; + ${A(x)}; + let offset${x} = ${w.indicesToOffset(`dataIndices${x}`)}; + let index${x} = offset${x} / 4u; + let component${x} = offset${x} % 4u; + ${S}[${x}] = ${g}(${w.getByOffset(`index${x}`)}[component${x}]); + `;v=` + let outputOffset = global_idx * ${l}; + var value = vec4(0); + ${y("value",0,"u32")} + ${y("value",1,"u32")} + ${y("value",2,"u32")} + ${y("value",3,"u32")} + ${P.setByOffset("global_idx","value")} + `}else v=` + let outputIndices = ${P.offsetToIndices("global_idx")}; + ${A("")}; + let value = ${w.getByIndices("dataIndices")}; + ${P.setByOffset("global_idx","value")}; + `;return` + ${h.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(w,_,P)} + ${h.mainStart()} + ${h.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + ${v} + }`};return{name:"Gather",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:u}},u0=e=>Lt({axis:e.axis}),p0=(e,r)=>{let t=e.inputs;Y_(t),e.compute(Z_(e.inputs,r))}}),eg,h0,m0,rx=je(()=>{mt(),Mt(),xt(),eg=(e,r,t,s,i,n,o,a,l)=>{let d=[{type:12,data:n},{type:12,data:s},{type:12,data:i},{type:12,data:t},{type:12,data:o},{type:12,data:a},{type:12,data:l}],p=[n];d.push(...nt(r.dims,p));let u=h=>{let w=$e("indices_data",r.dataType,r.dims.length),_=tt("input_slice_offsets_data",12,1,1),P=[w,_],A=[{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:t.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + ${h.registerUniforms(A).declareVariables(...P)} + ${h.mainStart()} + ${h.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]);"} + } + ${t.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"} + } + + input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${i.length}_${t.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:p,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:d}),getShaderSource:u},{inputs:[r],outputs:[-1]})[0]},h0=(e,r)=>{let t=e.inputs,s=t[0].dims,i=t[0].dataType,n=t[1].dims,o=n[n.length-1],a=xe.sizeToDimension(n,n.length-1),l=xe.sizeFromDimension(s,r.batchDims+o),d=xe.sizeToDimension(s,r.batchDims),p=xe.sizeFromDimension(s,r.batchDims),u=a/d,h=new Array(o),w=l;for(let x=0;xs.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let A=n.slice(0,-1).concat(s.slice(P)),v=xe.size(A),y=[{type:12,data:v},{type:12,data:l},...nt(t[0].dims,_.dims,A)],S=x=>{let g=$e("data",t[0].dataType,t[0].dims.length),M=$e("slice_offsets",12,_.dims.length),E=tt("output",t[0].dataType,A.length);return` + ${x.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(g,M,E)} + ${x.mainStart()} + ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; + output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; + }`};e.compute({name:"GatherND",shaderCache:{hint:r.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:A,dataType:i}],dispatchGroup:{x:Math.ceil(v/64)},programUniforms:y}),getShaderSource:S},{inputs:[t[0],_]})},m0=e=>({batchDims:e.batch_dims,cacheKey:""})}),tg,rg,f0,_0,sx=je(()=>{mt(),Mt(),tr(),xt(),tg=(e,r)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let t=xe.normalizeAxis(r.quantizeAxis,e[0].dims.length),s=r.blockSize,i=e[0],n=e[2],o=e.length===4?e[3]:void 0;if(n.dims.length!==i.dims.length||!i.dims.map((a,l)=>l===t?Math.ceil(a/s)===n.dims[l]:a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(o){if(o.dataType!==i.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(o.dims.length!==n.dims.length||!o.dims.map((a,l)=>a===n.dims[l]).reduce((a,l)=>a&&l,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},rg=(e,r)=>{let t=e[0].dims,s=e[1].dims,i=t.length,n=xe.normalizeAxis(r.gatherAxis,i),o=xe.normalizeAxis(r.quantizeAxis,i),a=t.slice(0);a.splice(n,1,...s);let l=xe.size(a),d=e[2].dataType,p=e[0].dataType===22,u=[{type:12,data:l},{type:12,data:o},{type:12,data:n},{type:12,data:r.blockSize},...nt(...e.map((w,_)=>w.dims),a)],h=w=>{let _=$e("data",e[0].dataType,e[0].dims.length),P=$e("inputIndices",e[1].dataType,e[1].dims.length),A=$e("scales",e[2].dataType,e[2].dims.length),v=e.length>3?$e("zeroPoint",e[3].dataType,e[3].dims.length):void 0,y=tt("output",d,a.length),S=[_,P,A];v&&S.push(v);let x=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${w.registerUniforms(x).declareVariables(...S,y)} + ${w.mainStart()} + let output_indices = ${y.offsetToIndices("global_idx")}; + var indices_indices = ${P.type.indices}(0); + ${s.length>1?` + for (var i: u32 = 0; i < ${s.length}; i++) { + let index = ${y.indicesGet("output_indices","uniforms.gather_axis + i")}; + ${P.indicesSet("indices_indices","i","index")}; + }`:`indices_indices = ${y.indicesGet("output_indices","uniforms.gather_axis")};`}; + var data_indices = ${_.type.indices}(0); + for (var i: u32 = 0; i < uniforms.gather_axis; i++) { + let index = ${y.indicesGet("output_indices","i")}; + ${_.indicesSet("data_indices","i","index")}; + } + var index_from_indices = ${P.getByIndices("indices_indices")}; + if (index_from_indices < 0) { + index_from_indices += ${t[n]}; + } + ${_.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")}; + for (var i = uniforms.gather_axis + 1; i < ${a.length}; i++) { + let index = ${y.indicesGet("output_indices",`i + ${s.length} - 1`)}; + ${_.indicesSet("data_indices","i","index")}; + } + let data_offset = ${_.indicesToOffset("data_indices")}; + let data_index = data_offset % 8; + // Convert 4-bit packed data to 8-bit packed data. + let packed_4bit_quantized_data = ${_.getByOffset("data_offset / 8")}; + let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f; + let quantized_data_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data)); + let quantized_data = quantized_data_vec[data_index / 2]; + var scale_indices = data_indices; + let quantize_axis_index = ${A.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size; + ${A.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")}; + var scale = ${A.getByIndices("scale_indices")}; + ${v?` + let zero_point_indices = scale_indices; + let zero_point_offset = ${v.indicesToOffset("zero_point_indices")}; + let zero_point_index = zero_point_offset % 8; + let packed_4bit_zero_points = ${v.getByOffset("zero_point_offset / 8")}; + let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f; + let zero_point_vec = ${p?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points)); + let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; + let dequantized_data = ${Cr(d)}(quantized_data - zero_point) * scale; + ${y.setByOffset("global_idx","dequantized_data")}; + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${r.cacheKey};${e.filter((w,_)=>_!==1).map(w=>w.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(w,_)=>"rank")},getRunData:()=>({outputs:[{dims:a,dataType:d}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:u}),getShaderSource:h}},f0=(e,r)=>{let t=e.inputs;tg(t,r),e.compute(rg(e.inputs,r))},_0=e=>Lt({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),sg,ng,g0,w0,nx=je(()=>{mt(),Mt(),tr(),xt(),sg=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.`)},ng=(e,r)=>{let t=e[0].dims,s=e[0].dataType,i=t.length,n=e[1].dims,o=e[1].dataType,a=xe.normalizeAxis(r.axis,i),l=t[a],d=n.slice(0),p=xe.size(d),u=$e("input",s,i),h=$e("indicesInput",o,n.length),w=tt("output",s,d.length),_=[{type:12,data:p},{type:6,data:l},{type:12,data:a}];return _.push(...nt(t,n,d)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:_}),getShaderSource:P=>` + ${P.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(u,h,w)} + ${P.mainStart()} + ${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let outputIndices = ${w.offsetToIndices("global_idx")}; + + var idx = ${h.getByOffset("global_idx")}; + if (idx < 0) { + idx = idx + uniforms.axisDimLimit; + } + var inputIndices = ${u.type.indices}(outputIndices); + ${u.indicesSet("inputIndices","uniforms.axis","u32(idx)")}; + let value = ${u.getByIndices("inputIndices")}; + + ${w.setByOffset("global_idx","value")}; + }`}},g0=e=>Lt({axis:e.axis}),w0=(e,r)=>{let t=e.inputs;sg(t),e.compute(ng(e.inputs,r))}}),ig,og,y0,M0,ix=je(()=>{mt(),Mt(),xt(),ig=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")},og=(e,r)=>{let t=e[0].dims.slice(),s=e[1].dims.slice(),[i,n,o]=by.getShapeOfGemmResult(t,r.transA,s,r.transB,e.length===3?e[2].dims:void 0),a=[i,n];if(!a)throw new Error("Can't use gemm on the given tensors");let l=16,d=Math.ceil(n/l),p=Math.ceil(i/l),u=!0,h=xe.size(a),w=[{type:12,data:u?d:h},{type:12,data:i},{type:12,data:n},{type:12,data:o},{type:1,data:r.alpha},{type:1,data:r.beta}],_=["type","type"];e.length===3&&(w.push(...nt(e[2].dims)),_.push("rank")),w.push(...nt(a));let P=v=>{let y="";r.transA&&r.transB?y="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":r.transA&&!r.transB?y="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!r.transA&&r.transB?y="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!r.transA&&!r.transB&&(y="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let S=r.alpha===1?"":"value *= uniforms.alpha;",x=$e("a",e[0].dataType,e[0].dims),g=$e("b",e[1].dataType,e[1].dims),M=x.type.value,E=null,k=[x,g];e.length===3&&(E=$e("c",e[2].dataType,e[2].dims.length),k.push(E));let B=tt("output",e[0].dataType,a.length);k.push(B);let R=[{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` + ${v.registerUniforms(R).declareVariables(...k)} + + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let m = global_idx / uniforms.N; + let n = global_idx % uniforms.N; + + var value = ${M}(0); + for (var k: u32 = 0u; k < uniforms.K; k++) { + ${y} + } + + ${S} + ${E!=null?`let cOffset = ${E.broadcastedIndicesToOffset("vec2(m, n)",B)}; value += ${M}(uniforms.beta) * ${E.getByOffset("cOffset")};`:""} + output[global_idx] = value; + }`},A=v=>{let y=$e("a",e[0].dataType,e[0].dims),S=$e("b",e[1].dataType,e[1].dims),x=null,g=[y,S];e.length===3&&(x=$e("c",e[2].dataType,e[2].dims.length),g.push(x));let M=tt("output",e[0].dataType,a.length);g.push(M);let E=[{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"}],k="",B="";r.transA&&r.transB?(B=` + 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] = ${y.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + } + `,k="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):r.transA&&!r.transB?(B=` + 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] = ${y.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + } + `,k="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!r.transA&&r.transB?(B=` + 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] = ${y.type.value}(0); + } + + col = k_start + local_id.x; + row = tile_col_start + local_id.y; + if (col < uniforms.K && row < uniforms.N) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col]; + } else { + tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + } + `,k="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!r.transA&&!r.transB&&(B=` + 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] = ${y.type.value}(0); + } + + col = tile_col_start + local_id.x; + row = k_start + local_id.y; + if (col < uniforms.N && row < uniforms.K) { + tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col]; + } else { + tile_b[local_id.y][local_id.x] = ${S.type.value}(0); + } + `,k="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let R=r.alpha===1?"":"value *= uniforms.alpha;";return` + ${v.registerUniforms(E).declareVariables(...g)} + var tile_a: array, ${l}>; + var tile_b: array, ${l}>; + ${v.mainStart([l,l,1])} + let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${l}; + let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${l}; + let num_tiles = (uniforms.K - 1) / ${l} + 1; + var k_start = 0u; + var value = ${M.type.value}(0); + for (var t: u32 = 0u; t < num_tiles; t++) { + ${B} + k_start = k_start + ${l}; + workgroupBarrier(); + + for (var k: u32 = 0u; k < ${l}; k++) { + ${k} + } + workgroupBarrier(); + } + + ${R} + let m = tile_row_start + local_id.y; + let n = tile_col_start + local_id.x; + ${x!=null?`let cOffset = ${x.broadcastedIndicesToOffset("vec2(m, n)",M)}; value += ${M.type.value}(uniforms.beta) * ${x.getByOffset("cOffset")};`:""} + if (m < uniforms.M && n < uniforms.N) { + output[m * uniforms.N + n] = value; + } + }`};return u?{name:"GemmShared",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:d*p},programUniforms:w}),getShaderSource:A}:{name:"Gemm",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:a,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:w}),getShaderSource:P}},y0=e=>{let r=e.transA,t=e.transB,s=e.alpha,i=e.beta;return{transA:r,transB:t,alpha:s,beta:i,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},M0=(e,r)=>{ig(e.inputs),e.compute(og(e.inputs,r))}}),Ss,Rs,Tn,En,ag,lg,dg,cg,ug,pg,hg,mg,b0,v0,ox=je(()=>{mt(),Mt(),tr(),xt(),[Ss,Rs,Tn,En]=[0,1,2,3],ag=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")},lg=` + 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; + } +`,dg=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; + } +`,cg=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)); + `} + } +`,ug=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); + }`:""} +`,pg=(e,r,t)=>` + fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${r} { + var pixel = ${r}(0); + var indices = vec4(0); + indices[${Ss}] = batch; + indices[${Rs}] = channel;`+(()=>{switch(t.paddingMode){case"zeros":return` + if (r >= 0 && r < H && c >=0 && c < W) { + indices[${Tn}] = u32(r); + indices[${En}] = u32(c); + } + `;case"border":return` + indices[${Tn}] = u32(clamp(r, 0, H - 1)); + indices[${En}] = u32(clamp(c, 0, W - 1)); + `;case"reflection":return` + indices[${Tn}] = gs_reflect(r, border[1], border[3]); + indices[${En}] = gs_reflect(c, border[0], border[2]); + `;default:throw new Error(`padding mode ${t.paddingMode} is not supported`)}})()+` + return ${e.getByIndices("indices")}; + } +`,hg=(e,r,t)=>(()=>{switch(t.mode){case"nearest":return` + let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Ss}], indices[${Rs}], 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[${Ss}], indices[${Rs}], border); + let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${Ss}], indices[${Rs}], border); + let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${Ss}], indices[${Rs}], border); + let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${Ss}], indices[${Rs}], border); + + let dx2 = ${r}(f32(x2) - x); + let dx1 = ${r}(x - f32(x1)); + let dy2 = ${r}(f32(y2) - y); + let dy1 = ${r}(y - f32(y1)); + let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22); + `;case"bicubic":return` + let x0 = i32(floor(x)) - 1; + let y0 = i32(floor(y)) - 1; + var p: mat4x4<${r}>; + for (var h = 0; h < 4; h++) { + for (var w = 0; w < 4; w++) { + p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${Ss}], indices[${Rs}], border); + } + } + + let dx = x - f32(x0 + 1); + let dy = y - f32(y0 + 1); + let result = gs_bicubic_interpolate(p, dx, dy); + `;default:throw new Error(`mode ${t.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,mg=(e,r)=>{let t=$e("x",e[0].dataType,e[0].dims.length),s=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],i=$e("grid",e[1].dataType,s.length,2),n=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];r.format==="NHWC"&&(n=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[Ss,Rs,Tn,En]=[0,3,1,2]);let o=tt("output",e[0].dataType,n.length),a=t.type.value,l=xe.size(n),d=[{type:12,data:l},...nt(e[0].dims,s,n)],p=u=>` + ${u.registerUniform("output_size","u32").declareVariables(t,i,o)} + ${lg} + ${dg(a)} + ${cg(r)} + ${ug(r)} + ${pg(t,a,r)} + + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let H_in = i32(uniforms.x_shape[${Tn}]); + let W_in = i32(uniforms.x_shape[${En}]); + + ${r.alignCorners===0?` + let x_min = -0.5; + let x_max = f32(W_in) - 0.5; + let y_min = -0.5; + let y_max = f32(H_in) - 0.5; + `:` + let x_min = 0.0; + let x_max = f32(W_in) - 1.0; + let y_min = 0.0; + let y_max = f32(H_in) - 1.0; + `}; + let border = vec4(x_min, y_min, x_max, y_max); + + let indices = ${o.offsetToIndices("global_idx")}; + var grid_indices = vec3(indices[${Ss}], indices[${Tn}], indices[${En}]); + let nxy = ${i.getByIndices("grid_indices")}; + var x = gs_denormalize(f32(nxy[0]), W_in); + var y = gs_denormalize(f32(nxy[1]), H_in); + + ${hg(o,a,r)} + }`;return{name:"GridSample",shaderCache:{hint:`${r.cacheKey}`,inputDependencies:["type","type"]},getRunData:u=>{let h=xe.size(n);return{outputs:[{dims:n,dataType:u[0].dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:d}},getShaderSource:p}},b0=(e,r)=>{ag(e.inputs),e.compute(mg(e.inputs,r))},v0=e=>Lt({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),Ar,fg,x0,xc,_g,da,T0,E0=je(()=>{mt(),Mt(),tr(),xu(),Pu(),xt(),un(),Ar=(e,r)=>e.length>r&&e[r].dims.length>0?e[r]:void 0,fg=(e,r)=>{let t=e[0],s=Ar(e,1),i=Ar(e,2),n=Ar(e,3),o=Ar(e,4),a=Ar(e,5),l=Ar(e,6),d=Ar(e,7);if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let p=t.dims[0],u=t.dims[1],h=t.dims.length===3?t.dims[2]:r.numHeads*t.dims[4],w=u,_=0,P=0,A=Math.floor(h/r.numHeads);if(l&&d&&xe.size(l.dims)&&xe.size(d.dims)){if(l.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(l.dims[0]!==p||l.dims[1]!==r.numHeads||l.dims[3]!==A)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(d.dims[0]!==p||d.dims[1]!==r.numHeads||d.dims[3]!==A)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(l.dims[2]!==d.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(d.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');_=l.dims[2],P=l.dims[2]}else if(l&&xe.size(l.dims)||d&&xe.size(d.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v;if(s&&xe.size(s.dims)>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(s.dims[2]!==t.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');v=2,w=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.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.');v=5,w=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==A)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');v=0,w=s.dims[2]}}else{if(t.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(t.dims[2]!==r.numHeads||t.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');v=3}if(n&&xe.size(n.dims)>0){if(n.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(s&&s.dims.length===5&&s.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let y=_+w,S=0;if(o&&xe.size(o.dims)>0){S=8;let E=o.dims;throw E.length===1?E[0]===p?S=1:E[0]===3*p+2&&(S=3):E.length===2&&E[0]===p&&E[1]===y&&(S=5),S===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let x=!1,g=h;if(i&&xe.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(t.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(w!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');g=i.dims[2]}else{if(w!==i.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');g=i.dims[1]*i.dims[3],x=!0}}let M=!1;if(o&&xe.size(o.dims)>0)throw new Error("Key padding mask is not supported");if(a&&xe.size(a.dims)>0){if(a.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(a.dims[0]!==p||a.dims[1]!==r.numHeads||a.dims[2]!==u||a.dims[3]!==y)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:p,sequenceLength:u,pastSequenceLength:_,kvSequenceLength:w,totalSequenceLength:y,maxSequenceLength:P,inputHiddenSize:0,hiddenSize:h,vHiddenSize:g,headSize:A,vHeadSize:Math.floor(g/r.numHeads),numHeads:r.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:r.maskFilterValue,maskType:S,scale:r.scale,broadcastResPosBias:M,passPastInKv:x,qkvFormat:v}},x0=e=>Lt({...e}),xc=Lt({perm:[0,2,1,3]}),_g=(e,r,t,s,i,n,o)=>{let a=[s,i,n],l=xe.size(a),d=[{type:12,data:l},{type:12,data:o},{type:12,data:n}],p=u=>{let h=tt("qkv_with_bias",r.dataType,a),w=$e("qkv",r.dataType,a),_=$e("bias",t.dataType,a),P=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${u.registerUniforms(P).declareVariables(w,_,h)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; + + qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; + }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:a,dataType:r.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:d}),getShaderSource:p},{inputs:[r,t],outputs:[-1]})[0]},da=(e,r,t,s,i,n,o,a)=>{let l=n;if(o&&xe.size(o.dims)>0){if(s===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return l=_g(e,n,o,r,s,t*i,a),l=l.reshape([r,s,t,i]),t===1||s===1?l:e.compute(Vr(l,xc.perm),{inputs:[l],outputs:[-1]})[0]}else return n.dims.length===3&&(l=n.reshape([r,s,t,i])),t===1||s===1?l:e.compute(Vr(l,xc.perm),{inputs:[l],outputs:[-1]})[0]},T0=(e,r)=>{let t=fg(e.inputs,r),s=e.inputs[0],i=Ar(e.inputs,1),n=Ar(e.inputs,2),o=Ar(e.inputs,3),a=Ar(e.inputs,4),l=Ar(e.inputs,5),d=Ar(e.inputs,6),p=Ar(e.inputs,7);if(s.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 u=i&&n&&i.dims.length===4&&n.dims.length===4,h=da(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,s,o,0);if(u)return fa(e,h,i,n,a,void 0,d,p,l,t);if(!i||!n)throw new Error("key and value must be provided");let w=da(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.headSize,i,o,t.hiddenSize),_=da(e,t.batchSize,t.numHeads,t.kvSequenceLength,t.vHeadSize,n,o,2*t.hiddenSize);fa(e,h,w,_,a,void 0,d,p,l,t)}}),gg,wg,yg,Mg,iu,P0,C0,S0=je(()=>{mt(),Mt(),tr(),xt(),gg=e=>{if(!e||e.length<1)throw new Error("too few inputs")},wg=(e,r)=>{let t=[],s=r.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(i=>t.push(Number(i))),s=t.length),Lt({numOutputs:s,axis:r.axis,splitSizes:t})},yg=e=>` +fn calculateOutputIndex(index: u32) -> u32 { + for (var i: u32 = 0u; i < ${e}u; i += 1u ) { + if (index < ${rt("uniforms.size_in_split_axis","i",e)}) { + return i; + } + } + return ${e}u; +}`,Mg=e=>{let r=e.length,t=[];for(let s=0;s{let t=e[0].dims,s=xe.size(t),i=e[0].dataType,n=xe.normalizeAxis(r.axis,t.length),o=new Array(r.numOutputs),a=$e("input",i,t.length),l=new Array(r.numOutputs),d=[],p=[],u=0,h=[{type:12,data:s}];for(let _=0;_` + ${_.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",l.length).declareVariables(a,...o)} + ${yg(l.length)} + ${Mg(o)} + + ${_.mainStart()} + ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} + + var indices = ${a.offsetToIndices("global_idx")}; + var index = ${a.indicesGet("indices",n)}; + let output_number = calculateOutputIndex(index); + if (output_number != 0) { + index -= ${rt("uniforms.size_in_split_axis","output_number - 1u",l.length)}; + ${a.indicesSet("indices",n,"index")}; + } + writeBufferData(output_number, indices, global_idx); + }`;return{name:"Split",shaderCache:{hint:r.cacheKey,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:d,dispatchGroup:{x:Math.ceil(s/64)},programUniforms:h})}},P0=(e,r)=>{gg(e.inputs);let t=e.inputs.length===1?r:wg(e.inputs,r);e.compute(iu(e.inputs,t),{inputs:[0]})},C0=e=>{let r=e.axis,t=e.splitSizes,s=e.numOutputs<0?t.length:e.numOutputs;if(s!==t.length)throw new Error("numOutputs and splitSizes lengh must be equal");return Lt({axis:r,numOutputs:s,splitSizes:t})}}),bg,vg,Tc,$0,ax=je(()=>{tr(),Pu(),E0(),S0(),un(),bg=(e,r)=>{if(r.doRotary)throw new Error("GroupQuerryAttention do_rotary attribute is not supported");if(r.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let t=e[0],s=e[1],i=e[2],n=e[3],o=e[4];if(r.localWindowSize!==-1)throw new Error("Local attention is not supported");if(r.softcap!==0)throw new Error("Softcap is not supported");if(r.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(r.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(t.dims.length!==3&&t.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let a=!1,l=t.dims[0],d=t.dims[1],p=t.dims.length===3?a?t.dims[2]/3:t.dims[2]:r.numHeads*t.dims[4],u=d,h=0,w=!s||s.dims.length===0,_=Math.floor(w?p/(r.numHeads+2*r.kvNumHeads):p/r.numHeads);w&&(p=_*r.numHeads);let P=n&&n.dims.length!==0,A=o&&o.dims.length!==0;if(P&&n.dims.length===4&&n.dims[0]===l&&n.dims[1]!==r.kvNumHeads&&n.dims[2]===r.kvNumHeads&&n.dims[3]===_)throw new Error("BSNH pastKey/pastValue is not supported");if(P&&A){if(n.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(o.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');h=n.dims[2]}else if(P||A)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let v=1;if(s&&s.dims.length>0){if(t.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(s.dims.length<3||s.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(t.dims[0]!==s.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(s.dims.length===3){if(t.dims[2]%s.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');u=s.dims[1]}else if(s.dims.length===5){if(s.dims[2]!==r.numHeads||s.dims[3]!==2||s.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(i)throw new Error('Expect "value" be none when "key" has packed kv format.');u=s.dims[1]}else{if(s.dims[1]!==r.numHeads||s.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');u=s.dims[2]}}else{if(t.dims.length!==3&&t.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(t.dims.length===5&&(t.dims[2]!==r.numHeads||t.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');v=3}let y=0,S=!1,x=r.kvNumHeads?_*r.kvNumHeads:p;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(t.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(u!==i.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');x=i.dims[2]}else{if(u!==i.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');x=i.dims[1]*i.dims[3],S=!0}}let g=e.length>4?e[5]:void 0;if(g&&g.dims.length!==1&&g.dims[0]!==l)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:l,sequenceLength:d,pastSequenceLength:h,kvSequenceLength:u,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:p,vHiddenSize:x,headSize:_,vHeadSize:Math.floor(x/r.kvNumHeads),numHeads:r.numHeads,kvNumHeads:r.kvNumHeads,nReps:r.numHeads/r.kvNumHeads,pastPresentShareBuffer:!1,maskType:y,scale:r.scale,broadcastResPosBias:!1,passPastInKv:S,qkvFormat:v}},vg=Lt({perm:[0,2,1,3]}),Tc=(e,r,t)=>{let s=r,i=t.kvNumHeads;return r.dims.length===3&&t.kvSequenceLength!==0&&(s=r.reshape([t.batchSize,t.kvSequenceLength,i,t.headSize]),s=e.compute(Vr(s,vg.perm),{inputs:[s],outputs:[-1]})[0]),s},$0=(e,r)=>{var A;let t=bg(e.inputs,r);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((A=e.inputs[1])==null?void 0:A.dims.length)===5)throw new Error("Packed KV is not implemented");let s=e.inputs[0],i=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,n=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,o=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,a=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,l=e.inputs.length>4?e.inputs[5]:void 0,d=e.inputs.length>5?e.inputs[6]:void 0,p=t.kvNumHeads?t.kvNumHeads:t.numHeads,u=Lt({axis:2,numOutputs:3,splitSizes:[t.numHeads*t.headSize,p*t.headSize,p*t.headSize]}),[h,w,_]=!i&&!n?e.compute(iu([s],u),{inputs:[s],outputs:[-1,-1,-1]}):[s,i,n],P=da(e,t.batchSize,t.numHeads,t.sequenceLength,t.headSize,h,void 0,0);fa(e,P,Tc(e,w,t),Tc(e,_,t),void 0,void 0,o,a,void 0,t,l,d)}}),Ec,xg,Tg,k0,lx=je(()=>{mt(),Mt(),un(),xt(),Ec=(e,r,t,s,i,n,o,a)=>{let l=Jt(n),d=l===1?"f32":`vec${l}f`,p=l===1?"vec2f":`mat2x${l}f`,u=i*o,h=64;u===1&&(h=256);let w=[i,o,n/l],_=[i,o,2],P=["rank","type","type"],A=[];A.push(...nt(w,_));let v=y=>{let S=$e("x",r.dataType,3,l),x=$e("scale",t.dataType,t.dims),g=$e("bias",s.dataType,s.dims),M=tt("output",1,3,2),E=[S,x,g,M];return` + var workgroup_shared : array<${p}, ${h}>; + const workgroup_size = ${h}u; + ${y.declareVariables(...E)} + ${y.mainStart(h)} + 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 = ${d}(0); + var squared_sum = ${d}(0); + for (var h = local_idx; h < hight; h += workgroup_size) { + let value = ${d}(${S.get("batch","channel","h")}); + sum += value; + squared_sum += value * value; + } + workgroup_shared[local_idx] = ${p}(sum, squared_sum); + workgroupBarrier(); + + for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) { + if (local_idx < currSize) { + workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize]; + } + workgroupBarrier(); + } + if (local_idx == 0) { + let sum_final = ${cn("workgroup_shared[0][0]",l)} / f32(hight * ${l}); + let squared_sum_final = ${cn("workgroup_shared[0][1]",l)} / f32(hight * ${l}); + + let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${a})); + let channel_scale = inv_std_dev * f32(scale[channel]); + let channel_shift = f32(bias[channel]) - sum_final * channel_scale; + output[workgroup_index] = vec2f(channel_scale, channel_shift); + } + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${l};${a};${h}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:_,dataType:1}],dispatchGroup:{x:u},programUniforms:A}),getShaderSource:v},{inputs:[r,t,s],outputs:[-1]})[0]},xg=(e,r,t)=>{let s=r[0].dims,i=s,n=2,o=s[0],a=s[1],l=xe.sizeFromDimension(s,n),d=Jt(l),p=xe.size(i)/d,u=Ec(e,r[0],r[1],r[2],o,l,a,t.epsilon),h=[o,a,l/d],w=[o,a],_=["type","none"],P=A=>{let v=$e("x",r[0].dataType,h.length,d),y=$e("scale_shift",1,w.length,2),S=tt("output",r[0].dataType,h.length,d),x=[v,y,S];return` + ${A.registerUniform("output_size","u32").declareVariables(...x)} + ${A.mainStart()} + ${A.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let outputIndices = ${S.offsetToIndices("global_idx")}; + let batch = outputIndices[0]; + let channel = outputIndices[1]; + let scale_shift = ${y.getByIndices("vec2(batch, channel)")}; + let value = ${v.getByOffset("global_idx")} * ${S.type.value}(scale_shift.x) + ${S.type.value}(scale_shift.y); + ${S.setByOffset("global_idx","value")}; + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${d}`,inputDependencies:_},getRunData:()=>({outputs:[{dims:i,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},...nt(h,w,h)]}),getShaderSource:P},{inputs:[r[0],u]})},Tg=(e,r,t)=>{let s=r[0].dims,i=s,n=s[0],o=s[s.length-1],a=xe.sizeFromDimension(s,1)/o,l=Jt(o),d=xe.size(i)/l,p=[{type:12,data:a},{type:12,data:Math.floor(o/l)}],u=["type","type"],h=!1,w=[0,s.length-1];for(let v=0;vs[w[y]])),P=Ec(e,_,r[1],r[2],n,a,o,t.epsilon),A=v=>{let y=pr(r[0].dataType),S=l===1?"vec2f":`mat${l}x2f`,x=E=>{let k=E===0?"x":"y",B=l===1?"f32":`vec${l}f`;switch(l){case 1:return`${y}(${B}(scale.${k}))`;case 2:return`vec2<${y}>(${B}(scale[0].${k}, scale[1].${k}))`;case 4:return`vec4<${y}>(${B}(scale[0].${k}, scale[1].${k}, scale[2].${k}, scale[3].${k}))`;default:throw new Error(`Not supported compoents ${l}`)}},g=$e("input",r[0].dataType,r[0].dims,l),M=tt("output",r[0].dataType,i,l);return` + @group(0) @binding(0) var input : array<${g.type.storage}>; + @group(0) @binding(1) var scale_input : array<${S}>; + @group(0) @binding(2) var output : array<${M.type.storage}>; + struct Uniforms {H: u32, C : u32}; + @group(0) @binding(3) var uniforms: Uniforms; + + ${v.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], ${x(0)}, ${x(1)}); + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${l}`,inputDependencies:u},getRunData:()=>({outputs:[{dims:i,dataType:r[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:p}),getShaderSource:A},{inputs:[r[0],P]})},k0=(e,r)=>{r.format==="NHWC"?Tg(e,e.inputs,r):xg(e,e.inputs,r)}}),Eg,Pg,I0,dx=je(()=>{mt(),Mt(),xt(),Eg=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},Pg=(e,r,t)=>{let s=r.simplified,i=e[0].dims,n=e[1],o=!s&&e[2],a=i,l=xe.normalizeAxis(r.axis,i.length),d=xe.sizeToDimension(i,l),p=xe.sizeFromDimension(i,l),u=xe.size(n.dims),h=o?xe.size(o.dims):0;if(u!==p||o&&h!==p)throw new Error(`Size of X.shape()[axis:] == ${p}. + Size of scale and bias (if provided) must match this. + Got scale size of ${u} and bias size of ${h}`);let w=[];for(let g=0;g1,y=t>2,S=g=>{let M=pr(e[0].dataType),E=[$e("x",e[0].dataType,e[0].dims,_),$e("scale",n.dataType,n.dims,_)];o&&E.push($e("bias",o.dataType,o.dims,_)),E.push(tt("output",e[0].dataType,a,_)),v&&E.push(tt("mean_data_output",1,w)),y&&E.push(tt("inv_std_output",1,w));let k=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + ${g.registerUniforms(k).declareVariables(...E)} + ${g.mainStart()} + ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} + let offset = global_idx * uniforms.norm_size_vectorized; + var mean_vector = ${Xc("f32",_)}; + var mean_square_vector = ${Xc("f32",_)}; + + for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { + let value = ${xi(M,_,"x[h + offset]")}; + mean_vector += value; + mean_square_vector += value * value; + } + let mean = ${cn("mean_vector",_)} / uniforms.norm_size; + let inv_std_dev = inverseSqrt(${cn("mean_square_vector",_)} / uniforms.norm_size ${s?"":"- mean * mean"} + uniforms.epsilon); + + for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) { + let f32input = ${xi(M,_,"x[j + offset]")}; + let f32scale = ${xi(M,_,"scale[j]")}; + output[j + offset] = ${E[0].type.value}((f32input ${s?"":"- mean"}) * inv_std_dev * f32scale + ${o?`+ ${xi(M,_,"bias[j]")}`:""} + ); + } + + ${v?"mean_data_output[global_idx] = mean":""}; + ${y?"inv_std_output[global_idx] = inv_std_dev":""}; + }`},x=[{dims:a,dataType:e[0].dataType}];return v&&x.push({dims:w,dataType:1}),y&&x.push({dims:w,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${_};${t};${s}`,inputDependencies:P},getRunData:()=>({outputs:x,dispatchGroup:{x:Math.ceil(d/64)},programUniforms:A}),getShaderSource:S}},I0=(e,r)=>{Eg(e.inputs),e.compute(Pg(e.inputs,r,e.outputCount))}}),Cg,A0,cx=je(()=>{Mt(),Iu(),Au(),Cg=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.")},A0=e=>{Cg(e.inputs);let r=Ei.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!r)throw new Error("Can't use matmul on the given tensors");let t=r[r.length-1],s=e.inputs[0].dims[e.inputs[0].dims.length-1];if(t<8&&s<8)e.compute(ku(e.inputs,{activation:""},r));else{let i=r[r.length-2],n=xe.size(e.inputs[0].dims.slice(0,-2)),o=xe.size(e.inputs[1].dims.slice(0,-2));if(n!==1&&i===1&&o===1){let a=e.inputs[0].reshape([1,n,s]),l=e.inputs[1].reshape([1,s,t]),d=[1,n,t],p=[a,l];e.compute(dd(p,{activation:""},r,d),{inputs:p})}else e.compute(dd(e.inputs,{activation:""},r))}}}),Sg,$g,kg,F0,O0,ux=je(()=>{mt(),Mt(),tr(),xt(),Sg=(e,r)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let t=e[0],s=t.dims.length;if(t.dims[s-1]!==r.k)throw new Error("The last dim of input shape does not match the k value");let i=Math.floor((r.k+r.blockSize-1)/r.blockSize),n=r.blockSize/8*r.bits,o=e[1];if(!xe.areEqual(o.dims,[r.n,i,n]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let a=e[2].dims;if(xe.size(a)!==r.n*i)throw new Error("scales input size error.");if(e.length===4){let l=e[3].dims,d=r.bits>4?r.n*i:r.n*Math.floor((i+1)/2);if(xe.size(l)!==d)throw new Error("zeroPoints input size error.")}},$g=(e,r)=>{let t=e[0].dims,s=t.length,i=t[s-2],n=r.k,o=r.n,a=t.slice(0,s-2),l=xe.size(a),d=e[1].dims[2]/4,p=e[0].dataType,u=Jt(r.k),h=Jt(d),w=Jt(o),_=a.concat([i,o]),P=i>1&&o/w%2===0?2:1,A=xe.size(_)/w/P,v=64,y=[],S=[l,i,n/u],x=xe.convertShape(e[1].dims).slice();x.splice(-1,1,d/h),y.push(...nt(S)),y.push(...nt(x)),y.push(...nt(e[2].dims)),e.length===4&&y.push(...nt(xe.convertShape(e[3].dims)));let g=[l,i,o/w];y.push(...nt(g));let M=E=>{let k=S.length,B=$e("a",e[0].dataType,k,u),R=$e("b",12,x.length,h),J=$e("scales",e[2].dataType,e[2].dims.length),q=[B,R,J],V=e.length===4?$e("zero_points",12,e[3].dims.length):void 0;V&&q.push(V);let Y=g.length,H=tt("output",e[0].dataType,Y,w),Q=pr(e[0].dataType),ie=(()=>{switch(u){case 1:return`array<${Q}, 8>`;case 2:return`mat4x2<${Q}>`;case 4:return`mat2x4<${Q}>`;default:throw new Error(`${u}-component is not supported.`)}})(),le=()=>{let N=` + // reuse a data + var input_offset = ${B.indicesToOffset(`${B.type.indices}(batch, row, word_offset)`)}; + var a_data: ${ie}; + for (var j: u32 = 0; j < ${8/u}; j++) { + a_data[j] = ${B.getByOffset("input_offset")}; + input_offset++; + } + `;for(let O=0;O> 4) & b_mask); + b_quantized_values = ${ie}(${Array.from({length:4},(G,ne)=>`${Q}(b_value_lower[${ne}]), ${Q}(b_value_upper[${ne}])`).join(", ")}); + b_dequantized_values = ${u===1?`${ie}(${Array.from({length:8},(G,ne)=>`(b_quantized_values[${ne}] - ${V?`zero_point${O}`:"zero_point"}) * scale${O}`).join(", ")});`:`(b_quantized_values - ${ie}(${Array(8).fill(`${V?`zero_point${O}`:"zero_point"}`).join(",")})) * scale${O};`}; + workgroup_shared[local_id.x * ${P} + ${Math.floor(O/w)}]${w>1?`[${O%w}]`:""} += ${Array.from({length:8/u},(G,ne)=>`${u===1?`a_data[${ne}] * b_dequantized_values[${ne}]`:`dot(a_data[${ne}], b_dequantized_values[${ne}])`}`).join(" + ")}; + `;return N},ae=()=>{let N=` + var col_index = col * ${w}; + ${V?` + let zero_point_bytes_per_col = (nBlocksPerCol + 1) / 2; + var zero_point_byte_count: u32; + var zero_point_word_index: u32; + var zero_point_byte_offset: u32; + let zero_point_nibble_offset: u32 = block & 0x1u; + var zero_point_bits_offset: u32; + var zero_point_word: u32;`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${Q}(8);`} + `;for(let O=0;O> 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 = ${V.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point${O} = ${Q}((zero_point_word) & 0xFu);`:""} + col_index += 1;`;return N},ge=()=>{let N=`col_index = col * ${w};`;for(let O=0;O; + var b_value_upper: vec4; + var b_quantized_values: ${ie}; + var b_dequantized_values: ${ie};`,N};return` + var workgroup_shared: array<${H.type.value}, ${P*v}>; + ${E.declareVariables(...q,H)} + ${E.mainStart([v,1,1])} + let output_indices = ${H.offsetToIndices(`(global_idx / ${v}) * ${P}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let nBlocksPerCol = uniforms.b_shape[1]; + + for (var block = local_id.x; block < nBlocksPerCol; block += ${v}) { + //process one block + var word_offset: u32 = block * ${r.blockSize/u}; + ${ae()} + for (var word: u32 = 0; word < ${d}; word += ${h}) { + ${ge()} + for (var i: u32 = 0; i < ${h}; i++) { + ${le()} + word_offset += ${8/u}; + } + } + } + workgroupBarrier(); + + if (local_id.x < ${P}) { + var output_value: ${H.type.value} = ${H.type.value}(0); + var workgroup_shared_offset: u32 = local_id.x; + for (var b: u32 = 0u; b < ${v}u; b++) { + output_value += workgroup_shared[workgroup_shared_offset]; + workgroup_shared_offset += ${P}; + } + ${H.setByIndices(`${H.type.indices}(batch, row, col + local_id.x)`,"output_value")}; + } + }`};return{name:"MatMulNBits",shaderCache:{hint:`${r.blockSize};${r.bits};${u};${h};${w};${P};${v}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:_,dataType:p}],dispatchGroup:{x:A},programUniforms:y}),getShaderSource:M}},kg=(e,r)=>{let t=e[0].dims,s=t.length,i=t[s-2],n=r.k,o=r.n,a=t.slice(0,s-2),l=xe.size(a),d=e[1].dims[2]/4,p=e[0].dataType,u=Jt(r.k),h=Jt(d),w=a.concat([i,o]),_=128,P=o%8===0?8:o%4===0?4:1,A=_/P,v=A*h*8,y=v/u,S=v/r.blockSize,x=xe.size(w)/P,g=[],M=[l,i,n/u],E=xe.convertShape(e[1].dims).slice();E.splice(-1,1,d/h),g.push(...nt(M)),g.push(...nt(E)),g.push(...nt(e[2].dims)),e.length===4&&g.push(...nt(xe.convertShape(e[3].dims)));let k=[l,i,o];g.push(...nt(k));let B=R=>{let J=M.length,q=$e("a",e[0].dataType,J,u),V=$e("b",12,E.length,h),Y=$e("scales",e[2].dataType,e[2].dims.length),H=[q,V,Y],Q=e.length===4?$e("zero_points",12,e[3].dims.length):void 0;Q&&H.push(Q);let ie=k.length,le=tt("output",e[0].dataType,ie),ae=pr(e[0].dataType),ge=()=>{switch(u){case 1:return` + let a_data0 = vec4<${ae}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); + let a_data1 = vec4<${ae}>(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<${ae}>(sub_a[word_offset], sub_a[word_offset + 1]); + let a_data1 = vec4<${ae}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return` + let a_data0 = sub_a[word_offset]; + let a_data1 = sub_a[word_offset + 1];`;default:throw new Error(`${u}-component is not supported.`)}};return` + var sub_a: array<${q.type.value}, ${y}>; + var inter_results: array, ${P}>; + ${R.declareVariables(...H,le)} + ${R.mainStart([A,P,1])} + let output_indices = ${le.offsetToIndices(`workgroup_index * ${P}`)}; + let col = output_indices[2]; + let row = output_indices[1]; + let batch = output_indices[0]; + let n_blocks_per_col = uniforms.b_shape[1]; + let num_tiles = (n_blocks_per_col - 1) / ${S} + 1; + + // Loop over shared dimension. + for (var tile: u32 = 0; tile < num_tiles; tile += 1) { + let a_col_start = tile * ${y}; + // load one tile A data into shared memory. + for (var a_offset = local_idx; a_offset < ${y}; a_offset += ${_}) + { + let a_col = a_col_start + a_offset; + if (a_col < uniforms.a_shape[2]) + { + sub_a[a_offset] = ${q.getByIndices(`${q.type.indices}(batch, row, a_col)`)}; + } else { + sub_a[a_offset] = ${q.type.value}(0); + } + } + workgroupBarrier(); + + // each thread process one block + let b_row = col + local_id.y; + let block = tile * ${S} + local_id.x; + ${Q?` + let zero_point_bytes_per_col = (n_blocks_per_col + 1) / 2; + let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block >> 0x1u); + let zero_point_word_index = zero_point_byte_count >> 0x2u; + let zero_point_byte_offset = zero_point_byte_count & 0x3u; + let zero_point_nibble_offset: u32 = block & 0x1u; + let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_nibble_offset << 2); + let zero_point_word = ${Q.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; + let zero_point = ${ae}((zero_point_word) & 0xFu);`:` + // The default zero point is 8 for unsigned 4-bit quantization. + let zero_point = ${ae}(8);`} + let scale = ${Y.getByOffset("b_row * n_blocks_per_col + block")}; + let b_data = ${V.getByIndices(`${V.type.indices}(b_row, block, 0)`)}; + var word_offset = local_id.x * ${r.blockSize/u}; + for (var i: u32 = 0; i < ${h}; i++) { + ${ge()} + let b_value = ${h===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<${ae}>(${Array.from({length:4},(N,O)=>`${ae}(b_value_lower[${O}]), ${ae}(b_value_upper[${O}])`).join(", ")}); + let b_dequantized_values = (b_quantized_values - mat2x4<${ae}>(${Array(8).fill("zero_point").join(",")})) * scale; + inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(N,O)=>`${`dot(a_data${O}, b_dequantized_values[${O}])`}`).join(" + ")}; + word_offset += ${8/u}; + } + workgroupBarrier(); + } + + if (local_idx < ${P}) { + var output_value: ${le.type.value} = ${le.type.value}(0); + for (var b = 0u; b < ${A}; b++) { + output_value += inter_results[local_idx][b]; + } + if (col + local_idx < uniforms.output_shape[2]) + { + ${le.setByIndices(`${le.type.indices}(batch, row, col + local_idx)`,"output_value")} + } + } + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${r.blockSize};${u};${h};${A};${P}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:w,dataType:p}],dispatchGroup:{x},programUniforms:g}),getShaderSource:B}},F0=(e,r)=>{Sg(e.inputs,r),r.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(kg(e.inputs,r)):e.compute($g(e.inputs,r))},O0=e=>Lt(e)}),Ig,Ag,Fg,Og,Dg,Lg,zg,Bg,D0,px=je(()=>{mt(),Mt(),xt(),Ig=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let r=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(r=e[3].dims[0]*2===e[1].dims[0]),!r)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Ag=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` + k = i32(${e.indicesGet("indices",i)}) - ${rt("uniforms.pads",i,t)}; + if (k < 0) { + break; + } + if (k >= i32(${rt("uniforms.x_shape",i,r)})) { + break; + } + offset += k * i32(${rt("uniforms.x_strides",i,r)}); + `;return` + value = ${e.type.value}(uniforms.constant_value); + for (var i = 0; i < 1; i++) { + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + } + `},Fg=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` + k = i32(${e.indicesGet("indices",i)}) - ${rt("uniforms.pads",i,t)}; + if (k < 0) { + k = -k; + } + { + let _2n_1 = 2 * (i32(${rt("uniforms.x_shape",i,r)}) - 1); + k = k % _2n_1; + if(k >= i32(${rt("uniforms.x_shape",i,r)})) { + k = _2n_1 - k; + } + } + offset += k * i32(${rt("uniforms.x_strides",i,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},Og=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` + k = i32(${e.indicesGet("indices",i)}) - ${rt("uniforms.pads",i,t)}; + if (k < 0) { + k = 0; + } + if (k >= i32(${rt("uniforms.x_shape",i,r)})) { + k = i32(${rt("uniforms.x_shape",i,r)}) - 1; + } + offset += k * i32(${rt("uniforms.x_strides",i,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},Dg=(e,r,t)=>{let s="";for(let i=r-1;i>=0;--i)s+=` + k = i32(${e.indicesGet("indices",i)}) - ${rt("uniforms.pads",i,t)}; + if (k < 0) { + k += i32(${rt("uniforms.x_shape",i,r)}]); + } + if (k >= i32(${rt("uniforms.x_shape",i,r)})) { + k -= i32(${rt("uniforms.x_shape",i,r)}); + } + offset += k * i32(${rt("uniforms.x_strides",i,r)}); + `;return` + var offset = 0; + var k = 0; + ${s} + value = x[offset]; + `},Lg=(e,r,t)=>{switch(t.mode){case 0:return Ag(e,r,t.pads.length);case 1:return Fg(e,r,t.pads.length);case 2:return Og(e,r,t.pads.length);case 3:return Dg(e,r,t.pads.length);default:throw new Error("Invalid mode")}},zg=(e,r)=>{let t=xe.padShape(e[0].dims.slice(),r.pads),s=e[0].dims,i=xe.size(t),n=[{type:12,data:i},{type:6,data:r.pads}],o=e.length>=3&&e[2].data;r.mode===0&&n.push({type:o?e[2].dataType:1,data:r.value}),n.push(...nt(e[0].dims,t));let a=["rank"],l=d=>{let p=tt("output",e[0].dataType,t.length),u=$e("x",e[0].dataType,s.length),h=u.type.value,w=Lg(p,s.length,r),_=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:r.pads.length}];return r.mode===0&&_.push({name:"constant_value",type:o?h:"f32"}),` + ${d.registerUniforms(_).declareVariables(u,p)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + + let indices = ${p.offsetToIndices("global_idx")}; + + var value = ${h}(0); + ${w} + output[global_idx] = value; + }`};return{name:"Pad",shaderCache:{hint:`${r.mode}${o}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(xe.size(t)/64)},programUniforms:n}),getShaderSource:l}},Bg=(e,r)=>{if(e.length>1){let t=e[1].getBigInt64Array(),s=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,i=e[0].dims.length,n=new Int32Array(2*i).fill(0);if(e.length>=4){let a=e[3].getBigInt64Array();for(let l=0;ln[Number(l)]=Number(a));let o=[];return n.forEach(a=>o.push(a)),{mode:r.mode,value:s,pads:o}}else return r},D0=(e,r)=>{Ig(e.inputs);let t=Bg(e.inputs,r);e.compute(zg(e.inputs,t),{inputs:[0]})}}),ra,Pc,Cc,Sc,$c,Rg,Ng,kc,Ic,L0,z0,Ac,B0,R0,Fc,N0,j0,U0,V0,hx=je(()=>{Ms(),mt(),Mt(),xt(),ra=e=>{if(Kt.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Pc=(e,r,t)=>{let s=r.format==="NHWC",i=e.dims.slice();s&&i.splice(1,0,i.pop());let n=Object.hasOwnProperty.call(r,"dilations"),o=r.kernelShape.slice(),a=r.strides.slice(),l=n?r.dilations.slice():[],d=r.pads.slice();ad.adjustPoolAttributes(t,i,o,a,l,d);let p=ad.computePoolOutputShape(t,i,a,l,o,d,r.autoPad),u=Object.assign({},r);n?Object.assign(u,{kernelShape:o,strides:a,pads:d,dilations:l,cacheKey:r.cacheKey}):Object.assign(u,{kernelShape:o,strides:a,pads:d,cacheKey:r.cacheKey});let h=p.slice();return h.push(h.splice(1,1)[0]),[u,s?h:p]},Cc=(e,r)=>{let t=r.format==="NHWC",s=xe.size(e),i=xe.size(r.kernelShape),n=[{type:12,data:s},{type:12,data:i}],o=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(r.kernelShape.length<=2){let a=r.kernelShape[r.kernelShape.length-1],l=r.strides[r.strides.length-1],d=r.pads[r.pads.length/2-1],p=r.pads[r.pads.length-1],u=!!(d+p);n.push({type:12,data:a},{type:12,data:l},{type:12,data:d},{type:12,data:p}),o.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let h=!1;if(r.kernelShape.length===2){let w=r.kernelShape[r.kernelShape.length-2],_=r.strides[r.strides.length-2],P=r.pads[r.pads.length/2-2],A=r.pads[r.pads.length-2];h=!!(P+A),n.push({type:12,data:w},{type:12,data:_},{type:12,data:P},{type:12,data:A}),o.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[n,o,!0,u,h]}else{if(t)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let a=xe.computeStrides(r.kernelShape);n.push({type:12,data:a},{type:12,data:r.pads},{type:12,data:r.strides}),o.push({name:"kernelStrides",type:"u32",length:a.length},{name:"pads",type:"u32",length:r.pads.length},{name:"strides",type:"u32",length:r.strides.length});let l=r.pads.reduce((d,p)=>d+p);return[n,o,!!l,!1,!1]}},Sc=(e,r,t,s,i,n,o,a,l,d,p,u)=>{let h=i.format==="NHWC",w=r.type.value,_=tt("output",r.type.tensor,s);if(i.kernelShape.length<=2){let P="",A="",v="",y=t-(h?2:1);if(p?P=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i; + if (xIndices[${y}] < 0 || xIndices[${y}] + >= uniforms.x_shape[${y}]) { + pad++; + continue; + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:P=` + for (var i: u32 = 0u; i < uniforms.kw; i++) { + xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i; + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`,i.kernelShape.length===2){let S=t-(h?3:2);u?A=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${S}] = indices[${S}] * uniforms.sh - uniforms.phStart + j; + if (xIndices[${S}] < 0 || xIndices[${S}] >= uniforms.x_shape[${S}]) { + pad += i32(uniforms.kw); + continue; + } + `:A=` + for (var j: u32 = 0u; j < uniforms.kh; j++) { + xIndices[${S}] = indices[${S}] * uniforms.sh - uniforms.phStart + j; + `,v=` + } + `}return` + ${e.registerUniforms(l).declareVariables(r,_)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + + let indices = ${_.offsetToIndices("global_idx")}; + var xIndices = ${_.offsetToIndices("global_idx")}; + + var value = ${w}(${a}); + var pad = 0; + ${A} + ${P} + ${v} + ${o} + + output[global_idx] = value; + }`}else{if(h)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let P=i.kernelShape.length,A=i.pads.length,v="";return d?v=` + if (xIndices[j] >= uniforms.x_shape[j]) { + pad++; + isPad = true; + break; + } + } + if (!isPad) { + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + }`:v=` + } + let x_val = x[${r.indicesToOffset("xIndices")}]; + ${n} + `,` + ${e.registerUniforms(l).declareVariables(r,_)} + + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let indices = ${_.offsetToIndices("global_idx")}; + var xIndices = ${_.offsetToIndices("global_idx")}; + + var offsets: array; + + var value = ${w}(${a}); + var pad = 0; + var isPad = false; + + for (var i: u32 = 0u; i < uniforms.kernelSize; i++) { + var offset = i; + for (var j = 0u; j < ${P-1}u; j++) { + offsets[j] = offset / ${rt("uniforms.kernelStrides","j",P)}; + offset -= offsets[j] * ${rt("uniforms.kernelStrides","j",P)}; + } + offsets[${P-1}] = offset; + + isPad = false; + for (var j = ${t-P}u; j < ${t}u; j++) { + xIndices[j] = indices[j] * ${rt("uniforms.strides",`j - ${t-P}u`,P)} + + offsets[j - ${t-P}u] - ${rt("uniforms.pads","j - 2u",A)}; + ${v} + } + ${o} + + output[global_idx] = value; + }`}},$c=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,Rg=e=>`${$c(e)};${e.countIncludePad}`,Ng=e=>`${$c(e)};${e.storageOrder};${e.dilations}`,kc=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}),Ic=(e,r,t,s)=>{let[i,n]=Pc(r,s,t),o=$e("x",r.dataType,r.dims.length),a=o.type.value,l="value += x_val;",d="";i.countIncludePad?d+=`value /= ${a}(uniforms.kernelSize);`:d+=`value /= ${a}(i32(uniforms.kernelSize) - pad);`;let[p,u,h,w,_]=Cc(n,i);p.push(...nt(r.dims,n));let P=["rank"];return{name:e,shaderCache:{hint:`${s.cacheKey};${h};${w};${_}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(xe.size(n)/64)},programUniforms:p}),getShaderSource:A=>Sc(A,o,r.dims.length,n.length,i,l,d,0,u,h,w,_)}},L0=e=>{let r=e.count_include_pad!==0,t=kc(e);if(t.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let s={countIncludePad:r,...t,cacheKey:""};return{...s,cacheKey:Rg(s)}},z0=(e,r)=>{ra(e.inputs),e.compute(Ic("AveragePool",e.inputs[0],!1,r))},Ac={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},B0=e=>{let r=e.format;return{format:r,...Ac,cacheKey:r}},R0=(e,r)=>{ra(e.inputs),e.compute(Ic("GlobalAveragePool",e.inputs[0],!0,r))},Fc=(e,r,t,s)=>{let[i,n]=Pc(r,s,t),o=` + value = max(x_val, value); + `,a="",l=$e("x",r.dataType,r.dims.length),d=["rank"],[p,u,h,w,_]=Cc(n,i);return p.push(...nt(r.dims,n)),{name:e,shaderCache:{hint:`${s.cacheKey};${h};${w};${_}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:n,dataType:r.dataType}],dispatchGroup:{x:Math.ceil(xe.size(n)/64)},programUniforms:p}),getShaderSource:P=>Sc(P,l,r.dims.length,n.length,i,o,a,r.dataType===10?-65504:-1e5,u,h,w,_)}},N0=(e,r)=>{ra(e.inputs),e.compute(Fc("MaxPool",e.inputs[0],!1,r))},j0=e=>{let r=e.storage_order,t=e.dilations,s=kc(e);if(r!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(s.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let i={storageOrder:r,dilations:t,...s,cacheKey:""};return{...i,cacheKey:Ng(i)}},U0=e=>{let r=e.format;return{format:r,...Ac,cacheKey:r}},V0=(e,r)=>{ra(e.inputs),e.compute(Fc("GlobalMaxPool",e.inputs[0],!0,r))}}),jg,Ug,W0,G0,mx=je(()=>{mt(),Mt(),tr(),xt(),jg=(e,r)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[0].dataType===6&&e.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((t,s)=>t===e[2].dims[s]).reduce((t,s)=>t&&s,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(r.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((i,n)=>n===r.axis||i===e[0].dims[n]).reduce((i,n)=>i&&n,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let t=e[0].dims[r.axis],s=e[1].dims[r.axis];if(r.blockSizeMath.ceil(t/(s-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Ug=(e,r)=>{let t=xe.normalizeAxis(r.axis,e[0].dims.length),s=e[0].dataType,i=s===3,n=e[0].dims,o=e[1].dataType,a=xe.size(n),l=s===3||s===2,d=l?[Math.ceil(xe.size(e[0].dims)/4)]:e[0].dims,p=e[1].dims,u=e.length>2?e[2]:void 0,h=u?l?[Math.ceil(xe.size(u.dims)/4)]:u.dims:void 0,w=p.length===0||p.length===1&&p[0]===1,_=w===!1&&p.length===1,P=Jt(a),A=w&&(!l||P===4),v=A?P:1,y=A&&!l?P:1,S=$e("input",l?12:s,d.length,y),x=$e("scale",o,p.length),g=u?$e("zero_point",l?12:s,h.length):void 0,M=tt("output",o,n.length,v),E=[S,x];g&&E.push(g);let k=[d,p];u&&k.push(h);let B=[{type:12,data:a/v},{type:12,data:t},{type:12,data:r.blockSize},...nt(...k,n)],R=J=>{let q=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${J.registerUniforms(q).declareVariables(...E,M)} + ${J.mainStart()} + ${J.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${M.offsetToIndices("global_idx")}; + + // Set input x + ${l?` + let input = ${S.getByOffset("global_idx / 4")}; + let x_vec = ${i?"unpack4xI8(input)":"unpack4xU8(input)"}; + let x_value = ${v===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${S.getByOffset("global_idx")};`}; + + // Set scale input + ${w?`let scale_value= ${x.getByOffset("0")}`:_?` + let scale_index = ${M.indicesGet("output_indices","uniforms.axis")}; + let scale_value= ${x.getByOffset("scale_index")};`:` + var scale_indices: ${x.type.indices} = output_indices; + let index = ${x.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size; + ${x.indicesSet("scale_indices","uniforms.axis","index")}; + let scale_value= ${x.getByIndices("scale_indices")};`}; + + // Set zero-point input + ${g?w?l?` + let zero_point_input = ${g.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 = ${g.getByOffset("0")}`:_?l?` + let zero_point_index = ${M.indicesGet("output_indices","uniforms.axis")}; + let zero_point_input = ${g.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 = ${M.indicesGet("output_indices","uniforms.axis")}; + let zero_point_value = ${g.getByOffset("zero_point_index")};`:l?` + let zero_point_offset = ${x.indicesToOffset("scale_indices")}; + let zero_point_input = ${g.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 = ${g.getByIndices("scale_indices")};`:`let zero_point_value = ${l?i?"i32":"u32":S.type.value}(0);`}; + // Compute and write output + ${M.setByOffset("global_idx",`${M.type.value}(x_value - zero_point_value) * scale_value`)}; + }`};return{name:"DequantizeLinear",shaderCache:{hint:r.cacheKey,inputDependencies:g?["rank","rank","rank"]:["rank","rank"]},getShaderSource:R,getRunData:()=>({outputs:[{dims:n,dataType:o}],dispatchGroup:{x:Math.ceil(a/v/64),y:1,z:1},programUniforms:B})}},W0=(e,r)=>{jg(e.inputs,r),e.compute(Ug(e.inputs,r))},G0=e=>Lt({axis:e.axis,blockSize:e.blockSize})}),Vg,Wg,K0,fx=je(()=>{Ms(),mt(),xt(),Vg=(e,r,t)=>{let s=e===r,i=er&&t>0;if(s||i||n)throw new Error("Range these inputs' contents are invalid.")},Wg=(e,r,t,s)=>{let i=Math.abs(Math.ceil((r-e)/t)),n=[i],o=i,a=[{type:12,data:o},{type:s,data:e},{type:s,data:t},...nt(n)],l=d=>{let p=tt("output",s,n.length),u=p.type.value,h=[{name:"outputSize",type:"u32"},{name:"start",type:u},{name:"delta",type:u}];return` + ${d.registerUniforms(h).declareVariables(p)} + ${d.mainStart()} + ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + output[global_idx] = uniforms.start + ${u}(global_idx) * uniforms.delta; + }`};return{name:"Range",shaderCache:{hint:`${s}`},getShaderSource:l,getRunData:()=>({outputs:[{dims:n,dataType:s}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:a})}},K0=e=>{let r=0,t=0,s=0;e.inputs[0].dataType===6?(r=e.inputs[0].getInt32Array()[0],t=e.inputs[1].getInt32Array()[0],s=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(r=e.inputs[0].getFloat32Array()[0],t=e.inputs[1].getFloat32Array()[0],s=e.inputs[2].getFloat32Array()[0]),Kt.webgpu.validateInputContent&&Vg(r,t,s),e.compute(Wg(r,t,s,e.inputs[0].dataType),{inputs:[]})}}),Gg,Kg,H0,q0,_x=je(()=>{mt(),Mt(),tr(),xt(),Gg=(e,r,t,s)=>{if(e!=="none"&&s!=="i32"&&s!=="u32"&&s!=="f32")throw new Error(`Input ${s} is not supported with reduction ${e}.`);let i=`{ + var oldValue = 0; + loop { + let newValueF32 =`,n=`; + let newValue = bitcast(newValueF32); + let res = atomicCompareExchangeWeak(&${r}, oldValue, newValue); + if res.exchanged { + break; + } + oldValue = res.old_value; + } + }`;switch(e){case"none":return`${r}=${t};`;case"add":return s==="i32"||s==="u32"?`atomicAdd(&${r}, bitcast<${s}>(${t}));`:` + ${i}bitcast<${s}>(oldValue) + (${t})${n}`;case"max":return s==="i32"||s==="u32"?`atomicMax(&${r}, bitcast<${s}>(${t}));`:` + ${i}max(bitcast(oldValue), (${t}))${n}`;case"min":return s==="i32"||s==="u32"?`atomicMin(&${r}, bitcast<${s}>(${t}));`:`${i}min(bitcast<${s}>(oldValue), (${t}))${n}`;case"mul":return`${i}(bitcast<${s}>(oldValue) * (${t}))${n}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Kg=(e,r)=>{let t=e[0].dims,s=e[1].dims,i=t,n=1,o=Math.ceil(xe.size(s)/n),a=s[s.length-1],l=xe.sizeFromDimension(t,a),d=[{type:12,data:o},{type:12,data:a},{type:12,data:l},...nt(e[1].dims,e[2].dims,i)],p=u=>{let h=$e("indices",e[1].dataType,e[1].dims.length),w=$e("updates",e[2].dataType,e[2].dims.length,n),_=r.reduction!=="none"&&r.reduction!==""?Ty("output",e[0].dataType,i.length):tt("output",e[0].dataType,i.length,n);return` + ${u.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(h,w,_)} + ${u.mainStart()} + ${u.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + var hasDuplicates = false; + if (${r.reduction==="none"}) { + let n = ${xe.size(s)}; + for (var i = 0; i < n; i = i + 1) { + for (var j = i + 1; j < n; 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; + } + } + } + + var data_offset = 0u; + var indices_start = uniforms.last_index_dimension * global_idx; + if (${r.reduction==="none"} && hasDuplicates) { + if (global_idx != 0u) { + return; + } + indices_start = 0u; + } + let indices_end = indices_start + uniforms.last_index_dimension; + for (var i = indices_start; i < indices_end; i++) { + var index = i32(indices[i].x); + ${e[0].dims.length===1?` + let element_count_dim = uniforms.output_strides; + let dim_value = uniforms.output_shape;`:` + let element_count_dim = uniforms.output_strides[i - indices_start]; + let dim_value = uniforms.output_shape[i - indices_start + 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)); + } + + for (var i = 0u; i < uniforms.num_updates_elements; i++) { + let value = updates[uniforms.num_updates_elements * global_idx + i]; + ${Gg(r.reduction,"output[data_offset + i]","value",_.type.value)} + } + + }`};return{name:"ScatterND",shaderCache:{hint:`${r.cacheKey}_${r.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:d}),getShaderSource:p}},H0=e=>Lt({reduction:e.reduction}),q0=(e,r)=>{e.compute(Kg(e.inputs,r),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Hg,qg,Qg,Oc,Xg,Jg,Yg,Zg,ew,tw,rw,sw,Dc,nw,iw,ow,aw,lw,Q0,X0,gx=je(()=>{mt(),Mt(),tr(),xt(),Hg=(e,r)=>{if(e.every(t=>t>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(r.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(r.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},qg=(e,r,t)=>{r.every(i=>i>=0&&i{throw new Error("Resize requires axes input values to be positive and less than rank")}));let s=new Array(t).fill(1);return r.forEach((i,n)=>s[i]=e[n]),s},Qg=(e,r,t,s,i,n)=>{let[o,a,l]=t>10?[1,2,3]:[-1,e.length>1?1:-1,-1],d=e[0].dims.length;if(o>0&&e.length>o&&e[o].dims.length>0)e[o].getFloat32Array().forEach(p=>n.push(p));else if(r.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(a>0&&e.length>a&&e[a].dims.length===1&&e[a].dims[0]>0){if(e[a].getFloat32Array().forEach(p=>s.push(p)),s.length!==0&&s.length!==d&&t>=18&&s.length!==r.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Hg(s,r),r.axes.length>0&&qg(s,r.axes,d).forEach((p,u)=>s[u]=p)}if(l>0&&e.length>l&&e[l].dims.length===1&&e[l].dims[0]>0&&(e[l].getBigInt64Array().forEach(p=>i.push(Number(p))),i.length!==0&&i.length!==d&&t>=18&&i.length!==r.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(r.axes.length>0){if(s.length!==0&&s.length!==r.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(i.length!==0&&i.length!==r.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof s<"u"&&typeof i<"u"&&s.length>0&&i.length>d)throw new Error("Resize requires only of scales or sizes to be specified")},Oc=(e,r,t,s)=>` + // The whole part and the fractional part are calculated separately due to inaccuracy of floating + // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an + // offset-by-one error later in floor(). + let big = (${e}) * (${r}); + let whole = ${s}(big / (${t})); + let fract = ${s}(big % (${t})) / ${s}(${t}); + return whole + fract; +`,Xg=(e,r)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, + lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${r} { `+(()=>{switch(e){case"asymmetric":return` + if (xScale < 1.0 || floor(xScale) != xScale) { + return ${r}(xResized) / ${r}(xScale); + } else { + ${Oc("xResized","lengthOriginal","lengthResized",r)} + } + `;case"pytorch_half_pixel":return`if (lengthResized > 1) { + return (${r}(xResized) + 0.5) / ${r}(xScale) - 0.5; + } else { + return 0.0; + }`;case"tf_half_pixel_for_nn":return`return (${r}(xResized) + 0.5) / ${r}(xScale);`;case"align_corners":return`if (lengthResized == 1) { + return 0.0; + } else { + ${Oc("xResized","lengthOriginal - 1","lengthResized - 1",r)} + }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { + return ${r}(roiStart) * ${r}(lengthOriginal - 1) + + (${r}(xResized) * ${r}(roiEnd - roiStart) * ${r}(lengthOriginal - 1)) / + ${r}(lengthResized - 1); + } else { + return 0.5 * ${r}(roiStart + roiEnd) * ${r}(lengthOriginal - 1); + }`;case"half_pixel_symmetric":return`const outputWidth = ${r}xScale * ${r}(lengthResized); + const adjustment = ${r}(lengthResized) / outputWidth; + const center = ${r}(lengthOriginal) / 2; + const offset = center * (1 - adjustment); + return offset + ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;case"half_pixel":return`return ((${r}(xResized) + 0.5) / ${r}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",Jg=(e,r,t)=>`fn getNearestPixelFromOriginal(xOriginal: ${t}, isDownSample: bool) -> ${t} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(r<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Yg=(e,r,t)=>{let s=new Array(t).fill(0).concat(new Array(t).fill(1)),i=e.length===0?s:e.slice();return r.length>0?(r.forEach((n,o)=>{s[n]=i[o],s[o+t]=i[r.length+o]}),s):i},Zg=(e,r,t,s)=>{let i=[];if(t.length>0)if(s.length>0){if(e.forEach(n=>i.push(n)),Math.max(...s)>e.length)throw new Error("axes is out of bound");s.forEach((n,o)=>i[n]=t[o])}else t.forEach(n=>i.push(n));else{if(r.length===0)throw new Error("Resize requires either scales or sizes.");i=e.map((n,o)=>Math.round(n*r[o]))}return i},ew=(e,r,t)=>{let s=(()=>{switch(t.keepAspectRatioPolicy){case"not_larger":return t.axes.length>0?Math.min(...t.axes.map(n=>r[n]),Number.MAX_VALUE):Math.min(...r,Number.MAX_VALUE);case"not_smaller":return t.axes.length>0?Math.max(...t.axes.map(n=>r[n]),Number.MIN_VALUE):Math.max(...r,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${t.keepAspectRatioPolicy} is not supported`)}})();r.fill(1,0,r.length);let i=e.slice();return t.axes.length>0?(t.axes.forEach(n=>r[n]=s),t.axes.forEach(n=>i[n]=Math.round(e[n]*r[n]))):(r.fill(s,0,r.length),i.forEach((n,o)=>i[o]=Math.round(n*r[o]))),i},tw=(e,r,t,s,i)=>` + fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${t.length}> { + var original_indices: array<${e.type.value}, ${t.length}>; + for (var i:u32 = 0; i < ${t.length}; i++) { + var output_index = ${e.indicesGet("output_indices","i")}; + var scale = ${rt("uniforms.scales","i",s)}; + var roi_low = ${rt("uniforms.roi","i",i)}; + var roi_hi = ${rt("uniforms.roi",`i + ${r.length}`,i)}; + if (scale == 1.0) { + original_indices[i] = ${e.type.value}(output_index); + } else { + var input_shape_i = ${rt("uniforms.input_shape","i",r.length)}; + var output_shape_i = ${rt("uniforms.output_shape","i",t.length)}; + original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + } + } + return original_indices; + }`,rw=(e,r,t,s,i,n,o)=>` + fn calculateInputIndicesFromOutputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + for (var i:u32 = 0; i < ${s.length}; i++) { + var output_index = ${r.indicesGet("output_indices","i")}; + var input_index: u32; + var scale = ${rt("uniforms.scales","i",i)}; + if (scale == 1.0) { + input_index = output_index; + } else { + var roi_low = ${rt("uniforms.roi","i",n)}; + var roi_hi = ${rt("uniforms.roi",`i + ${t.length}`,n)}; + var input_shape_i = ${rt("uniforms.input_shape","i",t.length)}; + var output_shape_i = ${rt("uniforms.output_shape","i",s.length)}; + var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i, + input_shape_i, roi_low, roi_hi); + if (!${o} || (original_idx >= 0 && original_idx < ${r.type.value}(input_shape_i))) { + if (original_idx < 0) { + input_index = 0; + } else if (original_idx > ${r.type.value}(input_shape_i - 1)) { + input_index = input_shape_i - 1; + } else { + input_index = u32(getNearestPixelFromOriginal(original_idx, scale < 1)); + } + } else { + input_index = u32(original_idx); + } + } + ${e.indicesSet("input_indices","i","input_index")} + } + return input_indices; + }`,sw=(e,r)=>` + fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { + for (var i:u32 = 0; i < ${r.length}; i++) { + var input_index = ${e.indicesGet("input_indices","i")}; + if (input_index < 0 || input_index >= ${rt("uniforms.input_shape","i",r.length)}) { + return false; + } + } + return true; + }`,Dc=(e,r,t,s)=>e.rank>s?` + ${e.indicesSet("input_indices",r,"channel")}; + ${e.indicesSet("input_indices",t,"batch")}; +`:"",nw=(e,r,t,s,i)=>{let[n,o,a,l]=t.length===2?[-1,0,1,-1]:[0,2,3,1],d=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${d} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",o,`max(0, min(row, ${t[o]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(col, ${t[a]} - 1))`)}; + ${Dc(e,l,n,2)} + return ${e.getByIndices("input_indices")}; + } + + fn bilinearInterpolation(output_indices: ${r.type.indices}) -> ${d} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var row:${d} = originalIndices[${o}]; + var col:${d} = originalIndices[${a}]; + ${s?`if (row < 0 || row > (${t[o]} - 1) || col < 0 || col > (${t[a]} - 1)) { + return ${i}; + }`:""}; + row = max(0, min(row, ${t[o]} - 1)); + col = max(0, min(col, ${t[a]} - 1)); + var row1: u32 = u32(row); + var col1: u32 = u32(col); + var row2: u32 = u32(row + 1); + var col2: u32 = u32(col + 1); + var channel: u32 = ${t.length>2?`u32(originalIndices[${l}])`:"0"}; + var batch: u32 = ${t.length>2?`u32(originalIndices[${n}])`:"0"}; + var x11: ${d} = getInputValue(batch, channel, row1, col1); + var x12: ${d} = getInputValue(batch, channel, row1, col2); + var x21: ${d} = getInputValue(batch, channel, row2, col1); + var x22: ${d} = getInputValue(batch, channel, row2, col2); + var dx1: ${d} = abs(row - ${d}(row1)); + var dx2: ${d} = abs(${d}(row2) - row); + var dy1: ${d} = abs(col - ${d}(col1)); + var dy2: ${d} = abs(${d}(col2) - col); + if (row1 == row2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (col1 == col2) { + dy1 = 0.5; + dy2 = 0.5; + } + return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); + }`},iw=(e,r,t,s,i,n,o,a,l,d)=>{let p=t.length===2,[u,h]=p?[0,1]:[2,3],w=e.type.value,_=P=>{let A=P===u?"row":"col";return` + fn ${A}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${r.type.indices}) -> ${w} { + var output_index = ${r.indicesGet("output_indices",P)}; + var originalIdx: ${w} = getOriginalCoordinateFromResizedCoordinate(output_index, ${i[P]}, + ${s[P]}, ${t[P]}, ${n[P]}, ${n[P]} + ${t.length}); + var fractOriginalIdx: ${w} = originalIdx - floor(originalIdx); + var coefs = getCubicInterpolationCoefs(fractOriginalIdx); + + if (${a} && (originalIdx < 0 || originalIdx > (${t[P]} - 1))) { + return ${l}; + } + var data: array<${w}, 4> = array<${w}, 4>(0.0, 0.0, 0.0, 0.0); + for (var i: i32 = -1; i < 3; i++) { + var ${A}: ${w} = originalIdx + ${w}(i); + if (${A} < 0 || ${A} >= ${t[P]}) { + ${d?`coefs[i + 1] = 0.0; + continue;`:a?`return ${l};`:`${A} = max(0, min(${A}, ${t[P]} - 1));`}; + } + var input_indices_copy: ${e.type.indices} = input_indices; + ${e.indicesSet("input_indices_copy",P,`u32(${A})`)}; + data[i + 1] = ${P===u?e.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"}; + } + return cubicInterpolation1D(data, coefs); + }`};return` + ${_(u)}; + ${_(h)}; + fn getCubicInterpolationCoefs(s: ${w}) -> array<${w}, 4> { + var absS = abs(s); + var coeffs: array<${w}, 4> = array<${w}, 4>(0.0, 0.0, 0.0, 0.0); + var oneMinusAbsS: ${w} = 1.0 - absS; + var twoMinusAbsS: ${w} = 2.0 - absS; + var onePlusAbsS: ${w} = 1.0 + absS; + coeffs[0] = ((${o} * onePlusAbsS - 5 * ${o}) * onePlusAbsS + 8 * ${o}) * onePlusAbsS - 4 * ${o}; + coeffs[1] = ((${o} + 2) * absS - (${o} + 3)) * absS * absS + 1; + coeffs[2] = ((${o} + 2) * oneMinusAbsS - (${o} + 3)) * oneMinusAbsS * oneMinusAbsS + 1; + coeffs[3] = ((${o} * twoMinusAbsS - 5 * ${o}) * twoMinusAbsS + 8 * ${o}) * twoMinusAbsS - 4 * ${o}; + return coeffs; + } + + fn cubicInterpolation1D(x: array<${w}, 4>, coefs: array<${w}, 4>) -> ${w} { + var coefsSum: ${w} = coefs[0] + coefs[1] + coefs[2] + coefs[3]; + return (x[0] * coefs[0] + x[1] * coefs[1]+ x[2] * coefs[2]+ x[3] * coefs[3]) / coefsSum; + } + + fn bicubicInterpolation(output_indices: ${r.type.indices}) -> ${w} { + var input_indices: ${e.type.indices} = output_indices; + return colCubicInterpolation(input_indices, output_indices); + } + `},ow=(e,r,t,s,i)=>{let[n,o,a,l,d]=t.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],p=e.type.value;return` + fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${p} { + var input_indices: ${e.type.indices}; + ${e.indicesSet("input_indices",o,`max(0, min(depth, ${t[o]} - 1))`)}; + ${e.indicesSet("input_indices",a,`max(0, min(height, ${t[a]} - 1))`)}; + ${e.indicesSet("input_indices",l,`max(0, min(width, ${t[l]} - 1))`)}; + ${Dc(e,d,n,3)} + return ${e.getByIndices("input_indices")}; + } + + fn trilinearInterpolation(output_indices: ${r.type.indices}) -> ${p} { + var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices); + var depth:${p} = originalIndices[${o}]; + var height:${p} = originalIndices[${a}]; + var width:${p} = originalIndices[${l}]; + ${s?`if (depth < 0 || depth > (${t[o]} - 1) || height < 0 || height > (${t[a]} - 1) || width < 0 || (width > ${t[l]} - 1)) { + return ${i}; + }`:""}; + + depth = max(0, min(depth, ${t[o]} - 1)); + height = max(0, min(height, ${t[a]} - 1)); + width = max(0, min(width, ${t[l]} - 1)); + var depth1: u32 = u32(depth); + var height1: u32 = u32(height); + var width1: u32 = u32(width); + var depth2: u32 = u32(depth + 1); + var height2: u32 = u32(height + 1); + var width2: u32 = u32(width + 1); + var channel: u32 = ${t.length>3?`u32(originalIndices[${d}])`:"0"}; + var batch: u32 = ${t.length>3?`u32(originalIndices[${n}])`:"0"}; + + var x111: ${p} = getInputValue(batch, channel, depth1, height1, width1); + var x112: ${p} = getInputValue(batch, channel, depth1, height1, width2); + var x121: ${p} = getInputValue(batch, channel, depth1, height2, width1); + var x122: ${p} = getInputValue(batch, channel, depth1, height2, width2); + var x211: ${p} = getInputValue(batch, channel, depth2, height1, width1); + var x212: ${p} = getInputValue(batch, channel, depth2, height1, width2); + var x221: ${p} = getInputValue(batch, channel, depth2, height2, width1); + var x222: ${p} = getInputValue(batch, channel, depth2, height2, width2); + var dx1: ${p} = abs(depth - ${p}(depth1)); + var dx2: ${p} = abs(${p}(depth2) - depth); + var dy1: ${p} = abs(height - ${p}(height1)); + var dy2: ${p} = abs(${p}(height2) - height); + var dz1: ${p} = abs(width - ${p}(width1)); + var dz2: ${p} = abs(${p}(width2) - width); + if (depth1 == depth2) { + dx1 = 0.5; + dx2 = 0.5; + } + if (height1 == height2) { + dy1 = 0.5; + dy2 = 0.5; + } + if (width1 == width2) { + dz1 = 0.5; + dz2 = 0.5; + } + return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 + + x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1); + }`},aw=(e,r,t,s,i,n)=>{let o=e.dims,a=Yg(n,r.axes,o.length),l=Zg(o,s,i,r.axes),d=s.slice();s.length===0&&(d=o.map((y,S)=>y===0?1:l[S]/y),r.keepAspectRatioPolicy!=="stretch"&&(l=ew(o,d,r)));let p=tt("output",e.dataType,l.length),u=$e("input",e.dataType,o.length),h=xe.size(l),w=o.length===l.length&&o.every((y,S)=>y===l[S]),_=r.coordinateTransformMode==="tf_crop_and_resize",P=r.extrapolationValue,A=u.type.value,v=y=>` + ${w?"":` + ${Xg(r.coordinateTransformMode,A)}; + ${(()=>{switch(r.mode){case"nearest":return` + ${sw(u,o)}; + ${Jg(r.nearestMode,t,A)}; + ${rw(u,p,o,l,d.length,a.length,_)}; + `;case"linear":return` + ${tw(p,o,l,d.length,a.length)}; + ${(()=>{if(o.length===2||o.length===4)return`${nw(u,p,o,_,P)}`;if(o.length===3||o.length===5)return`${ow(u,p,o,_,P)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + `;case"cubic":return` + ${(()=>{if(o.length===2||o.length===4)return`${iw(u,p,o,l,d,a,r.cubicCoeffA,_,r.extrapolationValue,r.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + `;default:throw Error("Invalid resize mode")}})()}; + `} + ${y.registerUniform("output_size","u32").registerUniform("scales","f32",d.length).registerUniform("roi","f32",a.length).declareVariables(u,p)} + ${y.mainStart()} + ${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + ${w?"output[global_idx] = input[global_idx];":` + let output_indices = ${p.offsetToIndices("global_idx")}; + var input_indices: ${u.type.indices}; + ${(()=>{switch(r.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices); + if (checkInputIndices(input_indices)) { + output[global_idx] = ${u.getByIndices("input_indices")}; + } else { + output[global_idx] = ${r.extrapolationValue}; + }`;case"linear":return`output[global_idx] = ${o.length===2||o.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${r.mode}`)}})()}; +`} + }`;return{name:"Resize",shaderCache:{hint:`${r.cacheKey}|${t}|${d.length>0?r.mode==="cubic"?d:d.length:""}|${i.length>0?i:""}|${a.length>0?a:""}|${w}|${r.mode==="nearest"?o.length:o}`,inputDependencies:["rank"]},getShaderSource:v,getRunData:()=>({outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(h/64)},programUniforms:[{type:12,data:h},{type:1,data:d},{type:1,data:a},...nt(o,l)]})}},lw=e=>{let r=e.customDataBuffer;return new Uint32Array(r,r.byteOffset,1)[0]},Q0=(e,r)=>{let t=[],s=[],i=[],n=lw(e);if(r.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Qg(e.inputs,r,n,t,s,i),e.compute(aw(e.inputs[0],r,n,t,s,i),{inputs:[0]})},X0=e=>{let r=e.antialias,t=e.axes,s=e.coordinateTransformMode,i=e.cubicCoeffA,n=e.excludeOutside!==0,o=e.extrapolationValue,a=e.keepAspectRatioPolicy,l=e.mode,d=e.nearestMode===""?"simple":e.nearestMode;return Lt({antialias:r,axes:t,coordinateTransformMode:s,cubicCoeffA:i,excludeOutside:n,extrapolationValue:o,keepAspectRatioPolicy:a,mode:l,nearestMode:d})}}),dw,cw,J0,wx=je(()=>{mt(),Mt(),tr(),xt(),dw=(e,r)=>{let[t,s,i,n]=e,{numHeads:o,rotaryEmbeddingDim:a}=r;if(t.dims.length!==3&&t.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${t.dims.length}`);if(!xe.areEqual(s.dims,[])&&!xe.areEqual(s.dims,[1])&&s.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${s.dims.length}`);if(i.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${i.dims.length}`);if(n.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${n.dims.length}`);if(!xe.areEqual(i.dims,n.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(a>0&&o===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let l=t.dims[0],d=t.dims[t.dims.length-2],p=i.dims[0],u=xe.sizeFromDimension(t.dims,1)/d,h=a===0?i.dims[1]*2:u/o;if(a>h)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(s.dims.length===2){if(l!==s.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${s.dims[0]}`);if(d!==s.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${s.dims[1]}`)}if(h/2!==i.dims[1]&&a/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(d>p)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},cw=(e,r)=>{let{interleaved:t,numHeads:s,rotaryEmbeddingDim:i,scale:n}=r,o=e[0].dims[0],a=xe.sizeFromDimension(e[0].dims,1),l=e[0].dims[e[0].dims.length-2],d=a/l,p=e[2].dims[1],u=i===0?p*2:d/s,h=new Array(o,l,d/u,u-p),w=xe.computeStrides(h),_=[{type:1,data:n},{type:12,data:h},{type:12,data:w},...e[0].dims.length===3?new Array({type:12,data:[a,d,u,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[a,u,l*u,1]}):[],...nt(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],P=A=>{let v=$e("input",e[0].dataType,e[0].dims.length),y=$e("position_ids",e[1].dataType,e[1].dims.length),S=$e("cos_cache",e[2].dataType,e[2].dims.length),x=$e("sin_cache",e[3].dataType,e[3].dims.length),g=tt("output",e[0].dataType,e[0].dims.length);return A.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:h.length},{name:"global_strides",type:"u32",length:w.length},{name:"input_output_strides",type:"u32",length:w.length}]),` + ${A.declareVariables(v,y,S,x,g)} + + ${A.mainStart(Pi)} + let half_rotary_emb_dim = uniforms.${S.name}_shape[1]; + let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape; + let size = uniforms.global_shape[0] * uniforms.global_strides[0]; + ${A.guardAgainstOutOfBoundsWorkgroupSizes("size")} + + if (bsnh[3] < half_rotary_emb_dim) { + let position_ids_idx = + ${y.broadcastedIndicesToOffset("bsnh.xy",tt("",y.type.tensor,2))}; + let position_id = + u32(${y.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0); + let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${t}); + let j = i + select(half_rotary_emb_dim, 1, ${t}); + let re = ${v.getByOffset("i")} * ${S.get("position_id","bsnh[3]")} - + ${v.getByOffset("j")} * ${x.get("position_id","bsnh[3]")}; + ${g.setByOffset("i","re")} + let im = ${v.getByOffset("i")} * ${x.get("position_id","bsnh[3]")} + + ${v.getByOffset("j")} * ${S.get("position_id","bsnh[3]")}; + ${g.setByOffset("j","im")} + } else { + let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; + ${g.setByOffset("k",v.getByOffset("k"))} + } + }`};return{name:"RotaryEmbedding",shaderCache:{hint:Lt({interleaved:t}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:P,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(xe.size(h)/Pi)},programUniforms:_})}},J0=(e,r)=>{dw(e.inputs,r),e.compute(cw(e.inputs,r))}}),uw,pw,Y0,yx=je(()=>{mt(),Mt(),xt(),uw=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let r=e[0],t=e[1],s=e[2];if(r.dataType!==t.dataType||r.dataType!==s.dataType)throw new Error("All inputs must have the same data type");if(r.dims.length!==3&&r.dims.length!==2)throw new Error("Input must be 2D or 3D");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Skip must be 2D or 3D");let i=r.dims[r.dims.length-1],n=r.dims[r.dims.length-2];if(t.dims[t.dims.length-1]!==i)throw new Error("Skip must have the same hidden size as input");if(t.dims[t.dims.length-2]!==n)throw new Error("Skip must have the same sequence length as input");if(s.dims.length!==1)throw new Error("Gamma must be 1D");if(s.dims[s.dims.length-1]!==i)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let o=e[3];if(o.dims.length!==1)throw new Error("Beta must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let o=e[4];if(o.dims.length!==1)throw new Error("Bias must be 1D");if(o.dims[o.dims.length-1]!==i)throw new Error("Bias must have the same hidden size as input")}},pw=(e,r,t,s)=>{let i=r.simplified,n=e[0].dims,o=xe.size(n),a=n,l=o,d=n.slice(-1)[0],p=s?n.slice(0,-1).concat(1):[],u=!i&&e.length>3,h=e.length>4,w=s&&t>1,_=s&&t>2,P=t>3,A=64,v=Jt(d),y=[{type:12,data:l},{type:12,data:v},{type:12,data:d},{type:1,data:r.epsilon}],S=g=>{let M=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],E=[$e("x",e[0].dataType,e[0].dims,v),$e("skip",e[1].dataType,e[1].dims,v),$e("gamma",e[2].dataType,e[2].dims,v)];u&&E.push($e("beta",e[3].dataType,e[3].dims,v)),h&&E.push($e("bias",e[4].dataType,e[4].dims,v)),E.push(tt("output",e[0].dataType,a,v)),w&&E.push(tt("mean_output",1,p)),_&&E.push(tt("inv_std_output",1,p)),P&&E.push(tt("input_skip_bias_sum",e[0].dataType,a,v));let k=pr(e[0].dataType),B=pr(1,v);return` + + ${g.registerUniforms(M).declareVariables(...E)} + var sum_shared : array<${B}, ${A}>; + var sum_squared_shared : array<${B}, ${A}>; + + ${g.mainStart([A,1,1])} + let ix = local_id.x; + let iy = global_id.x / ${A}; + + let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components; + var stride = hidden_size_vectorized / ${A}; + let offset = ix * stride + iy * hidden_size_vectorized; + let offset1d = stride * ix; + if (ix == ${A-1}) { + stride = hidden_size_vectorized - stride * ix; + } + for (var i: u32 = 0; i < stride; i++) { + let skip_value = skip[offset + i]; + let bias_value = ${h?"bias[offset1d + i]":k+"(0.0)"}; + let input_value = x[offset + i]; + let value = input_value + skip_value + bias_value; + ${P?"input_skip_bias_sum[offset + i] = value;":""} + output[offset + i] = value; + let f32_value = ${xi(k,v,"value")}; + sum_shared[ix] += f32_value; + sum_squared_shared[ix] += f32_value * f32_value; + } + workgroupBarrier(); + + var reduce_size : u32 = ${A}; + 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 = ${cn("sum",v)} / f32(uniforms.hidden_size); + let inv_std_dev = inverseSqrt(${cn("square_sum",v)} / f32(uniforms.hidden_size) ${i?"":"- mean * mean"} + uniforms.epsilon); + ${w?"mean_output[global_idx] = mean;":""} + ${_?"inv_std_output[global_idx] = inv_std_dev;":""} + + for (var i: u32 = 0; i < stride; i++) { + output[offset + i] = (output[offset + i] ${i?"":`- ${k}(mean)`}) * + ${k}(inv_std_dev) * gamma[offset1d + i] + ${u?"+ beta[offset1d + i]":""}; + } + }`},x=[{dims:a,dataType:e[0].dataType}];return t>1&&x.push({dims:p,dataType:1}),t>2&&x.push({dims:p,dataType:1}),t>3&&x.push({dims:n,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${v};${w};${_};${P}`,inputDependencies:e.map((g,M)=>"type")},getShaderSource:S,getRunData:()=>({outputs:x,dispatchGroup:{x:Math.ceil(l/d)},programUniforms:y})}},Y0=(e,r)=>{uw(e.inputs);let t=[0];e.outputCount>1&&t.push(-3),e.outputCount>2&&t.push(-3),e.outputCount>3&&t.push(3),e.compute(pw(e.inputs,r,e.outputCount,!1),{outputs:t})}}),hw,sa,mw,Lc,fw,_w,Z0,eb,Mx=je(()=>{mt(),Mt(),tr(),xt(),hw=(e,r)=>{if(!e||e.length<1)throw new Error("too few inputs");if(r.axes.length!==0){if(r.axes.length!==r.starts.length||r.axes.length!==r.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(r.starts.length!==r.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((t,s)=>{if(e[s+1].dataType!==6&&e[s+1].dataType!==7)throw new Error(`Input ${s} must be an array of int32 or int64`)})},sa=(e,r)=>{let t=[];if(e.length>r)if(e[r].dataType===7)e[r].getBigInt64Array().forEach(s=>t.push(Number(s)));else if(e[r].dataType===6)e[r].getInt32Array().forEach(s=>t.push(Number(s)));else throw new Error(`Input ${r} must be an array of int32 or int64`);return t},mw=(e,r)=>{if(e.length>1){let t=sa(e,1),s=sa(e,2),i=sa(e,3);return i.length===0&&(i=[...Array(e[0].dims.length).keys()]),Lt({starts:t,ends:s,axes:i})}else return r},Lc=(e,r,t,s,i)=>{let n=e;return e<0&&(n+=t[s[r]]),i[r]<0?Math.max(0,Math.min(n,t[s[r]]-1)):Math.max(0,Math.min(n,t[s[r]]))},fw=(e,r,t)=>`fn calculateInputIndices(output_indices: ${r.type.indices}) -> ${e.type.indices} { + var input_indices: ${e.type.indices}; + var carry = 0u; + for (var i = ${t.length}; i >= 0; i--) { + let input_shape_i = ${rt("uniforms.input_shape","i",t.length)}; + let steps_i = ${rt("uniforms.steps","i",t.length)}; + let signs_i = ${rt("uniforms.signs","i",t.length)}; + let starts_i = ${rt("uniforms.starts","i",t.length)}; + var output_index = ${r.indicesGet("output_indices","i")}; + var input_index = output_index * steps_i + starts_i + carry; + carry = input_index / input_shape_i; + input_index = input_index % input_shape_i; + if (signs_i < 0) { + input_index = input_shape_i - input_index - 1u + starts_i; + } + ${e.indicesSet("input_indices","i","input_index")}; + } + return input_indices; + }`,_w=(e,r)=>{let t=e[0].dims,s=xe.size(t),i=r.axes.length>0?xe.normalizeAxes(r.axes,t.length):[...Array(t.length).keys()],n=sa(e,4);n.forEach(v=>v!==0||(()=>{throw new Error("step cannot be 0")})),n.length===0&&(n=Array(i.length).fill(1));let o=r.starts.map((v,y)=>Lc(v,y,t,i,n)),a=r.ends.map((v,y)=>Lc(v,y,t,i,n));if(i.length!==o.length||i.length!==a.length)throw new Error("start, ends and axes should have the same number of elements");if(i.length!==t.length)for(let v=0;vMath.sign(v));n.forEach((v,y,S)=>{if(v<0){let x=(a[y]-o[y])/v,g=o[y],M=g+x*n[y];o[y]=M,a[y]=g,S[y]=-v}});let d=t.slice(0);i.forEach((v,y)=>{d[v]=Math.ceil((a[v]-o[v])/n[v])});let p={dims:d,dataType:e[0].dataType},u=tt("output",e[0].dataType,d.length),h=$e("input",e[0].dataType,e[0].dims.length),w=xe.size(d),_=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:o.length},{name:"signs",type:"i32",length:l.length},{name:"steps",type:"u32",length:n.length}],P=[{type:12,data:w},{type:12,data:o},{type:6,data:l},{type:12,data:n},...nt(e[0].dims,d)],A=v=>` + ${v.registerUniforms(_).declareVariables(h,u)} + ${fw(h,u,t)} + ${v.mainStart()} + ${v.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} + let output_indices = ${u.offsetToIndices("global_idx")}; + let input_indices = calculateInputIndices(output_indices); + ${u.setByOffset("global_idx",h.getByIndices("input_indices"))} + }`;return{name:"Slice",shaderCache:{hint:`${l.length}_${o.length}_${n.length}`,inputDependencies:["rank"]},getShaderSource:A,getRunData:()=>({outputs:[p],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:P})}},Z0=(e,r)=>{hw(e.inputs,r);let t=mw(e.inputs,r);e.compute(_w(e.inputs,t),{inputs:[0]})},eb=e=>{let r=e.starts,t=e.ends,s=e.axes;return Lt({starts:r,ends:t,axes:s})}}),gw,ww,tb,rb,bx=je(()=>{mt(),Mt(),tr(),un(),xt(),gw=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},ww=(e,r)=>{let t=e.inputs[0],s=t.dims,i=xe.size(s),n=s.length,o=xe.normalizeAxis(r.axis,n),a=ok),d[o]=n-1,d[n-1]=o,l=e.compute(Vr(t,d),{inputs:[t],outputs:[-1]})[0]):l=t;let p=l.dims,u=p[n-1],h=i/u,w=Jt(u),_=u/w,P=64;h===1&&(P=256);let A=(E,k)=>k===4?`max(max(${E}.x, ${E}.y), max(${E}.z, ${E}.w))`:k===2?`max(${E}.x, ${E}.y)`:k===3?`max(max(${E}.x, ${E}.y), ${E}.z)`:E,v=$e("x",l.dataType,l.dims,w),y=tt("result",l.dataType,l.dims,w),S=v.type.value,x=pr(l.dataType)==="f32"?`var threadMax = ${S}(-3.402823e+38f);`:`var threadMax = ${S}(-65504.0h);`,g=E=>` + var rowMaxShared : ${S}; + var rowSumShared : ${S}; + var threadShared : array<${S}, ${P}>; + + fn getValue(row: i32, col: i32, row_stride: i32) -> ${S} { + let index = row * row_stride + col; + return x[index]; + } + + fn setValue(row: i32, col: i32, row_stride: i32, value: ${S}) { + let index = row * row_stride + col; + result[index] = value; + } + ${E.registerUniform("packedCols","i32").declareVariables(v,y)} + ${E.mainStart(P)} + let gindex = i32(global_idx); + let lindex = i32(local_idx); + const wg = ${P}; + let row = gindex / wg; + let cols = uniforms.packedCols; + let row_stride : i32 = uniforms.packedCols; + + // find the rows max + ${x} + for (var col = lindex; col < cols; col += wg) { + let value = getValue(row, col, row_stride); + threadMax = max(threadMax, value); + } + if (lindex < cols) { + threadShared[lindex] = threadMax; + } + workgroupBarrier(); + + var reduceSize = min(cols, wg); + for (var currSize = reduceSize >> 1; currSize > 0; currSize = reduceSize >> 1) { + reduceSize = currSize + (reduceSize & 1); + if (lindex < currSize) { + threadShared[lindex] = max(threadShared[lindex], threadShared[lindex + reduceSize]); + } + workgroupBarrier(); + } + if (lindex == 0) { + rowMaxShared = ${S}(${A("threadShared[0]",w)}); + } + workgroupBarrier(); + + // find the rows sum + var threadSum = ${S}(0.0); + for (var col = lindex; col < cols; col += wg) { + let subExp = exp(getValue(row, col, row_stride) - rowMaxShared); + threadSum += subExp; + } + threadShared[lindex] = threadSum; + workgroupBarrier(); + + for (var currSize = wg >> 1; currSize > 0; currSize = currSize >> 1) { + if (lindex < currSize) { + threadShared[lindex] = threadShared[lindex] + threadShared[lindex + currSize]; + } + workgroupBarrier(); + } + if (lindex == 0) { + rowSumShared = ${S}(${cn("threadShared[0]",w)}); + } + workgroupBarrier(); + + // calculate final value for each element in the row + for (var col = lindex; col < cols; col += wg) { + let value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared; + setValue(row, col, row_stride, value); + } + }`,M=e.compute({name:"Softmax",shaderCache:{hint:`${w};${P}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:p,dataType:l.dataType}],dispatchGroup:{x:h},programUniforms:[{type:6,data:_}]}),getShaderSource:g},{inputs:[l],outputs:[a?-1:0]})[0];a&&e.compute(Vr(M,d),{inputs:[M]})},tb=(e,r)=>{gw(e.inputs),ww(e,r)},rb=e=>Lt({axis:e.axis})}),zc,yw,Mw,bw,sb,vx=je(()=>{mt(),Mt(),xt(),zc=e=>Array.from(e.getBigInt64Array(),Number),yw=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(zc(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")},Mw=(e,r)=>{let t=[];for(let s=0;s{let t=e[0].dims,s=r??zc(e[1]),i=Mw(t,s),n=xe.size(i),o=e[0].dataType,a=$e("input",o,t.length),l=tt("output",o,i.length),d=p=>` + const inputShape = ${a.indices(...t)}; + ${p.registerUniform("output_size","u32").declareVariables(a,l)} + ${p.mainStart()} + ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} + let output_indices = ${l.offsetToIndices("global_idx")}; + var input_indices: ${a.type.indices}; + for (var i = 0; i < ${t.length}; i++) { + let input_dim_i = ${a.indicesGet("uniforms.input_shape","i")}; + let input_dim_value = ${l.indicesGet("output_indices","i")} % input_dim_i; + + ${a.indicesSet("input_indices","i","input_dim_value")} + } + ${l.setByOffset("global_idx",a.getByIndices("input_indices"))} + }`;return{name:"Tile",shaderCache:{hint:`${s}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(n/64)},programUniforms:[{type:12,data:n},...nt(e[0].dims,i)]}),getShaderSource:d}},sb=e=>{yw(e.inputs),e.compute(bw(e.inputs),{inputs:[0]})}}),vw,xw,nb,xx=je(()=>{mt(),Mt(),xt(),vw=(e,r,t,s,i)=>{let n=tt("output_data",i,t.length,4),o=$e("a_data",r[1].dataType,r[1].dims.length,4),a=$e("b_data",r[2].dataType,r[2].dims.length,4),l=$e("c_data",r[0].dataType,r[0].dims.length,4),d,p=(u,h,w)=>`select(${h}, ${u}, ${w})`;if(!s)d=n.setByOffset("global_idx",p(o.getByOffset("global_idx"),a.getByOffset("global_idx"),l.getByOffset("global_idx")));else{let u=(h,w,_="")=>{let P=`a_data[index_a${w}][component_a${w}]`,A=`b_data[index_b${w}][component_b${w}]`,v=`bool(c_data[index_c${w}] & (0xffu << (component_c${w} * 8)))`;return` + let output_indices${w} = ${n.offsetToIndices(`global_idx * 4u + ${w}u`)}; + let offset_a${w} = ${o.broadcastedIndicesToOffset(`output_indices${w}`,n)}; + let offset_b${w} = ${a.broadcastedIndicesToOffset(`output_indices${w}`,n)}; + let offset_c${w} = ${l.broadcastedIndicesToOffset(`output_indices${w}`,n)}; + let index_a${w} = offset_a${w} / 4u; + let index_b${w} = offset_b${w} / 4u; + let index_c${w} = offset_c${w} / 4u; + let component_a${w} = offset_a${w} % 4u; + let component_b${w} = offset_b${w} % 4u; + let component_c${w} = offset_c${w} % 4u; + ${h}[${w}] = ${_}(${p(P,A,v)}); + `};i===9?d=` + var data = vec4(0); + ${u("data",0,"u32")} + ${u("data",1,"u32")} + ${u("data",2,"u32")} + ${u("data",3,"u32")} + output_data[global_idx] = dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(data));`:d=` + ${u("output_data[global_idx]",0)} + ${u("output_data[global_idx]",1)} + ${u("output_data[global_idx]",2)} + ${u("output_data[global_idx]",3)} + `}return` + ${e.registerUniform("vec_size","u32").declareVariables(l,o,a,n)} + ${e.mainStart()} + ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} + ${d} + }`},xw=e=>{let r=e[1].dims,t=e[2].dims,s=e[0].dims,i=e[1].dataType,n=!(xe.areEqual(r,t)&&xe.areEqual(t,s)),o=r,a=xe.size(r);if(n){let d=Ei.calcShape(Ei.calcShape(r,t,!1),s,!1);if(!d)throw new Error("Can't perform where op on the given tensors");o=d,a=xe.size(o)}let l=Math.ceil(a/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:d=>vw(d,e,o,n,i),getRunData:()=>({outputs:[{dims:o,dataType:i}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:l},...nt(s,r,t,o)]})}},nb=e=>{e.compute(xw(e.inputs))}}),ib,Tx=je(()=>{zv(),Pu(),Bv(),Rv(),Nv(),jv(),Uv(),Hv(),Qv(),Xv(),Jv(),Yv(),Zv(),ex(),tx(),rx(),sx(),nx(),ix(),ox(),ax(),lx(),dx(),cx(),ux(),E0(),px(),hx(),mx(),fx(),_x(),Eu(),gx(),wx(),yx(),Mx(),bx(),S0(),vx(),un(),Cu(),xx(),ib=new Map([["Abs",[Zy]],["Acos",[eM]],["Acosh",[tM]],["Add",[DM]],["ArgMax",[Qy,Yc]],["ArgMin",[qy,Yc]],["Asin",[rM]],["Asinh",[sM]],["Atan",[nM]],["Atanh",[iM]],["Attention",[Xy]],["AveragePool",[z0,L0]],["BatchNormalization",[Jy]],["BiasAdd",[Yy]],["BiasSplitGelu",[OM]],["Cast",[aM,oM]],["Ceil",[dM]],["Clip",[lM]],["Concat",[GM,KM]],["Conv",[nu,su]],["ConvTranspose",[r0,t0]],["Cos",[cM]],["Cosh",[uM]],["CumSum",[s0,n0]],["DepthToSpace",[i0,o0]],["DequantizeLinear",[W0,G0]],["Div",[LM]],["Einsum",[a0,l0]],["Elu",[pM,la]],["Equal",[zM]],["Erf",[hM]],["Exp",[mM]],["Expand",[d0]],["FastGelu",[c0]],["Floor",[fM]],["FusedConv",[nu,su]],["Gather",[p0,u0]],["GatherElements",[w0,g0]],["GatherBlockQuantized",[f0,_0]],["GatherND",[h0,m0]],["Gelu",[_M]],["Gemm",[M0,y0]],["GlobalAveragePool",[R0,B0]],["GlobalMaxPool",[V0,U0]],["Greater",[jM]],["GreaterOrEqual",[VM]],["GridSample",[b0,v0]],["GroupQueryAttention",[$0]],["HardSigmoid",[TM,xM]],["InstanceNormalization",[k0]],["LayerNormalization",[I0]],["LeakyRelu",[gM,la]],["Less",[UM]],["LessOrEqual",[WM]],["Log",[AM]],["MatMul",[A0]],["MatMulNBits",[F0,O0]],["MaxPool",[N0,j0]],["Mul",[BM]],["MultiHeadAttention",[T0,x0]],["Neg",[yM]],["Not",[wM]],["Pad",[D0]],["Pow",[RM]],["QuickGelu",[FM,la]],["Range",[K0]],["Reciprocal",[MM]],["ReduceMin",[Vy]],["ReduceMean",[By]],["ReduceMax",[Uy]],["ReduceSum",[Gy]],["ReduceProd",[Wy]],["ReduceL1",[Ry]],["ReduceL2",[Ny]],["ReduceLogSum",[Hy]],["ReduceLogSumExp",[jy]],["ReduceSumSquare",[Ky]],["Relu",[bM]],["Resize",[Q0,X0]],["RotaryEmbedding",[J0]],["ScatterND",[q0,H0]],["Sigmoid",[vM]],["Sin",[EM]],["Sinh",[PM]],["Slice",[Z0,eb]],["SkipLayerNormalization",[Y0]],["Split",[P0,C0]],["Sqrt",[CM]],["Softmax",[tb,rb]],["Sub",[NM]],["Tan",[SM]],["Tanh",[$M]],["ThresholdedRelu",[IM,la]],["Tile",[sb]],["Transpose",[Py,Cy]],["Where",[nb]]])}),ob,Ex=je(()=>{Ms(),Vs(),xt(),ob=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,r){this.repo.set(e,r)}run(e,r,t,s,i){ys(e.programInfo.name);let n=this.backend.device,o=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let a=[];for(let d of r)a.push({binding:a.length,resource:{buffer:d.buffer}});for(let d of t)a.push({binding:a.length,resource:{buffer:d.buffer}});i&&a.push({binding:a.length,resource:i});let l=n.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:a,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let d={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:l,dispatchGroup:s};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(d)}o.setPipeline(e.computePipeline),o.setBindGroup(0,l),o.dispatchWorkgroups(...s),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),Yr(e.programInfo.name)}dispose(){}build(e,r){ys(e.name);let t=this.backend.device,s=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(d=>{t.features.has(d.feature)&&s.push(`enable ${d.extension};`)});let i=Ey(r,this.backend.device.limits),n=e.getShaderSource(i),o=`${s.join(` +`)} +${i.additionalImplementations} +${n}`,a=t.createShaderModule({code:o,label:e.name});St("verbose",()=>`[WebGPU] ${e.name} shader code: ${o}`);let l=t.createComputePipeline({compute:{module:a,entryPoint:"main"},layout:"auto",label:e.name});return Yr(e.name),{programInfo:e,computePipeline:l,uniformVariablesInfo:i.variablesInfo}}normalizeDispatchGroupSize(e){let r=typeof e=="number"?e:e.x,t=typeof e=="number"?1:e.y||1,s=typeof e=="number"?1:e.z||1,i=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(r<=i&&t<=i&&s<=i)return[r,t,s];let n=r*t*s,o=Math.ceil(Math.sqrt(n));if(o>i){if(o=Math.ceil(Math.cbrt(n)),o>i)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[o,o,o]}else return[o,o,1]}}}),Tw,Ew,Pw,ab,Px=je(()=>{Ms(),mt(),Vs(),yy(),Dv(),Tx(),Ex(),Tw=(e,r)=>{if(r.length!==e.length)throw new Error(`inputDependencies length ${r.length} is not equal to inputTensors length ${e.length}.`);let t=[];for(let s=0;s{var i,n;let s=e.name;return(i=e.shaderCache)!=null&&i.hint&&(s+="["+e.shaderCache.hint+"]"),s+=":"+t+`:${Tw(r,((n=e.shaderCache)==null?void 0:n.inputDependencies)??new Array(r.length).fill("dims"))}`,s},Pw=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},ab=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,r){this.env=e;let t=[],s={requiredLimits:{maxComputeWorkgroupStorageSize:r.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:r.limits.maxStorageBufferBindingSize,maxBufferSize:r.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:r.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:r.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:r.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:r.limits.maxComputeWorkgroupSizeZ},requiredFeatures:t},i=n=>r.features.has(n)&&t.push(n)&&!0;i("chromium-experimental-timestamp-query-inside-passes")||i("timestamp-query"),i("shader-f16"),i("subgroups"),this.device=await r.requestDevice(s),this.adapterInfo=new Pw(r.info||await r.requestAdapterInfo()),this.gpuDataManager=My(this),this.programManager=new ob(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,bu(e.logLevel,!!e.debug),this.device.onuncapturederror=n=>{n.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${n.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:r,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose()}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),r={};this.queryType==="at-passes"&&(r.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(r)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;ys(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{var s;let r=new BigUint64Array(e.getMappedRange()),t=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=w);let P=Number(w-this.queryTimeBase),A=Number(_-this.queryTimeBase);if(!Number.isSafeInteger(P)||!Number.isSafeInteger(A))throw new RangeError("incorrect timestamp range");if((s=this.env.webgpu.profiling)!=null&&s.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:u.map(v=>({dims:v.dims,dataType:kn(v.dataType)})),outputsMetadata:h.map(v=>({dims:v.dims,dataType:kn(v.dataType)})),kernelId:o,kernelType:l,kernelName:d,programName:p,startTime:P,endTime:A});else{let v="";u.forEach((S,x)=>{v+=`input[${x}]: [${S.dims}] | ${kn(S.dataType)}, `});let y="";h.forEach((S,x)=>{y+=`output[${x}]: [${S.dims}] | ${kn(S.dataType)}, `}),console.log(`[profiling] kernel "${o}|${l}|${d}|${p}" ${v}${y}execution time: ${A-P} ns`)}ma("GPU",`${p}::${w}::${_}`)}e.unmap(),this.pendingQueries.delete(e)}),Yr()}run(e,r,t,s,i,n){ys(e.name);let o=[];for(let y=0;yS):t;if(p.length!==a.length)throw new Error(`Output size ${p.length} must be equal to ${a.length}.`);let u=[],h=[];for(let y=0;y=n)throw new Error(`Invalid output index: ${p[y]}`);if(p[y]===-3)continue;let S=p[y]===-1,x=p[y]===-2,g=S||x?i(a[y].dataType,a[y].dims):s(p[y],a[y].dataType,a[y].dims);if(u.push(g),g.data===0)continue;let M=this.gpuDataManager.get(g.data);if(!M)throw new Error(`no GPU data for output: ${g.data}`);if(S&&this.temporaryData.push(M),x){let E=this.kernelPersistentData.get(this.currentKernelId);E||(E=[],this.kernelPersistentData.set(this.currentKernelId,E)),E.push(M)}h.push(M)}if(o.length!==r.length||h.length!==u.length){if(h.length===0)return Yr(e.name),u;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let w;if(d){let y=0,S=[];d.forEach(E=>{let k=typeof E.data=="number"?[E.data]:E.data;if(k.length===0)return;let B=E.type===10?2:4,R,J;E.type===10?(J=k.length>4?16:k.length>2?8:k.length*B,R=k.length>4?16:B*k.length):(J=k.length<=2?k.length*B:16,R=16),y=Math.ceil(y/J)*J,S.push(y);let q=E.type===10?8:4;y+=k.length>4?Math.ceil(k.length/q)*R:k.length*B});let x=16;y=Math.ceil(y/x)*x;let g=new ArrayBuffer(y);d.forEach((E,k)=>{let B=S[k],R=typeof E.data=="number"?[E.data]:E.data;if(E.type===6)new Int32Array(g,B,R.length).set(R);else if(E.type===12)new Uint32Array(g,B,R.length).set(R);else if(E.type===10)new Uint16Array(g,B,R.length).set(R);else if(E.type===1)new Float32Array(g,B,R.length).set(R);else throw new Error(`Unsupported uniform type: ${kn(E.type)}`)});let M=this.gpuDataManager.create(y,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(M.buffer,0,g,0,y),this.gpuDataManager.release(M.id),w={offset:0,size:y,buffer:M.buffer}}let _=this.programManager.normalizeDispatchGroupSize(l),P=_[1]===1&&_[2]===1,A=Ew(e,r,P),v=this.programManager.getArtifact(A);if(v||(v=this.programManager.build(e,_),this.programManager.setArtifact(A,v),St("info",()=>`[artifact] key: ${A}, programName: ${e.name}`)),d&&v.uniformVariablesInfo){if(d.length!==v.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${v.uniformVariablesInfo.length}, got ${d.length} in program "${v.programInfo.name}".`);for(let y=0;y`[ProgramManager] run "${e.name}" (key=${A}) with ${_[0]}x${_[1]}x${_[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let y={kernelId:this.currentKernelId,programName:v.programInfo.name,inputTensorViews:r,outputTensorViews:u};this.pendingKernels.push(y),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(y)}return this.programManager.run(v,o,h,_,w),Yr(e.name),u}upload(e,r){this.gpuDataManager.upload(e,r)}memcpy(e,r){this.gpuDataManager.memcpy(e,r)}async download(e,r){await this.gpuDataManager.download(e,r)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,r,t,s){let i=ib.get(e);if(!i)throw new Error(`kernel not implemented: ${e}`);let n={kernelType:e,kernelName:s,kernelEntry:i[0],attributes:[i[1],t]};this.kernels.set(r,n)}releaseKernel(e){let r=this.kernelPersistentData.get(e);if(r){for(let t of r)this.gpuDataManager.release(t.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,r,t){let s=this.kernels.get(e);if(!s)throw new Error(`kernel not created: ${e}`);let i=s.kernelType,n=s.kernelName,o=s.kernelEntry,a=s.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${i}] ${n}" is not allowed to be called recursively`);this.currentKernelId=e,a[0]&&(a[1]=a[0](a[1]),a[0]=void 0),St("info",()=>`[WebGPU] Start to run kernel "[${i}] ${n}"...`);let l=this.env.debug;this.temporaryData=[];try{return l&&this.device.pushErrorScope("validation"),o(r,a[1]),0}catch(d){return t.push(Promise.resolve(`[WebGPU] Kernel "[${i}] ${n}" failed. ${d}`)),1}finally{l&&t.push(this.device.popErrorScope().then(d=>d?`GPU validation error for kernel "[${i}] ${n}": ${d.message}`:null));for(let d of this.temporaryData)this.gpuDataManager.release(d.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,r,t,s){let i=this.sessionExternalDataMapping.get(e);i||(i=new Map,this.sessionExternalDataMapping.set(e,i));let n=i.get(r),o=this.gpuDataManager.registerExternalBuffer(t,s,n);return i.set(r,[o,t]),o}unregisterBuffers(e){let r=this.sessionExternalDataMapping.get(e);r&&(r.forEach(t=>this.gpuDataManager.unregisterExternalBuffer(t[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let r=this.gpuDataManager.get(e);if(!r)throw new Error(`no GPU data for buffer: ${e}`);return r.buffer}createDownloader(e,r,t){return async()=>{let s=await Qc(this,e,r);return vu(s.buffer,t)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){var e;this.queryType="none",(((e=this.env.webgpu.profiling)==null?void 0:e.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){St("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(){St("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){St("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),r=this.capturedPendingKernels.get(this.currentSessionId),t=e.length;this.pendingKernels=[];for(let s=0;s=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),Cw,Bc,Sw,Rc,Nc,jc,$w,lb,Cx=je(()=>{Vs(),Cw=1,Bc=()=>Cw++,Sw=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Rc=(e,r)=>{let t=Sw.get(e);if(!t)throw new Error("Unsupported data type.");return r.length>0?Math.ceil(r.reduce((s,i)=>s*i)*t/8):0},Nc=class{constructor(e){this.sessionId=e.sessionId,this.mlContext=e.context,this.mlTensor=e.tensor,this.dataType=e.dataType,this.tensorShape=e.shape}get tensor(){return this.mlTensor}get type(){return this.dataType}get shape(){return this.tensorShape}get byteLength(){return Rc(this.dataType,this.tensorShape)}destroy(){St("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,r,t){return this.mlContext===e&&this.dataType===r&&this.tensorShape.length===t.length&&this.tensorShape.every((s,i)=>s===t[i])}},jc=class{constructor(e,r){this.tensorManager=e,this.wrapper=r}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,r,t,s){let i=this.tensorManager.getMLContext(e);if(this.wrapper){if(this.wrapper.canReuseTensor(i,r,t))return this.wrapper.tensor;if(s){if(this.wrapper.byteLength!==Rc(r,t))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let n=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,r,t,n,!0,!0),s&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){if(this.wrapper)if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(e);return}else St("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor();this.activeUpload?this.activeUpload.set(e):this.activeUpload=new Uint8Array(e)}async download(e){if(this.activeUpload)if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(this.activeUpload):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(this.activeUpload);return}else return this.activeUpload.buffer;if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},$w=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let r=this.backend.getMLContext(e);if(!r)throw new Error("MLContext not found for session.");return r}reserveTensorId(){let e=Bc();return this.tensorTrackersById.set(e,new jc(this)),e}releaseTensorId(e){let r=this.tensorTrackersById.get(e);r&&(this.tensorTrackersById.delete(e),r.tensorWrapper&&this.releaseTensor(r.tensorWrapper))}async ensureTensor(e,r,t,s,i){St("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${r}, dataType: ${t}, shape: ${s}, copyOld: ${i}}`);let n=this.tensorTrackersById.get(r);if(!n)throw new Error("Tensor not found.");return n.ensureTensor(e,t,s,i)}upload(e,r){let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");t.upload(r)}async download(e,r){St("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${r==null?void 0:r.byteLength}}`);let t=this.tensorTrackersById.get(e);if(!t)throw new Error("Tensor not found.");return t.download(r)}releaseTensorsForSession(e){for(let r of this.freeTensors)r.sessionId===e&&r.destroy();this.freeTensors=this.freeTensors.filter(r=>r.sessionId!==e)}registerTensor(e,r,t,s){let i=this.getMLContext(e),n=Bc(),o=new Nc({sessionId:e,context:i,tensor:r,dataType:t,shape:s});return this.tensorTrackersById.set(n,new jc(this,o)),this.externalTensors.add(o),n}async getCachedTensor(e,r,t,s,i,n){let o=this.getMLContext(e);for(let[l,d]of this.freeTensors.entries())if(d.canReuseTensor(o,r,t)){St("verbose",()=>`[WebNN] Reusing tensor {dataType: ${r}, shape: ${t}}`);let p=this.freeTensors.splice(l,1)[0];return p.sessionId=e,p}St("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${r}, shape: ${t}}`);let a=await o.createTensor({dataType:r,shape:t,dimensions:t,usage:s,writable:i,readable:n});return new Nc({sessionId:e,context:o,tensor:a,dataType:r,shape:t})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},lb=(...e)=>new $w(...e)}),Xl,kw,db,Sx=je(()=>{mt(),Ln(),yy(),Cx(),Vs(),Xl=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),kw=(e,r)=>{if(e===r)return!0;if(e===void 0||r===void 0)return!1;let t=Object.keys(e).sort(),s=Object.keys(r).sort();return t.length===s.length&&t.every((i,n)=>i===s[n]&&e[i]===r[i])},db=class{constructor(e){this.tensorManager=lb(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.temporaryGraphInputs=[],this.temporarySessionTensorIds=new Map,bu(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){St("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){St("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let r=this.temporarySessionTensorIds.get(e);if(r){for(let t of r)St("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${t}}`),this.tensorManager.releaseTensorId(t);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(s=>s.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:s}),s}}else if(e===void 0){let t=this.mlContextCache.findIndex(s=>s.options===void 0&&s.gpuDevice===void 0);if(t!==-1)return this.mlContextCache[t].mlContext;{let s=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:s}),s}}let r=this.mlContextCache.findIndex(t=>kw(t.options,e));if(r!==-1)return this.mlContextCache[r].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,r){this.mlContextBySessionId.set(e,r);let t=this.sessionIdsByMLContext.get(r);t||(t=new Set,this.sessionIdsByMLContext.set(r,t)),t.add(e),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e);let r=this.mlContextBySessionId.get(e);if(!r)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e);let t=this.sessionIdsByMLContext.get(r);if(t.delete(e),t.size===0){this.sessionIdsByMLContext.delete(r);let s=this.mlContextCache.findIndex(i=>i.mlContext===r);s!==-1&&this.mlContextCache.splice(s,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){St("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,r,t,s,i){let n=Xl.get(t);if(!n)throw new Error(`Unsupported ONNX data type: ${t}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,r,n,s,i)}async createTemporaryTensor(e,r,t){St("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${r}, shape: ${t}}`);let s=Xl.get(r);if(!s)throw new Error(`Unsupported ONNX data type: ${r}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,s,t,!1);let n=this.temporarySessionTensorIds.get(e);return n?n.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,r){if(!ur().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");St("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${r.byteLength}}`),this.tensorManager.upload(e,r)}async downloadTensor(e,r){return this.tensorManager.download(e,r)}createMLTensorDownloader(e,r){return async()=>{let t=await this.tensorManager.download(e);return vu(t,r)}}registerMLTensor(e,r,t,s){let i=Xl.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let n=this.tensorManager.registerTensor(e,r,i,s);return St("verbose",()=>`[WebNN] registerMLTensor {tensor: ${r}, dataType: ${i}, dimensions: ${s}} -> {tensorId: ${n}}`),n}registerMLConstant(e,r,t,s,i,n){if(!n)throw new Error("External mounted files are not available.");let o=e;e.startsWith("./")&&(o=e.substring(2));let a=n.get(o);if(!a)throw new Error(`File with name ${o} not found in preloaded files.`);if(r+t>a.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let l=a.slice(r,r+t).buffer,d;switch(i.dataType){case"float32":d=new Float32Array(l);break;case"float16":d=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(l):new Uint16Array(l);break;case"int32":d=new Int32Array(l);break;case"uint32":d=new Uint32Array(l);break;case"int64":d=new BigInt64Array(l);break;case"uint64":d=new BigUint64Array(l);break;case"int8":d=new Int8Array(l);break;case"int4":case"uint4":case"uint8":d=new Uint8Array(l);break;default:throw new Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return St("verbose",()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}}`),s.constant(i,d)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}isGraphInput(e,r){let t=this.sessionGraphInputs.get(e);return t?t.includes(r):!1}flush(){}}}),cb={};_a(cb,{init:()=>ub});var Jl,Iw,ub,$x=je(()=>{mt(),Px(),Vs(),Mt(),Sx(),Jl=class pb{constructor(r,t,s,i){this.module=r,this.dataType=t,this.data=s,this.dims=i}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let r=xe.size(this.dims);return r===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,r)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let r=xe.size(this.dims);return r===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,r)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let r=xe.size(this.dims);return r===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,r)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let r=xe.size(this.dims);return r===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,r)}reshape(r){if(xe.size(r)!==xe.size(this.dims))throw new Error("Invalid new shape");return new pb(this.module,this.dataType,this.data,r)}},Iw=class{constructor(e,r,t){this.module=e,this.backend=r,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=r.adapterInfo;let s=e.PTR_SIZE,i=t/e.PTR_SIZE,n=s===4?"i32":"i64";this.opKernelContext=Number(e.getValue(s*i++,n));let o=Number(e.getValue(s*i++,n));this.outputCount=Number(e.getValue(s*i++,n)),this.customDataOffset=Number(e.getValue(s*i++,"*")),this.customDataSize=Number(e.getValue(s*i++,n));let a=[];for(let l=0;ltypeof a=="number"?this.inputs[a]:a))??this.inputs,s=(r==null?void 0:r.outputs)??[],i=(a,l,d)=>new Jl(this.module,l,this.output(a,d),d),n=(a,l)=>{let d=In(a,l);if(!d)throw new Error(`Unsupported data type: ${a}`);let p=d>0?this.backend.gpuDataManager.create(d).id:0;return new Jl(this.module,a,p,l)};return this.backend.run(e,t,s,i,n,this.outputCount)}output(e,r){let t=this.module.stackSave();try{let s=this.module.PTR_SIZE,i=s===4?"i32":"i64",n=this.module.stackAlloc((1+r.length)*s);this.module.setValue(n,r.length,i);for(let o=0;o{let i=r.jsepInit;if(!i)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let n=new ab;await n.initialize(t,s),i("webgpu",[n,o=>n.alloc(Number(o)),o=>n.free(o),(o,a,l,d=!1)=>{if(d)St("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(o)}, dst=${Number(a)}, size=${Number(l)}`),n.memcpy(Number(o),Number(a));else{St("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(o)}, gpuDataId=${Number(a)}, size=${Number(l)}`);let p=r.HEAPU8.subarray(Number(o>>>0),Number(o>>>0)+Number(l));n.upload(Number(a),p)}},async(o,a,l)=>{St("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${o}, dataOffset=${a}, size=${l}`),await n.download(Number(o),()=>r.HEAPU8.subarray(Number(a)>>>0,Number(a+l)>>>0))},(o,a,l)=>n.createKernel(o,Number(a),l,r.UTF8ToString(r._JsepGetNodeName(Number(a)))),o=>n.releaseKernel(o),(o,a,l,d)=>{St("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${l}, kernel=${o}, contextDataOffset=${a}`);let p=new Iw(r,n,Number(a));return n.computeKernel(Number(o),p,d)},()=>n.captureBegin(),()=>n.captureEnd(),()=>n.replay()])}else{let n=new db(t);i("webnn",[n,()=>n.reserveTensorId(),o=>n.releaseTensorId(o),async(o,a,l,d,p)=>n.ensureTensor(o,a,l,d,p),(o,a)=>{n.uploadTensor(o,a)},async(o,a)=>n.downloadTensor(o,a)])}}}),Aw,Fu,Ou,ln,Fw,cd,Du,Lu,Uc,zu,Bu,Ru,hb=je(()=>{Fv(),Ov(),mt(),Ln(),_u(),wy(),Aw=(e,r)=>{ur()._OrtInit(e,r)!==0&&Ot("Can't initialize onnxruntime.")},Fu=async e=>{Aw(e.wasm.numThreads,od(e.logLevel))},Ou=async(e,r)=>{{let t=($x(),nd(cb)).init;if(r==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");let s=e.webgpu.adapter;if(s){if(typeof s.limits!="object"||typeof s.features!="object"||typeof s.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let n=e.webgpu.forceFallbackAdapter;if(n!==void 0&&typeof n!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${n}"`);if(s=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:n}),!s)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}await t("webgpu",ur(),e,s)}if(r==="webnn"){if(typeof navigator>"u"||!navigator.ml)throw new Error("WebNN is not supported in current environment");await t("webnn",ur(),e)}}},ln=new Map,Fw=e=>{let r=ur(),t=r.stackSave();try{let s=r.PTR_SIZE,i=r.stackAlloc(2*s);r._OrtGetInputOutputCount(e,i,i+s)!==0&&Ot("Can't get session input/output count.");let n=s===4?"i32":"i64";return[Number(r.getValue(i,n)),Number(r.getValue(i+s,n))]}finally{r.stackRestore(t)}},cd=e=>{let r=ur(),t=r._malloc(e.byteLength);if(t===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return r.HEAPU8.set(e,t),[t,e.byteLength]},Du=async(e,r)=>{var u,h,w;let t,s,i=ur();Array.isArray(e)?[t,s]=e:e.buffer===i.HEAPU8.buffer?[t,s]=[e.byteOffset,e.byteLength]:[t,s]=cd(e);let n=0,o=0,a=0,l=[],d=[],p=[];try{if([o,l]=gy(r),(r==null?void 0:r.externalData)&&i.mountExternalData){let g=[];for(let M of r.externalData){let E=typeof M=="string"?M:M.path;g.push(Mu(typeof M=="string"?M:M.data).then(k=>{i.mountExternalData(E,k)}))}await Promise.all(g)}for(let g of(r==null?void 0:r.executionProviders)??[])if((typeof g=="string"?g:g.name)==="webnn"){if(i.shouldTransferToMLTensor=!1,typeof g!="string"){let M=g,E=M==null?void 0:M.context,k=M==null?void 0:M.gpuDevice,B=M==null?void 0:M.deviceType,R=M==null?void 0:M.powerPreference;E?i.currentContext=E:k?i.currentContext=await i.jsepCreateMLContext(k):i.currentContext=await i.jsepCreateMLContext({deviceType:B,powerPreference:R})}else i.currentContext=await i.jsepCreateMLContext();break}n=await i._OrtCreateSession(t,s,o),n===0&&Ot("Can't create a session."),(u=i.jsepOnCreateSession)==null||u.call(i),i.currentContext&&(i.jsepRegisterMLContext(n,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[_,P]=Fw(n),A=!!(r!=null&&r.enableGraphCapture),v=[],y=[],S=[];for(let g=0;g<_;g++){let M=i._OrtGetInputName(n,g);M===0&&Ot("Can't get an input name."),d.push(M),v.push(i.UTF8ToString(M))}for(let g=0;gg==="gpu-buffer"||g==="ml-tensor")&&(a=i._OrtCreateBinding(n),a===0&&Ot("Can't create IO binding."),x={handle:a,outputPreferredLocations:S,outputPreferredLocationsEncoded:S.map(g=>qc(g))}),ln.set(n,[n,d,p,x,A,!1]),[n,v,y]}catch(_){throw d.forEach(P=>i._OrtFree(P)),p.forEach(P=>i._OrtFree(P)),a!==0&&i._OrtReleaseBinding(a)!==0&&Ot("Can't release IO binding."),n!==0&&i._OrtReleaseSession(n)!==0&&Ot("Can't release session."),_}finally{i._free(t),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&Ot("Can't release session options."),l.forEach(_=>i._free(_)),(w=i.unmountExternalData)==null||w.call(i)}},Lu=e=>{var l;let r=ur(),t=ln.get(e);if(!t)throw new Error(`cannot release session. invalid session id: ${e}`);let[s,i,n,o,a]=t;o&&(a&&r._OrtClearBoundOutputs(o.handle)!==0&&Ot("Can't clear bound outputs."),r._OrtReleaseBinding(o.handle)!==0&&Ot("Can't release IO binding.")),(l=r.jsepOnReleaseSession)==null||l.call(r,e),i.forEach(d=>r._OrtFree(d)),n.forEach(d=>r._OrtFree(d)),r._OrtReleaseSession(s)!==0&&Ot("Can't release session."),ln.delete(e)},Uc=async(e,r,t,s,i,n=!1)=>{if(!e){r.push(0);return}let o=ur(),a=o.PTR_SIZE,l=e[0],d=e[1],p=e[3],u=p,h,w;if(l==="string"&&(p==="gpu-buffer"||p==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(n&&p!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${i} when enableGraphCapture is true.`);if(p==="gpu-buffer"){let A=e[2].gpuBuffer;w=In(bi(l),d);let v=o.jsepRegisterBuffer;if(!v)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=v(s,i,A,w)}else if(p==="ml-tensor"){let A=e[2].mlTensor;w=In(bi(l),d);let v=o.jsepRegisterMLTensor;if(!v)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=v(s,A,bi(l),d)}else{let A=e[2];if(Array.isArray(A)){w=a*A.length,h=o._malloc(w),t.push(h);for(let v=0;vo.setValue(P+y*a,v,a===4?"i32":"i64"));let A=o._OrtCreateTensor(bi(l),h,w,P,d.length,qc(u));A===0&&Ot(`Can't create tensor for input/output. session=${s}, index=${i}.`),r.push(A)}finally{o.stackRestore(_)}},zu=async(e,r,t,s,i,n)=>{var J,q,V;let o=ur(),a=o.PTR_SIZE,l=ln.get(e);if(!l)throw new Error(`cannot run inference. invalid session id: ${e}`);let d=l[0],p=l[1],u=l[2],h=l[3],w=l[4],_=l[5],P=r.length,A=s.length,v=0,y=[],S=[],x=[],g=[],M=o.stackSave(),E=o.stackAlloc(P*a),k=o.stackAlloc(P*a),B=o.stackAlloc(A*a),R=o.stackAlloc(A*a);try{[v,y]=_y(n);for(let Q=0;QMe*K,1);N=kn(ne);let He=h==null?void 0:h.outputPreferredLocations[s[Q]];if(N==="string"){if(He==="gpu-buffer"||He==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Me=[];for(let K=0;K0){let Me=o.jsepGetBuffer;if(!Me)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let K=Me(O),U=In(ne,ke);if(U===void 0||!wu(N))throw new Error(`Unsupported data type: ${N}`);ge=!0,H.push([N,fe,{gpuBuffer:K,download:o.jsepCreateDownloader(K,U,N),dispose:()=>{o._OrtReleaseTensor(ie)!==0&&Ot("Can't release tensor.")}},"gpu-buffer"])}else if(He==="ml-tensor"&&ke>0){let Me=o.jsepEnsureTensor;if(!Me)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(In(ne,ke)===void 0||!yu(N))throw new Error(`Unsupported data type: ${N}`);let K=await Me(e,O,ne,fe,!1);ge=!0,H.push([N,fe,{mlTensor:K,download:o.jsepCreateMLTensorDownloader(O,N),dispose:()=>{o.jsepReleaseTensorId(O),o._OrtReleaseTensor(ie)}},"ml-tensor"])}else{let Me=gu(N),K=new Me(ke);new Uint8Array(K.buffer,K.byteOffset,K.byteLength).set(o.HEAPU8.subarray(O,O+K.byteLength)),H.push([N,fe,K,"cpu"])}}finally{o.stackRestore(le),N==="string"&&O&&o._free(O),ge||o._OrtReleaseTensor(ie),(V=o.jsepOnRunEnd)==null||V.call(o,d)}}return h&&!w&&(o._OrtClearBoundOutputs(h.handle)!==0&&Ot("Can't clear bound outputs."),ln.set(e,[d,p,u,h,w,!1])),H}finally{o.stackRestore(M),S.forEach(Y=>o._OrtReleaseTensor(Y)),x.forEach(Y=>o._OrtReleaseTensor(Y)),g.forEach(Y=>o._free(Y)),v!==0&&o._OrtReleaseRunOptions(v),y.forEach(Y=>o._free(Y))}},Bu=e=>{let r=ur(),t=ln.get(e);if(!t)throw new Error("invalid session id");let s=t[0],i=r._OrtEndProfiling(s);i===0&&Ot("Can't get an profile file name."),r._OrtFree(i)},Ru=e=>{let r=[];for(let t of e){let s=t[2];!Array.isArray(s)&&"buffer"in s&&r.push(s.buffer)}return r}}),dn,Lr,Mi,na,ia,Yl,Vc,Zl,Pn,Cn,Ow,mb,fb,_b,gb,wb,yb,Mb,bb=je(()=>{Ms(),hb(),Ln(),mu(),dn=()=>!!Kt.wasm.proxy&&typeof document<"u",Mi=!1,na=!1,ia=!1,Zl=new Map,Pn=(e,r)=>{let t=Zl.get(e);t?t.push(r):Zl.set(e,[r])},Cn=()=>{if(Mi||!na||ia||!Lr)throw new Error("worker not ready")},Ow=e=>{switch(e.data.type){case"init-wasm":Mi=!1,e.data.err?(ia=!0,Vc[1](e.data.err)):(na=!0,Vc[0]()),Yl&&(URL.revokeObjectURL(Yl),Yl=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let r=Zl.get(e.data.type);e.data.err?r.shift()[1](e.data.err):r.shift()[0](e.data.out);break}}},mb=async()=>{if(!na){if(Mi)throw new Error("multiple calls to 'initWasm()' detected.");if(ia)throw new Error("previous call to 'initWasm()' failed.");if(Mi=!0,dn())return new Promise((e,r)=>{Lr==null||Lr.terminate(),my().then(([t,s])=>{try{Lr=s,Lr.onerror=n=>r(n),Lr.onmessage=Ow,Vc=[e,r];let i={type:"init-wasm",in:Kt};!i.in.wasm.wasmPaths&&(t||Hc)&&(i.in.wasm.wasmPaths={wasm:new URL("/assets/ort-wasm-simd-threaded.jsep-BAR87mbD.wasm",import.meta.url).href}),Lr.postMessage(i),Yl=t}catch(i){r(i)}},r)});try{await fu(Kt.wasm),await Fu(Kt),na=!0}catch(e){throw ia=!0,e}finally{Mi=!1}}},fb=async e=>{if(dn())return Cn(),new Promise((r,t)=>{Pn("init-ep",[r,t]);let s={type:"init-ep",in:{epName:e,env:Kt}};Lr.postMessage(s)});await Ou(Kt,e)},_b=async e=>dn()?(Cn(),new Promise((r,t)=>{Pn("copy-from",[r,t]);let s={type:"copy-from",in:{buffer:e}};Lr.postMessage(s,[e.buffer])})):cd(e),gb=async(e,r)=>{if(dn()){if(r!=null&&r.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Cn(),new Promise((t,s)=>{Pn("create",[t,s]);let i={type:"create",in:{model:e,options:{...r}}},n=[];e instanceof Uint8Array&&n.push(e.buffer),Lr.postMessage(i,n)})}else return Du(e,r)},wb=async e=>{if(dn())return Cn(),new Promise((r,t)=>{Pn("release",[r,t]);let s={type:"release",in:e};Lr.postMessage(s)});Lu(e)},yb=async(e,r,t,s,i,n)=>{if(dn()){if(t.some(o=>o[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(i.some(o=>o))throw new Error("pre-allocated output tensor is not supported for proxy.");return Cn(),new Promise((o,a)=>{Pn("run",[o,a]);let l=t,d={type:"run",in:{sessionId:e,inputIndices:r,inputs:l,outputIndices:s,options:n}};Lr.postMessage(d,Ru(l))})}else return zu(e,r,t,s,i,n)},Mb=async e=>{if(dn())return Cn(),new Promise((r,t)=>{Pn("end-profiling",[r,t]);let s={type:"end-profiling",in:e};Lr.postMessage(s)});Bu(e)}}),Wc,Dw,vb,kx=je(()=>{Ms(),bb(),mt(),hu(),wy(),Wc=(e,r)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${r()}`)}},Dw=e=>{switch(e[3]){case"cpu":return new gs(e[0],e[2],e[1]);case"gpu-buffer":{let r=e[0];if(!wu(r))throw new Error(`not supported data type: ${r} for deserializing GPU tensor`);let{gpuBuffer:t,download:s,dispose:i}=e[2];return gs.fromGpuBuffer(t,{dataType:r,dims:e[1],download:s,dispose:i})}case"ml-tensor":{let r=e[0];if(!yu(r))throw new Error(`not supported data type: ${r} for deserializing MLTensor tensor`);let{mlTensor:t,download:s,dispose:i}=e[2];return gs.fromMLTensor(t,{dataType:r,dims:e[1],download:s,dispose:i})}default:throw new Error(`invalid data location: ${e[3]}`)}},vb=class{async fetchModelAndCopyToWasmMemory(e){return _b(await Mu(e))}async loadModel(e,r){ys();let t;typeof e=="string"?t=await this.fetchModelAndCopyToWasmMemory(e):t=e,[this.sessionId,this.inputNames,this.outputNames]=await gb(t,r),Yr()}async dispose(){return wb(this.sessionId)}async run(e,r,t){ys();let s=[],i=[];Object.entries(e).forEach(u=>{let h=u[0],w=u[1],_=this.inputNames.indexOf(h);if(_===-1)throw new Error(`invalid input '${h}'`);s.push(w),i.push(_)});let n=[],o=[];Object.entries(r).forEach(u=>{let h=u[0],w=u[1],_=this.outputNames.indexOf(h);if(_===-1)throw new Error(`invalid output '${h}'`);n.push(w),o.push(_)});let a=s.map((u,h)=>Wc(u,()=>`input "${this.inputNames[i[h]]}"`)),l=n.map((u,h)=>u?Wc(u,()=>`output "${this.outputNames[o[h]]}"`):null),d=await yb(this.sessionId,i,a,o,l,t),p={};for(let u=0;uau,initializeFlags:()=>ou,wasmBackend:()=>Tb});var ou,au,Tb,Ix=je(()=>{Ms(),bb(),kx(),ou=()=>{if((typeof Kt.wasm.initTimeout!="number"||Kt.wasm.initTimeout<0)&&(Kt.wasm.initTimeout=0),Kt.wasm.simd===!1&&console.warn('Deprecated property "env.wasm.simd" is set to false. non-SIMD build is no longer provided, and this setting will be ignored.'),typeof Kt.wasm.proxy!="boolean"&&(Kt.wasm.proxy=!1),typeof Kt.wasm.trace!="boolean"&&(Kt.wasm.trace=!1),typeof Kt.wasm.numThreads!="number"||!Number.isInteger(Kt.wasm.numThreads)||Kt.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Kt.wasm.numThreads=1;else{let e=typeof navigator>"u"?_v("node:os").cpus().length:navigator.hardwareConcurrency;Kt.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},au=class{async init(e){ou(),await mb(),await fb(e)}async createInferenceSessionHandler(e,r){let t=new vb;return await t.loadModel(e,r),Promise.resolve(t)}},Tb=new au});Ms();Ms();Ms();var Ax="1.22.0-dev.20250306-ccf8fdd9ea",Fx=ly;{let e=(Ix(),nd(xb)).wasmBackend;An("webgpu",e,5),An("webnn",e,5),An("cpu",e,10),An("wasm",e,10)}Object.defineProperty(Kt.versions,"web",{value:Ax,enumerable:!0});/** +* @license +* Copyright 2021 Google LLC. All Rights Reserved. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============================================================================= +*//** + * @license + * Copyright 2020 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + *//** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */var Ox=Object.freeze({__proto__:null,get InferenceSession(){return pu},get TRACE(){return ma},get TRACE_FUNC_BEGIN(){return ys},get TRACE_FUNC_END(){return Yr},get Tensor(){return gs},default:Fx,get env(){return Kt},get registerBackend(){return An}}),Ns={},Dx={"onnxruntime-common":e=>{e.exports=pv},"onnxruntime-web":e=>{e.exports=Ox},"?2ce3":()=>{},"?7a2c":()=>{},"?a42a":()=>{},"?2b25":()=>{},"?569f":()=>{},"?3f59":()=>{},"?154a":()=>{},"./node_modules/@huggingface/jinja/dist/index.js":(e,r,t)=>{t.r(r),t.d(r,{Environment:()=>Fe,Interpreter:()=>Ie,Template:()=>Ve,parse:()=>N,tokenize:()=>u});var s=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",BooleanLiteral:"BooleanLiteral",NullLiteral:"NullLiteral",StringLiteral:"StringLiteral",Identifier:"Identifier",Equals:"Equals",OpenParen:"OpenParen",CloseParen:"CloseParen",OpenStatement:"OpenStatement",CloseStatement:"CloseStatement",OpenExpression:"OpenExpression",CloseExpression:"CloseExpression",OpenSquareBracket:"OpenSquareBracket",CloseSquareBracket:"CloseSquareBracket",OpenCurlyBracket:"OpenCurlyBracket",CloseCurlyBracket:"CloseCurlyBracket",Comma:"Comma",Dot:"Dot",Colon:"Colon",Pipe:"Pipe",CallOperator:"CallOperator",AdditiveBinaryOperator:"AdditiveBinaryOperator",MultiplicativeBinaryOperator:"MultiplicativeBinaryOperator",ComparisonBinaryOperator:"ComparisonBinaryOperator",UnaryOperator:"UnaryOperator",Set:"Set",If:"If",For:"For",In:"In",Is:"Is",NotIn:"NotIn",Else:"Else",EndIf:"EndIf",ElseIf:"ElseIf",EndFor:"EndFor",And:"And",Or:"Or",Not:"UnaryOperator",Macro:"Macro",EndMacro:"EndMacro"}),i=Object.freeze({set:s.Set,for:s.For,in:s.In,is:s.Is,if:s.If,else:s.Else,endif:s.EndIf,elif:s.ElseIf,endfor:s.EndFor,and:s.And,or:s.Or,not:s.Not,"not in":s.NotIn,macro:s.Macro,endmacro:s.EndMacro,true:s.BooleanLiteral,false:s.BooleanLiteral,none:s.NullLiteral,True:s.BooleanLiteral,False:s.BooleanLiteral,None:s.NullLiteral}),n=class{constructor(D,Z){this.value=D,this.type=Z}};function o(D){return/\w/.test(D)}function a(D){return/[0-9]/.test(D)}var l=[["{%",s.OpenStatement],["%}",s.CloseStatement],["{{",s.OpenExpression],["}}",s.CloseExpression],["(",s.OpenParen],[")",s.CloseParen],["{",s.OpenCurlyBracket],["}",s.CloseCurlyBracket],["[",s.OpenSquareBracket],["]",s.CloseSquareBracket],[",",s.Comma],[".",s.Dot],[":",s.Colon],["|",s.Pipe],["<=",s.ComparisonBinaryOperator],[">=",s.ComparisonBinaryOperator],["==",s.ComparisonBinaryOperator],["!=",s.ComparisonBinaryOperator],["<",s.ComparisonBinaryOperator],[">",s.ComparisonBinaryOperator],["+",s.AdditiveBinaryOperator],["-",s.AdditiveBinaryOperator],["*",s.MultiplicativeBinaryOperator],["/",s.MultiplicativeBinaryOperator],["%",s.MultiplicativeBinaryOperator],["=",s.Equals]],d=new Map([["n",` +`],["t"," "],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function p(D,Z={}){return D.endsWith(` +`)&&(D=D.slice(0,-1)),D=D.replace(/{#.*?#}/gs,"{##}"),Z.lstrip_blocks&&(D=D.replace(/^[ \t]*({[#%])/gm,"$1")),Z.trim_blocks&&(D=D.replace(/([#%]})\n/g,"$1")),D.replace(/{##}/g,"").replace(/-%}\s*/g,"%}").replace(/\s*{%-/g,"{%").replace(/-}}\s*/g,"}}").replace(/\s*{{-/g,"{{")}function u(D,Z={}){var ve,Re,Ae;const z=[],ee=p(D,Z);let ce=0;const be=Ue=>{let Qe="";for(;Ue(ee[ce]);){if(ee[ce]==="\\"){if(++ce,ce>=ee.length)throw new SyntaxError("Unexpected end of input");const Xe=ee[ce++],ct=d.get(Xe);if(ct===void 0)throw new SyntaxError(`Unexpected escaped character: ${Xe}`);Qe+=ct;continue}if(Qe+=ee[ce++],ce>=ee.length)throw new SyntaxError("Unexpected end of input")}return Qe};e:for(;ce0){z.push(new n(Xe,s.Text));continue}}be(Xe=>/\s/.test(Xe));const Qe=ee[ce];if(Qe==="-"||Qe==="+"){const Xe=(Re=z.at(-1))==null?void 0:Re.type;if(Xe===s.Text||Xe===void 0)throw new SyntaxError(`Unexpected character: ${Qe}`);switch(Xe){case s.Identifier:case s.NumericLiteral:case s.BooleanLiteral:case s.NullLiteral:case s.StringLiteral:case s.CloseParen:case s.CloseSquareBracket:break;default:{++ce;const ct=be(a);z.push(new n(`${Qe}${ct}`,ct.length>0?s.NumericLiteral:s.UnaryOperator));continue}}}for(const[Xe,ct]of l)if(ee.slice(ce,ce+Xe.length)===Xe){z.push(new n(Xe,ct)),ce+=Xe.length;continue e}if(Qe==="'"||Qe==='"'){++ce;const Xe=be(ct=>ct!==Qe);z.push(new n(Xe,s.StringLiteral)),++ce;continue}if(a(Qe)){const Xe=be(a);z.push(new n(Xe,s.NumericLiteral));continue}if(o(Qe)){const Xe=be(o),ct=Object.hasOwn(i,Xe)?i[Xe]:s.Identifier;ct===s.In&&((Ae=z.at(-1))==null?void 0:Ae.type)===s.Not?(z.pop(),z.push(new n("not in",s.NotIn))):z.push(new n(Xe,ct));continue}throw new SyntaxError(`Unexpected character: ${Qe}`)}return z}var h=class{constructor(){re(this,"type","Statement")}},w=class extends h{constructor(Z){super();re(this,"type","Program");this.body=Z}},_=class extends h{constructor(Z,z,ee){super();re(this,"type","If");this.test=Z,this.body=z,this.alternate=ee}},P=class extends h{constructor(Z,z,ee,ce){super();re(this,"type","For");this.loopvar=Z,this.iterable=z,this.body=ee,this.defaultBlock=ce}},A=class extends h{constructor(Z,z){super();re(this,"type","Set");this.assignee=Z,this.value=z}},v=class extends h{constructor(Z,z,ee){super();re(this,"type","Macro");this.name=Z,this.args=z,this.body=ee}},y=class extends h{constructor(){super(...arguments);re(this,"type","Expression")}},S=class extends y{constructor(Z,z,ee){super();re(this,"type","MemberExpression");this.object=Z,this.property=z,this.computed=ee}},x=class extends y{constructor(Z,z){super();re(this,"type","CallExpression");this.callee=Z,this.args=z}},g=class extends y{constructor(Z){super();re(this,"type","Identifier");this.value=Z}},M=class extends y{constructor(Z){super();re(this,"type","Literal");this.value=Z}},E=class extends M{constructor(){super(...arguments);re(this,"type","NumericLiteral")}},k=class extends M{constructor(){super(...arguments);re(this,"type","StringLiteral")}},B=class extends M{constructor(){super(...arguments);re(this,"type","BooleanLiteral")}},R=class extends M{constructor(){super(...arguments);re(this,"type","NullLiteral")}},J=class extends M{constructor(){super(...arguments);re(this,"type","ArrayLiteral")}},q=class extends M{constructor(){super(...arguments);re(this,"type","TupleLiteral")}},V=class extends M{constructor(){super(...arguments);re(this,"type","ObjectLiteral")}},Y=class extends y{constructor(Z,z,ee){super();re(this,"type","BinaryExpression");this.operator=Z,this.left=z,this.right=ee}},H=class extends y{constructor(Z,z){super();re(this,"type","FilterExpression");this.operand=Z,this.filter=z}},Q=class extends y{constructor(Z,z){super();re(this,"type","SelectExpression");this.iterable=Z,this.test=z}},ie=class extends y{constructor(Z,z,ee){super();re(this,"type","TestExpression");this.operand=Z,this.negate=z,this.test=ee}},le=class extends y{constructor(Z,z){super();re(this,"type","UnaryExpression");this.operator=Z,this.argument=z}},ae=class extends y{constructor(Z=void 0,z=void 0,ee=void 0){super();re(this,"type","SliceExpression");this.start=Z,this.stop=z,this.step=ee}},ge=class extends y{constructor(Z,z){super();re(this,"type","KeywordArgumentExpression");this.key=Z,this.value=z}};function N(D){const Z=new w([]);let z=0;function ee(Be,et){const it=D[z++];if(!it||it.type!==Be)throw new Error(`Parser Error: ${et}. ${it.type} !== ${Be}.`);return it}function ce(){switch(D[z].type){case s.Text:return Re();case s.OpenStatement:return Ae();case s.OpenExpression:return Ue();default:throw new SyntaxError(`Unexpected token type: ${D[z].type}`)}}function be(...Be){return z+Be.length<=D.length&&Be.some((et,it)=>et!==D[z+it].type)}function ve(...Be){return z+Be.length<=D.length&&Be.every((et,it)=>et===D[z+it].type)}function Re(){return new k(ee(s.Text,"Expected text token").value)}function Ae(){ee(s.OpenStatement,"Expected opening statement token");let Be;switch(D[z].type){case s.Set:++z,Be=Qe(),ee(s.CloseStatement,"Expected closing statement token");break;case s.If:++z,Be=Xe(),ee(s.OpenStatement,"Expected {% token"),ee(s.EndIf,"Expected endif token"),ee(s.CloseStatement,"Expected %} token");break;case s.Macro:++z,Be=ct(),ee(s.OpenStatement,"Expected {% token"),ee(s.EndMacro,"Expected endmacro token"),ee(s.CloseStatement,"Expected %} token");break;case s.For:++z,Be=nr(),ee(s.OpenStatement,"Expected {% token"),ee(s.EndFor,"Expected endfor token"),ee(s.CloseStatement,"Expected %} token");break;default:throw new SyntaxError(`Unknown statement type: ${D[z].type}`)}return Be}function Ue(){ee(s.OpenExpression,"Expected opening expression token");const Be=jt();return ee(s.CloseExpression,"Expected closing expression token"),Be}function Qe(){const Be=jt();if(ve(s.Equals)){++z;const et=Qe();return new A(Be,et)}return Be}function Xe(){var rr,zt,Sr,rs,ss,Tr,ns,is;const Be=jt();ee(s.CloseStatement,"Expected closing statement token");const et=[],it=[];for(;!(((rr=D[z])==null?void 0:rr.type)===s.OpenStatement&&(((zt=D[z+1])==null?void 0:zt.type)===s.ElseIf||((Sr=D[z+1])==null?void 0:Sr.type)===s.Else||((rs=D[z+1])==null?void 0:rs.type)===s.EndIf));)et.push(ce());if(((ss=D[z])==null?void 0:ss.type)===s.OpenStatement&&((Tr=D[z+1])==null?void 0:Tr.type)!==s.EndIf)if(++z,ve(s.ElseIf))ee(s.ElseIf,"Expected elseif token"),it.push(Xe());else for(ee(s.Else,"Expected else token"),ee(s.CloseStatement,"Expected closing statement token");!(((ns=D[z])==null?void 0:ns.type)===s.OpenStatement&&((is=D[z+1])==null?void 0:is.type)===s.EndIf);)it.push(ce());return new _(Be,et,it)}function ct(){const Be=hr();if(Be.type!=="Identifier")throw new SyntaxError("Expected identifier following macro statement");const et=Wr();ee(s.CloseStatement,"Expected closing statement token");const it=[];for(;be(s.OpenStatement,s.EndMacro);)it.push(ce());return new v(Be,et,it)}function vt(Be=!1){const et=Be?hr:jt,it=[et()],rr=ve(s.Comma);for(;rr&&(++z,it.push(et()),!!ve(s.Comma)););return rr?new q(it):it[0]}function nr(){const Be=vt(!0);if(!(Be instanceof g||Be instanceof q))throw new SyntaxError(`Expected identifier/tuple for the loop variable, got ${Be.type} instead`);ee(s.In,"Expected `in` keyword following loop variable");const et=jt();ee(s.CloseStatement,"Expected closing statement token");const it=[];for(;be(s.OpenStatement,s.EndFor)&&be(s.OpenStatement,s.Else);)it.push(ce());const rr=[];if(ve(s.OpenStatement,s.Else))for(++z,++z,ee(s.CloseStatement,"Expected closing statement token");be(s.OpenStatement,s.EndFor);)rr.push(ce());return new P(Be,et,it,rr)}function jt(){return ar()}function ar(){const Be=Zr();if(ve(s.If)){++z;const et=Zr();if(ve(s.Else)){++z;const it=Zr();return new _(et,[Be],[it])}else return new Q(Be,et)}return Be}function Zr(){let Be=$s();for(;ve(s.Or);){const et=D[z];++z;const it=$s();Be=new Y(et,Be,it)}return Be}function $s(){let Be=Fr();for(;ve(s.And);){const et=D[z];++z;const it=Fr();Be=new Y(et,Be,it)}return Be}function Fr(){let Be;for(;ve(s.Not);){const et=D[z];++z;const it=Fr();Be=new le(et,it)}return Be??es()}function es(){let Be=ks();for(;ve(s.ComparisonBinaryOperator)||ve(s.In)||ve(s.NotIn);){const et=D[z];++z;const it=ks();Be=new Y(et,Be,it)}return Be}function ks(){let Be=vs();for(;ve(s.AdditiveBinaryOperator);){const et=D[z];++z;const it=vs();Be=new Y(et,Be,it)}return Be}function zr(){const Be=bs(hr());return ve(s.OpenParen)?dt(Be):Be}function dt(Be){let et=new x(Be,Wr());return et=bs(et),ve(s.OpenParen)&&(et=dt(et)),et}function Wr(){ee(s.OpenParen,"Expected opening parenthesis for arguments list");const Be=Br();return ee(s.CloseParen,"Expected closing parenthesis for arguments list"),Be}function Br(){const Be=[];for(;!ve(s.CloseParen);){let et=jt();if(ve(s.Equals)){if(++z,!(et instanceof g))throw new SyntaxError("Expected identifier for keyword argument");const it=jt();et=new ge(et,it)}Be.push(et),ve(s.Comma)&&++z}return Be}function ts(){const Be=[];let et=!1;for(;!ve(s.CloseSquareBracket);)ve(s.Colon)?(Be.push(void 0),++z,et=!0):(Be.push(jt()),ve(s.Colon)&&(++z,et=!0));if(Be.length===0)throw new SyntaxError("Expected at least one argument for member/slice expression");if(et){if(Be.length>3)throw new SyntaxError("Expected 0-3 arguments for slice expression");return new ae(...Be)}return Be[0]}function bs(Be){for(;ve(s.Dot)||ve(s.OpenSquareBracket);){const et=D[z];++z;let it;const rr=et.type!==s.Dot;if(rr)it=ts(),ee(s.CloseSquareBracket,"Expected closing square bracket");else if(it=hr(),it.type!=="Identifier")throw new SyntaxError("Expected identifier following dot operator");Be=new S(Be,it,rr)}return Be}function vs(){let Be=xs();for(;ve(s.MultiplicativeBinaryOperator);){const et=D[z];++z;const it=xs();Be=new Y(et,Be,it)}return Be}function xs(){let Be=Is();for(;ve(s.Is);){++z;const et=ve(s.Not);et&&++z;let it=hr();if(it instanceof B?it=new g(it.value.toString()):it instanceof R&&(it=new g("none")),!(it instanceof g))throw new SyntaxError("Expected identifier for the test");Be=new ie(Be,et,it)}return Be}function Is(){let Be=zr();for(;ve(s.Pipe);){++z;let et=hr();if(!(et instanceof g))throw new SyntaxError("Expected identifier for the filter");ve(s.OpenParen)&&(et=dt(et)),Be=new H(Be,et)}return Be}function hr(){const Be=D[z];switch(Be.type){case s.NumericLiteral:return++z,new E(Number(Be.value));case s.StringLiteral:return++z,new k(Be.value);case s.BooleanLiteral:return++z,new B(Be.value.toLowerCase()==="true");case s.NullLiteral:return++z,new R(null);case s.Identifier:return++z,new g(Be.value);case s.OpenParen:{++z;const et=vt();if(D[z].type!==s.CloseParen)throw new SyntaxError(`Expected closing parenthesis, got ${D[z].type} instead`);return++z,et}case s.OpenSquareBracket:{++z;const et=[];for(;!ve(s.CloseSquareBracket);)et.push(jt()),ve(s.Comma)&&++z;return++z,new J(et)}case s.OpenCurlyBracket:{++z;const et=new Map;for(;!ve(s.CloseCurlyBracket);){const it=jt();ee(s.Colon,"Expected colon between key and value in object literal");const rr=jt();et.set(it,rr),ve(s.Comma)&&++z}return++z,new V(et)}default:throw new SyntaxError(`Unexpected token: ${Be.type}`)}}for(;z=0?(Z=(Z??(Z=0))<0?Math.max(D.length+Z,0):Math.min(Z,D.length),z=(z??(z=D.length))<0?Math.max(D.length+z,0):Math.min(z,D.length)):(Z=(Z??(Z=D.length-1))<0?Math.max(D.length+Z,-1):Math.min(Z,D.length-1),z=(z??(z=-1))<-1?Math.max(D.length+z,-1):Math.min(z,D.length-1));const be=[];for(let ve=Z;ce*veZ.toUpperCase())}var X=class{constructor(D=void 0){re(this,"type","RuntimeValue");re(this,"value");re(this,"builtins",new Map);this.value=D}__bool__(){return new ke(!!this.value)}},we=class extends X{constructor(){super(...arguments);re(this,"type","NumericValue")}},fe=class extends X{constructor(){super(...arguments);re(this,"type","StringValue");re(this,"builtins",new Map([["upper",new pe(()=>new fe(this.value.toUpperCase()))],["lower",new pe(()=>new fe(this.value.toLowerCase()))],["strip",new pe(()=>new fe(this.value.trim()))],["title",new pe(()=>new fe(ne(this.value)))],["length",new we(this.value.length)],["rstrip",new pe(()=>new fe(this.value.trimEnd()))],["lstrip",new pe(()=>new fe(this.value.trimStart()))],["split",new pe(Z=>{const z=Z[0]??new Pe;if(!(z instanceof fe||z instanceof Pe))throw new Error("sep argument must be a string or null");const ee=Z[1]??new we(-1);if(!(ee instanceof we))throw new Error("maxsplit argument must be a number");let ce=[];if(z instanceof Pe){const be=this.value.trimStart();for(const{0:ve,index:Re}of be.matchAll(/\S+/g)){if(ee.value!==-1&&ce.length>=ee.value&&Re!==void 0){ce.push(ve+be.slice(Re+ve.length));break}ce.push(ve)}}else{if(z.value==="")throw new Error("empty separator");ce=this.value.split(z.value),ee.value!==-1&&ce.length>ee.value&&ce.push(ce.splice(ee.value).join(z.value))}return new K(ce.map(be=>new fe(be)))})]]))}},ke=class extends X{constructor(){super(...arguments);re(this,"type","BooleanValue")}},He=class extends X{constructor(){super(...arguments);re(this,"type","ObjectValue");re(this,"builtins",new Map([["get",new pe(([Z,z])=>{if(!(Z instanceof fe))throw new Error(`Object key must be a string: got ${Z.type}`);return this.value.get(Z.value)??z??new Pe})],["items",new pe(()=>new K(Array.from(this.value.entries()).map(([Z,z])=>new K([new fe(Z),z]))))]]))}__bool__(){return new ke(this.value.size>0)}},Me=class extends He{constructor(){super(...arguments);re(this,"type","KeywordArgumentsValue")}},K=class extends X{constructor(){super(...arguments);re(this,"type","ArrayValue");re(this,"builtins",new Map([["length",new we(this.value.length)]]))}__bool__(){return new ke(this.value.length>0)}},U=class extends K{constructor(){super(...arguments);re(this,"type","TupleValue")}},pe=class extends X{constructor(){super(...arguments);re(this,"type","FunctionValue")}},Pe=class extends X{constructor(){super(...arguments);re(this,"type","NullValue")}},Ee=class extends X{constructor(){super(...arguments);re(this,"type","UndefinedValue")}},Fe=class{constructor(D){re(this,"variables",new Map([["namespace",new pe(D=>{if(D.length===0)return new He(new Map);if(D.length!==1||!(D[0]instanceof He))throw new Error("`namespace` expects either zero arguments or a single object argument");return D[0]})]]));re(this,"tests",new Map([["boolean",D=>D.type==="BooleanValue"],["callable",D=>D instanceof pe],["odd",D=>{if(D.type!=="NumericValue")throw new Error(`Cannot apply test "odd" to type: ${D.type}`);return D.value%2!==0}],["even",D=>{if(D.type!=="NumericValue")throw new Error(`Cannot apply test "even" to type: ${D.type}`);return D.value%2===0}],["false",D=>D.type==="BooleanValue"&&!D.value],["true",D=>D.type==="BooleanValue"&&D.value],["none",D=>D.type==="NullValue"],["string",D=>D.type==="StringValue"],["number",D=>D.type==="NumericValue"],["integer",D=>D.type==="NumericValue"&&Number.isInteger(D.value)],["iterable",D=>D.type==="ArrayValue"||D.type==="StringValue"],["mapping",D=>D.type==="ObjectValue"],["lower",D=>{const Z=D.value;return D.type==="StringValue"&&Z===Z.toLowerCase()}],["upper",D=>{const Z=D.value;return D.type==="StringValue"&&Z===Z.toUpperCase()}],["none",D=>D.type==="NullValue"],["defined",D=>D.type!=="UndefinedValue"],["undefined",D=>D.type==="UndefinedValue"],["equalto",(D,Z)=>D.value===Z.value],["eq",(D,Z)=>D.value===Z.value]]));this.parent=D}set(D,Z){return this.declareVariable(D,Le(Z))}declareVariable(D,Z){if(this.variables.has(D))throw new SyntaxError(`Variable already declared: ${D}`);return this.variables.set(D,Z),Z}setVariable(D,Z){return this.variables.set(D,Z),Z}resolve(D){if(this.variables.has(D))return this;if(this.parent)return this.parent.resolve(D);throw new Error(`Unknown variable: ${D}`)}lookupVariable(D){try{return this.resolve(D).variables.get(D)??new Ee}catch{return new Ee}}},Ie=class{constructor(D){re(this,"global");this.global=D??new Fe}run(D){return this.evaluate(D,this.global)}evaluateBinaryExpression(D,Z){const z=this.evaluate(D.left,Z);switch(D.operator.value){case"and":return z.__bool__().value?this.evaluate(D.right,Z):z;case"or":return z.__bool__().value?z:this.evaluate(D.right,Z)}const ee=this.evaluate(D.right,Z);switch(D.operator.value){case"==":return new ke(z.value==ee.value);case"!=":return new ke(z.value!=ee.value)}if(z instanceof Ee||ee instanceof Ee)throw new Error("Cannot perform operation on undefined values");if(z instanceof Pe||ee instanceof Pe)throw new Error("Cannot perform operation on null values");if(z instanceof we&&ee instanceof we)switch(D.operator.value){case"+":return new we(z.value+ee.value);case"-":return new we(z.value-ee.value);case"*":return new we(z.value*ee.value);case"/":return new we(z.value/ee.value);case"%":return new we(z.value%ee.value);case"<":return new ke(z.value":return new ke(z.value>ee.value);case">=":return new ke(z.value>=ee.value);case"<=":return new ke(z.value<=ee.value)}else if(z instanceof K&&ee instanceof K)switch(D.operator.value){case"+":return new K(z.value.concat(ee.value))}else if(ee instanceof K){const ce=ee.value.find(be=>be.value===z.value)!==void 0;switch(D.operator.value){case"in":return new ke(ce);case"not in":return new ke(!ce)}}if(z instanceof fe||ee instanceof fe)switch(D.operator.value){case"+":return new fe(z.value.toString()+ee.value.toString())}if(z instanceof fe&&ee instanceof fe)switch(D.operator.value){case"in":return new ke(ee.value.includes(z.value));case"not in":return new ke(!ee.value.includes(z.value))}if(z instanceof fe&&ee instanceof He)switch(D.operator.value){case"in":return new ke(ee.value.has(z.value));case"not in":return new ke(!ee.value.has(z.value))}throw new SyntaxError(`Unknown operator "${D.operator.value}" between ${z.type} and ${ee.type}`)}evaluateArguments(D,Z){const z=[],ee=new Map;for(const ce of D)if(ce.type==="KeywordArgumentExpression"){const be=ce;ee.set(be.key.value,this.evaluate(be.value,Z))}else{if(ee.size>0)throw new Error("Positional arguments must come before keyword arguments");z.push(this.evaluate(ce,Z))}return[z,ee]}evaluateFilterExpression(D,Z){const z=this.evaluate(D.operand,Z);if(D.filter.type==="Identifier"){const ee=D.filter;if(ee.value==="tojson")return new fe(Ne(z));if(z instanceof K)switch(ee.value){case"list":return z;case"first":return z.value[0];case"last":return z.value[z.value.length-1];case"length":return new we(z.value.length);case"reverse":return new K(z.value.reverse());case"sort":return new K(z.value.sort((ce,be)=>{if(ce.type!==be.type)throw new Error(`Cannot compare different types: ${ce.type} and ${be.type}`);switch(ce.type){case"NumericValue":return ce.value-be.value;case"StringValue":return ce.value.localeCompare(be.value);default:throw new Error(`Cannot compare type: ${ce.type}`)}}));case"join":return new fe(z.value.map(ce=>ce.value).join(""));default:throw new Error(`Unknown ArrayValue filter: ${ee.value}`)}else if(z instanceof fe)switch(ee.value){case"length":return new we(z.value.length);case"upper":return new fe(z.value.toUpperCase());case"lower":return new fe(z.value.toLowerCase());case"title":return new fe(ne(z.value));case"capitalize":return new fe(z.value.charAt(0).toUpperCase()+z.value.slice(1));case"trim":return new fe(z.value.trim());case"indent":return new fe(z.value.split(` +`).map((ce,be)=>be===0||ce.length===0?ce:" "+ce).join(` +`));case"join":case"string":return z;default:throw new Error(`Unknown StringValue filter: ${ee.value}`)}else if(z instanceof we)switch(ee.value){case"abs":return new we(Math.abs(z.value));default:throw new Error(`Unknown NumericValue filter: ${ee.value}`)}else if(z instanceof He)switch(ee.value){case"items":return new K(Array.from(z.value.entries()).map(([ce,be])=>new K([new fe(ce),be])));case"length":return new we(z.value.size);default:throw new Error(`Unknown ObjectValue filter: ${ee.value}`)}throw new Error(`Cannot apply filter "${ee.value}" to type: ${z.type}`)}else if(D.filter.type==="CallExpression"){const ee=D.filter;if(ee.callee.type!=="Identifier")throw new Error(`Unknown filter: ${ee.callee.type}`);const ce=ee.callee.value;if(ce==="tojson"){const[,be]=this.evaluateArguments(ee.args,Z),ve=be.get("indent")??new Pe;if(!(ve instanceof we||ve instanceof Pe))throw new Error("If set, indent must be a number");return new fe(Ne(z,ve.value))}else if(ce==="join"){let be;if(z instanceof fe)be=Array.from(z.value);else if(z instanceof K)be=z.value.map(Ue=>Ue.value);else throw new Error(`Cannot apply filter "${ce}" to type: ${z.type}`);const[ve,Re]=this.evaluateArguments(ee.args,Z),Ae=ve.at(0)??Re.get("separator")??new fe("");if(!(Ae instanceof fe))throw new Error("separator must be a string");return new fe(be.join(Ae.value))}if(z instanceof K){switch(ce){case"selectattr":case"rejectattr":{const be=ce==="selectattr";if(z.value.some(Xe=>!(Xe instanceof He)))throw new Error(`\`${ce}\` can only be applied to array of objects`);if(ee.args.some(Xe=>Xe.type!=="StringLiteral"))throw new Error(`arguments of \`${ce}\` must be strings`);const[ve,Re,Ae]=ee.args.map(Xe=>this.evaluate(Xe,Z));let Ue;if(Re){const Xe=Z.tests.get(Re.value);if(!Xe)throw new Error(`Unknown test: ${Re.value}`);Ue=Xe}else Ue=(...Xe)=>Xe[0].__bool__().value;const Qe=z.value.filter(Xe=>{const ct=Xe.value.get(ve.value),vt=ct?Ue(ct,Ae):!1;return be?vt:!vt});return new K(Qe)}case"map":{const[,be]=this.evaluateArguments(ee.args,Z);if(be.has("attribute")){const ve=be.get("attribute");if(!(ve instanceof fe))throw new Error("attribute must be a string");const Re=be.get("default"),Ae=z.value.map(Ue=>{if(!(Ue instanceof He))throw new Error("items in map must be an object");return Ue.value.get(ve.value)??Re??new Ee});return new K(Ae)}else throw new Error("`map` expressions without `attribute` set are not currently supported.")}}throw new Error(`Unknown ArrayValue filter: ${ce}`)}else if(z instanceof fe){switch(ce){case"indent":{const[be,ve]=this.evaluateArguments(ee.args,Z),Re=be.at(0)??ve.get("width")??new we(4);if(!(Re instanceof we))throw new Error("width must be a number");const Ae=be.at(1)??ve.get("first")??new ke(!1),Ue=be.at(2)??ve.get("blank")??new ke(!1),Qe=z.value.split(` +`),Xe=" ".repeat(Re.value),ct=Qe.map((vt,nr)=>!Ae.value&&nr===0||!Ue.value&&vt.length===0?vt:Xe+vt);return new fe(ct.join(` +`))}}throw new Error(`Unknown StringValue filter: ${ce}`)}else throw new Error(`Cannot apply filter "${ce}" to type: ${z.type}`)}throw new Error(`Unknown filter: ${D.filter.type}`)}evaluateTestExpression(D,Z){const z=this.evaluate(D.operand,Z),ee=Z.tests.get(D.test.value);if(!ee)throw new Error(`Unknown test: ${D.test.value}`);const ce=ee(z);return new ke(D.negate?!ce:ce)}evaluateUnaryExpression(D,Z){const z=this.evaluate(D.argument,Z);switch(D.operator.value){case"not":return new ke(!z.value);default:throw new SyntaxError(`Unknown operator: ${D.operator.value}`)}}evalProgram(D,Z){return this.evaluateBlock(D.body,Z)}evaluateBlock(D,Z){let z="";for(const ee of D){const ce=this.evaluate(ee,Z);ce.type!=="NullValue"&&ce.type!=="UndefinedValue"&&(z+=ce.value)}return new fe(z)}evaluateIdentifier(D,Z){return Z.lookupVariable(D.value)}evaluateCallExpression(D,Z){const[z,ee]=this.evaluateArguments(D.args,Z);ee.size>0&&z.push(new Me(ee));const ce=this.evaluate(D.callee,Z);if(ce.type!=="FunctionValue")throw new Error(`Cannot call something that is not a function: got ${ce.type}`);return ce.value(z,Z)}evaluateSliceExpression(D,Z,z){if(!(D instanceof K||D instanceof fe))throw new Error("Slice object must be an array or string");const ee=this.evaluate(Z.start,z),ce=this.evaluate(Z.stop,z),be=this.evaluate(Z.step,z);if(!(ee instanceof we||ee instanceof Ee))throw new Error("Slice start must be numeric or undefined");if(!(ce instanceof we||ce instanceof Ee))throw new Error("Slice stop must be numeric or undefined");if(!(be instanceof we||be instanceof Ee))throw new Error("Slice step must be numeric or undefined");return D instanceof K?new K(G(D.value,ee.value,ce.value,be.value)):new fe(G(Array.from(D.value),ee.value,ce.value,be.value).join(""))}evaluateMemberExpression(D,Z){const z=this.evaluate(D.object,Z);let ee;if(D.computed){if(D.property.type==="SliceExpression")return this.evaluateSliceExpression(z,D.property,Z);ee=this.evaluate(D.property,Z)}else ee=new fe(D.property.value);let ce;if(z instanceof He){if(!(ee instanceof fe))throw new Error(`Cannot access property with non-string: got ${ee.type}`);ce=z.value.get(ee.value)??z.builtins.get(ee.value)}else if(z instanceof K||z instanceof fe)if(ee instanceof we)ce=z.value.at(ee.value),z instanceof fe&&(ce=new fe(z.value.at(ee.value)));else if(ee instanceof fe)ce=z.builtins.get(ee.value);else throw new Error(`Cannot access property with non-string/non-number: got ${ee.type}`);else{if(!(ee instanceof fe))throw new Error(`Cannot access property with non-string: got ${ee.type}`);ce=z.builtins.get(ee.value)}return ce instanceof X?ce:new Ee}evaluateSet(D,Z){const z=this.evaluate(D.value,Z);if(D.assignee.type==="Identifier"){const ee=D.assignee.value;Z.setVariable(ee,z)}else if(D.assignee.type==="MemberExpression"){const ee=D.assignee,ce=this.evaluate(ee.object,Z);if(!(ce instanceof He))throw new Error("Cannot assign to member of non-object");if(ee.property.type!=="Identifier")throw new Error("Cannot assign to member with non-identifier property");ce.value.set(ee.property.value,z)}else throw new Error(`Invalid LHS inside assignment expression: ${JSON.stringify(D.assignee)}`);return new Pe}evaluateIf(D,Z){const z=this.evaluate(D.test,Z);return this.evaluateBlock(z.__bool__().value?D.body:D.alternate,Z)}evaluateFor(D,Z){const z=new Fe(Z);let ee,ce;if(D.iterable.type==="SelectExpression"){const Ue=D.iterable;ce=this.evaluate(Ue.iterable,z),ee=Ue.test}else ce=this.evaluate(D.iterable,z);if(!(ce instanceof K))throw new Error(`Expected iterable type in for loop: got ${ce.type}`);const be=[],ve=[];for(let Ue=0;Uevt.setVariable(D.loopvar.value,Xe);else if(D.loopvar.type==="TupleLiteral"){const vt=D.loopvar;if(Xe.type!=="ArrayValue")throw new Error(`Cannot unpack non-iterable type: ${Xe.type}`);const nr=Xe;if(vt.value.length!==nr.value.length)throw new Error(`Too ${vt.value.length>nr.value.length?"few":"many"} items to unpack`);ct=jt=>{for(let ar=0;ar0?be[Ue-1]:new Ee],["nextitem",Ue{var ve;const ce=new Fe(ee);z=z.slice();let be;((ve=z.at(-1))==null?void 0:ve.type)==="KeywordArgumentsValue"&&(be=z.pop());for(let Re=0;Rethis.evaluate(z,Z)));case"TupleLiteral":return new U(D.value.map(z=>this.evaluate(z,Z)));case"ObjectLiteral":{const z=new Map;for(const[ee,ce]of D.value){const be=this.evaluate(ee,Z);if(!(be instanceof fe))throw new Error(`Object keys must be strings: got ${be.type}`);z.set(be.value,this.evaluate(ce,Z))}return new He(z)}case"Identifier":return this.evaluateIdentifier(D,Z);case"CallExpression":return this.evaluateCallExpression(D,Z);case"MemberExpression":return this.evaluateMemberExpression(D,Z);case"UnaryExpression":return this.evaluateUnaryExpression(D,Z);case"BinaryExpression":return this.evaluateBinaryExpression(D,Z);case"FilterExpression":return this.evaluateFilterExpression(D,Z);case"TestExpression":return this.evaluateTestExpression(D,Z);default:throw new SyntaxError(`Unknown node type: ${D.type}`)}}};function Le(D){switch(typeof D){case"number":return new we(D);case"string":return new fe(D);case"boolean":return new ke(D);case"undefined":return new Ee;case"object":return D===null?new Pe:Array.isArray(D)?new K(D.map(Le)):new He(new Map(Object.entries(D).map(([Z,z])=>[Z,Le(z)])));case"function":return new pe((Z,z)=>{const ee=D(...Z.map(ce=>ce.value))??null;return Le(ee)});default:throw new Error(`Cannot convert to runtime value: ${D}`)}}function Ne(D,Z,z){const ee=z??0;switch(D.type){case"NullValue":case"UndefinedValue":return"null";case"NumericValue":case"StringValue":case"BooleanValue":return JSON.stringify(D.value);case"ArrayValue":case"ObjectValue":{const ce=Z?" ".repeat(Z):"",be=` +`+ce.repeat(ee),ve=be+ce;if(D.type==="ArrayValue"){const Re=D.value.map(Ae=>Ne(Ae,Z,ee+1));return Z?`[${ve}${Re.join(`,${ve}`)}${be}]`:`[${Re.join(", ")}]`}else{const Re=Array.from(D.value.entries()).map(([Ae,Ue])=>{const Qe=`"${Ae}": ${Ne(Ue,Z,ee+1)}`;return Z?`${ve}${Qe}`:Qe});return Z?`{${Re.join(",")}${be}}`:`{${Re.join(", ")}}`}}default:throw new Error(`Cannot convert to JSON: ${D.type}`)}}var Ve=class{constructor(D){re(this,"parsed");const Z=u(D,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=N(Z)}render(D){const Z=new Fe;if(Z.set("false",!1),Z.set("true",!0),Z.set("raise_exception",ce=>{throw new Error(ce)}),Z.set("range",O),D)for(const[ce,be]of Object.entries(D))Z.set(ce,be);return new Ie(Z).run(this.parsed).value}}},"./src/backends/onnx.js":(e,r,t)=>{var s;t.r(r),t.d(r,{Tensor:()=>a.Tensor,createInferenceSession:()=>A,deviceToExecutionProviders:()=>_,isONNXProxy:()=>S,isONNXTensor:()=>v});var i=t("./src/env.js"),n=t("?2ce3"),o=t("onnxruntime-web"),a=t("onnxruntime-common");const l=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}}),d=[];let p,u;const h=Symbol.for("onnxruntime");if(h in globalThis)u=globalThis[h];else if(i.apis.IS_NODE_ENV){switch(u=n??(s||(s=t.t(n,2))),process.platform){case"win32":d.push("dml");break;case"linux":process.arch==="x64"&&d.push("cuda");break}d.push("cpu"),p=["cpu"]}else u=o,i.apis.IS_WEBNN_AVAILABLE&&d.push("webnn-npu","webnn-gpu","webnn-cpu","webnn"),i.apis.IS_WEBGPU_AVAILABLE&&d.push("webgpu"),d.push("wasm"),p=["wasm"];const w=u.InferenceSession;function _(x=null){if(!x)return p;switch(x){case"auto":return d;case"gpu":return d.filter(g=>["webgpu","cuda","dml","webnn-gpu"].includes(g))}if(d.includes(x))return[l[x]??x];throw new Error(`Unsupported device: "${x}". Should be one of: ${d.join(", ")}.`)}let P=null;async function A(x,g,M){P&&await P;const E=w.create(x,g);P??(P=E);const k=await E;return k.config=M,k}function v(x){return x instanceof u.Tensor}const y=u==null?void 0:u.env;y!=null&&y.wasm&&(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&!y.wasm.wasmPaths&&(y.wasm.wasmPaths=`https://cdn.jsdelivr.net/npm/@huggingface/transformers@${i.env.version}/dist/`),y.wasm.proxy=!1),y!=null&&y.webgpu&&(y.webgpu.powerPreference="high-performance");function S(){var x;return(x=y==null?void 0:y.wasm)==null?void 0:x.proxy}i.env.backends.onnx=y},"./src/base/feature_extraction_utils.js":(e,r,t)=>{t.r(r),t.d(r,{FeatureExtractor:()=>o,validate_audio_inputs:()=>a});var s=t("./src/utils/constants.js"),i=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class o extends i.Callable{constructor(d){super(),this.config=d}static async from_pretrained(d,p){const u=await(0,n.getModelJSON)(d,s.FEATURE_EXTRACTOR_NAME,!0,p);return new this(u)}}function a(l,d){var p;if(!(l instanceof Float32Array||l instanceof Float64Array))throw new Error(`${d} expects input to be a Float32Array or a Float64Array, but got ${((p=l==null?void 0:l.constructor)==null?void 0:p.name)??typeof l} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}},"./src/base/image_processors_utils.js":(e,r,t)=>{t.r(r),t.d(r,{ImageProcessor:()=>x,center_to_corners_format:()=>u,post_process_instance_segmentation:()=>S,post_process_object_detection:()=>h,post_process_panoptic_segmentation:()=>y,post_process_semantic_segmentation:()=>w});var s=t("./src/utils/generic.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/utils/image.js");var o=t("./src/utils/core.js"),a=t("./src/utils/hub.js"),l=t("./src/utils/constants.js");function d(g,M,E=0,k=null){const B=g/M;let R=(0,n.bankers_round)(B)*M;return k!==null&&R>k&&(R=Math.floor(B)*M),RM&&O.push(ne)}else{let ne=(0,n.max)(N.data)[1];if(ne===V-1||(G=(0,n.softmax)(N.data),G[ne]we*Q[(fe+1)%2])),ie.boxes.push(X),ie.classes.push(ne),ie.scores.push(G[ne])}}Y.push(ie)}return Y}function w(g,M=null){const E=g.logits,k=E.dims[0];if(M!==null&&M.length!==k)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const B=[];for(let R=0;RQ[O]&&(Q[O]=N[O],ie[O]=ge)}const le=new Array(q.dims[0]);for(let ge=0;gege!==void 0);B.push({segmentation:H,labels:ae})}return B}function _(g,M,E,k){const B=[],R=[],J=[];for(let q=0;qE&&(B.push(Y),R.push(ie),J.push(H))}return[B,R,J]}function P(g,M,E,k=.5,B=.8){const R=[];let J=0,q=0;const V=M[E].data;for(let H=0;H=k&&++q;let Y=J>0&&q>0;return Y&&(Y=J/q>B),[Y,R]}function A(g,M,E,k,B,R=null,J=null){const[q,V]=J??g[0].dims,Y=new i.Tensor("int32",new Int32Array(q*V),[q,V]),H=[];if(J!==null)for(let ge=0;geie[G]&&(Q[G]=ge,ie[G]=O[G])}let le=0;const ae=Y.data;for(let ge=0;ge200)throw new Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(g,M)/Math.min(g,M)}`);let R=Math.round(g/E)*E,J=Math.round(M/E)*E;if(R*J>B){const q=Math.sqrt(g*M/B);R=Math.floor(g/q/E)*E,J=Math.floor(M/q/E)*E}else if(R*JR?Y=Math.floor(R*V/B):R>B&&(V=Math.floor(B*Y/R)),await M.resize(Y,V,{resample:k}))}async crop_margin(M,E=200){const k=M.clone().grayscale(),B=(0,n.min)(k.data)[0],J=(0,n.max)(k.data)[0]-B;if(J===0)return M;const q=E/255;let V=k.width,Y=k.height,H=0,Q=0;const ie=k.data;for(let le=0;lethis.preprocess(R)));return{pixel_values:(0,i.stack)(k.map(R=>R.pixel_values),0),original_sizes:k.map(R=>R.original_size),reshaped_input_sizes:k.map(R=>R.reshaped_input_size)}}static async from_pretrained(M,E){const k=await(0,a.getModelJSON)(M,l.IMAGE_PROCESSOR_NAME,!0,E);return new this(k)}}},"./src/base/processing_utils.js":(e,r,t)=>{t.r(r),t.d(r,{Processor:()=>o});var s=t("./src/utils/constants.js"),i=t("./src/utils/generic.js"),n=t("./src/utils/hub.js");class o extends i.Callable{constructor(l,d){super(),this.config=l,this.components=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(l,d={}){if(!this.tokenizer)throw new Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(l,{tokenize:!1,...d})}batch_decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...l)}decode(...l){if(!this.tokenizer)throw new Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...l)}async _call(l,...d){for(const p of[this.image_processor,this.feature_extractor,this.tokenizer])if(p)return p(l,...d);throw new Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(l,d){const[p,u]=await Promise.all([this.uses_processor_config?(0,n.getModelJSON)(l,s.PROCESSOR_NAME,!0,d):{},Promise.all(this.classes.filter(h=>h in this).map(async h=>{const w=await this[h].from_pretrained(l,d);return[h.replace(/_class$/,""),w]})).then(Object.fromEntries)]);return new this(p,u)}}re(o,"classes",["image_processor_class","tokenizer_class","feature_extractor_class"]),re(o,"uses_processor_config",!1)},"./src/configs.js":(e,r,t)=>{t.r(r),t.d(r,{AutoConfig:()=>d,PretrainedConfig:()=>l,getKeyValueShapes:()=>a});var s=t("./src/utils/core.js"),i=t("./src/utils/hub.js");async function n(p,u){return await(0,i.getModelJSON)(p,"config.json",!0,u)}function o(p){const u={};let h={};switch(p.model_type){case"llava":case"paligemma":case"florence2":case"llava_onevision":case"idefics3":case"ultravox":case"smolvlm":h=o(p.text_config);break;case"moondream1":h=o(p.phi_config);break;case"musicgen":h=o(p.decoder);break;case"multi_modality":h=o(p.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":u.num_heads="num_attention_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size";break;case"llama":case"olmo":case"olmo2":case"mobilellm":case"granite":case"cohere":case"mistral":case"starcoder2":case"qwen2":case"qwen2_vl":case"phi":case"phi3":case"phi3_v":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.hidden_size="hidden_size",u.num_attention_heads="num_attention_heads";break;case"gemma":case"gemma2":case"glm":case"helium":u.num_heads="num_key_value_heads",u.num_layers="num_hidden_layers",u.dim_kv="head_dim";break;case"openelm":u.num_heads="num_kv_heads",u.num_layers="num_transformer_layers",u.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":u.num_heads="num_heads",u.num_layers="num_layers",u.hidden_size="hidden_size";break;case"bloom":u.num_heads="n_head",u.num_layers="n_layer",u.hidden_size="hidden_size";break;case"mpt":u.num_heads="n_heads",u.num_layers="n_layers",u.hidden_size="d_model";break;case"exaone":u.num_heads="num_key_value_heads",u.num_layers="num_layers",u.dim_kv="head_dim",u.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":u.num_decoder_layers="num_decoder_layers",u.num_decoder_heads="num_heads",u.decoder_dim_kv="d_kv",u.num_encoder_layers="num_layers",u.num_encoder_heads="num_heads",u.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="d_model",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="d_model";break;case"speecht5":u.num_decoder_layers="decoder_layers",u.num_decoder_heads="decoder_attention_heads",u.decoder_hidden_size="hidden_size",u.num_encoder_layers="encoder_layers",u.num_encoder_heads="encoder_attention_heads",u.encoder_hidden_size="hidden_size";break;case"trocr":u.num_encoder_layers=u.num_decoder_layers="decoder_layers",u.num_encoder_heads=u.num_decoder_heads="decoder_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="d_model";break;case"musicgen_decoder":u.num_encoder_layers=u.num_decoder_layers="num_hidden_layers",u.num_encoder_heads=u.num_decoder_heads="num_attention_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"moonshine":u.num_decoder_layers="decoder_num_hidden_layers",u.num_decoder_heads="decoder_num_key_value_heads",u.num_encoder_layers="encoder_num_hidden_layers",u.num_encoder_heads="encoder_num_key_value_heads",u.encoder_hidden_size=u.decoder_hidden_size="hidden_size";break;case"vision-encoder-decoder":const _=o(p.decoder),P="num_decoder_layers"in _,A=(0,s.pick)(p,["model_type","is_encoder_decoder"]);return P?(A.num_decoder_layers=_.num_decoder_layers,A.num_decoder_heads=_.num_decoder_heads,A.decoder_hidden_size=_.decoder_hidden_size,A.num_encoder_layers=_.num_encoder_layers,A.num_encoder_heads=_.num_encoder_heads,A.encoder_hidden_size=_.encoder_hidden_size):(A.num_layers=_.num_layers,A.num_heads=_.num_heads,A.hidden_size=_.hidden_size),A}const w={...h,...(0,s.pick)(p,["model_type","multi_query","is_encoder_decoder"])};for(const _ in u)w[_]=p[u[_]];return w}function a(p,{prefix:u="past_key_values",batch_size:h=1}={}){const w={},_=p.normalized_config;if(_.is_encoder_decoder&&"num_encoder_heads"in _&&"num_decoder_heads"in _){const P=_.encoder_dim_kv??_.encoder_hidden_size/_.num_encoder_heads,A=_.decoder_dim_kv??_.decoder_hidden_size/_.num_decoder_heads,v=[h,_.num_encoder_heads,0,P],y=[h,_.num_decoder_heads,0,A];for(let S=0;S<_.num_decoder_layers;++S)w[`${u}.${S}.encoder.key`]=v,w[`${u}.${S}.encoder.value`]=v,w[`${u}.${S}.decoder.key`]=y,w[`${u}.${S}.decoder.value`]=y}else{const P=_.num_heads,A=_.num_layers,v=_.dim_kv??_.hidden_size/(_.num_attention_heads??P);if(_.model_type==="falcon"){const y=[h*P,0,v];for(let S=0;S{var k,B;t.r(r),t.d(r,{apis:()=>A,env:()=>M});var s=t("?569f"),i=t("?3f59"),n=t("?154a");const o="3.4.0",a=typeof window<"u"&&typeof window.document<"u",l=typeof self<"u"&&((k=self.constructor)==null?void 0:k.name)==="DedicatedWorkerGlobalScope",d=typeof self<"u"&&"caches"in self,p=typeof navigator<"u"&&"gpu"in navigator,u=typeof navigator<"u"&&"ml"in navigator,h=typeof process<"u",w=h&&((B=process==null?void 0:process.release)==null?void 0:B.name)==="node",_=!E(s),P=!E(i),A=Object.freeze({IS_BROWSER_ENV:a,IS_WEBWORKER_ENV:l,IS_WEB_CACHE_AVAILABLE:d,IS_WEBGPU_AVAILABLE:p,IS_WEBNN_AVAILABLE:u,IS_PROCESS_AVAILABLE:h,IS_NODE_ENV:w,IS_FS_AVAILABLE:_,IS_PATH_AVAILABLE:P}),v=_&&P;let y="./";if(v){const R=Object(import.meta).url;R?y=i.dirname(i.dirname(n.fileURLToPath(R))):typeof __dirname<"u"&&(y=i.dirname(__dirname))}const S=v?i.join(y,"/.cache/"):null,x="/models/",g=v?i.join(y,x):x,M={version:o,backends:{onnx:{}},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(a||l),localModelPath:g,useFS:_,useBrowserCache:d,useFSCache:_,cacheDir:S,useCustomCache:!1,customCache:null};function E(R){return Object.keys(R).length===0}},"./src/generation/configuration_utils.js":(e,r,t)=>{t.r(r),t.d(r,{GenerationConfig:()=>i});var s=t("./src/utils/core.js");class i{constructor(o){re(this,"max_length",20);re(this,"max_new_tokens",null);re(this,"min_length",0);re(this,"min_new_tokens",null);re(this,"early_stopping",!1);re(this,"max_time",null);re(this,"do_sample",!1);re(this,"num_beams",1);re(this,"num_beam_groups",1);re(this,"penalty_alpha",null);re(this,"use_cache",!0);re(this,"temperature",1);re(this,"top_k",50);re(this,"top_p",1);re(this,"typical_p",1);re(this,"epsilon_cutoff",0);re(this,"eta_cutoff",0);re(this,"diversity_penalty",0);re(this,"repetition_penalty",1);re(this,"encoder_repetition_penalty",1);re(this,"length_penalty",1);re(this,"no_repeat_ngram_size",0);re(this,"bad_words_ids",null);re(this,"force_words_ids",null);re(this,"renormalize_logits",!1);re(this,"constraints",null);re(this,"forced_bos_token_id",null);re(this,"forced_eos_token_id",null);re(this,"remove_invalid_values",!1);re(this,"exponential_decay_length_penalty",null);re(this,"suppress_tokens",null);re(this,"streamer",null);re(this,"begin_suppress_tokens",null);re(this,"forced_decoder_ids",null);re(this,"guidance_scale",null);re(this,"num_return_sequences",1);re(this,"output_attentions",!1);re(this,"output_hidden_states",!1);re(this,"output_scores",!1);re(this,"return_dict_in_generate",!1);re(this,"pad_token_id",null);re(this,"bos_token_id",null);re(this,"eos_token_id",null);re(this,"encoder_no_repeat_ngram_size",0);re(this,"decoder_start_token_id",null);re(this,"generation_kwargs",{});Object.assign(this,(0,s.pick)(o,Object.getOwnPropertyNames(this)))}}},"./src/generation/logits_process.js":(e,r,t)=>{t.r(r),t.d(r,{ClassifierFreeGuidanceLogitsProcessor:()=>v,ForcedBOSTokenLogitsProcessor:()=>l,ForcedEOSTokenLogitsProcessor:()=>d,LogitsProcessor:()=>n,LogitsProcessorList:()=>a,LogitsWarper:()=>o,MinLengthLogitsProcessor:()=>_,MinNewTokensLengthLogitsProcessor:()=>P,NoBadWordsLogitsProcessor:()=>A,NoRepeatNGramLogitsProcessor:()=>h,RepetitionPenaltyLogitsProcessor:()=>w,SuppressTokensAtBeginLogitsProcessor:()=>p,TemperatureLogitsWarper:()=>y,TopKLogitsWarper:()=>x,TopPLogitsWarper:()=>S,WhisperTimeStampLogitsProcessor:()=>u});var s=t("./src/utils/generic.js");t("./src/utils/tensor.js");var i=t("./src/utils/maths.js");class n extends s.Callable{_call(M,E){throw Error("`_call` should be implemented in a subclass")}}class o extends s.Callable{_call(M,E){throw Error("`_call` should be implemented in a subclass")}}class a extends s.Callable{constructor(){super(),this.processors=[]}push(M){this.processors.push(M)}extend(M){this.processors.push(...M)}_call(M,E){let k=E;for(const B of this.processors)k=B(M,k);return k}[Symbol.iterator](){return this.processors.values()}}class l extends n{constructor(M){super(),this.bos_token_id=M}_call(M,E){for(let k=0;k=1&&R[R.length-1]>=this.timestamp_begin,q=R.length<2||R[R.length-2]>=this.timestamp_begin;if(J&&(q?B.subarray(this.timestamp_begin).fill(-1/0):B.subarray(0,this.eos_token_id).fill(-1/0)),M[k].length===this.begin_index&&this.max_initial_timestamp_index!==null){const Q=this.timestamp_begin+this.max_initial_timestamp_index;B.subarray(Q+1).fill(-1/0)}const V=(0,i.log_softmax)(B),Y=Math.log(V.subarray(this.timestamp_begin).map(Math.exp).reduce((Q,ie)=>Q+ie)),H=(0,i.max)(V.subarray(0,this.timestamp_begin))[0];Y>H&&B.subarray(0,this.timestamp_begin).fill(-1/0)}return E}}class h extends n{constructor(M){super(),this.no_repeat_ngram_size=M}getNgrams(M){const E=M.length,k=[];for(let R=0;R1 to use the classifier free guidance processor, got guidance scale ${M}.`);this.guidance_scale=M}_call(M,E){if(E.dims[0]!==2*M.length)throw new Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${E.dims[0]} for the logits and ${M.length} for the input ids.`);const k=M.length,B=E.slice([0,k],null),R=E.slice([k,E.dims[0]],null);for(let J=0;J1)throw new Error(`\`top_p\` must be a float > 0 and < 1, but is ${M}`);if(!Number.isInteger(k)||k<1)throw new Error(`\`min_tokens_to_keep\` must be a positive integer, but is ${k}`);this.top_p=M,this.filter_value=E,this.min_tokens_to_keep=k}}class x extends o{constructor(M,{filter_value:E=-1/0,min_tokens_to_keep:k=1}={}){if(super(),!Number.isInteger(M)||M<0)throw new Error(`\`top_k\` must be a positive integer, but is ${M}`);this.top_k=Math.max(M,k),this.filter_value=E}}},"./src/generation/logits_sampler.js":(e,r,t)=>{t.r(r),t.d(r,{LogitsSampler:()=>o});var s=t("./src/utils/generic.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");t("./src/generation/configuration_utils.js");class o extends s.Callable{constructor(u){super(),this.generation_config=u}async _call(u){return this.sample(u)}async sample(u){throw Error("sample should be implemented in subclasses.")}getLogits(u,h){let w=u.dims.at(-1),_=u.data;if(h===-1)_=_.slice(-w);else{let P=h*w;_=_.slice(P,P+w)}return _}randomSelect(u){let h=0;for(let _=0;_1)return new d(u);if(u.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${u.num_return_sequences}.`);return new a(u)}}class a extends o{async sample(u){const h=(0,n.max)(u.data)[1];return[[BigInt(h),0]]}}class l extends o{async sample(u){let h=u.dims.at(-1);this.generation_config.top_k>0&&(h=Math.min(this.generation_config.top_k,h));const[w,_]=await(0,i.topk)(u,h),P=(0,n.softmax)(w.data);return Array.from({length:this.generation_config.num_beams},()=>{const A=this.randomSelect(P);return[_.data[A],Math.log(P[A])]})}}class d extends o{async sample(u){let h=u.dims.at(-1);this.generation_config.top_k>0&&(h=Math.min(this.generation_config.top_k,h));const[w,_]=await(0,i.topk)(u,h),P=(0,n.softmax)(w.data);return Array.from({length:this.generation_config.num_beams},(A,v)=>[_.data[v],Math.log(P[v])])}}},"./src/generation/stopping_criteria.js":(e,r,t)=>{t.r(r),t.d(r,{EosTokenCriteria:()=>a,InterruptableStoppingCriteria:()=>l,MaxLengthCriteria:()=>o,StoppingCriteria:()=>i,StoppingCriteriaList:()=>n});var s=t("./src/utils/generic.js");class i extends s.Callable{_call(p,u){throw Error("StoppingCriteria needs to be subclassed")}}class n extends s.Callable{constructor(){super(),this.criteria=[]}push(p){this.criteria.push(p)}extend(p){p instanceof n?p=p.criteria:p instanceof i&&(p=[p]),this.criteria.push(...p)}_call(p,u){const h=new Array(p.length).fill(!1);for(const w of this.criteria){const _=w(p,u);for(let P=0;Pu.length>=this.max_length)}}class a extends i{constructor(p){super(),Array.isArray(p)||(p=[p]),this.eos_token_id=p}_call(p,u){return p.map(h=>{const w=h.at(-1);return this.eos_token_id.some(_=>w==_)})}}class l extends i{constructor(){super(),this.interrupted=!1}interrupt(){this.interrupted=!0}reset(){this.interrupted=!1}_call(p,u){return new Array(p.length).fill(this.interrupted)}}},"./src/generation/streamers.js":(e,r,t)=>{t.r(r),t.d(r,{BaseStreamer:()=>o,TextStreamer:()=>l,WhisperTextStreamer:()=>d});var s=t("./src/utils/core.js"),i=t("./src/tokenizers.js"),n=t("./src/env.js");class o{put(u){throw Error("Not implemented")}end(){throw Error("Not implemented")}}const a=n.apis.IS_PROCESS_AVAILABLE?p=>process.stdout.write(p):p=>console.log(p);class l extends o{constructor(u,{skip_prompt:h=!1,callback_function:w=null,token_callback_function:_=null,skip_special_tokens:P=!0,decode_kwargs:A={},...v}={}){super(),this.tokenizer=u,this.skip_prompt=h,this.callback_function=w??a,this.token_callback_function=_,this.decode_kwargs={skip_special_tokens:P,...A,...v},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0}put(u){var A;if(u.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 w=u[0];(A=this.token_callback_function)==null||A.call(this,w),this.token_cache=(0,s.mergeArrays)(this.token_cache,w);const _=this.tokenizer.decode(this.token_cache,this.decode_kwargs);let P;h||_.endsWith(` +`)?(P=_.slice(this.print_len),this.token_cache=[],this.print_len=0):_.length>0&&(0,i.is_chinese_char)(_.charCodeAt(_.length-1))?(P=_.slice(this.print_len),this.print_len+=P.length):(P=_.slice(this.print_len,_.lastIndexOf(" ")+1),this.print_len+=P.length),this.on_finalized_text(P,!1)}end(){let u;this.token_cache.length>0?(u=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):u="",this.next_tokens_are_prompt=!0,this.on_finalized_text(u,!0)}on_finalized_text(u,h){var w,_;u.length>0&&((w=this.callback_function)==null||w.call(this,u)),h&&this.callback_function===a&&n.apis.IS_PROCESS_AVAILABLE&&((_=this.callback_function)==null||_.call(this,` +`))}}class d extends l{constructor(u,{skip_prompt:h=!1,callback_function:w=null,token_callback_function:_=null,on_chunk_start:P=null,on_chunk_end:A=null,on_finalize:v=null,time_precision:y=.02,skip_special_tokens:S=!0,decode_kwargs:x={}}={}){super(u,{skip_prompt:h,skip_special_tokens:S,callback_function:w,token_callback_function:_,decode_kwargs:x}),this.timestamp_begin=u.timestamp_begin,this.on_chunk_start=P,this.on_chunk_end=A,this.on_finalize=v,this.time_precision=y,this.waiting_for_timestamp=!1}put(u){var w,_;if(u.length>1)throw Error("WhisperTextStreamer only supports batch size of 1");const h=u[0];if(h.length===1){const P=Number(h[0])-this.timestamp_begin;if(P>=0){const A=P*this.time_precision;this.waiting_for_timestamp?(w=this.on_chunk_end)==null||w.call(this,A):(_=this.on_chunk_start)==null||_.call(this,A),this.waiting_for_timestamp=!this.waiting_for_timestamp,u=[[]]}}return super.put(u)}end(){var u;super.end(),(u=this.on_finalize)==null||u.call(this)}}},"./src/models.js":(e,r,t)=>{t.r(r),t.d(r,{ASTForAudioClassification:()=>xa,ASTModel:()=>va,ASTPreTrainedModel:()=>ki,AlbertForMaskedLM:()=>j,AlbertForQuestionAnswering:()=>F,AlbertForSequenceClassification:()=>ue,AlbertModel:()=>fn,AlbertPreTrainedModel:()=>Ps,AutoModel:()=>jd,AutoModelForAudioClassification:()=>Nm,AutoModelForAudioFrameClassification:()=>Um,AutoModelForAudioTextToText:()=>Jm,AutoModelForCTC:()=>Rm,AutoModelForCausalLM:()=>Sm,AutoModelForDepthEstimation:()=>Km,AutoModelForDocumentQuestionAnswering:()=>Vm,AutoModelForImageClassification:()=>Am,AutoModelForImageFeatureExtraction:()=>Qm,AutoModelForImageMatting:()=>Wm,AutoModelForImageSegmentation:()=>Fm,AutoModelForImageTextToText:()=>Xm,AutoModelForImageToImage:()=>Gm,AutoModelForMaskGeneration:()=>Bm,AutoModelForMaskedLM:()=>$m,AutoModelForNormalEstimation:()=>Hm,AutoModelForObjectDetection:()=>Lm,AutoModelForPoseEstimation:()=>qm,AutoModelForQuestionAnswering:()=>km,AutoModelForSemanticSegmentation:()=>Om,AutoModelForSeq2SeqLM:()=>Tm,AutoModelForSequenceClassification:()=>vm,AutoModelForSpeechSeq2Seq:()=>Em,AutoModelForTextToSpectrogram:()=>Pm,AutoModelForTextToWaveform:()=>Cm,AutoModelForTokenClassification:()=>xm,AutoModelForUniversalSegmentation:()=>Dm,AutoModelForVision2Seq:()=>Im,AutoModelForXVector:()=>jm,AutoModelForZeroShotObjectDetection:()=>zm,BartForConditionalGeneration:()=>Vt,BartForSequenceClassification:()=>At,BartModel:()=>$t,BartPretrainedModel:()=>Ct,BaseModelOutput:()=>Pe,BeitForImageClassification:()=>dl,BeitModel:()=>ll,BeitPreTrainedModel:()=>Uo,BertForMaskedLM:()=>Ie,BertForQuestionAnswering:()=>Ve,BertForSequenceClassification:()=>Le,BertForTokenClassification:()=>Ne,BertModel:()=>Fe,BertPreTrainedModel:()=>Ee,BlenderbotForConditionalGeneration:()=>Yt,BlenderbotModel:()=>Wt,BlenderbotPreTrainedModel:()=>as,BlenderbotSmallForConditionalGeneration:()=>ls,BlenderbotSmallModel:()=>Qr,BlenderbotSmallPreTrainedModel:()=>_r,BloomForCausalLM:()=>xo,BloomModel:()=>vo,BloomPreTrainedModel:()=>ci,CLIPModel:()=>Bi,CLIPPreTrainedModel:()=>zs,CLIPSegForImageSegmentation:()=>Ri,CLIPSegModel:()=>en,CLIPSegPreTrainedModel:()=>Zs,CLIPTextModel:()=>fd,CLIPTextModelWithProjection:()=>Aa,CLIPVisionModel:()=>_d,CLIPVisionModelWithProjection:()=>Un,CamembertForMaskedLM:()=>bs,CamembertForQuestionAnswering:()=>Is,CamembertForSequenceClassification:()=>vs,CamembertForTokenClassification:()=>xs,CamembertModel:()=>ts,CamembertPreTrainedModel:()=>Br,CausalLMOutput:()=>bn,CausalLMOutputWithPast:()=>Nb,ChineseCLIPModel:()=>za,ChineseCLIPPreTrainedModel:()=>La,ClapAudioModelWithProjection:()=>ah,ClapModel:()=>ih,ClapPreTrainedModel:()=>El,ClapTextModelWithProjection:()=>oh,CodeGenForCausalLM:()=>Rr,CodeGenModel:()=>yn,CodeGenPreTrainedModel:()=>qn,CohereForCausalLM:()=>oo,CohereModel:()=>io,CoherePreTrainedModel:()=>si,ConvBertForMaskedLM:()=>jt,ConvBertForQuestionAnswering:()=>$s,ConvBertForSequenceClassification:()=>ar,ConvBertForTokenClassification:()=>Zr,ConvBertModel:()=>nr,ConvBertPreTrainedModel:()=>vt,ConvNextForImageClassification:()=>tp,ConvNextModel:()=>ep,ConvNextPreTrainedModel:()=>yd,ConvNextV2ForImageClassification:()=>sp,ConvNextV2Model:()=>rp,ConvNextV2PreTrainedModel:()=>Md,DPTForDepthEstimation:()=>Bt,DPTModel:()=>gt,DPTPreTrainedModel:()=>ot,DacDecoderModel:()=>Qh,DacDecoderOutput:()=>Kh,DacEncoderModel:()=>qh,DacEncoderOutput:()=>Gh,DacModel:()=>Hh,DacPreTrainedModel:()=>Al,DebertaForMaskedLM:()=>et,DebertaForQuestionAnswering:()=>zt,DebertaForSequenceClassification:()=>it,DebertaForTokenClassification:()=>rr,DebertaModel:()=>Be,DebertaPreTrainedModel:()=>hr,DebertaV2ForMaskedLM:()=>ss,DebertaV2ForQuestionAnswering:()=>is,DebertaV2ForSequenceClassification:()=>Tr,DebertaV2ForTokenClassification:()=>ns,DebertaV2Model:()=>rs,DebertaV2PreTrainedModel:()=>Sr,DecisionTransformerModel:()=>Sh,DecisionTransformerPreTrainedModel:()=>Ch,DeiTForImageClassification:()=>Ml,DeiTModel:()=>yl,DeiTPreTrainedModel:()=>Ho,DepthAnythingForDepthEstimation:()=>rn,DepthAnythingPreTrainedModel:()=>Ir,DepthProForDepthEstimation:()=>Hu,DepthProPreTrainedModel:()=>Ku,DetrForObjectDetection:()=>ul,DetrForSegmentation:()=>Vo,DetrModel:()=>cl,DetrObjectDetectionOutput:()=>Wo,DetrPreTrainedModel:()=>_i,DetrSegmentationOutput:()=>pl,Dinov2ForImageClassification:()=>ip,Dinov2Model:()=>np,Dinov2PreTrainedModel:()=>bd,Dinov2WithRegistersForImageClassification:()=>ap,Dinov2WithRegistersModel:()=>op,Dinov2WithRegistersPreTrainedModel:()=>vd,DistilBertForMaskedLM:()=>Hs,DistilBertForQuestionAnswering:()=>Ks,DistilBertForSequenceClassification:()=>Ws,DistilBertForTokenClassification:()=>Gs,DistilBertModel:()=>Ts,DistilBertPreTrainedModel:()=>Gr,DonutSwinModel:()=>Zu,DonutSwinPreTrainedModel:()=>Yu,EfficientNetForImageClassification:()=>mh,EfficientNetModel:()=>hh,EfficientNetPreTrainedModel:()=>Ad,ElectraForMaskedLM:()=>ks,ElectraForQuestionAnswering:()=>Wr,ElectraForSequenceClassification:()=>zr,ElectraForTokenClassification:()=>dt,ElectraModel:()=>es,ElectraPreTrainedModel:()=>Fr,EsmForMaskedLM:()=>Qs,EsmForSequenceClassification:()=>Xs,EsmForTokenClassification:()=>Or,EsmModel:()=>qs,EsmPreTrainedModel:()=>os,ExaoneForCausalLM:()=>ht,ExaoneModel:()=>Yi,ExaonePreTrainedModel:()=>Bs,FalconForCausalLM:()=>nh,FalconModel:()=>sh,FalconPreTrainedModel:()=>$d,FastViTForImageClassification:()=>Ja,FastViTModel:()=>Xa,FastViTPreTrainedModel:()=>zo,Florence2ForConditionalGeneration:()=>Oi,Florence2PreTrainedModel:()=>ka,GLPNForDepthEstimation:()=>Ju,GLPNModel:()=>Xu,GLPNPreTrainedModel:()=>wd,GPT2LMHeadModel:()=>Gn,GPT2Model:()=>ja,GPT2PreTrainedModel:()=>Ni,GPTBigCodeForCausalLM:()=>qi,GPTBigCodeModel:()=>Va,GPTBigCodePreTrainedModel:()=>Oe,GPTJForCausalLM:()=>wn,GPTJModel:()=>Hi,GPTJPreTrainedModel:()=>Ki,GPTNeoForCausalLM:()=>Wi,GPTNeoModel:()=>Vi,GPTNeoPreTrainedModel:()=>Kn,GPTNeoXForCausalLM:()=>Gi,GPTNeoXModel:()=>Ua,GPTNeoXPreTrainedModel:()=>Hn,Gemma2ForCausalLM:()=>uo,Gemma2Model:()=>co,Gemma2PreTrainedModel:()=>ii,GemmaForCausalLM:()=>lo,GemmaModel:()=>ao,GemmaPreTrainedModel:()=>ni,GlmForCausalLM:()=>_t,GlmModel:()=>Ji,GlmPreTrainedModel:()=>Yn,GraniteForCausalLM:()=>no,GraniteModel:()=>so,GranitePreTrainedModel:()=>ri,GroundingDinoForObjectDetection:()=>dp,GroundingDinoPreTrainedModel:()=>lp,GroupViTModel:()=>Qa,GroupViTPreTrainedModel:()=>qa,HeliumForCausalLM:()=>Jn,HeliumModel:()=>Xi,HeliumPreTrainedModel:()=>Xn,HieraForImageClassification:()=>c,HieraModel:()=>Qo,HieraPreTrainedModel:()=>qo,HubertForCTC:()=>Rp,HubertForSequenceClassification:()=>Np,HubertModel:()=>Bp,HubertPreTrainedModel:()=>Pb,IJepaForImageClassification:()=>Io,IJepaModel:()=>ko,IJepaPreTrainedModel:()=>mi,Idefics3ForConditionalGeneration:()=>Nn,Idefics3PreTrainedModel:()=>Ia,ImageMattingOutput:()=>Zm,JAISLMHeadModel:()=>Ui,JAISModel:()=>ji,JAISPreTrainedModel:()=>gn,JinaCLIPModel:()=>Ba,JinaCLIPPreTrainedModel:()=>Wn,JinaCLIPTextModel:()=>Ra,JinaCLIPVisionModel:()=>Na,LiteWhisperForConditionalGeneration:()=>Ea,LlamaForCausalLM:()=>Qi,LlamaModel:()=>Qn,LlamaPreTrainedModel:()=>tn,LlavaForConditionalGeneration:()=>Rn,LlavaOnevisionForConditionalGeneration:()=>Sa,LlavaPreTrainedModel:()=>Ca,LongT5ForConditionalGeneration:()=>qe,LongT5Model:()=>We,LongT5PreTrainedModel:()=>Ce,M2M100ForConditionalGeneration:()=>yp,M2M100Model:()=>wp,M2M100PreTrainedModel:()=>Ed,MBartForCausalLM:()=>vr,MBartForConditionalGeneration:()=>fr,MBartForSequenceClassification:()=>qr,MBartModel:()=>br,MBartPreTrainedModel:()=>Ut,MPNetForMaskedLM:()=>Dr,MPNetForQuestionAnswering:()=>kr,MPNetForSequenceClassification:()=>hn,MPNetForTokenClassification:()=>Os,MPNetModel:()=>pn,MPNetPreTrainedModel:()=>Kr,MT5ForConditionalGeneration:()=>pt,MT5Model:()=>Ze,MT5PreTrainedModel:()=>Ke,MarianMTModel:()=>gp,MarianModel:()=>_p,MarianPreTrainedModel:()=>Td,MaskFormerForInstanceSegmentation:()=>Qu,MaskFormerModel:()=>qu,MaskFormerPreTrainedModel:()=>gd,MaskedLMOutput:()=>gr,MgpstrForSceneTextRecognition:()=>Fh,MgpstrModelOutput:()=>Ih,MgpstrPreTrainedModel:()=>Ah,MimiDecoderModel:()=>Wh,MimiDecoderOutput:()=>jh,MimiEncoderModel:()=>Vh,MimiEncoderOutput:()=>Nh,MimiModel:()=>Uh,MimiPreTrainedModel:()=>Il,MistralForCausalLM:()=>eh,MistralModel:()=>Zp,MistralPreTrainedModel:()=>Cd,MobileBertForMaskedLM:()=>As,MobileBertForQuestionAnswering:()=>$r,MobileBertForSequenceClassification:()=>Fs,MobileBertModel:()=>Mr,MobileBertPreTrainedModel:()=>Es,MobileLLMForCausalLM:()=>Zi,MobileLLMModel:()=>ft,MobileLLMPreTrainedModel:()=>Mn,MobileNetV1ForImageClassification:()=>_h,MobileNetV1ForSemanticSegmentation:()=>gh,MobileNetV1Model:()=>fh,MobileNetV1PreTrainedModel:()=>Cl,MobileNetV2ForImageClassification:()=>yh,MobileNetV2ForSemanticSegmentation:()=>Mh,MobileNetV2Model:()=>wh,MobileNetV2PreTrainedModel:()=>Sl,MobileNetV3ForImageClassification:()=>vh,MobileNetV3ForSemanticSegmentation:()=>xh,MobileNetV3Model:()=>bh,MobileNetV3PreTrainedModel:()=>$l,MobileNetV4ForImageClassification:()=>Eh,MobileNetV4ForSemanticSegmentation:()=>Ph,MobileNetV4Model:()=>Th,MobileNetV4PreTrainedModel:()=>kl,MobileViTForImageClassification:()=>tl,MobileViTModel:()=>el,MobileViTPreTrainedModel:()=>Bo,MobileViTV2ForImageClassification:()=>sl,MobileViTV2Model:()=>rl,MobileViTV2PreTrainedModel:()=>Ro,ModelOutput:()=>pe,ModernBertForMaskedLM:()=>z,ModernBertForSequenceClassification:()=>ee,ModernBertForTokenClassification:()=>ce,ModernBertModel:()=>Z,ModernBertPreTrainedModel:()=>D,Moondream1ForConditionalGeneration:()=>$a,MoonshineForConditionalGeneration:()=>Pa,MoonshineModel:()=>md,MoonshinePreTrainedModel:()=>Ai,MptForCausalLM:()=>Eo,MptModel:()=>To,MptPreTrainedModel:()=>ui,MultiModalityCausalLM:()=>kh,MultiModalityPreTrainedModel:()=>$h,MusicgenForCausalLM:()=>kb,MusicgenForConditionalGeneration:()=>Od,MusicgenModel:()=>$b,MusicgenPreTrainedModel:()=>Fd,NomicBertModel:()=>ve,NomicBertPreTrainedModel:()=>be,OPTForCausalLM:()=>Co,OPTModel:()=>Po,OPTPreTrainedModel:()=>pi,Olmo2ForCausalLM:()=>ti,Olmo2Model:()=>ro,Olmo2PreTrainedModel:()=>ei,OlmoForCausalLM:()=>to,OlmoModel:()=>eo,OlmoPreTrainedModel:()=>Zn,OpenELMForCausalLM:()=>ho,OpenELMModel:()=>po,OpenELMPreTrainedModel:()=>oi,OwlViTForObjectDetection:()=>il,OwlViTModel:()=>nl,OwlViTPreTrainedModel:()=>No,Owlv2ForObjectDetection:()=>al,Owlv2Model:()=>ol,Owlv2PreTrainedModel:()=>jo,PaliGemmaForConditionalGeneration:()=>Li,PaliGemmaPreTrainedModel:()=>Di,PatchTSMixerForPrediction:()=>zh,PatchTSMixerModel:()=>Lh,PatchTSMixerPreTrainedModel:()=>Ld,PatchTSTForPrediction:()=>Dh,PatchTSTModel:()=>Oh,PatchTSTPreTrainedModel:()=>Dd,Phi3ForCausalLM:()=>bo,Phi3Model:()=>Mo,Phi3PreTrainedModel:()=>di,Phi3VForCausalLM:()=>Ls,Phi3VPreTrainedModel:()=>zi,PhiForCausalLM:()=>yo,PhiModel:()=>wo,PhiPreTrainedModel:()=>li,PreTrainedModel:()=>U,PretrainedMixin:()=>kt,PvtForImageClassification:()=>Do,PvtModel:()=>Oo,PvtPreTrainedModel:()=>fi,PyAnnoteForAudioFrameClassification:()=>Ep,PyAnnoteModel:()=>Tp,PyAnnotePreTrainedModel:()=>Pd,QuestionAnsweringModelOutput:()=>Er,Qwen2ForCausalLM:()=>fo,Qwen2Model:()=>mo,Qwen2PreTrainedModel:()=>ai,Qwen2VLForConditionalGeneration:()=>go,Qwen2VLPreTrainedModel:()=>_o,RTDetrForObjectDetection:()=>ml,RTDetrModel:()=>hl,RTDetrObjectDetectionOutput:()=>fl,RTDetrPreTrainedModel:()=>Go,ResNetForImageClassification:()=>C,ResNetModel:()=>b,ResNetPreTrainedModel:()=>m,RoFormerForMaskedLM:()=>Ue,RoFormerForQuestionAnswering:()=>ct,RoFormerForSequenceClassification:()=>Qe,RoFormerForTokenClassification:()=>Xe,RoFormerModel:()=>Ae,RoFormerPreTrainedModel:()=>Re,RobertaForMaskedLM:()=>Rt,RobertaForQuestionAnswering:()=>Zt,RobertaForSequenceClassification:()=>Xt,RobertaForTokenClassification:()=>qt,RobertaModel:()=>dr,RobertaPreTrainedModel:()=>Ht,SamImageSegmentationOutput:()=>fp,SamModel:()=>mp,SamPreTrainedModel:()=>hp,SapiensForDepthEstimation:()=>Wu,SapiensForNormalEstimation:()=>Gu,SapiensForSemanticSegmentation:()=>Vu,SapiensPreTrainedModel:()=>bl,SegformerForImageClassification:()=>dh,SegformerForSemanticSegmentation:()=>ch,SegformerModel:()=>Sb,SegformerPreTrainedModel:()=>Pl,Seq2SeqLMOutput:()=>Rb,SequenceClassifierOutput:()=>yt,SiglipModel:()=>Fa,SiglipPreTrainedModel:()=>Vn,SiglipTextModel:()=>Oa,SiglipVisionModel:()=>Da,SmolVLMForConditionalGeneration:()=>jn,SpeechT5ForSpeechToText:()=>qp,SpeechT5ForTextToSpeech:()=>Qp,SpeechT5HifiGan:()=>Xp,SpeechT5Model:()=>Cb,SpeechT5PreTrainedModel:()=>Tl,SqueezeBertForMaskedLM:()=>mr,SqueezeBertForQuestionAnswering:()=>mn,SqueezeBertForSequenceClassification:()=>Ds,SqueezeBertModel:()=>lr,SqueezeBertPreTrainedModel:()=>Hr,StableLmForCausalLM:()=>ph,StableLmModel:()=>uh,StableLmPreTrainedModel:()=>Id,Starcoder2ForCausalLM:()=>rh,Starcoder2Model:()=>th,Starcoder2PreTrainedModel:()=>Sd,StyleTextToSpeech2Model:()=>Hp,StyleTextToSpeech2PreTrainedModel:()=>Kp,Swin2SRForImageSuperResolution:()=>Ye,Swin2SRModel:()=>ze,Swin2SRPreTrainedModel:()=>Te,SwinForImageClassification:()=>se,SwinForSemanticSegmentation:()=>ye,SwinModel:()=>W,SwinPreTrainedModel:()=>I,T5ForConditionalGeneration:()=>he,T5Model:()=>de,T5PreTrainedModel:()=>te,TableTransformerForObjectDetection:()=>gl,TableTransformerModel:()=>_l,TableTransformerObjectDetectionOutput:()=>wl,TableTransformerPreTrainedModel:()=>Ko,TokenClassifierOutput:()=>cr,TrOCRForCausalLM:()=>Yp,TrOCRPreTrainedModel:()=>Jp,UltravoxModel:()=>Rh,UltravoxPreTrainedModel:()=>Bh,UniSpeechForCTC:()=>$p,UniSpeechForSequenceClassification:()=>kp,UniSpeechModel:()=>Sp,UniSpeechPreTrainedModel:()=>vl,UniSpeechSatForAudioFrameClassification:()=>Op,UniSpeechSatForCTC:()=>Ap,UniSpeechSatForSequenceClassification:()=>Fp,UniSpeechSatModel:()=>Ip,UniSpeechSatPreTrainedModel:()=>Xo,ViTForImageClassification:()=>$o,ViTMAEModel:()=>Ga,ViTMAEPreTrainedModel:()=>Wa,ViTMSNForImageClassification:()=>Ha,ViTMSNModel:()=>Ka,ViTMSNPreTrainedModel:()=>Lo,ViTModel:()=>So,ViTPreTrainedModel:()=>hi,VisionEncoderDecoderModel:()=>Fi,VitMatteForImageMatting:()=>Za,VitMattePreTrainedModel:()=>Ya,VitPoseForPoseEstimation:()=>Fo,VitPosePreTrainedModel:()=>Ao,VitsModel:()=>kd,VitsModelOutput:()=>ef,VitsPreTrainedModel:()=>lh,Wav2Vec2BertForCTC:()=>Lp,Wav2Vec2BertForSequenceClassification:()=>zp,Wav2Vec2BertModel:()=>Dp,Wav2Vec2BertPreTrainedModel:()=>xl,Wav2Vec2ForAudioFrameClassification:()=>xp,Wav2Vec2ForCTC:()=>bp,Wav2Vec2ForSequenceClassification:()=>vp,Wav2Vec2Model:()=>Mp,Wav2Vec2PreTrainedModel:()=>sn,WavLMForAudioFrameClassification:()=>Gp,WavLMForCTC:()=>Up,WavLMForSequenceClassification:()=>Vp,WavLMForXVector:()=>Wp,WavLMModel:()=>jp,WavLMPreTrainedModel:()=>gi,WeSpeakerResNetModel:()=>Cp,WeSpeakerResNetPreTrainedModel:()=>Pp,WhisperForConditionalGeneration:()=>Ii,WhisperModel:()=>Ta,WhisperPreTrainedModel:()=>Bn,XLMForQuestionAnswering:()=>wa,XLMForSequenceClassification:()=>ga,XLMForTokenClassification:()=>Si,XLMModel:()=>Js,XLMPreTrainedModel:()=>ir,XLMRobertaForMaskedLM:()=>Ma,XLMRobertaForQuestionAnswering:()=>$i,XLMRobertaForSequenceClassification:()=>_n,XLMRobertaForTokenClassification:()=>ba,XLMRobertaModel:()=>ya,XLMRobertaPreTrainedModel:()=>ds,XLMWithLMHeadModel:()=>Ys,XVectorOutput:()=>Ym,YolosForObjectDetection:()=>up,YolosModel:()=>cp,YolosObjectDetectionOutput:()=>pp,YolosPreTrainedModel:()=>xd});var s=t("./src/configs.js"),i=t("./src/backends/onnx.js"),n=t("./src/utils/dtypes.js"),o=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/hub.js"),d=t("./src/utils/constants.js"),p=t("./src/generation/logits_process.js"),u=t("./src/generation/configuration_utils.js"),h=t("./src/utils/tensor.js"),w=t("./src/utils/image.js"),_=t("./src/utils/maths.js"),P=t("./src/generation/stopping_criteria.js"),A=t("./src/generation/logits_sampler.js"),v=t("./src/env.js"),y=t("./src/models/whisper/generation_whisper.js"),S=t("./src/models/whisper/common_whisper.js");const x={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,MaskGeneration:5,ImageTextToText:6,Musicgen:7,MultiModality:8,Phi3V:9,AudioTextToText:10,AutoEncoder:11},g=new Map,M=new Map,E=new Map;async function k(T,$,L){var wr;const oe=((wr=L.config)==null?void 0:wr["transformers.js_config"])??{};let _e=L.device??oe.device;_e&&typeof _e!="string"&&(_e.hasOwnProperty($)?_e=_e[$]:(console.warn(`device not specified for "${$}". Using the default device.`),_e=null));const me=_e??(v.apis.IS_NODE_ENV?"cpu":"wasm"),Se=(0,i.deviceToExecutionProviders)(me);let De=L.dtype??oe.dtype;if(typeof De!="string"&&(De&&De.hasOwnProperty($)?De=De[$]:(De=n.DEFAULT_DEVICE_DTYPE_MAPPING[me]??n.DATA_TYPES.fp32,console.warn(`dtype not specified for "${$}". Using the default dtype (${De}) for this device (${me}).`))),De===n.DATA_TYPES.auto){let Pt=oe.dtype;typeof Pt!="string"&&(Pt=Pt[$]),Pt&&Pt!==n.DATA_TYPES.auto&&n.DATA_TYPES.hasOwnProperty(Pt)?De=Pt:De=n.DEFAULT_DEVICE_DTYPE_MAPPING[me]??n.DATA_TYPES.fp32}const Ge=De;if(n.DEFAULT_DTYPE_SUFFIX_MAPPING.hasOwnProperty(Ge)){if(Ge===n.DATA_TYPES.fp16&&me==="webgpu"&&!await(0,n.isWebGpuFp16Supported)())throw new Error(`The device (${me}) does not support fp16.`)}else throw new Error(`Invalid dtype: ${Ge}. Should be one of: ${Object.keys(n.DATA_TYPES).join(", ")}`);const Je=oe.kv_cache_dtype?typeof oe.kv_cache_dtype=="string"?oe.kv_cache_dtype:oe.kv_cache_dtype[Ge]??"float32":void 0;if(Je&&!["float32","float16"].includes(Je))throw new Error(`Invalid kv_cache_dtype: ${Je}. Should be one of: float32, float16`);const lt={dtype:Ge,kv_cache_dtype:Je},wt=n.DEFAULT_DTYPE_SUFFIX_MAPPING[Ge],st=`${$}${wt}.onnx`,Et=`${L.subfolder??""}/${st}`,at={...L.session_options};at.executionProviders??(at.executionProviders=Se);const bt=oe.free_dimension_overrides;bt?at.freeDimensionOverrides??(at.freeDimensionOverrides=bt):me.startsWith("webnn")&&!at.freeDimensionOverrides&&console.warn('WebNN does not currently support dynamic shapes and requires `free_dimension_overrides` to be set in config.json as a field within "transformers.js_config". When `free_dimension_overrides` is not set, you may experience significant performance degradation.');const ut=(0,l.getModelFile)(T,Et,!0,L,v.apis.IS_NODE_ENV),Tt=L.use_external_data_format??oe.use_external_data_format;let Dt=[];if(Tt){let Pt;typeof Tt=="object"?Tt.hasOwnProperty(st)?Pt=Tt[st]:Tt.hasOwnProperty($)?Pt=Tt[$]:Pt=!1:Pt=Tt;const Nt=+Pt;if(Nt>l.MAX_EXTERNAL_DATA_CHUNKS)throw new Error(`The number of external data chunks (${Nt}) exceeds the maximum allowed value (${l.MAX_EXTERNAL_DATA_CHUNKS}).`);for(let er=0;er{const Pr=await(0,l.getModelFile)(T,Nr,!0,L,v.apis.IS_NODE_ENV);nn(Pr instanceof Uint8Array?{path:sr,data:Pr}:sr)}))}}else at.externalData!==void 0&&(Dt=at.externalData.map(async Pt=>{if(typeof Pt.data=="string"){const Nt=await(0,l.getModelFile)(T,Pt.data,!0,L);return{...Pt,data:Nt}}return Pt}));if(Dt.length>0){const Pt=await Promise.all(Dt);v.apis.IS_NODE_ENV||(at.externalData=Pt)}if(me==="webgpu"){const Pt=(0,s.getKeyValueShapes)(L.config,{prefix:"present"});if(Object.keys(Pt).length>0&&!(0,i.isONNXProxy)()){const Nt={};for(const er in Pt)Nt[er]="gpu-buffer";at.preferredOutputLocation=Nt}}return{buffer_or_path:await ut,session_options:at,session_config:lt}}async function B(T,$,L){return Object.fromEntries(await Promise.all(Object.keys($).map(async oe=>{const{buffer_or_path:_e,session_options:me,session_config:Se}=await k(T,$[oe],L),De=await(0,i.createInferenceSession)(_e,me,Se);return[oe,De]})))}async function R(T,$,L){return Object.fromEntries(await Promise.all(Object.keys($).map(async oe=>{const _e=await(0,l.getModelJSON)(T,$[oe],!1,L);return[oe,_e]})))}function J(T,$){const L=Object.create(null),oe=[];for(const Se of T.inputNames){const De=$[Se];if(!(De instanceof h.Tensor)){oe.push(Se);continue}L[Se]=(0,i.isONNXProxy)()?De.clone():De}if(oe.length>0)throw new Error(`An error occurred during model execution: "Missing the following inputs: ${oe.join(", ")}.`);const _e=Object.keys($).length,me=T.inputNames.length;if(_e>me){let Se=Object.keys($).filter(De=>!T.inputNames.includes(De));console.warn(`WARNING: Too many inputs were provided (${_e} > ${me}). The following inputs will be ignored: "${Se.join(", ")}".`)}return L}async function q(T,$){const L=J(T,$);try{const oe=Object.fromEntries(Object.entries(L).map(([me,Se])=>[me,Se.ort_tensor]));let _e=await T.run(oe);return _e=V(_e),_e}catch(oe){const _e=Object.fromEntries(Object.entries(L).map(([me,{type:Se,dims:De,data:Ge}])=>[me,{type:Se,dims:De,data:Ge}]));throw console.error(`An error occurred during model execution: "${oe}".`),console.error("Inputs given to model:",_e),oe}}function V(T){for(let $ in T)(0,i.isONNXTensor)(T[$])?T[$]=new h.Tensor(T[$]):typeof T[$]=="object"&&V(T[$]);return T}function Y(T){if(T instanceof h.Tensor)return T;if(T.length===0)throw Error("items must be non-empty");if(Array.isArray(T[0])){if(T.some($=>$.length!==T[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(T.flat().map($=>BigInt($))),[T.length,T[0].length])}else return new h.Tensor("int64",BigInt64Array.from(T.map($=>BigInt($))),[1,T.length])}function H(T){return new h.Tensor("bool",[T],[1])}async function Q(T,$){let{encoder_outputs:L,input_ids:oe,decoder_input_ids:_e,...me}=$;if(!L){const De=(0,a.pick)($,T.sessions.model.inputNames);L=(await ie(T,De)).last_hidden_state}return me.input_ids=_e,me.encoder_hidden_states=L,T.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask")&&(me.encoder_attention_mask=$.attention_mask),await ae(T,me,!0)}async function ie(T,$){const L=T.sessions.model,oe=(0,a.pick)($,L.inputNames);if(L.inputNames.includes("inputs_embeds")&&!oe.inputs_embeds){if(!$.input_ids)throw new Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");oe.inputs_embeds=await T.encode_text({input_ids:$.input_ids})}if(L.inputNames.includes("token_type_ids")&&!oe.token_type_ids){if(!oe.input_ids)throw new Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");oe.token_type_ids=(0,h.zeros_like)(oe.input_ids)}if(L.inputNames.includes("pixel_mask")&&!oe.pixel_mask){if(!oe.pixel_values)throw new Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");const _e=oe.pixel_values.dims;oe.pixel_mask=(0,h.ones)([_e[0],_e[2],_e[3]])}return await q(L,oe)}async function le(T,$){const L=await T.encode($);return await T.decode(L)}async function ae(T,$,L=!1){const oe=T.sessions[L?"decoder_model_merged":"model"],{past_key_values:_e,...me}=$;if(oe.inputNames.includes("use_cache_branch")&&(me.use_cache_branch=H(!!_e)),oe.inputNames.includes("position_ids")&&me.attention_mask&&!me.position_ids){const De=T.config.model_type==="paligemma"?1:0;me.position_ids=fe(me,_e,De)}T.addPastKeyValues(me,_e);const Se=(0,a.pick)(me,oe.inputNames);return await q(oe,Se)}function ge({modality_token_id:T,inputs_embeds:$,modality_features:L,input_ids:oe,attention_mask:_e}){const me=oe.tolist().map(Je=>Je.reduce((lt,wt,st)=>(wt==T&<.push(st),lt),[])),Se=me.reduce((Je,lt)=>Je+lt.length,0),De=L.dims[0];if(Se!==De)throw new Error(`Number of tokens and features do not match: tokens: ${Se}, features ${De}`);let Ge=0;for(let Je=0;Jeme.dims[1])){if(_eDe==T.config.image_token_index)){const De=T.config.num_image_tokens;if(!De)throw new Error("`num_image_tokens` is missing in the model configuration.");const Ge=me.dims[1]-(_e-De);L.input_ids=me.slice(null,[-Ge,null]),L.attention_mask=(0,h.ones)([1,_e+Ge])}}}return L}function He(T,$,L,oe){return L.past_key_values&&($=$.map(_e=>[_e.at(-1)])),{...L,decoder_input_ids:Y($)}}function Me(T,...$){return T.config.is_encoder_decoder?He(T,...$):ke(T,...$)}function K(T,$,L,oe){const _e=!!L.past_key_values;return oe.guidance_scale!==null&&oe.guidance_scale>1&&(_e?L.input_ids=(0,h.cat)([L.input_ids,L.input_ids],0):(L.input_ids=(0,h.cat)([L.input_ids,(0,h.full_like)(L.input_ids,BigInt(oe.pad_token_id))],0),L.attention_mask=(0,h.cat)([L.attention_mask,(0,h.full_like)(L.attention_mask,0n)],0))),(_e||!L.pixel_values)&&(L.pixel_values=(0,h.full)([0,0,3,384,384],1)),_e&&(L.images_seq_mask=new h.Tensor("bool",new Array(1).fill(!0).fill(!1,0,1),[1,1]),L.images_emb_mask=new h.Tensor("bool",new Array(0).fill(!1),[1,1,0])),L}class U extends o.Callable{constructor(L,oe,_e){super();re(this,"main_input_name","input_ids");re(this,"forward_params",["input_ids","attention_mask"]);this.config=L,this.sessions=oe,this.configs=_e;const me=E.get(this.constructor),Se=g.get(me);switch(this.can_generate=!1,this._forward=null,this._prepare_inputs_for_generation=null,Se){case x.DecoderOnly:this.can_generate=!0,this._forward=ae,this._prepare_inputs_for_generation=ke;break;case x.Seq2Seq:case x.Vision2Seq:case x.Musicgen:this.can_generate=!0,this._forward=Q,this._prepare_inputs_for_generation=He;break;case x.EncoderDecoder:this._forward=Q;break;case x.ImageTextToText:this.can_generate=!0,this._forward=X,this._prepare_inputs_for_generation=Me;break;case x.AudioTextToText:this.can_generate=!0,this._forward=ne,this._prepare_inputs_for_generation=Me;break;case x.Phi3V:this.can_generate=!0,this._prepare_inputs_for_generation=Me;break;case x.MultiModality:this.can_generate=!0,this._prepare_inputs_for_generation=K;break;case x.AutoEncoder:this._forward=le;break;default:this._forward=ie;break}this.can_generate&&this.forward_params.push("past_key_values"),this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){var oe;const L=[];for(const _e of Object.values(this.sessions))(oe=_e==null?void 0:_e.handler)!=null&&oe.dispose&&L.push(_e.handler.dispose());return await Promise.all(L)}static async from_pretrained(L,{progress_callback:oe=null,config:_e=null,cache_dir:me=null,local_files_only:Se=!1,revision:De="main",model_file_name:Ge=null,subfolder:Je="onnx",device:lt=null,dtype:wt=null,use_external_data_format:st=null,session_options:Et={}}={}){let at={progress_callback:oe,config:_e,cache_dir:me,local_files_only:Se,revision:De,model_file_name:Ge,subfolder:Je,device:lt,dtype:wt,use_external_data_format:st,session_options:Et};const bt=E.get(this),ut=g.get(bt);_e=at.config=await s.AutoConfig.from_pretrained(L,at);let Tt;if(ut===x.DecoderOnly)Tt=await Promise.all([B(L,{model:at.model_file_name??"model"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===x.Seq2Seq||ut===x.Vision2Seq)Tt=await Promise.all([B(L,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===x.MaskGeneration)Tt=await Promise.all([B(L,{model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"},at)]);else if(ut===x.EncoderDecoder)Tt=await Promise.all([B(L,{model:"encoder_model",decoder_model_merged:"decoder_model_merged"},at)]);else if(ut===x.ImageTextToText){const Dt={embed_tokens:"embed_tokens",vision_encoder:"vision_encoder",decoder_model_merged:"decoder_model_merged"};_e.is_encoder_decoder&&(Dt.model="encoder_model"),Tt=await Promise.all([B(L,Dt,at),R(L,{generation_config:"generation_config.json"},at)])}else if(ut===x.AudioTextToText){const Dt={embed_tokens:"embed_tokens",audio_encoder:"audio_encoder",decoder_model_merged:"decoder_model_merged"};Tt=await Promise.all([B(L,Dt,at),R(L,{generation_config:"generation_config.json"},at)])}else if(ut===x.Musicgen)Tt=await Promise.all([B(L,{model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===x.MultiModality)Tt=await Promise.all([B(L,{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"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===x.Phi3V)Tt=await Promise.all([B(L,{prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"},at),R(L,{generation_config:"generation_config.json"},at)]);else if(ut===x.AutoEncoder)Tt=await Promise.all([B(L,{encoder_model:"encoder_model",decoder_model:"decoder_model"},at)]);else{if(ut!==x.EncoderOnly){const Dt=bt??(_e==null?void 0:_e.model_type);Dt!=="custom"&&console.warn(`Model type for '${Dt}' not found, assuming encoder-only architecture. Please report this at ${d.GITHUB_ISSUE_URL}.`)}Tt=await Promise.all([B(L,{model:at.model_file_name??"model"},at)])}return new this(_e,...Tt)}async _call(L){return await this.forward(L)}async forward(L){return await this._forward(this,L)}get generation_config(){var L;return((L=this.configs)==null?void 0:L.generation_config)??null}_get_logits_warper(L){const oe=new p.LogitsProcessorList;return L.temperature!==null&&L.temperature!==1&&oe.push(new p.TemperatureLogitsWarper(L.temperature)),L.top_k!==null&&L.top_k!==0&&oe.push(new p.TopKLogitsWarper(L.top_k)),L.top_p!==null&&L.top_p<1&&oe.push(new p.TopPLogitsWarper(L.top_p)),oe}_get_logits_processor(L,oe,_e=null){const me=new p.LogitsProcessorList;if(L.repetition_penalty!==null&&L.repetition_penalty!==1&&me.push(new p.RepetitionPenaltyLogitsProcessor(L.repetition_penalty)),L.no_repeat_ngram_size!==null&&L.no_repeat_ngram_size>0&&me.push(new p.NoRepeatNGramLogitsProcessor(L.no_repeat_ngram_size)),L.bad_words_ids!==null&&me.push(new p.NoBadWordsLogitsProcessor(L.bad_words_ids,L.eos_token_id)),L.min_length!==null&&L.eos_token_id!==null&&L.min_length>0&&me.push(new p.MinLengthLogitsProcessor(L.min_length,L.eos_token_id)),L.min_new_tokens!==null&&L.eos_token_id!==null&&L.min_new_tokens>0&&me.push(new p.MinNewTokensLengthLogitsProcessor(oe,L.min_new_tokens,L.eos_token_id)),L.forced_bos_token_id!==null&&me.push(new p.ForcedBOSTokenLogitsProcessor(L.forced_bos_token_id)),L.forced_eos_token_id!==null&&me.push(new p.ForcedEOSTokenLogitsProcessor(L.max_length,L.forced_eos_token_id)),L.begin_suppress_tokens!==null){const Se=oe>1||L.forced_bos_token_id===null?oe:oe+1;me.push(new p.SuppressTokensAtBeginLogitsProcessor(L.begin_suppress_tokens,Se))}return L.guidance_scale!==null&&L.guidance_scale>1&&me.push(new p.ClassifierFreeGuidanceLogitsProcessor(L.guidance_scale)),_e!==null&&me.extend(_e),me}_prepare_generation_config(L,oe,_e=u.GenerationConfig){const me={...this.config};for(const De of["decoder","generator","text_config"])De in me&&Object.assign(me,me[De]);const Se=new _e(me);return Object.assign(Se,this.generation_config??{}),L&&Object.assign(Se,L),oe&&Object.assign(Se,(0,a.pick)(oe,Object.getOwnPropertyNames(Se))),Se}_get_stopping_criteria(L,oe=null){const _e=new P.StoppingCriteriaList;return L.max_length!==null&&_e.push(new P.MaxLengthCriteria(L.max_length,this.config.max_position_embeddings??null)),L.eos_token_id!==null&&_e.push(new P.EosTokenCriteria(L.eos_token_id)),oe&&_e.extend(oe),_e}_validate_model_class(){if(!this.can_generate){const L=[Rd,Nd,Bd,zd],oe=E.get(this.constructor),_e=new Set,me=this.config.model_type;for(const De of L){const Ge=De.get(me);Ge&&_e.add(Ge[0])}let Se=`The current model class (${oe}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw _e.size>0&&(Se+=` Please use the following class instead: ${[..._e].join(", ")}`),Error(Se)}}prepare_inputs_for_generation(...L){return this._prepare_inputs_for_generation(this,...L)}_update_model_kwargs_for_generation({generated_input_ids:L,outputs:oe,model_inputs:_e,is_encoder_decoder:me}){return _e.past_key_values=this.getPastKeyValues(oe,_e.past_key_values),_e.input_ids=new h.Tensor("int64",L.flat(),[L.length,1]),me||(_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:L,bos_token_id:oe,model_kwargs:_e}){const me=(0,a.pick)(_e,this.forward_params),Se=this.main_input_name;if(Se in me){if(L)throw new Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else me[Se]=L;return{inputs_tensor:me[Se],model_inputs:me,model_input_name:Se}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:L,model_inputs:oe,model_input_name:_e,generation_config:me}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!oe.inputs_embeds&&"_prepare_inputs_embeds"in this){const{input_ids:De,pixel_values:Ge,attention_mask:Je,...lt}=oe,wt=await this._prepare_inputs_embeds(oe);oe={...lt,...(0,a.pick)(wt,["inputs_embeds","attention_mask"])}}let{last_hidden_state:Se}=await ie(this,oe);if(me.guidance_scale!==null&&me.guidance_scale>1)Se=(0,h.cat)([Se,(0,h.full_like)(Se,0)],0),"attention_mask"in oe&&(oe.attention_mask=(0,h.cat)([oe.attention_mask,(0,h.zeros_like)(oe.attention_mask)],0));else if(oe.decoder_input_ids){const De=Y(oe.decoder_input_ids).dims[0];if(De!==Se.dims[0]){if(Se.dims[0]!==1)throw new Error(`The encoder outputs have a different batch size (${Se.dims[0]}) than the decoder inputs (${De}).`);Se=(0,h.cat)(Array.from({length:De},()=>Se),0)}}return oe.encoder_outputs=Se,oe}_prepare_decoder_input_ids_for_generation({batch_size:L,model_input_name:oe,model_kwargs:_e,decoder_start_token_id:me,bos_token_id:Se,generation_config:De}){let{decoder_input_ids:Ge,...Je}=_e;if(!(Ge instanceof h.Tensor)){if(Ge)Array.isArray(Ge[0])||(Ge=Array.from({length:L},()=>Ge));else if(me??(me=Se),this.config.model_type==="musicgen")Ge=Array.from({length:L*this.config.decoder.num_codebooks},()=>[me]);else if(Array.isArray(me)){if(me.length!==L)throw new Error(`\`decoder_start_token_id\` expcted to have length ${L} but got ${me.length}`);Ge=me}else Ge=Array.from({length:L},()=>[me]);Ge=Y(Ge)}return _e.decoder_attention_mask=(0,h.ones_like)(Ge),{input_ids:Ge,model_inputs:Je}}async generate({inputs:L=null,generation_config:oe=null,logits_processor:_e=null,stopping_criteria:me=null,streamer:Se=null,...De}){this._validate_model_class(),oe=this._prepare_generation_config(oe,De);let{inputs_tensor:Ge,model_inputs:Je,model_input_name:lt}=this._prepare_model_inputs({inputs:L,model_kwargs:De});const wt=this.config.is_encoder_decoder;wt&&("encoder_outputs"in Je||(Je=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Ge,model_inputs:Je,model_input_name:lt,generation_config:oe})));let st;wt?{input_ids:st,model_inputs:Je}=this._prepare_decoder_input_ids_for_generation({batch_size:Je[lt].dims.at(0),model_input_name:lt,model_kwargs:Je,decoder_start_token_id:oe.decoder_start_token_id,bos_token_id:oe.bos_token_id,generation_config:oe}):st=Je[lt];let Et=st.dims.at(-1);oe.max_new_tokens!==null&&(oe.max_length=Et+oe.max_new_tokens);const at=this._get_logits_processor(oe,Et,_e),bt=this._get_stopping_criteria(oe,me),ut=Je[lt].dims.at(0),Tt=A.LogitsSampler.getSampler(oe),Dt=new Array(ut).fill(0),Qt=st.tolist();Se&&Se.put(Qt);let wr,Pt={};for(;;){if(Je=this.prepare_inputs_for_generation(Qt,Je,oe),wr=await this.forward(Je),oe.output_attentions&&oe.return_dict_in_generate){const Pr=this.getAttentions(wr);for(const Cs in Pr)Cs in Pt||(Pt[Cs]=[]),Pt[Cs].push(Pr[Cs])}const sr=wr.logits.slice(null,-1,null),Nr=at(Qt,sr),nn=[];for(let Pr=0;PrPr))break;Je=this._update_model_kwargs_for_generation({generated_input_ids:nn,outputs:wr,model_inputs:Je,is_encoder_decoder:wt})}Se&&Se.end();const Nt=this.getPastKeyValues(wr,Je.past_key_values,!0),er=new h.Tensor("int64",Qt.flat(),[Qt.length,Qt[0].length]);if(oe.return_dict_in_generate)return{sequences:er,past_key_values:Nt,...Pt};for(const sr of Object.values(wr))sr.location==="gpu-buffer"&&sr.dispose();return er}getPastKeyValues(L,oe,_e=!1){const me=Object.create(null);for(const Se in L)if(Se.startsWith("present")){const De=Se.replace("present","past_key_values"),Ge=Se.includes("encoder");if(Ge&&oe?me[De]=oe[De]:me[De]=L[Se],oe&&(!Ge||_e)){const Je=oe[De];Je.location==="gpu-buffer"&&Je.dispose()}}return me}getAttentions(L){const oe={};for(const _e of["cross_attentions","encoder_attentions","decoder_attentions"])for(const me in L)me.startsWith(_e)&&(_e in oe||(oe[_e]=[]),oe[_e].push(L[me]));return oe}addPastKeyValues(L,oe){var _e,me,Se;if(oe)Object.assign(L,oe);else{const De=this.sessions.decoder_model_merged??this.sessions.model,Ge=((_e=De==null?void 0:De.config)==null?void 0:_e.kv_cache_dtype)??"float32",Je=Ge==="float16"?new h.DataTypeMap.float16:[],lt=((Se=(me=L[this.main_input_name]??L.attention_mask)==null?void 0:me.dims)==null?void 0:Se[0])??1,wt=(0,s.getKeyValueShapes)(this.config,{batch_size:lt});for(const st in wt)L[st]=new h.Tensor(Ge,Je,wt[st])}}async encode_image({pixel_values:L}){const oe=(await q(this.sessions.vision_encoder,{pixel_values:L})).image_features;return this.config.num_image_tokens||(console.warn(`The number of image tokens was not set in the model configuration. Setting it to the number of features detected by the vision encoder (${oe.dims[1]}).`),this.config.num_image_tokens=oe.dims[1]),oe}async encode_text({input_ids:L}){return(await q(this.sessions.embed_tokens,{input_ids:L})).inputs_embeds}async encode_audio({audio_values:L}){return(await q(this.sessions.audio_encoder,{audio_values:L})).audio_features}}class pe{}class Pe extends pe{constructor({last_hidden_state:$,hidden_states:L=null,attentions:oe=null}){super(),this.last_hidden_state=$,this.hidden_states=L,this.attentions=oe}}class Ee extends U{}class Fe extends Ee{}class Ie extends Ee{async _call($){return new gr(await super._call($))}}class Le extends Ee{async _call($){return new yt(await super._call($))}}class Ne extends Ee{async _call($){return new cr(await super._call($))}}class Ve extends Ee{async _call($){return new Er(await super._call($))}}class D extends U{}class Z extends D{}class z extends D{async _call($){return new gr(await super._call($))}}class ee extends D{async _call($){return new yt(await super._call($))}}class ce extends D{async _call($){return new cr(await super._call($))}}class be extends U{}class ve extends be{}class Re extends U{}class Ae extends Re{}class Ue extends Re{async _call($){return new gr(await super._call($))}}class Qe extends Re{async _call($){return new yt(await super._call($))}}class Xe extends Re{async _call($){return new cr(await super._call($))}}class ct extends Re{async _call($){return new Er(await super._call($))}}class vt extends U{}class nr extends vt{}class jt extends vt{async _call($){return new gr(await super._call($))}}class ar extends vt{async _call($){return new yt(await super._call($))}}class Zr extends vt{async _call($){return new cr(await super._call($))}}class $s extends vt{async _call($){return new Er(await super._call($))}}class Fr extends U{}class es extends Fr{}class ks extends Fr{async _call($){return new gr(await super._call($))}}class zr extends Fr{async _call($){return new yt(await super._call($))}}class dt extends Fr{async _call($){return new cr(await super._call($))}}class Wr extends Fr{async _call($){return new Er(await super._call($))}}class Br extends U{}class ts extends Br{}class bs extends Br{async _call($){return new gr(await super._call($))}}class vs extends Br{async _call($){return new yt(await super._call($))}}class xs extends Br{async _call($){return new cr(await super._call($))}}class Is extends Br{async _call($){return new Er(await super._call($))}}class hr extends U{}class Be extends hr{}class et extends hr{async _call($){return new gr(await super._call($))}}class it extends hr{async _call($){return new yt(await super._call($))}}class rr extends hr{async _call($){return new cr(await super._call($))}}class zt extends hr{async _call($){return new Er(await super._call($))}}class Sr extends U{}class rs extends Sr{}class ss extends Sr{async _call($){return new gr(await super._call($))}}class Tr extends Sr{async _call($){return new yt(await super._call($))}}class ns extends Sr{async _call($){return new cr(await super._call($))}}class is extends Sr{async _call($){return new Er(await super._call($))}}class Gr extends U{}class Ts extends Gr{}class Ws extends Gr{async _call($){return new yt(await super._call($))}}class Gs extends Gr{async _call($){return new cr(await super._call($))}}class Ks extends Gr{async _call($){return new Er(await super._call($))}}class Hs extends Gr{async _call($){return new gr(await super._call($))}}class os extends U{}class qs extends os{}class Qs extends os{async _call($){return new gr(await super._call($))}}class Xs extends os{async _call($){return new yt(await super._call($))}}class Or extends os{async _call($){return new cr(await super._call($))}}class Es extends U{}class Mr extends Es{}class As extends Es{async _call($){return new gr(await super._call($))}}class Fs extends Es{async _call($){return new yt(await super._call($))}}class $r extends Es{async _call($){return new Er(await super._call($))}}class Kr extends U{}class pn extends Kr{}class Dr extends Kr{async _call($){return new gr(await super._call($))}}class hn extends Kr{async _call($){return new yt(await super._call($))}}class Os extends Kr{async _call($){return new cr(await super._call($))}}class kr extends Kr{async _call($){return new Er(await super._call($))}}class Hr extends U{}class lr extends Hr{}class mr extends Hr{async _call($){return new gr(await super._call($))}}class Ds extends Hr{async _call($){return new yt(await super._call($))}}class mn extends Hr{async _call($){return new Er(await super._call($))}}class Ps extends U{}class fn extends Ps{}class ue extends Ps{async _call($){return new yt(await super._call($))}}class F extends Ps{async _call($){return new Er(await super._call($))}}class j extends Ps{async _call($){return new gr(await super._call($))}}class te extends U{constructor(){super(...arguments);re(this,"forward_params",["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class de extends te{}class he extends te{}class Ce extends U{}class We extends Ce{}class qe extends Ce{}class Ke extends U{}class Ze extends Ke{}class pt extends Ke{}class Ct extends U{}class $t extends Ct{}class Vt extends Ct{}class At extends Ct{async _call($){return new yt(await super._call($))}}class Ut extends U{}class br extends Ut{}class fr extends Ut{}class qr extends Ut{async _call($){return new yt(await super._call($))}}class vr extends Ut{}class as extends U{}class Wt extends as{}class Yt extends as{}class _r extends U{}class Qr extends _r{}class ls extends _r{}class Ht extends U{}class dr extends Ht{}class Rt extends Ht{async _call($){return new gr(await super._call($))}}class Xt extends Ht{async _call($){return new yt(await super._call($))}}class qt extends Ht{async _call($){return new cr(await super._call($))}}class Zt extends Ht{async _call($){return new Er(await super._call($))}}class ir extends U{}class Js extends ir{}class Ys extends ir{async _call($){return new gr(await super._call($))}}class ga extends ir{async _call($){return new yt(await super._call($))}}class Si extends ir{async _call($){return new cr(await super._call($))}}class wa extends ir{async _call($){return new Er(await super._call($))}}class ds extends U{}class ya extends ds{}class Ma extends ds{async _call($){return new gr(await super._call($))}}class _n extends ds{async _call($){return new yt(await super._call($))}}class ba extends ds{async _call($){return new cr(await super._call($))}}class $i extends ds{async _call($){return new Er(await super._call($))}}class ki extends U{}class va extends ki{}class xa extends ki{}class Bn extends U{constructor(){super(...arguments);re(this,"requires_attention_mask",!1);re(this,"main_input_name","input_features");re(this,"forward_params",["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"])}}class Ta extends Bn{}class Ii extends Bn{_prepare_generation_config($,L){return super._prepare_generation_config($,L,y.WhisperGenerationConfig)}_retrieve_init_tokens($){const L=[$.decoder_start_token_id];let oe=$.language;const _e=$.task;if($.is_multilingual){oe||(console.warn("No language specified - defaulting to English (en)."),oe="en");const Se=`<|${(0,S.whisper_language_to_code)(oe)}|>`;L.push($.lang_to_id[Se]),L.push($.task_to_id[_e??"transcribe"])}else if(oe||_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!$.return_timestamps&&$.no_timestamps_token_id&&L.at(-1)!==$.no_timestamps_token_id?L.push($.no_timestamps_token_id):$.return_timestamps&&L.at(-1)===$.no_timestamps_token_id&&(console.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),L.pop()),L.filter(me=>me!=null)}async generate({inputs:$=null,generation_config:L=null,logits_processor:oe=null,stopping_criteria:_e=null,...me}){L=this._prepare_generation_config(L,me);const Se=me.decoder_input_ids??this._retrieve_init_tokens(L);if(L.return_timestamps&&(oe??(oe=new p.LogitsProcessorList),oe.push(new p.WhisperTimeStampLogitsProcessor(L,Se))),L.begin_suppress_tokens&&(oe??(oe=new p.LogitsProcessorList),oe.push(new p.SuppressTokensAtBeginLogitsProcessor(L.begin_suppress_tokens,Se.length))),L.return_token_timestamps){if(!L.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.");L.task==="translate"&&console.warn("Token-level timestamps may not be reliable for task 'translate'."),L.output_attentions=!0,L.return_dict_in_generate=!0}const De=await super.generate({inputs:$,generation_config:L,logits_processor:oe,decoder_input_ids:Se,...me});return L.return_token_timestamps&&(De.token_timestamps=this._extract_token_timestamps(De,L.alignment_heads,L.num_frames)),De}_extract_token_timestamps($,L,oe=null,_e=.02){if(!$.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`.");oe==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 me=this.config.median_filter_width;me===void 0&&(console.warn("Model config has no `median_filter_width`, using default value of 7."),me=7);const Se=$.cross_attentions,De=Array.from({length:this.config.decoder_layers},(bt,ut)=>(0,h.cat)(Se.map(Tt=>Tt[ut]),2)),Ge=(0,h.stack)(L.map(([bt,ut])=>{if(bt>=De.length)throw new Error(`Layer index ${bt} is out of bounds for cross attentions (length ${De.length}).`);return oe?De[bt].slice(null,ut,null,[0,oe]):De[bt].slice(null,ut)})).transpose(1,0,2,3),[Je,lt]=(0,h.std_mean)(Ge,-2,0,!0),wt=Ge.clone();for(let bt=0;btTt[er+1]-Tt[er]),wr=(0,a.mergeArrays)([1],Qt).map(Nt=>!!Nt),Pt=[];for(let Nt=0;Ntst.findIndex(Et=>Et==me)),Ge=De.every(st=>st===-1),Je=De.every(st=>st!==-1);if(!Ge&&!Je)throw new Error("Every input should contain either 0 or 1 image token.");if(Ge)return{inputs_embeds:$,attention_mask:_e};const lt=[],wt=[];for(let st=0;stArray.from({length:$.dims[0]},Qt=>Array.from({length:$.dims[1]},wr=>1))),at=L?L.tolist():[],bt=oe?oe.tolist():[];let ut=0,Tt=0;for(let Dt=0;Dtst[Dt][or]==1),Pt=Qt.reduce((Gt,or,on)=>(or==Ge&&Gt.push(on),Gt),[]).map(Gt=>Qt[Gt+1]),Nt=Pt.filter(Gt=>Gt==Se).length,er=Pt.filter(Gt=>Gt==De).length;let sr=[],Nr=0,nn=Nt,Fl=er;for(let Gt=0;Gtcs>Nr&&xn==Se),on=Qt.findIndex((xn,cs)=>cs>Nr&&xn==De),vn=nn>0&&or!==-1?or:Qt.length+1,yi=Fl>0&&on!==-1?on:Qt.length+1;let zl,Vd,Wd,Gd;vn0?(0,_.max)(sr.at(-1))[0]+1:0;sr.push(Array.from({length:3*Hd},(xn,cs)=>tf+cs%Hd));const qd=Hd+tf,Rl=jb*Kd*Bl,Ub=Array.from({length:Rl},(xn,cs)=>qd+Math.floor(cs/(Kd*Bl))),Vb=Array.from({length:Rl},(xn,cs)=>qd+Math.floor(cs/Bl)%Kd),Wb=Array.from({length:Rl},(xn,cs)=>qd+cs%Bl);sr.push([Ub,Vb,Wb].flat()),Nr=zl+Rl}if(Nr0?(0,_.max)(sr.at(-1))[0]+1:0,or=Qt.length-Nr;sr.push(Array.from({length:3*or},(on,vn)=>Gt+vn%or))}const Pr=sr.reduce((Gt,or)=>Gt+or.length,0),Cs=new Array(Pr);let Ud=0;for(let Gt=0;Gt<3;++Gt)for(let or=0;orwt[ut%wt.length]),at=Array.from({length:st[0]},(bt,ut)=>(0,_.max)(wt.subarray(st[1]*ut,st[1]*(ut+1)))[0]+1n+BigInt(st[1]));return[new h.Tensor("int64",Et,[3,...st]),new h.Tensor("int64",at,[at.length,1])]}else{const[wt,st]=$.dims,Et=BigInt64Array.from({length:3*wt*st},(at,bt)=>BigInt(Math.floor(bt%st/wt)));return[new h.Tensor("int64",Et,[3,...$.dims]),(0,h.zeros)([wt,1])]}}async encode_image({pixel_values:$,image_grid_thw:L}){return(await q(this.sessions.vision_encoder,{pixel_values:$,grid_thw:L})).image_features}_merge_input_ids_with_image_features($){return N({image_token_id:this.config.image_token_id,...$})}prepare_inputs_for_generation($,L,oe){if(L.attention_mask&&!L.position_ids)if(!L.past_key_values)[L.position_ids,L.rope_deltas]=this.get_rope_index(L.input_ids,L.image_grid_thw,L.video_grid_thw,L.attention_mask);else{L.pixel_values=null;const _e=BigInt(Object.values(L.past_key_values)[0].dims.at(-2)),me=L.rope_deltas.map(Se=>_e+Se);L.position_ids=(0,h.stack)([me,me,me],0)}return L}}class li extends U{}class wo extends li{}class yo extends li{}class di extends U{}class Mo extends di{}class bo extends di{}class ci extends U{}class vo extends ci{}class xo extends ci{}class ui extends U{}class To extends ui{}class Eo extends ui{}class pi extends U{}class Po extends pi{}class Co extends pi{}class hi extends U{}class So extends hi{}class $o extends hi{async _call($){return new yt(await super._call($))}}class mi extends U{}class ko extends mi{}class Io extends mi{async _call($){return new yt(await super._call($))}}class Ao extends U{}class Fo extends Ao{}class fi extends U{}class Oo extends fi{}class Do extends fi{async _call($){return new yt(await super._call($))}}class Wa extends U{}class Ga extends Wa{}class Lo extends U{}class Ka extends Lo{}class Ha extends Lo{async _call($){return new yt(await super._call($))}}class qa extends U{}class Qa extends qa{}class zo extends U{}class Xa extends zo{}class Ja extends zo{async _call($){return new yt(await super._call($))}}class Ya extends U{}class Za extends Ya{async _call($){return new Zm(await super._call($))}}class Bo extends U{}class el extends Bo{}class tl extends Bo{async _call($){return new yt(await super._call($))}}class Ro extends U{}class rl extends Ro{}class sl extends Ro{async _call($){return new yt(await super._call($))}}class No extends U{}class nl extends No{}class il extends No{}class jo extends U{}class ol extends jo{}class al extends jo{}class Uo extends U{}class ll extends Uo{}class dl extends Uo{async _call($){return new yt(await super._call($))}}class _i extends U{}class cl extends _i{}class ul extends _i{async _call($){return new Wo(await super._call($))}}class Vo extends _i{async _call($){return new pl(await super._call($))}}class Wo extends pe{constructor({logits:$,pred_boxes:L}){super(),this.logits=$,this.pred_boxes=L}}class pl extends pe{constructor({logits:$,pred_boxes:L,pred_masks:oe}){super(),this.logits=$,this.pred_boxes=L,this.pred_masks=oe}}class Go extends U{}class hl extends Go{}class ml extends Go{async _call($){return new fl(await super._call($))}}class fl extends pe{constructor({logits:$,pred_boxes:L}){super(),this.logits=$,this.pred_boxes=L}}class Ko extends U{}class _l extends Ko{}class gl extends Ko{async _call($){return new wl(await super._call($))}}class wl extends Wo{}class Ho extends U{}class yl extends Ho{}class Ml extends Ho{async _call($){return new yt(await super._call($))}}class qo extends U{}class Qo extends qo{}class c extends qo{async _call($){return new yt(await super._call($))}}class m extends U{}class b extends m{}class C extends m{async _call($){return new yt(await super._call($))}}class I extends U{}class W extends I{}class se extends I{async _call($){return new yt(await super._call($))}}class ye extends I{}class Te extends U{}class ze extends Te{}class Ye extends Te{}class ot extends U{}class gt extends ot{}class Bt extends ot{}class Ir extends U{}class rn extends Ir{}class bl extends U{}class Vu extends bl{}class Wu extends bl{}class Gu extends bl{}class Ku extends U{}class Hu extends Ku{}class gd extends U{}class qu extends gd{}class Qu extends gd{}class wd extends U{}class Xu extends wd{}class Ju extends wd{}class Yu extends U{}class Zu extends Yu{}class yd extends U{}class ep extends yd{}class tp extends yd{async _call($){return new yt(await super._call($))}}class Md extends U{}class rp extends Md{}class sp extends Md{async _call($){return new yt(await super._call($))}}class bd extends U{}class np extends bd{}class ip extends bd{async _call($){return new yt(await super._call($))}}class vd extends U{}class op extends vd{}class ap extends vd{async _call($){return new yt(await super._call($))}}class lp extends U{}class dp extends lp{}class xd extends U{}class cp extends xd{}class up extends xd{async _call($){return new pp(await super._call($))}}class pp extends pe{constructor({logits:$,pred_boxes:L}){super(),this.logits=$,this.pred_boxes=L}}class hp extends U{}class mp extends hp{async get_image_embeddings({pixel_values:$}){return await ie(this,{pixel_values:$})}async forward($){if((!$.image_embeddings||!$.image_positional_embeddings)&&($={...$,...await this.get_image_embeddings($)}),!$.input_labels&&$.input_points){const oe=$.input_points.dims.slice(0,-1),_e=oe.reduce((me,Se)=>me*Se,1);$.input_labels=new h.Tensor("int64",new BigInt64Array(_e).fill(1n),oe)}const L={image_embeddings:$.image_embeddings,image_positional_embeddings:$.image_positional_embeddings};return $.input_points&&(L.input_points=$.input_points),$.input_labels&&(L.input_labels=$.input_labels),$.input_boxes&&(L.input_boxes=$.input_boxes),await q(this.sessions.prompt_encoder_mask_decoder,L)}async _call($){return new fp(await super._call($))}}class fp extends pe{constructor({iou_scores:$,pred_masks:L}){super(),this.iou_scores=$,this.pred_masks=L}}class Td extends U{}class _p extends Td{}class gp extends Td{}class Ed extends U{}class wp extends Ed{}class yp extends Ed{}class sn extends U{}class Mp extends sn{}class bp extends sn{async _call($){return new bn(await super._call($))}}class vp extends sn{async _call($){return new yt(await super._call($))}}class xp extends sn{async _call($){return new cr(await super._call($))}}class Pd extends U{}class Tp extends Pd{}class Ep extends Pd{async _call($){return new cr(await super._call($))}}class Pp extends U{}class Cp extends Pp{}class vl extends U{}class Sp extends vl{}class $p extends vl{async _call($){return new bn(await super._call($))}}class kp extends vl{async _call($){return new yt(await super._call($))}}class Xo extends U{}class Ip extends Xo{}class Ap extends Xo{async _call($){return new bn(await super._call($))}}class Fp extends Xo{async _call($){return new yt(await super._call($))}}class Op extends Xo{async _call($){return new cr(await super._call($))}}class xl extends U{}class Dp extends xl{}class Lp extends xl{async _call($){return new bn(await super._call($))}}class zp extends xl{async _call($){return new yt(await super._call($))}}class Pb extends U{}class Bp extends sn{}class Rp extends sn{async _call($){return new bn(await super._call($))}}class Np extends sn{async _call($){return new yt(await super._call($))}}class gi extends U{}class jp extends gi{}class Up extends gi{async _call($){return new bn(await super._call($))}}class Vp extends gi{async _call($){return new yt(await super._call($))}}class Wp extends gi{async _call($){return new Ym(await super._call($))}}class Gp extends gi{async _call($){return new cr(await super._call($))}}class Kp extends U{}class Hp extends Kp{}class Tl extends U{}class Cb extends Tl{}class qp extends Tl{}class Qp extends Tl{async generate_speech($,L,{threshold:oe=.5,minlenratio:_e=0,maxlenratio:me=20,vocoder:Se=null}={}){const De={input_ids:$},{encoder_outputs:Ge,encoder_attention_mask:Je}=await ie(this,De),lt=Ge.dims[1]/this.config.reduction_factor,wt=Math.floor(lt*me),st=Math.floor(lt*_e),Et=this.config.num_mel_bins;let at=[],bt=null,ut=null,Tt=0;for(;;){++Tt;const wr=H(!!ut);let Pt;ut?Pt=ut.output_sequence_out:Pt=new h.Tensor("float32",new Float32Array(Et),[1,1,Et]);let Nt={use_cache_branch:wr,output_sequence:Pt,encoder_attention_mask:Je,speaker_embeddings:L,encoder_hidden_states:Ge};this.addPastKeyValues(Nt,bt),ut=await q(this.sessions.decoder_model_merged,Nt),bt=this.getPastKeyValues(ut,bt);const{prob:er,spectrum:sr}=ut;if(at.push(sr),Tt>=st&&(Array.from(er.data).filter(Nr=>Nr>=oe).length>0||Tt>=wt))break}const Dt=(0,h.cat)(at),{waveform:Qt}=await q(Se.sessions.model,{spectrogram:Dt});return{spectrogram:Dt,waveform:Qt}}}class Xp extends U{constructor(){super(...arguments);re(this,"main_input_name","spectrogram")}}class Jp extends U{}class Yp extends Jp{}class Cd extends U{}class Zp extends Cd{}class eh extends Cd{}class Sd extends U{}class th extends Sd{}class rh extends Sd{}class $d extends U{}class sh extends $d{}class nh extends $d{}class El extends U{}class ih extends El{}class oh extends El{static async from_pretrained($,L={}){return super.from_pretrained($,{...L,model_file_name:L.model_file_name??"text_model"})}}class ah extends El{static async from_pretrained($,L={}){return super.from_pretrained($,{...L,model_file_name:L.model_file_name??"audio_model"})}}class lh extends U{}class kd extends lh{async _call($){return new ef(await super._call($))}}class Pl extends U{}class Sb extends Pl{}class dh extends Pl{}class ch extends Pl{}class Id extends U{}class uh extends Id{}class ph extends Id{}class Ad extends U{}class hh extends Ad{}class mh extends Ad{async _call($){return new yt(await super._call($))}}class Fd extends U{}class $b extends Fd{}class kb extends Fd{}class Od extends U{constructor(){super(...arguments);re(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(L){const[oe,_e]=L.dims,me=this.config.decoder.num_codebooks,Se=_e-me;let De=0;for(let lt=0;lt0&&Et<=Se&&(L.data[De++]=L.data[lt])}const Ge=Math.floor(oe/me),Je=De/(Ge*me);return new h.Tensor(L.type,L.data.slice(0,De),[Ge,me,Je])}prepare_inputs_for_generation(L,oe,_e){let me=structuredClone(L);for(let De=0;De=Ge&&(me[De][Ge]=BigInt(this.config.decoder.pad_token_id));return _e.guidance_scale!==null&&_e.guidance_scale>1&&(me=me.concat(me)),super.prepare_inputs_for_generation(me,oe,_e)}async generate(L){const oe=await super.generate(L),_e=this._apply_and_filter_by_delay_pattern_mask(oe).unsqueeze_(0),{audio_values:me}=await q(this.sessions.encodec_decode,{audio_codes:_e});return me}}class Cl extends U{}class fh extends Cl{}class _h extends Cl{async _call($){return new yt(await super._call($))}}class gh extends Cl{}class Sl extends U{}class wh extends Sl{}class yh extends Sl{async _call($){return new yt(await super._call($))}}class Mh extends Sl{}class $l extends U{}class bh extends $l{}class vh extends $l{async _call($){return new yt(await super._call($))}}class xh extends $l{}class kl extends U{}class Th extends kl{}class Eh extends kl{async _call($){return new yt(await super._call($))}}class Ph extends kl{}class Ch extends U{}class Sh extends Ch{}class $h extends U{}class kh extends $h{constructor(...L){super(...L);re(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(L){const oe=this._generation_mode??"text";let _e;if(oe==="text"||!L.past_key_values){const Je=this.sessions.prepare_inputs_embeds,lt=(0,a.pick)(L,Je.inputNames);_e=await q(Je,lt)}else{const Je=this.sessions.gen_img_embeds,lt=(0,a.pick)({image_ids:L.input_ids},Je.inputNames);_e=await q(Je,lt)}const me={...L,..._e},Se=await ae(this,me),De=this.sessions[oe==="text"?"lm_head":"gen_head"];if(!De)throw new Error(`Unable to find "${De}" generation head`);const Ge=await q(De,(0,a.pick)(Se,De.inputNames));return{..._e,...Se,...Ge}}async generate(L){return this._generation_mode="text",super.generate(L)}async generate_images(L){this._generation_mode="image";const oe=(L.inputs??L[this.main_input_name]).dims[1],me=(await super.generate(L)).slice(null,[oe,null]),Se=this.sessions.image_decode,{decoded_image:De}=await q(Se,{generated_tokens:me}),Ge=De.add_(1).mul_(255/2).clamp_(0,255).to("uint8"),Je=[];for(const lt of Ge){const wt=w.RawImage.fromTensor(lt);Je.push(wt)}return Je}}class Ih extends pe{constructor({char_logits:$,bpe_logits:L,wp_logits:oe}){super(),this.char_logits=$,this.bpe_logits=L,this.wp_logits=oe}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}}class Ah extends U{}class Fh extends Ah{async _call($){return new Ih(await super._call($))}}class Dd extends U{}class Oh extends Dd{}class Dh extends Dd{}class Ld extends U{}class Lh extends Ld{}class zh extends Ld{}class Bh extends U{constructor(){super(...arguments);re(this,"forward_params",["input_ids","attention_mask","position_ids","audio_values","past_key_values"])}}class Rh extends Bh{_merge_input_ids_with_audio_features($){const L=$.audio_features.dims.at(-1),oe=$.audio_features.view(-1,L);return O({audio_token_id:this.config.ignore_index,...$,audio_features:oe})}}class Il extends U{constructor(){super(...arguments);re(this,"main_input_name","input_values");re(this,"forward_params",["input_values"])}}class Nh extends pe{constructor({audio_codes:$}){super(),this.audio_codes=$}}class jh extends pe{constructor({audio_values:$}){super(),this.audio_values=$}}class Uh extends Il{async encode($){return new Nh(await q(this.sessions.encoder_model,$))}async decode($){return new jh(await q(this.sessions.decoder_model,$))}}class Vh extends Il{static async from_pretrained($,L={}){return super.from_pretrained($,{...L,model_file_name:L.model_file_name??"encoder_model"})}}class Wh extends Il{static async from_pretrained($,L={}){return super.from_pretrained($,{...L,model_file_name:L.model_file_name??"decoder_model"})}}class Al extends U{constructor(){super(...arguments);re(this,"main_input_name","input_values");re(this,"forward_params",["input_values"])}}class Gh extends pe{constructor({audio_codes:$}){super(),this.audio_codes=$}}class Kh extends pe{constructor({audio_values:$}){super(),this.audio_values=$}}class Hh extends Al{async encode($){return new Gh(await q(this.sessions.encoder_model,$))}async decode($){return new Kh(await q(this.sessions.decoder_model,$))}}class qh extends Al{static async from_pretrained($,L={}){return super.from_pretrained($,{...L,model_file_name:L.model_file_name??"encoder_model"})}}class Qh extends Al{static async from_pretrained($,L={}){return super.from_pretrained($,{...L,model_file_name:L.model_file_name??"decoder_model"})}}class kt{static async from_pretrained($,{progress_callback:L=null,config:oe=null,cache_dir:_e=null,local_files_only:me=!1,revision:Se="main",model_file_name:De=null,subfolder:Ge="onnx",device:Je=null,dtype:lt=null,use_external_data_format:wt=null,session_options:st={}}={}){const Et={progress_callback:L,config:oe,cache_dir:_e,local_files_only:me,revision:Se,model_file_name:De,subfolder:Ge,device:Je,dtype:lt,use_external_data_format:wt,session_options:st};if(Et.config=await s.AutoConfig.from_pretrained($,Et),!this.MODEL_CLASS_MAPPINGS)throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);const at=Et.config.model_type;for(const bt of this.MODEL_CLASS_MAPPINGS){let ut=bt.get(at);if(!ut){for(const Tt of bt.values())if(Tt[0]===at){ut=Tt;break}if(!ut)continue}return await ut[1].from_pretrained($,Et)}if(this.BASE_IF_FAIL)return bm.has(at)||console.warn(`Unknown model class "${at}", attempting to construct from base class.`),await U.from_pretrained($,Et);throw Error(`Unsupported model type: ${at}`)}}re(kt,"MODEL_CLASS_MAPPINGS",null),re(kt,"BASE_IF_FAIL",!1);const Ib=new Map([["bert",["BertModel",Fe]],["modernbert",["ModernBertModel",Z]],["nomic_bert",["NomicBertModel",ve]],["roformer",["RoFormerModel",Ae]],["electra",["ElectraModel",es]],["esm",["EsmModel",qs]],["convbert",["ConvBertModel",nr]],["camembert",["CamembertModel",ts]],["deberta",["DebertaModel",Be]],["deberta-v2",["DebertaV2Model",rs]],["mpnet",["MPNetModel",pn]],["albert",["AlbertModel",fn]],["distilbert",["DistilBertModel",Ts]],["roberta",["RobertaModel",dr]],["xlm",["XLMModel",Js]],["xlm-roberta",["XLMRobertaModel",ya]],["clap",["ClapModel",ih]],["clip",["CLIPModel",Bi]],["clipseg",["CLIPSegModel",en]],["chinese_clip",["ChineseCLIPModel",za]],["siglip",["SiglipModel",Fa]],["jina_clip",["JinaCLIPModel",Ba]],["mobilebert",["MobileBertModel",Mr]],["squeezebert",["SqueezeBertModel",lr]],["wav2vec2",["Wav2Vec2Model",Mp]],["wav2vec2-bert",["Wav2Vec2BertModel",Dp]],["unispeech",["UniSpeechModel",Sp]],["unispeech-sat",["UniSpeechSatModel",Ip]],["hubert",["HubertModel",Bp]],["wavlm",["WavLMModel",jp]],["audio-spectrogram-transformer",["ASTModel",va]],["vits",["VitsModel",kd]],["pyannote",["PyAnnoteModel",Tp]],["wespeaker-resnet",["WeSpeakerResNetModel",Cp]],["detr",["DetrModel",cl]],["rt_detr",["RTDetrModel",hl]],["table-transformer",["TableTransformerModel",_l]],["vit",["ViTModel",So]],["ijepa",["IJepaModel",ko]],["pvt",["PvtModel",Oo]],["vit_msn",["ViTMSNModel",Ka]],["vit_mae",["ViTMAEModel",Ga]],["groupvit",["GroupViTModel",Qa]],["fastvit",["FastViTModel",Xa]],["mobilevit",["MobileViTModel",el]],["mobilevitv2",["MobileViTV2Model",rl]],["owlvit",["OwlViTModel",nl]],["owlv2",["Owlv2Model",ol]],["beit",["BeitModel",ll]],["deit",["DeiTModel",yl]],["hiera",["HieraModel",Qo]],["convnext",["ConvNextModel",ep]],["convnextv2",["ConvNextV2Model",rp]],["dinov2",["Dinov2Model",np]],["dinov2_with_registers",["Dinov2WithRegistersModel",op]],["resnet",["ResNetModel",b]],["swin",["SwinModel",W]],["swin2sr",["Swin2SRModel",ze]],["donut-swin",["DonutSwinModel",Zu]],["yolos",["YolosModel",cp]],["dpt",["DPTModel",gt]],["glpn",["GLPNModel",Xu]],["hifigan",["SpeechT5HifiGan",Xp]],["efficientnet",["EfficientNetModel",hh]],["decision_transformer",["DecisionTransformerModel",Sh]],["patchtst",["PatchTSTForPrediction",Oh]],["patchtsmixer",["PatchTSMixerForPrediction",Lh]],["mobilenet_v1",["MobileNetV1Model",fh]],["mobilenet_v2",["MobileNetV2Model",wh]],["mobilenet_v3",["MobileNetV3Model",bh]],["mobilenet_v4",["MobileNetV4Model",Th]],["maskformer",["MaskFormerModel",qu]],["mgp-str",["MgpstrForSceneTextRecognition",Fh]],["style_text_to_speech_2",["StyleTextToSpeech2Model",Hp]]]),Ab=new Map([["t5",["T5Model",de]],["longt5",["LongT5Model",We]],["mt5",["MT5Model",Ze]],["bart",["BartModel",$t]],["mbart",["MBartModel",br]],["marian",["MarianModel",_p]],["whisper",["WhisperModel",Ta]],["m2m_100",["M2M100Model",wp]],["blenderbot",["BlenderbotModel",Wt]],["blenderbot-small",["BlenderbotSmallModel",Qr]]]),Fb=new Map([["mimi",["MimiModel",Uh]],["dac",["DacModel",Hh]]]),Ob=new Map([["bloom",["BloomModel",vo]],["jais",["JAISModel",ji]],["gpt2",["GPT2Model",ja]],["gptj",["GPTJModel",Hi]],["gpt_bigcode",["GPTBigCodeModel",Va]],["gpt_neo",["GPTNeoModel",Vi]],["gpt_neox",["GPTNeoXModel",Ua]],["codegen",["CodeGenModel",yn]],["llama",["LlamaModel",Qn]],["exaone",["ExaoneModel",Yi]],["olmo",["OlmoModel",eo]],["olmo2",["Olmo2Model",ro]],["mobilellm",["MobileLLMModel",ft]],["granite",["GraniteModel",so]],["cohere",["CohereModel",io]],["gemma",["GemmaModel",ao]],["gemma2",["Gemma2Model",co]],["helium",["HeliumModel",Xi]],["glm",["GlmModel",Ji]],["openelm",["OpenELMModel",po]],["qwen2",["Qwen2Model",mo]],["phi",["PhiModel",wo]],["phi3",["Phi3Model",Mo]],["mpt",["MptModel",To]],["opt",["OPTModel",Po]],["mistral",["MistralModel",Zp]],["starcoder2",["Starcoder2Model",th]],["falcon",["FalconModel",sh]],["stablelm",["StableLmModel",uh]]]),zd=new Map([["speecht5",["SpeechT5ForSpeechToText",qp]],["whisper",["WhisperForConditionalGeneration",Ii]],["lite-whisper",["LiteWhisperForConditionalGeneration",Ea]],["moonshine",["MoonshineForConditionalGeneration",Pa]]]),Xh=new Map([["speecht5",["SpeechT5ForTextToSpeech",Qp]]]),Jh=new Map([["vits",["VitsModel",kd]],["musicgen",["MusicgenForConditionalGeneration",Od]]]),Yh=new Map([["bert",["BertForSequenceClassification",Le]],["modernbert",["ModernBertForSequenceClassification",ee]],["roformer",["RoFormerForSequenceClassification",Qe]],["electra",["ElectraForSequenceClassification",zr]],["esm",["EsmForSequenceClassification",Xs]],["convbert",["ConvBertForSequenceClassification",ar]],["camembert",["CamembertForSequenceClassification",vs]],["deberta",["DebertaForSequenceClassification",it]],["deberta-v2",["DebertaV2ForSequenceClassification",Tr]],["mpnet",["MPNetForSequenceClassification",hn]],["albert",["AlbertForSequenceClassification",ue]],["distilbert",["DistilBertForSequenceClassification",Ws]],["roberta",["RobertaForSequenceClassification",Xt]],["xlm",["XLMForSequenceClassification",ga]],["xlm-roberta",["XLMRobertaForSequenceClassification",_n]],["bart",["BartForSequenceClassification",At]],["mbart",["MBartForSequenceClassification",qr]],["mobilebert",["MobileBertForSequenceClassification",Fs]],["squeezebert",["SqueezeBertForSequenceClassification",Ds]]]),Zh=new Map([["bert",["BertForTokenClassification",Ne]],["modernbert",["ModernBertForTokenClassification",ce]],["roformer",["RoFormerForTokenClassification",Xe]],["electra",["ElectraForTokenClassification",dt]],["esm",["EsmForTokenClassification",Or]],["convbert",["ConvBertForTokenClassification",Zr]],["camembert",["CamembertForTokenClassification",xs]],["deberta",["DebertaForTokenClassification",rr]],["deberta-v2",["DebertaV2ForTokenClassification",ns]],["mpnet",["MPNetForTokenClassification",Os]],["distilbert",["DistilBertForTokenClassification",Gs]],["roberta",["RobertaForTokenClassification",qt]],["xlm",["XLMForTokenClassification",Si]],["xlm-roberta",["XLMRobertaForTokenClassification",ba]]]),Bd=new Map([["t5",["T5ForConditionalGeneration",he]],["longt5",["LongT5ForConditionalGeneration",qe]],["mt5",["MT5ForConditionalGeneration",pt]],["bart",["BartForConditionalGeneration",Vt]],["mbart",["MBartForConditionalGeneration",fr]],["marian",["MarianMTModel",gp]],["m2m_100",["M2M100ForConditionalGeneration",yp]],["blenderbot",["BlenderbotForConditionalGeneration",Yt]],["blenderbot-small",["BlenderbotSmallForConditionalGeneration",ls]]]),Rd=new Map([["bloom",["BloomForCausalLM",xo]],["gpt2",["GPT2LMHeadModel",Gn]],["jais",["JAISLMHeadModel",Ui]],["gptj",["GPTJForCausalLM",wn]],["gpt_bigcode",["GPTBigCodeForCausalLM",qi]],["gpt_neo",["GPTNeoForCausalLM",Wi]],["gpt_neox",["GPTNeoXForCausalLM",Gi]],["codegen",["CodeGenForCausalLM",Rr]],["llama",["LlamaForCausalLM",Qi]],["exaone",["ExaoneForCausalLM",ht]],["olmo",["OlmoForCausalLM",to]],["olmo2",["Olmo2ForCausalLM",ti]],["mobilellm",["MobileLLMForCausalLM",Zi]],["granite",["GraniteForCausalLM",no]],["cohere",["CohereForCausalLM",oo]],["gemma",["GemmaForCausalLM",lo]],["gemma2",["Gemma2ForCausalLM",uo]],["helium",["HeliumForCausalLM",Jn]],["glm",["GlmForCausalLM",_t]],["openelm",["OpenELMForCausalLM",ho]],["qwen2",["Qwen2ForCausalLM",fo]],["phi",["PhiForCausalLM",yo]],["phi3",["Phi3ForCausalLM",bo]],["mpt",["MptForCausalLM",Eo]],["opt",["OPTForCausalLM",Co]],["mbart",["MBartForCausalLM",vr]],["mistral",["MistralForCausalLM",eh]],["starcoder2",["Starcoder2ForCausalLM",rh]],["falcon",["FalconForCausalLM",nh]],["trocr",["TrOCRForCausalLM",Yp]],["stablelm",["StableLmForCausalLM",ph]],["phi3_v",["Phi3VForCausalLM",Ls]]]),Db=new Map([["multi_modality",["MultiModalityCausalLM",kh]]]),em=new Map([["bert",["BertForMaskedLM",Ie]],["modernbert",["ModernBertForMaskedLM",z]],["roformer",["RoFormerForMaskedLM",Ue]],["electra",["ElectraForMaskedLM",ks]],["esm",["EsmForMaskedLM",Qs]],["convbert",["ConvBertForMaskedLM",jt]],["camembert",["CamembertForMaskedLM",bs]],["deberta",["DebertaForMaskedLM",et]],["deberta-v2",["DebertaV2ForMaskedLM",ss]],["mpnet",["MPNetForMaskedLM",Dr]],["albert",["AlbertForMaskedLM",j]],["distilbert",["DistilBertForMaskedLM",Hs]],["roberta",["RobertaForMaskedLM",Rt]],["xlm",["XLMWithLMHeadModel",Ys]],["xlm-roberta",["XLMRobertaForMaskedLM",Ma]],["mobilebert",["MobileBertForMaskedLM",As]],["squeezebert",["SqueezeBertForMaskedLM",mr]]]),tm=new Map([["bert",["BertForQuestionAnswering",Ve]],["roformer",["RoFormerForQuestionAnswering",ct]],["electra",["ElectraForQuestionAnswering",Wr]],["convbert",["ConvBertForQuestionAnswering",$s]],["camembert",["CamembertForQuestionAnswering",Is]],["deberta",["DebertaForQuestionAnswering",zt]],["deberta-v2",["DebertaV2ForQuestionAnswering",is]],["mpnet",["MPNetForQuestionAnswering",kr]],["albert",["AlbertForQuestionAnswering",F]],["distilbert",["DistilBertForQuestionAnswering",Ks]],["roberta",["RobertaForQuestionAnswering",Zt]],["xlm",["XLMForQuestionAnswering",wa]],["xlm-roberta",["XLMRobertaForQuestionAnswering",$i]],["mobilebert",["MobileBertForQuestionAnswering",$r]],["squeezebert",["SqueezeBertForQuestionAnswering",mn]]]),Nd=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Fi]],["idefics3",["Idefics3ForConditionalGeneration",Nn]],["smolvlm",["SmolVLMForConditionalGeneration",jn]]]),rm=new Map([["llava",["LlavaForConditionalGeneration",Rn]],["llava_onevision",["LlavaOnevisionForConditionalGeneration",Sa]],["moondream1",["Moondream1ForConditionalGeneration",$a]],["florence2",["Florence2ForConditionalGeneration",Oi]],["qwen2-vl",["Qwen2VLForConditionalGeneration",go]],["idefics3",["Idefics3ForConditionalGeneration",Nn]],["smolvlm",["SmolVLMForConditionalGeneration",jn]],["paligemma",["PaliGemmaForConditionalGeneration",Li]]]),sm=new Map([["ultravox",["UltravoxModel",Rh]]]),Lb=new Map([["vision-encoder-decoder",["VisionEncoderDecoderModel",Fi]]]),nm=new Map([["vit",["ViTForImageClassification",$o]],["ijepa",["IJepaForImageClassification",Io]],["pvt",["PvtForImageClassification",Do]],["vit_msn",["ViTMSNForImageClassification",Ha]],["fastvit",["FastViTForImageClassification",Ja]],["mobilevit",["MobileViTForImageClassification",tl]],["mobilevitv2",["MobileViTV2ForImageClassification",sl]],["beit",["BeitForImageClassification",dl]],["deit",["DeiTForImageClassification",Ml]],["hiera",["HieraForImageClassification",c]],["convnext",["ConvNextForImageClassification",tp]],["convnextv2",["ConvNextV2ForImageClassification",sp]],["dinov2",["Dinov2ForImageClassification",ip]],["dinov2_with_registers",["Dinov2WithRegistersForImageClassification",ap]],["resnet",["ResNetForImageClassification",C]],["swin",["SwinForImageClassification",se]],["segformer",["SegformerForImageClassification",dh]],["efficientnet",["EfficientNetForImageClassification",mh]],["mobilenet_v1",["MobileNetV1ForImageClassification",_h]],["mobilenet_v2",["MobileNetV2ForImageClassification",yh]],["mobilenet_v3",["MobileNetV3ForImageClassification",vh]],["mobilenet_v4",["MobileNetV4ForImageClassification",Eh]]]),im=new Map([["detr",["DetrForObjectDetection",ul]],["rt_detr",["RTDetrForObjectDetection",ml]],["table-transformer",["TableTransformerForObjectDetection",gl]],["yolos",["YolosForObjectDetection",up]]]),om=new Map([["owlvit",["OwlViTForObjectDetection",il]],["owlv2",["Owlv2ForObjectDetection",al]],["grounding-dino",["GroundingDinoForObjectDetection",dp]]]),wi=new Map([["detr",["DetrForSegmentation",Vo]],["clipseg",["CLIPSegForImageSegmentation",Ri]]]),am=new Map([["segformer",["SegformerForSemanticSegmentation",ch]],["sapiens",["SapiensForSemanticSegmentation",Vu]],["swin",["SwinForSemanticSegmentation",ye]],["mobilenet_v1",["MobileNetV1ForSemanticSegmentation",gh]],["mobilenet_v2",["MobileNetV2ForSemanticSegmentation",Mh]],["mobilenet_v3",["MobileNetV3ForSemanticSegmentation",xh]],["mobilenet_v4",["MobileNetV4ForSemanticSegmentation",Ph]]]),lm=new Map([["detr",["DetrForSegmentation",Vo]],["maskformer",["MaskFormerForInstanceSegmentation",Qu]]]),dm=new Map([["sam",["SamModel",mp]]]),cm=new Map([["wav2vec2",["Wav2Vec2ForCTC",bp]],["wav2vec2-bert",["Wav2Vec2BertForCTC",Lp]],["unispeech",["UniSpeechForCTC",$p]],["unispeech-sat",["UniSpeechSatForCTC",Ap]],["wavlm",["WavLMForCTC",Up]],["hubert",["HubertForCTC",Rp]]]),um=new Map([["wav2vec2",["Wav2Vec2ForSequenceClassification",vp]],["wav2vec2-bert",["Wav2Vec2BertForSequenceClassification",zp]],["unispeech",["UniSpeechForSequenceClassification",kp]],["unispeech-sat",["UniSpeechSatForSequenceClassification",Fp]],["wavlm",["WavLMForSequenceClassification",Vp]],["hubert",["HubertForSequenceClassification",Np]],["audio-spectrogram-transformer",["ASTForAudioClassification",xa]]]),pm=new Map([["wavlm",["WavLMForXVector",Wp]]]),hm=new Map([["unispeech-sat",["UniSpeechSatForAudioFrameClassification",Op]],["wavlm",["WavLMForAudioFrameClassification",Gp]],["wav2vec2",["Wav2Vec2ForAudioFrameClassification",xp]],["pyannote",["PyAnnoteForAudioFrameClassification",Ep]]]),mm=new Map([["vitmatte",["VitMatteForImageMatting",Za]]]),zb=new Map([["patchtst",["PatchTSTForPrediction",Dh]],["patchtsmixer",["PatchTSMixerForPrediction",zh]]]),fm=new Map([["swin2sr",["Swin2SRForImageSuperResolution",Ye]]]),_m=new Map([["dpt",["DPTForDepthEstimation",Bt]],["depth_anything",["DepthAnythingForDepthEstimation",rn]],["glpn",["GLPNForDepthEstimation",Ju]],["sapiens",["SapiensForDepthEstimation",Wu]],["depth_pro",["DepthProForDepthEstimation",Hu]]]),gm=new Map([["sapiens",["SapiensForNormalEstimation",Gu]]]),wm=new Map([["vitpose",["VitPoseForPoseEstimation",Fo]]]),ym=new Map([["clip",["CLIPVisionModelWithProjection",Un]],["siglip",["SiglipVisionModel",Da]],["jina_clip",["JinaCLIPVisionModel",Na]]]),Mm=[[Ib,x.EncoderOnly],[Ab,x.EncoderDecoder],[Ob,x.DecoderOnly],[Fb,x.AutoEncoder],[Yh,x.EncoderOnly],[Zh,x.EncoderOnly],[Bd,x.Seq2Seq],[zd,x.Seq2Seq],[Rd,x.DecoderOnly],[Db,x.MultiModality],[em,x.EncoderOnly],[tm,x.EncoderOnly],[Nd,x.Vision2Seq],[rm,x.ImageTextToText],[sm,x.AudioTextToText],[nm,x.EncoderOnly],[wi,x.EncoderOnly],[lm,x.EncoderOnly],[am,x.EncoderOnly],[mm,x.EncoderOnly],[zb,x.EncoderOnly],[fm,x.EncoderOnly],[_m,x.EncoderOnly],[gm,x.EncoderOnly],[wm,x.EncoderOnly],[im,x.EncoderOnly],[om,x.EncoderOnly],[dm,x.MaskGeneration],[cm,x.EncoderOnly],[um,x.EncoderOnly],[Xh,x.Seq2Seq],[Jh,x.EncoderOnly],[pm,x.EncoderOnly],[hm,x.EncoderOnly],[ym,x.EncoderOnly]];for(const[T,$]of Mm)for(const[L,oe]of T.values())g.set(L,$),E.set(oe,L),M.set(L,oe);const Bb=[["MusicgenForConditionalGeneration",Od,x.Musicgen],["Phi3VForCausalLM",Ls,x.Phi3V],["CLIPTextModelWithProjection",Aa,x.EncoderOnly],["SiglipTextModel",Oa,x.EncoderOnly],["JinaCLIPTextModel",Ra,x.EncoderOnly],["ClapTextModelWithProjection",oh,x.EncoderOnly],["ClapAudioModelWithProjection",ah,x.EncoderOnly],["DacEncoderModel",qh,x.EncoderOnly],["DacDecoderModel",Qh,x.EncoderOnly],["MimiEncoderModel",Vh,x.EncoderOnly],["MimiDecoderModel",Wh,x.EncoderOnly]];for(const[T,$,L]of Bb)g.set(T,L),E.set($,T),M.set(T,$);const bm=new Map([["modnet",wi],["birefnet",wi],["isnet",wi],["ben",wi]]);for(const[T,$]of bm.entries())$.set(T,["PreTrainedModel",U]),g.set(T,x.EncoderOnly),E.set(U,T),M.set(T,U);class jd extends kt{}re(jd,"MODEL_CLASS_MAPPINGS",Mm.map($=>$[0])),re(jd,"BASE_IF_FAIL",!0);class vm extends kt{}re(vm,"MODEL_CLASS_MAPPINGS",[Yh]);class xm extends kt{}re(xm,"MODEL_CLASS_MAPPINGS",[Zh]);class Tm extends kt{}re(Tm,"MODEL_CLASS_MAPPINGS",[Bd]);class Em extends kt{}re(Em,"MODEL_CLASS_MAPPINGS",[zd]);class Pm extends kt{}re(Pm,"MODEL_CLASS_MAPPINGS",[Xh]);class Cm extends kt{}re(Cm,"MODEL_CLASS_MAPPINGS",[Jh]);class Sm extends kt{}re(Sm,"MODEL_CLASS_MAPPINGS",[Rd]);class $m extends kt{}re($m,"MODEL_CLASS_MAPPINGS",[em]);class km extends kt{}re(km,"MODEL_CLASS_MAPPINGS",[tm]);class Im extends kt{}re(Im,"MODEL_CLASS_MAPPINGS",[Nd]);class Am extends kt{}re(Am,"MODEL_CLASS_MAPPINGS",[nm]);class Fm extends kt{}re(Fm,"MODEL_CLASS_MAPPINGS",[wi]);class Om extends kt{}re(Om,"MODEL_CLASS_MAPPINGS",[am]);class Dm extends kt{}re(Dm,"MODEL_CLASS_MAPPINGS",[lm]);class Lm extends kt{}re(Lm,"MODEL_CLASS_MAPPINGS",[im]);class zm extends kt{}re(zm,"MODEL_CLASS_MAPPINGS",[om]);class Bm extends kt{}re(Bm,"MODEL_CLASS_MAPPINGS",[dm]);class Rm extends kt{}re(Rm,"MODEL_CLASS_MAPPINGS",[cm]);class Nm extends kt{}re(Nm,"MODEL_CLASS_MAPPINGS",[um]);class jm extends kt{}re(jm,"MODEL_CLASS_MAPPINGS",[pm]);class Um extends kt{}re(Um,"MODEL_CLASS_MAPPINGS",[hm]);class Vm extends kt{}re(Vm,"MODEL_CLASS_MAPPINGS",[Lb]);class Wm extends kt{}re(Wm,"MODEL_CLASS_MAPPINGS",[mm]);class Gm extends kt{}re(Gm,"MODEL_CLASS_MAPPINGS",[fm]);class Km extends kt{}re(Km,"MODEL_CLASS_MAPPINGS",[_m]);class Hm extends kt{}re(Hm,"MODEL_CLASS_MAPPINGS",[gm]);class qm extends kt{}re(qm,"MODEL_CLASS_MAPPINGS",[wm]);class Qm extends kt{}re(Qm,"MODEL_CLASS_MAPPINGS",[ym]);class Xm extends kt{}re(Xm,"MODEL_CLASS_MAPPINGS",[rm]);class Jm extends kt{}re(Jm,"MODEL_CLASS_MAPPINGS",[sm]);class Rb extends pe{constructor({logits:$,past_key_values:L,encoder_outputs:oe,decoder_attentions:_e=null,cross_attentions:me=null}){super(),this.logits=$,this.past_key_values=L,this.encoder_outputs=oe,this.decoder_attentions=_e,this.cross_attentions=me}}class yt extends pe{constructor({logits:$,...L}){super(),this.logits=$;const oe=Object.values(L);oe.length>0&&(this.attentions=oe)}}class Ym extends pe{constructor({logits:$,embeddings:L}){super(),this.logits=$,this.embeddings=L}}class cr extends pe{constructor({logits:$}){super(),this.logits=$}}class gr extends pe{constructor({logits:$}){super(),this.logits=$}}class Er extends pe{constructor({start_logits:$,end_logits:L}){super(),this.start_logits=$,this.end_logits=L}}class bn extends pe{constructor({logits:$}){super(),this.logits=$}}class Nb extends pe{constructor({logits:$,past_key_values:L}){super(),this.logits=$,this.past_key_values=L}}class Zm extends pe{constructor({alphas:$}){super(),this.alphas=$}}class ef extends pe{constructor({waveform:$,spectrogram:L}){super(),this.waveform=$,this.spectrogram=L}}},"./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var i=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,d=(0,i.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);for(let p=0;p{t.r(r),t.d(r,{AutoFeatureExtractor:()=>o});var s=t("./src/utils/constants.js"),i=t("./src/utils/hub.js");t("./src/base/feature_extraction_utils.js");var n=t("./src/models/feature_extractors.js");class o{static async from_pretrained(l,d={}){const p=await(0,i.getModelJSON)(l,s.FEATURE_EXTRACTOR_NAME,!0,d),u=p.feature_extractor_type,h=n[u];if(!h)throw new Error(`Unknown feature_extractor_type: '${u}'. Please report this at ${s.GITHUB_ISSUE_URL}.`);return new h(p)}}},"./src/models/auto/image_processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoImageProcessor:()=>a});var s=t("./src/utils/constants.js"),i=t("./src/utils/hub.js"),n=t("./src/base/image_processors_utils.js"),o=t("./src/models/image_processors.js");class a{static async from_pretrained(d,p={}){const u=await(0,i.getModelJSON)(d,s.IMAGE_PROCESSOR_NAME,!0,p),h=u.image_processor_type??u.feature_extractor_type;let w=o[h];return w||(h!==void 0&&console.warn(`Image processor type '${h}' not found, assuming base ImageProcessor. Please report this at ${s.GITHUB_ISSUE_URL}.`),w=n.ImageProcessor),new w(u)}}},"./src/models/auto/processing_auto.js":(e,r,t)=>{t.r(r),t.d(r,{AutoProcessor:()=>d});var s=t("./src/utils/constants.js"),i=t("./src/utils/hub.js"),n=t("./src/base/processing_utils.js"),o=t("./src/models/processors.js"),a=t("./src/models/image_processors.js"),l=t("./src/models/feature_extractors.js");class d{static async from_pretrained(u,h={}){const w=await(0,i.getModelJSON)(u,s.IMAGE_PROCESSOR_NAME,!0,h),{image_processor_type:_,feature_extractor_type:P,processor_class:A}=w;if(A&&o[A])return o[A].from_pretrained(u,h);if(!_&&!P)throw new Error("No `image_processor_type` or `feature_extractor_type` found in the config.");const v={};if(_){const S=a[_];if(!S)throw new Error(`Unknown image_processor_type: '${_}'.`);v.image_processor=new S(w)}if(P){const S=a[P];if(S)v.image_processor=new S(w);else{const x=l[P];if(!x)throw new Error(`Unknown feature_extractor_type: '${P}'.`);v.feature_extractor=new x(w)}}const y={};return new n.Processor(y,v)}}},"./src/models/beit/image_processing_beit.js":(e,r,t)=>{t.r(r),t.d(r,{BeitFeatureExtractor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/bit/image_processing_bit.js":(e,r,t)=>{t.r(r),t.d(r,{BitImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/chinese_clip/image_processing_chinese_clip.js":(e,r,t)=>{t.r(r),t.d(r,{ChineseCLIPFeatureExtractor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/clap/feature_extraction_clap.js":(e,r,t)=>{t.r(r),t.d(r,{ClapFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var i=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a),this.mel_filters=(0,i.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,i.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,i.window_function)(this.config.fft_window_size,"hann")}async _get_input_mel(a,l,d,p){let u;const h=a.length-l;if(h>0)if(d==="rand_trunc"){const w=Math.floor(Math.random()*(h+1));a=a.subarray(w,w+l),u=await this._extract_fbank_features(a,this.mel_filters_slaney,this.config.nb_max_samples)}else throw new Error(`Truncation strategy "${d}" not implemented`);else{if(h<0){let w=new Float64Array(l);if(w.set(a),p==="repeat")for(let _=a.length;_{t.r(r),t.d(r,{CLIPFeatureExtractor:()=>n,CLIPImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/convnext/image_processing_convnext.js":(e,r,t)=>{t.r(r),t.d(r,{ConvNextFeatureExtractor:()=>n,ConvNextImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(a){super(a),this.crop_pct=this.config.crop_pct??224/256}async resize(a){var d;const l=(d=this.size)==null?void 0:d.shortest_edge;if(l===void 0)throw new Error("Size dictionary must contain 'shortest_edge' key.");if(l<384){const p=Math.floor(l/this.crop_pct),[u,h]=this.get_resize_output_image_size(a,{shortest_edge:p});a=await a.resize(u,h,{resample:this.resample}),a=await a.center_crop(l,l)}else a=await a.resize(l,l,{resample:this.resample});return a}}class n extends i{}},"./src/models/dac/feature_extraction_dac.js":(e,r,t)=>{t.r(r),t.d(r,{DacFeatureExtractor:()=>i});var s=t("./src/models/encodec/feature_extraction_encodec.js");class i extends s.EncodecFeatureExtractor{}},"./src/models/deit/image_processing_deit.js":(e,r,t)=>{t.r(r),t.d(r,{DeiTFeatureExtractor:()=>n,DeiTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/detr/image_processing_detr.js":(e,r,t)=>{t.r(r),t.d(r,{DetrFeatureExtractor:()=>o,DetrImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(l){const d=await super._call(l),p=[d.pixel_values.dims[0],64,64],u=(0,i.full)(p,1n);return{...d,pixel_mask:u}}post_process_object_detection(...l){return(0,s.post_process_object_detection)(...l)}post_process_panoptic_segmentation(...l){return(0,s.post_process_panoptic_segmentation)(...l)}post_process_instance_segmentation(...l){return(0,s.post_process_instance_segmentation)(...l)}}class o extends n{}},"./src/models/donut/image_processing_donut.js":(e,r,t)=>{t.r(r),t.d(r,{DonutFeatureExtractor:()=>n,DonutImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{pad_image(a,l,d,p={}){const[u,h,w]=l;let _=this.image_mean;Array.isArray(this.image_mean)||(_=new Array(w).fill(_));let P=this.image_std;Array.isArray(P)||(P=new Array(w).fill(_));const A=_.map((v,y)=>-v/P[y]);return super.pad_image(a,l,d,{center:!0,constant_values:A,...p})}}class n extends i{}},"./src/models/dpt/image_processing_dpt.js":(e,r,t)=>{t.r(r),t.d(r,{DPTFeatureExtractor:()=>n,DPTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/efficientnet/image_processing_efficientnet.js":(e,r,t)=>{t.r(r),t.d(r,{EfficientNetImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(o){super(o),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(a=>a*a))}}},"./src/models/encodec/feature_extraction_encodec.js":(e,r,t)=>{t.r(r),t.d(r,{EncodecFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"EncodecFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=this.config.feature_size;if(a.length%l!==0)throw new Error(`The length of the audio data must be a multiple of the number of channels (${l}).`);const d=[1,l,a.length/l];return{input_values:new i.Tensor("float32",a,d)}}}},"./src/models/feature_extractors.js":(e,r,t)=>{t.r(r),t.d(r,{ASTFeatureExtractor:()=>s.ASTFeatureExtractor,ClapFeatureExtractor:()=>n.ClapFeatureExtractor,DacFeatureExtractor:()=>o.DacFeatureExtractor,EncodecFeatureExtractor:()=>i.EncodecFeatureExtractor,ImageFeatureExtractor:()=>_.ImageProcessor,MoonshineFeatureExtractor:()=>a.MoonshineFeatureExtractor,PyAnnoteFeatureExtractor:()=>l.PyAnnoteFeatureExtractor,SeamlessM4TFeatureExtractor:()=>d.SeamlessM4TFeatureExtractor,SpeechT5FeatureExtractor:()=>p.SpeechT5FeatureExtractor,Wav2Vec2FeatureExtractor:()=>u.Wav2Vec2FeatureExtractor,WeSpeakerFeatureExtractor:()=>h.WeSpeakerFeatureExtractor,WhisperFeatureExtractor:()=>w.WhisperFeatureExtractor});var s=t("./src/models/audio_spectrogram_transformer/feature_extraction_audio_spectrogram_transformer.js"),i=t("./src/models/encodec/feature_extraction_encodec.js"),n=t("./src/models/clap/feature_extraction_clap.js"),o=t("./src/models/dac/feature_extraction_dac.js"),a=t("./src/models/moonshine/feature_extraction_moonshine.js"),l=t("./src/models/pyannote/feature_extraction_pyannote.js"),d=t("./src/models/seamless_m4t/feature_extraction_seamless_m4t.js"),p=t("./src/models/speecht5/feature_extraction_speecht5.js"),u=t("./src/models/wav2vec2/feature_extraction_wav2vec2.js"),h=t("./src/models/wespeaker/feature_extraction_wespeaker.js"),w=t("./src/models/whisper/feature_extraction_whisper.js"),_=t("./src/base/image_processors_utils.js")},"./src/models/florence2/processing_florence2.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class o extends s.Processor{constructor(l,d){super(l,d);const{tasks_answer_post_processing_type:p,task_prompts_without_inputs:u,task_prompts_with_input:h}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(p??{})),this.task_prompts_without_inputs=new Map(Object.entries(u??{})),this.task_prompts_with_input=new Map(Object.entries(h??{})),this.regexes={quad_boxes:/(.+?)/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(l){typeof l=="string"&&(l=[l]);const d=[];for(const p of l)if(this.task_prompts_without_inputs.has(p))d.push(this.task_prompts_without_inputs.get(p));else{for(const[u,h]of this.task_prompts_with_input)if(p.includes(u)){d.push(h.replaceAll("{input}",p).replaceAll(u,""));break}d.length!==l.length&&d.push(p)}return d}post_process_generation(l,d,p){const u=this.tasks_answer_post_processing_type.get(d)??"pure_text";l=l.replaceAll("","").replaceAll("","");let h;switch(u){case"pure_text":h=l;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":const w=u==="ocr"?"quad_boxes":"bboxes",_=l.matchAll(this.regexes[w]),P=[],A=[];for(const[v,y,...S]of _)P.push(y?y.trim():P.at(-1)??""),A.push(S.map((x,g)=>(Number(x)+.5)/this.size_per_bin*p[g%2]));h={labels:P,[w]:A};break;default:throw new Error(`Task "${d}" (of type "${u}") not yet implemented.`)}return{[d]:h}}async _call(l,d=null,p={}){if(!l&&!d)throw new Error("Either text or images must be provided");const u=await this.image_processor(l,p),h=d?this.tokenizer(d,p):{};return{...u,...h}}}re(o,"tokenizer_class",n.AutoTokenizer),re(o,"image_processor_class",i.AutoImageProcessor)},"./src/models/glpn/image_processing_glpn.js":(e,r,t)=>{t.r(r),t.d(r,{GLPNFeatureExtractor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/grounding_dino/image_processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a){const l=await super._call(a),d=l.pixel_values.dims,p=(0,i.ones)([d[0],d[2],d[3]]);return{...l,pixel_mask:p}}}},"./src/models/grounding_dino/processing_grounding_dino.js":(e,r,t)=>{t.r(r),t.d(r,{GroundingDinoProcessor:()=>l});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/base/image_processors_utils.js");function a(d,p){const h=d.dims.at(-1)-1,w=d.tolist();w.fill(!1,0,1),w.fill(!1,h);const _=p.tolist();return w.map((P,A)=>P?A:null).filter(P=>P!==null).map(P=>_[P])}class l extends s.Processor{async _call(p,u,h={}){const w=p?await this.image_processor(p,h):{};return{...u?this.tokenizer(u,h):{},...w}}post_process_grounded_object_detection(p,u,{box_threshold:h=.25,text_threshold:w=.25,target_sizes:_=null}={}){const{logits:P,pred_boxes:A}=p,v=P.dims[0];if(_!==null&&_.length!==v)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");const y=P.dims.at(1),S=P.sigmoid(),x=S.max(-1).tolist(),g=A.tolist().map(E=>E.map(k=>(0,o.center_to_corners_format)(k))),M=[];for(let E=0;EV.map((Y,H)=>Y*k[(H+1)%2])));const B=x[E],R=[],J=[],q=[];for(let V=0;V{t.r(r),t.d(r,{Idefics3ImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{constructor(a){super(a),this.do_image_splitting=a.do_image_splitting??!0,this.max_image_size=a.max_image_size}get_resize_for_vision_encoder(a,l){let[d,p]=a.dims.slice(-2);const u=p/d;return p>=d?(p=Math.ceil(p/l)*l,d=Math.floor(p/u),d=Math.ceil(d/l)*l):(d=Math.ceil(d/l)*l,p=Math.floor(d*u),p=Math.ceil(p/l)*l),{height:d,width:p}}async _call(a,{do_image_splitting:l=null,return_row_col_info:d=!1}={}){let p;if(!Array.isArray(a))p=[[a]];else{if(a.length===0||!a[0])throw new Error("No images provided.");Array.isArray(a[0])?p=a:p=[a]}let u=[],h=[],w=[];const _=[],P=[];for(const E of p){let k=await Promise.all(E.map(J=>this.preprocess(J)));_.push(...k.map(J=>J.original_size)),P.push(...k.map(J=>J.reshaped_input_size)),k.forEach(J=>J.pixel_values.unsqueeze_(0));const{longest_edge:B}=this.max_image_size;let R;if(l??this.do_image_splitting){let J=new Array(k.length),q=new Array(k.length);R=await Promise.all(k.map(async(V,Y)=>{const H=this.get_resize_for_vision_encoder(V.pixel_values,B),Q=await(0,i.interpolate_4d)(V.pixel_values,{size:[H.height,H.width]}),{frames:ie,num_splits_h:le,num_splits_w:ae}=await this.split_image(Q,this.max_image_size);return J[Y]=le,q[Y]=ae,(0,i.cat)(ie,0)})),h.push(J),w.push(q)}else{const J=[B,B];R=await Promise.all(k.map(q=>(0,i.interpolate_4d)(q.pixel_values,{size:J}))),h.push(new Array(k.length).fill(0)),w.push(new Array(k.length).fill(0))}u.push((0,i.cat)(R,0))}const A=u.length,[v,y,S,x]=u[0].dims;let g,M;if(A===1)g=u[0].unsqueeze_(0),M=(0,i.full)([A,v,S,x],!0);else{const E=Math.max(...u.map(R=>R.dims.at(0)));M=(0,i.full)([A,E,S,x],!0);const k=M.data,B=E*S*x;for(let R=0;Rd||w>p){_=Math.ceil(h/d),P=Math.ceil(w/p);const A=Math.ceil(h/_),v=Math.ceil(w/P);for(let x=0;x<_;++x)for(let g=0;g{t.r(r),t.d(r,{Idefics3Processor:()=>p});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");var o=t("./src/utils/core.js");function a(u,h,w,_,P,A){let v="";for(let y=0;y`+P.repeat(u);v+=` +`}return v+=` +${_}${A}`+P.repeat(u)+`${_}`,v}function l(u,h,w,_){return`${h}${_}`+w.repeat(u)+`${h}`}function d(u,h,w,_,P,A){return u===0&&h===0?l(w,_,P,A):a(w,u,h,_,P,A)}class p extends s.Processor{constructor(){super(...arguments);re(this,"fake_image_token","");re(this,"image_token","");re(this,"global_img_token","")}async _call(w,_=null,P={}){P.return_row_col_info??(P.return_row_col_info=!0);let A;_&&(A=await this.image_processor(_,P)),Array.isArray(w)||(w=[w]);const v=A.rows??[new Array(w.length).fill(0)],y=A.cols??[new Array(w.length).fill(0)],S=this.config.image_seq_len,x=[],g=[];for(let E=0;Ed(Y,R[H],S,this.fake_image_token,this.image_token,this.global_img_token)),q=k.split(this.image_token);if(q.length===0)throw new Error("The image token should be present in the text.");let V=q[0];for(let Y=0;Y{t.r(r),t.d(r,{BeitFeatureExtractor:()=>s.BeitFeatureExtractor,BitImageProcessor:()=>i.BitImageProcessor,CLIPFeatureExtractor:()=>o.CLIPFeatureExtractor,CLIPImageProcessor:()=>o.CLIPImageProcessor,ChineseCLIPFeatureExtractor:()=>n.ChineseCLIPFeatureExtractor,ConvNextFeatureExtractor:()=>a.ConvNextFeatureExtractor,ConvNextImageProcessor:()=>a.ConvNextImageProcessor,DPTFeatureExtractor:()=>u.DPTFeatureExtractor,DPTImageProcessor:()=>u.DPTImageProcessor,DeiTFeatureExtractor:()=>l.DeiTFeatureExtractor,DeiTImageProcessor:()=>l.DeiTImageProcessor,DetrFeatureExtractor:()=>d.DetrFeatureExtractor,DetrImageProcessor:()=>d.DetrImageProcessor,DonutFeatureExtractor:()=>p.DonutFeatureExtractor,DonutImageProcessor:()=>p.DonutImageProcessor,EfficientNetImageProcessor:()=>h.EfficientNetImageProcessor,GLPNFeatureExtractor:()=>w.GLPNFeatureExtractor,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,Idefics3ImageProcessor:()=>P.Idefics3ImageProcessor,JinaCLIPImageProcessor:()=>v.JinaCLIPImageProcessor,LlavaOnevisionImageProcessor:()=>y.LlavaOnevisionImageProcessor,Mask2FormerImageProcessor:()=>S.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>x.MaskFormerFeatureExtractor,MaskFormerImageProcessor:()=>x.MaskFormerImageProcessor,MobileNetV1FeatureExtractor:()=>g.MobileNetV1FeatureExtractor,MobileNetV1ImageProcessor:()=>g.MobileNetV1ImageProcessor,MobileNetV2FeatureExtractor:()=>M.MobileNetV2FeatureExtractor,MobileNetV2ImageProcessor:()=>M.MobileNetV2ImageProcessor,MobileNetV3FeatureExtractor:()=>E.MobileNetV3FeatureExtractor,MobileNetV3ImageProcessor:()=>E.MobileNetV3ImageProcessor,MobileNetV4FeatureExtractor:()=>k.MobileNetV4FeatureExtractor,MobileNetV4ImageProcessor:()=>k.MobileNetV4ImageProcessor,MobileViTFeatureExtractor:()=>B.MobileViTFeatureExtractor,MobileViTImageProcessor:()=>B.MobileViTImageProcessor,NougatImageProcessor:()=>R.NougatImageProcessor,OwlViTFeatureExtractor:()=>q.OwlViTFeatureExtractor,OwlViTImageProcessor:()=>q.OwlViTImageProcessor,Owlv2ImageProcessor:()=>J.Owlv2ImageProcessor,Phi3VImageProcessor:()=>V.Phi3VImageProcessor,PvtImageProcessor:()=>Y.PvtImageProcessor,Qwen2VLImageProcessor:()=>H.Qwen2VLImageProcessor,RTDetrImageProcessor:()=>Q.RTDetrImageProcessor,SamImageProcessor:()=>ie.SamImageProcessor,SegformerFeatureExtractor:()=>le.SegformerFeatureExtractor,SegformerImageProcessor:()=>le.SegformerImageProcessor,SiglipImageProcessor:()=>ae.SiglipImageProcessor,SmolVLMImageProcessor:()=>ge.SmolVLMImageProcessor,Swin2SRImageProcessor:()=>N.Swin2SRImageProcessor,VLMImageProcessor:()=>A.VLMImageProcessor,ViTFeatureExtractor:()=>O.ViTFeatureExtractor,ViTImageProcessor:()=>O.ViTImageProcessor,VitMatteImageProcessor:()=>G.VitMatteImageProcessor,VitPoseImageProcessor:()=>ne.VitPoseImageProcessor,YolosFeatureExtractor:()=>X.YolosFeatureExtractor,YolosImageProcessor:()=>X.YolosImageProcessor});var s=t("./src/models/beit/image_processing_beit.js"),i=t("./src/models/bit/image_processing_bit.js"),n=t("./src/models/chinese_clip/image_processing_chinese_clip.js"),o=t("./src/models/clip/image_processing_clip.js"),a=t("./src/models/convnext/image_processing_convnext.js"),l=t("./src/models/deit/image_processing_deit.js"),d=t("./src/models/detr/image_processing_detr.js"),p=t("./src/models/donut/image_processing_donut.js"),u=t("./src/models/dpt/image_processing_dpt.js"),h=t("./src/models/efficientnet/image_processing_efficientnet.js"),w=t("./src/models/glpn/image_processing_glpn.js"),_=t("./src/models/grounding_dino/image_processing_grounding_dino.js"),P=t("./src/models/idefics3/image_processing_idefics3.js"),A=t("./src/models/janus/image_processing_janus.js"),v=t("./src/models/jina_clip/image_processing_jina_clip.js"),y=t("./src/models/llava_onevision/image_processing_llava_onevision.js"),S=t("./src/models/mask2former/image_processing_mask2former.js"),x=t("./src/models/maskformer/image_processing_maskformer.js"),g=t("./src/models/mobilenet_v1/image_processing_mobilenet_v1.js"),M=t("./src/models/mobilenet_v2/image_processing_mobilenet_v2.js"),E=t("./src/models/mobilenet_v3/image_processing_mobilenet_v3.js"),k=t("./src/models/mobilenet_v4/image_processing_mobilenet_v4.js"),B=t("./src/models/mobilevit/image_processing_mobilevit.js"),R=t("./src/models/nougat/image_processing_nougat.js"),J=t("./src/models/owlv2/image_processing_owlv2.js"),q=t("./src/models/owlvit/image_processing_owlvit.js"),V=t("./src/models/phi3_v/image_processing_phi3_v.js"),Y=t("./src/models/pvt/image_processing_pvt.js"),H=t("./src/models/qwen2_vl/image_processing_qwen2_vl.js"),Q=t("./src/models/rt_detr/image_processing_rt_detr.js"),ie=t("./src/models/sam/image_processing_sam.js"),le=t("./src/models/segformer/image_processing_segformer.js"),ae=t("./src/models/siglip/image_processing_siglip.js"),ge=t("./src/models/smolvlm/image_processing_smolvlm.js"),N=t("./src/models/swin2sr/image_processing_swin2sr.js"),O=t("./src/models/vit/image_processing_vit.js"),G=t("./src/models/vitmatte/image_processing_vitmatte.js"),ne=t("./src/models/vitpose/image_processing_vitpose.js"),X=t("./src/models/yolos/image_processing_yolos.js")},"./src/models/janus/image_processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLMImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(o){super({do_pad:!0,pad_size:{width:o.image_size,height:o.image_size},...o}),this.constant_values=this.config.background_color.map(a=>a*this.rescale_factor)}pad_image(o,a,l,d){return super.pad_image(o,a,l,{constant_values:this.constant_values,center:!0,...d})}}},"./src/models/janus/processing_janus.js":(e,r,t)=>{t.r(r),t.d(r,{VLChatProcessor:()=>d});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/utils/core.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/image.js");class d extends s.Processor{constructor(u,h){super(u,h),this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(u,{images:h=null,chat_template:w="default"}={}){h?Array.isArray(h)||(h=[h]):h=await Promise.all(u.filter(R=>R.images).flatMap(R=>R.images).map(R=>l.RawImage.read(R)));const _=this.tokenizer,P=_.apply_chat_template(u,{tokenize:!1,add_generation_prompt:!0,chat_template:w}),A=R=>_.encode(R,{add_special_tokens:!1}),v=P.split(this.image_tag),y=v.length-1;if(h.length!==y)throw new Error(`Number of images provided (${h.length}) does not match number of "${this.image_tag}" image tags (${y})`);const[S,x,g]=_.model.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]);let M=A(v[0]),E=new Array(M.length).fill(!1);for(let R=1;R0){const R=await this.image_processor(h);return R.pixel_values.unsqueeze_(0),{...B,...R}}return B}}re(d,"image_processor_class",i.AutoImageProcessor),re(d,"tokenizer_class",n.AutoTokenizer),re(d,"uses_processor_config",!0)},"./src/models/jina_clip/image_processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{constructor(o){const{resize_mode:a,fill_color:l,interpolation:d,size:p,...u}=o,h=a==="squash"?{width:p,height:p}:a==="shortest"?{shortest_edge:p}:{longest_edge:p},w=d==="bicubic"?3:2;super({...u,size:h,resample:w,do_center_crop:!0,crop_size:p,do_normalize:!0})}}},"./src/models/jina_clip/processing_jina_clip.js":(e,r,t)=>{t.r(r),t.d(r,{JinaCLIPProcessor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class o extends s.Processor{async _call(l=null,d=null,p={}){if(!l&&!d)throw new Error("Either text or images must be provided");const u=l?this.tokenizer(l,p):{},h=d?await this.image_processor(d,p):{};return{...u,...h}}}re(o,"tokenizer_class",n.AutoTokenizer),re(o,"image_processor_class",i.AutoImageProcessor)},"./src/models/llava_onevision/image_processing_llava_onevision.js":(e,r,t)=>{t.r(r),t.d(r,{LlavaOnevisionImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/mask2former/image_processing_mask2former.js":(e,r,t)=>{t.r(r),t.d(r,{Mask2FormerImageProcessor:()=>i});var s=t("./src/models/maskformer/image_processing_maskformer.js");class i extends s.MaskFormerImageProcessor{}},"./src/models/maskformer/image_processing_maskformer.js":(e,r,t)=>{t.r(r),t.d(r,{MaskFormerFeatureExtractor:()=>n,MaskFormerImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_panoptic_segmentation(...a){return(0,s.post_process_panoptic_segmentation)(...a)}post_process_instance_segmentation(...a){return(0,s.post_process_instance_segmentation)(...a)}}class n extends i{}},"./src/models/mgp_str/processing_mgp_str.js":(e,r,t)=>{t.r(r),t.d(r,{MgpstrProcessor:()=>l});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js"),o=t("./src/utils/maths.js");const a={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]};class l extends s.Processor{get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(p,u){if(!a.hasOwnProperty(u))throw new Error(`Format ${u} is not supported.`);const[h,w]=a[u],_=this[h].bind(this),[P,A]=p.dims,v=[],y=[],S=p.tolist();for(let g=0;g0?k.reduce((R,J)=>R*J,1):0;y.push(E),v.push(B)}return[_(y),v]}char_decode(p){return this.char_tokenizer.batch_decode(p).map(u=>u.replaceAll(" ",""))}bpe_decode(p){return this.bpe_tokenizer.batch_decode(p)}wp_decode(p){return this.wp_tokenizer.batch_decode(p).map(u=>u.replaceAll(" ",""))}batch_decode([p,u,h]){const[w,_]=this._decode_helper(p,"char"),[P,A]=this._decode_helper(u,"bpe"),[v,y]=this._decode_helper(h,"wp"),S=[],x=[];for(let g=0;g{t.r(r),t.d(r,{MobileNetV1FeatureExtractor:()=>n,MobileNetV1ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilenet_v2/image_processing_mobilenet_v2.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV2FeatureExtractor:()=>n,MobileNetV2ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilenet_v3/image_processing_mobilenet_v3.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV3FeatureExtractor:()=>n,MobileNetV3ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilenet_v4/image_processing_mobilenet_v4.js":(e,r,t)=>{t.r(r),t.d(r,{MobileNetV4FeatureExtractor:()=>n,MobileNetV4ImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/mobilevit/image_processing_mobilevit.js":(e,r,t)=>{t.r(r),t.d(r,{MobileViTFeatureExtractor:()=>n,MobileViTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/moonshine/feature_extraction_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{async _call(a){(0,s.validate_audio_inputs)(a,"MoonshineFeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));const l=[1,a.length];return{input_values:new i.Tensor("float32",a,l)}}}},"./src/models/moonshine/processing_moonshine.js":(e,r,t)=>{t.r(r),t.d(r,{MoonshineProcessor:()=>o});var s=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/nougat/image_processing_nougat.js":(e,r,t)=>{t.r(r),t.d(r,{NougatImageProcessor:()=>i});var s=t("./src/models/donut/image_processing_donut.js");class i extends s.DonutImageProcessor{}},"./src/models/owlv2/image_processing_owlv2.js":(e,r,t)=>{t.r(r),t.d(r,{Owlv2ImageProcessor:()=>i});var s=t("./src/models/owlvit/image_processing_owlvit.js");class i extends s.OwlViTImageProcessor{}},"./src/models/owlvit/image_processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTFeatureExtractor:()=>n,OwlViTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends i{}},"./src/models/owlvit/processing_owlvit.js":(e,r,t)=>{t.r(r),t.d(r,{OwlViTProcessor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");class o extends s.Processor{}re(o,"tokenizer_class",n.AutoTokenizer),re(o,"image_processor_class",i.AutoImageProcessor)},"./src/models/paligemma/processing_paligemma.js":(e,r,t)=>{t.r(r),t.d(r,{PaliGemmaProcessor:()=>l});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");const o="";function a(d,p,u,h,w){return`${h.repeat(u*w)}${p}${d} +`}class l extends s.Processor{async _call(p,u=null,h={}){u||(console.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),u=""),Array.isArray(p)||(p=[p]),Array.isArray(u)||(u=[u]);const w=this.tokenizer.bos_token,_=this.image_processor.config.image_seq_length;let P;u.some(y=>y.includes(o))?P=u.map(y=>{const S=y.replaceAll(o,o.repeat(_)),x=S.lastIndexOf(o),g=x===-1?0:x+o.length;return S.slice(0,g)+w+S.slice(g)+` +`}):(console.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),P=u.map(y=>a(y,w,_,o,p.length)));const A=this.tokenizer(P,h);return{...await this.image_processor(p,h),...A}}}re(l,"tokenizer_class",n.AutoTokenizer),re(l,"image_processor_class",i.AutoImageProcessor),re(l,"uses_processor_config",!1)},"./src/models/phi3_v/image_processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VImageProcessor:()=>p});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");const n=336,o=[2,3],{ceil:a,floor:l,sqrt:d}=Math;class p extends s.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,w){const{num_img_tokens:_}=this.config;return l((l(w/n)*l(h/n)+1)*_+1+(l(w/n)+1)*d(_))}get_resize_output_image_size(h,w){const _=this._num_crops,[P,A]=h.size;let v=P/A,y=1;for(;y*Math.ceil(y/v)<=_;)y+=1;y-=1;const S=Math.floor(y*336),x=Math.floor(S/v);return[S,x]}pad_image(h,w,_,P={}){const[A,v]=w,y=n*a(A/n),S=n*a(v/n),x=[1,1,1].map((g,M)=>(g-this.image_mean[M])/this.image_std[M]);return super.pad_image(h,w,{width:S,height:y},{center:!0,constant_values:x,...P})}async _call(h,{num_crops:w=null}={}){if(this._num_crops=w??(w=this.config.num_crops),w<4||d(w)%1!==0)throw new Error("num_crops must be a square number >= 4");Array.isArray(h)||(h=[h]);const _=h.length,P=await Promise.all(h.map(E=>this.preprocess(E))),A=P.map(E=>E.original_size),v=P.map(E=>E.reshaped_input_size),y=[];for(const{pixel_values:E}of P){E.unsqueeze_(0);const[k,B]=E.dims.slice(-2),R=await(0,i.interpolate_4d)(E,{size:[n,n],mode:"bicubic"});if(w>0){const J=[],q=d(w),V=l(B/q),Y=l(k/q);for(let Q=0;QE.map(k=>n*a(k/n))),g=new i.Tensor("int64",x.flat(),[_,2]),M=x.map(([E,k])=>this.calc_num_image_tokens_from_image_size(k,E));return{pixel_values:S,original_sizes:A,reshaped_input_sizes:v,image_sizes:g,num_img_tokens:M}}}},"./src/models/phi3_v/processing_phi3_v.js":(e,r,t)=>{t.r(r),t.d(r,{Phi3VProcessor:()=>l});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");const o="<|image|>",a=/<\|image_\d+\|>/g;class l extends s.Processor{async _call(p,u=null,{padding:h=!0,truncation:w=!0,num_crops:_=null}={}){Array.isArray(p)||(p=[p]);let P,A;if(u){A=await this.image_processor(u,{num_crops:_});const{num_img_tokens:v}=A,y=p.map((x,g)=>x.split(a).join(o.repeat(v[g])));P=this.tokenizer(y,{padding:h,truncation:w});const S=this.tokenizer.model.convert_tokens_to_ids([o])[0];P.input_ids.map_(x=>x==S?-x:x)}else P=this.tokenizer(p);return{...P,...A}}}re(l,"image_processor_class",i.AutoImageProcessor),re(l,"tokenizer_class",n.AutoTokenizer)},"./src/models/processors.js":(e,r,t)=>{t.r(r),t.d(r,{Florence2Processor:()=>s.Florence2Processor,GroundingDinoProcessor:()=>i.GroundingDinoProcessor,Idefics3Processor:()=>n.Idefics3Processor,JinaCLIPProcessor:()=>a.JinaCLIPProcessor,MgpstrProcessor:()=>l.MgpstrProcessor,MoonshineProcessor:()=>d.MoonshineProcessor,OwlViTProcessor:()=>p.OwlViTProcessor,PaliGemmaProcessor:()=>h.PaliGemmaProcessor,Phi3VProcessor:()=>u.Phi3VProcessor,PyAnnoteProcessor:()=>w.PyAnnoteProcessor,Qwen2VLProcessor:()=>_.Qwen2VLProcessor,SamProcessor:()=>P.SamProcessor,SmolVLMProcessor:()=>A.SmolVLMProcessor,SpeechT5Processor:()=>v.SpeechT5Processor,UltravoxProcessor:()=>y.UltravoxProcessor,VLChatProcessor:()=>o.VLChatProcessor,Wav2Vec2Processor:()=>S.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>x.Wav2Vec2ProcessorWithLM,WhisperProcessor:()=>g.WhisperProcessor});var s=t("./src/models/florence2/processing_florence2.js"),i=t("./src/models/grounding_dino/processing_grounding_dino.js"),n=t("./src/models/idefics3/processing_idefics3.js"),o=t("./src/models/janus/processing_janus.js"),a=t("./src/models/jina_clip/processing_jina_clip.js"),l=t("./src/models/mgp_str/processing_mgp_str.js"),d=t("./src/models/moonshine/processing_moonshine.js"),p=t("./src/models/owlvit/processing_owlvit.js"),u=t("./src/models/phi3_v/processing_phi3_v.js"),h=t("./src/models/paligemma/processing_paligemma.js"),w=t("./src/models/pyannote/processing_pyannote.js"),_=t("./src/models/qwen2_vl/processing_qwen2_vl.js"),P=t("./src/models/sam/processing_sam.js"),A=t("./src/models/smolvlm/processing_smolvlm.js"),v=t("./src/models/speecht5/processing_speecht5.js"),y=t("./src/models/ultravox/processing_ultravox.js"),S=t("./src/models/wav2vec2/processing_wav2vec2.js"),x=t("./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js"),g=t("./src/models/whisper/processing_whisper.js")},"./src/models/pvt/image_processing_pvt.js":(e,r,t)=>{t.r(r),t.d(r,{PvtImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/pyannote/feature_extraction_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/maths.js");class o extends s.FeatureExtractor{async _call(l){(0,s.validate_audio_inputs)(l,"PyAnnoteFeatureExtractor"),l instanceof Float64Array&&(l=new Float32Array(l));const d=[1,1,l.length];return{input_values:new i.Tensor("float32",l,d)}}samples_to_frames(l){return(l-this.config.offset)/this.config.step}post_process_speaker_diarization(l,d){const p=d/this.samples_to_frames(d)/this.config.sampling_rate,u=[];for(const h of l.tolist()){const w=[];let _=-1;for(let P=0;P({id:P,start:A*p,end:v*p,confidence:y/(v-A)})))}return u}}},"./src/models/pyannote/processing_pyannote.js":(e,r,t)=>{t.r(r),t.d(r,{PyAnnoteProcessor:()=>n});var s=t("./src/base/processing_utils.js"),i=t("./src/models/pyannote/feature_extraction_pyannote.js");class n extends s.Processor{async _call(a){return await this.feature_extractor(a)}post_process_speaker_diarization(...a){return this.feature_extractor.post_process_speaker_diarization(...a)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}}re(n,"feature_extractor_class",i.PyAnnoteFeatureExtractor)},"./src/models/qwen2_vl/image_processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,...l){const{pixel_values:d,original_sizes:p,reshaped_input_sizes:u}=await super._call(a,...l);let h=d;const{temporal_patch_size:w,merge_size:_,patch_size:P}=this.config;h.dims[0]===1&&(h=(0,i.cat)(Array.from({length:w},()=>h),0));const A=h.dims[0]/w,v=h.dims[1],y=Math.floor(h.dims[2]/P),S=Math.floor(h.dims[3]/P),x=h.view(A,w,v,Math.floor(y/_),_,P,Math.floor(S/_),_,P).permute(0,3,6,4,7,2,1,5,8).view(A*y*S,v*w*P*P),g=new i.Tensor("int64",[A,y,S],[1,3]);return{pixel_values:x,image_grid_thw:g,original_sizes:p,reshaped_input_sizes:u}}}},"./src/models/qwen2_vl/processing_qwen2_vl.js":(e,r,t)=>{t.r(r),t.d(r,{Qwen2VLProcessor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js"),n=t("./src/tokenizers.js");t("./src/utils/image.js");class o extends s.Processor{async _call(l,d=null,...p){Array.isArray(l)||(l=[l]);let u,h;if(d&&(u=await this.image_processor(d),h=u.image_grid_thw),h){let _=this.image_processor.config.merge_size**2,P=0;const A=h.tolist();l=l.map(v=>{for(;v.includes("<|image_pad|>");){const y=Number(A[P++].reduce((S,x)=>S*x,1n));v=v.replace("<|image_pad|>","<|placeholder|>".repeat(Math.floor(y/_)))}return v.replaceAll("<|placeholder|>","<|image_pad|>")})}return{...this.tokenizer(l),...u}}}re(o,"image_processor_class",i.AutoImageProcessor),re(o,"tokenizer_class",n.AutoTokenizer)},"./src/models/rt_detr/image_processing_rt_detr.js":(e,r,t)=>{t.r(r),t.d(r,{RTDetrImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_object_detection(...o){return(0,s.post_process_object_detection)(...o)}}},"./src/models/sam/image_processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamImageProcessor:()=>o});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/core.js"),n=t("./src/utils/tensor.js");class o extends s.ImageProcessor{reshape_input_points(l,d,p,u=!1){l=structuredClone(l);let h=(0,i.calculateDimensions)(l);if(h.length===3)u||(h=[1,...h]),l=[l];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 w=0;wu!==d.dims[h]))throw Error(`The first ${p.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new n.Tensor("int64",l.flat(1/0).map(BigInt),p)}async _call(l,{input_points:d=null,input_labels:p=null,input_boxes:u=null}={}){const h=await super._call(l);if(d&&(h.input_points=this.reshape_input_points(d,h.original_sizes,h.reshaped_input_sizes)),p){if(!h.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");h.input_labels=this.add_input_labels(p,h.input_points)}return u&&(h.input_boxes=this.reshape_input_points(u,h.original_sizes,h.reshaped_input_sizes,!0)),h}async post_process_masks(l,d,p,{mask_threshold:u=0,binarize:h=!0,pad_size:w=null}={}){const _=[];w=w??this.pad_size;const P=[w.height,w.width];for(let A=0;Au&&(g[M]=1);S=new n.Tensor("bool",g,S.dims)}_.push(S)}return _}generate_crop_boxes(l,d,{crop_n_layers:p=0,overlap_ratio:u=512/1500,points_per_crop:h=32,crop_n_points_downscale_factor:w=1}={}){}}},"./src/models/sam/processing_sam.js":(e,r,t)=>{t.r(r),t.d(r,{SamProcessor:()=>n});var s=t("./src/base/processing_utils.js"),i=t("./src/models/auto/image_processing_auto.js");class n extends s.Processor{async _call(...a){return await this.image_processor(...a)}post_process_masks(...a){return this.image_processor.post_process_masks(...a)}reshape_input_points(...a){return this.image_processor.reshape_input_points(...a)}}re(n,"image_processor_class",i.AutoImageProcessor)},"./src/models/seamless_m4t/feature_extraction_seamless_m4t.js":(e,r,t)=>{t.r(r),t.d(r,{SeamlessM4TFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js"),n=t("./src/utils/audio.js");class o extends s.FeatureExtractor{constructor(l){super(l);const d=this.config.sampling_rate,p=(0,n.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(d/2),d,null,"kaldi",!0);for(let u=0;up*32768),(0,n.spectrogram)(l,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,max_num_frames:d,transpose:!0})}async _call(l,{padding:d=!0,pad_to_multiple_of:p=2,do_normalize_per_mel_bins:u=!0,return_attention_mask:h=!0}={}){(0,s.validate_audio_inputs)(l,"SeamlessM4TFeatureExtractor");let w=await this._extract_fbank_features(l,this.config.max_length);if(u){const[g,M]=w.dims,E=w.data;for(let k=0;k0){const B=new Float32Array(M*(g+k));B.set(E),B.fill(this.config.padding_value,E.length);const R=g+k;w=new i.Tensor(w.type,B,[R,M]),h&&(_=new i.Tensor("int64",new BigInt64Array(R),[1,R]),_.data.fill(1n,0,g))}}const[P,A]=w.dims,v=this.config.stride;if(P%v!==0)throw new Error(`The number of frames (${P}) must be a multiple of the stride (${v}).`);const S=w.view(1,Math.floor(P/v),A*v),x={input_features:S};if(h){const g=S.dims[1],M=new BigInt64Array(g);if(_){const E=_.data;for(let k=1,B=0;k{t.r(r),t.d(r,{SegformerFeatureExtractor:()=>n,SegformerImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_semantic_segmentation(...a){return(0,s.post_process_semantic_segmentation)(...a)}}class n extends i{}},"./src/models/siglip/image_processing_siglip.js":(e,r,t)=>{t.r(r),t.d(r,{SiglipImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}},"./src/models/smolvlm/image_processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMImageProcessor:()=>s.Idefics3ImageProcessor});var s=t("./src/models/idefics3/image_processing_idefics3.js")},"./src/models/smolvlm/processing_smolvlm.js":(e,r,t)=>{t.r(r),t.d(r,{SmolVLMProcessor:()=>s.Idefics3Processor});var s=t("./src/models/idefics3/processing_idefics3.js")},"./src/models/speecht5/feature_extraction_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5FeatureExtractor:()=>i});var s=t("./src/base/feature_extraction_utils.js");class i extends s.FeatureExtractor{}},"./src/models/speecht5/processing_speecht5.js":(e,r,t)=>{t.r(r),t.d(r,{SpeechT5Processor:()=>o});var s=t("./src/base/processing_utils.js"),i=t("./src/tokenizers.js"),n=t("./src/models/auto/feature_extraction_auto.js");class o extends s.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",n.AutoFeatureExtractor)},"./src/models/swin2sr/image_processing_swin2sr.js":(e,r,t)=>{t.r(r),t.d(r,{Swin2SRImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{pad_image(o,a,l,d={}){const[p,u,h]=a;return super.pad_image(o,a,{width:u+(l-u%l)%l,height:p+(l-p%l)%l},{mode:"symmetric",center:!1,constant_values:-1,...d})}}},"./src/models/ultravox/processing_ultravox.js":(e,r,t)=>{t.r(r),t.d(r,{UltravoxProcessor:()=>o});var s=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l,d=null,p={}){if(Array.isArray(l))throw new Error("Batched inputs are not supported yet.");let u={};if(d){const w=d.length,{input_features:_}=await this.feature_extractor(d,{...p,max_length:w}),P=Math.round(w/this.config.encoder_ds_factor+1e-4),A=1+Math.ceil(P/this.config.stack_factor);u.audio_token_len=[A],u.audio_values=_;const v=this.config.audio_placeholder;if(!l.includes(v))throw new Error(`The input text does not contain the image token ${v}.`);l=l.replaceAll(v,v.repeat(A))}return{...this.tokenizer(l,{add_special_tokens:!1,...p}),...u}}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",s.AutoFeatureExtractor),re(o,"uses_processor_config",!0)},"./src/models/vit/image_processing_vit.js":(e,r,t)=>{t.r(r),t.d(r,{ViTFeatureExtractor:()=>n,ViTImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{}class n extends i{}},"./src/models/vitmatte/image_processing_vitmatte.js":(e,r,t)=>{t.r(r),t.d(r,{VitMatteImageProcessor:()=>n});var s=t("./src/base/image_processors_utils.js"),i=t("./src/utils/tensor.js");class n extends s.ImageProcessor{async _call(a,l){Array.isArray(a)||(a=[a]),Array.isArray(l)||(l=[l]);const d=await Promise.all(a.map(h=>this.preprocess(h))),p=await Promise.all(l.map(h=>this.preprocess(h,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:(0,i.stack)(d.map((h,w)=>(0,i.cat)([h.pixel_values,p[w].pixel_values],0)),0),original_sizes:d.map(h=>h.original_size),reshaped_input_sizes:d.map(h=>h.reshaped_input_size)}}}},"./src/models/vitpose/image_processing_vitpose.js":(e,r,t)=>{t.r(r),t.d(r,{VitPoseImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_pose_estimation(o,a,{threshold:l=null}={}){const d=o.tolist(),[p,u,h,w]=o.dims,_=[];for(let P=0;P{t.r(r),t.d(r,{Wav2Vec2FeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js"),i=t("./src/utils/tensor.js");class n extends s.FeatureExtractor{_zero_mean_unit_var_norm(a){const d=a.reduce((u,h)=>u+h,0)/a.length,p=a.reduce((u,h)=>u+(h-d)**2,0)/a.length;return a.map(u=>(u-d)/Math.sqrt(p+1e-7))}async _call(a){(0,s.validate_audio_inputs)(a,"Wav2Vec2FeatureExtractor"),a instanceof Float64Array&&(a=new Float32Array(a));let l=a;this.config.do_normalize&&(l=this._zero_mean_unit_var_norm(l));const d=[1,l.length];return{input_values:new i.Tensor("float32",l,d),attention_mask:new i.Tensor("int64",new BigInt64Array(l.length).fill(1n),d)}}}},"./src/models/wav2vec2/processing_wav2vec2.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2Processor:()=>o});var s=t("./src/tokenizers.js"),i=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",s.AutoTokenizer),re(o,"feature_extractor_class",i.AutoFeatureExtractor)},"./src/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.js":(e,r,t)=>{t.r(r),t.d(r,{Wav2Vec2ProcessorWithLM:()=>o});var s=t("./src/tokenizers.js"),i=t("./src/models/auto/feature_extraction_auto.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",s.AutoTokenizer),re(o,"feature_extractor_class",i.AutoFeatureExtractor)},"./src/models/wespeaker/feature_extraction_wespeaker.js":(e,r,t)=>{t.r(r),t.d(r,{WeSpeakerFeatureExtractor:()=>n});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var i=t("./src/utils/audio.js");class n extends s.FeatureExtractor{constructor(a){super(a);const l=this.config.sampling_rate,d=(0,i.mel_filter_bank)(256,this.config.num_mel_bins,20,Math.floor(l/2),l,null,"kaldi",!0);for(let p=0;pl*32768),(0,i.spectrogram)(a,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:1192092955078125e-22,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(a){(0,s.validate_audio_inputs)(a,"WeSpeakerFeatureExtractor");const l=(await this._extract_fbank_features(a)).unsqueeze_(0);if(this.config.fbank_centering_span===null){const d=l.mean(1).data,p=l.data,[u,h,w]=l.dims;for(let _=0;_{t.r(r),t.d(r,{WHISPER_LANGUAGE_MAPPING:()=>i,WHISPER_TO_LANGUAGE_CODE_MAPPING:()=>n,whisper_language_to_code:()=>o});const s=[["en","english"],["zh","chinese"],["de","german"],["es","spanish"],["ru","russian"],["ko","korean"],["fr","french"],["ja","japanese"],["pt","portuguese"],["tr","turkish"],["pl","polish"],["ca","catalan"],["nl","dutch"],["ar","arabic"],["sv","swedish"],["it","italian"],["id","indonesian"],["hi","hindi"],["fi","finnish"],["vi","vietnamese"],["he","hebrew"],["uk","ukrainian"],["el","greek"],["ms","malay"],["cs","czech"],["ro","romanian"],["da","danish"],["hu","hungarian"],["ta","tamil"],["no","norwegian"],["th","thai"],["ur","urdu"],["hr","croatian"],["bg","bulgarian"],["lt","lithuanian"],["la","latin"],["mi","maori"],["ml","malayalam"],["cy","welsh"],["sk","slovak"],["te","telugu"],["fa","persian"],["lv","latvian"],["bn","bengali"],["sr","serbian"],["az","azerbaijani"],["sl","slovenian"],["kn","kannada"],["et","estonian"],["mk","macedonian"],["br","breton"],["eu","basque"],["is","icelandic"],["hy","armenian"],["ne","nepali"],["mn","mongolian"],["bs","bosnian"],["kk","kazakh"],["sq","albanian"],["sw","swahili"],["gl","galician"],["mr","marathi"],["pa","punjabi"],["si","sinhala"],["km","khmer"],["sn","shona"],["yo","yoruba"],["so","somali"],["af","afrikaans"],["oc","occitan"],["ka","georgian"],["be","belarusian"],["tg","tajik"],["sd","sindhi"],["gu","gujarati"],["am","amharic"],["yi","yiddish"],["lo","lao"],["uz","uzbek"],["fo","faroese"],["ht","haitian creole"],["ps","pashto"],["tk","turkmen"],["nn","nynorsk"],["mt","maltese"],["sa","sanskrit"],["lb","luxembourgish"],["my","myanmar"],["bo","tibetan"],["tl","tagalog"],["mg","malagasy"],["as","assamese"],["tt","tatar"],["haw","hawaiian"],["ln","lingala"],["ha","hausa"],["ba","bashkir"],["jw","javanese"],["su","sundanese"]],i=new Map(s),n=new Map([...s.map(([a,l])=>[l,a]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function o(a){a=a.toLowerCase();let l=n.get(a);if(l===void 0){const d=a.match(/^<\|([a-z]{2})\|>$/);if(d&&(a=d[1]),i.has(a))l=a;else{const u=a.length===2?i.keys():i.values();throw new Error(`Language "${a}" is not supported. Must be one of: ${JSON.stringify(Array.from(u))}`)}}return l}},"./src/models/whisper/feature_extraction_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperFeatureExtractor:()=>o});var s=t("./src/base/feature_extraction_utils.js");t("./src/utils/tensor.js");var i=t("./src/utils/audio.js"),n=t("./src/utils/maths.js");class o extends s.FeatureExtractor{constructor(l){var d;super(l),(d=this.config).mel_filters??(d.mel_filters=(0,i.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,i.window_function)(this.config.n_fft,"hann")}async _extract_fbank_features(l){const d=await(0,i.spectrogram)(l,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10",max_num_frames:Math.min(Math.floor(l.length/this.config.hop_length),this.config.nb_max_frames)}),p=d.data,u=(0,n.max)(p)[0];for(let h=0;hu?(l.length>this.config.n_samples&&console.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),p=l.slice(0,u)):(p=new Float32Array(u),p.set(l)),{input_features:(await this._extract_fbank_features(p)).unsqueeze_(0)}}}},"./src/models/whisper/generation_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperGenerationConfig:()=>i});var s=t("./src/generation/configuration_utils.js");class i extends s.GenerationConfig{constructor(){super(...arguments);re(this,"return_timestamps",null);re(this,"return_token_timestamps",null);re(this,"num_frames",null);re(this,"alignment_heads",null);re(this,"task",null);re(this,"language",null);re(this,"no_timestamps_token_id",null);re(this,"prompt_ids",null);re(this,"is_multilingual",null);re(this,"lang_to_id",null);re(this,"task_to_id",null);re(this,"max_initial_timestamp_index",1)}}},"./src/models/whisper/processing_whisper.js":(e,r,t)=>{t.r(r),t.d(r,{WhisperProcessor:()=>o});var s=t("./src/models/auto/feature_extraction_auto.js"),i=t("./src/tokenizers.js"),n=t("./src/base/processing_utils.js");class o extends n.Processor{async _call(l){return await this.feature_extractor(l)}}re(o,"tokenizer_class",i.AutoTokenizer),re(o,"feature_extractor_class",s.AutoFeatureExtractor)},"./src/models/yolos/image_processing_yolos.js":(e,r,t)=>{t.r(r),t.d(r,{YolosFeatureExtractor:()=>n,YolosImageProcessor:()=>i});var s=t("./src/base/image_processors_utils.js");class i extends s.ImageProcessor{post_process_object_detection(...a){return(0,s.post_process_object_detection)(...a)}}class n extends i{}},"./src/ops/registry.js":(e,r,t)=>{t.r(r),t.d(r,{TensorOpRegistry:()=>l});var s=t("./src/backends/onnx.js"),i=t("./src/utils/tensor.js"),n=t("./src/env.js");const o=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV,a=async(d,p,u)=>{const h=await(0,s.createInferenceSession)(new Uint8Array(d),p);let w=Promise.resolve();return async _=>{const P=(0,s.isONNXProxy)(),A=Object.fromEntries(Object.entries(_).map(([y,S])=>[y,(P?S.clone():S).ort_tensor])),v=await(w=o?w.then(()=>h.run(A)):h.run(A));return Array.isArray(u)?u.map(y=>new i.Tensor(v[y])):new i.Tensor(v[u])}};class l{static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||(this._nearest_interpolate_4d=a([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,"y")),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||(this._bilinear_interpolate_4d=a([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||(this._bicubic_interpolate_4d=a([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,"y")),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||(this._matmul=a([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,"c")),this._matmul}static get stft(){return this._stft||(this._stft=a([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,"o")),this._stft}static get rfft(){return this._rfft||(this._rfft=a([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,"y")),this._rfft}static get top_k(){return this._top_k||(this._top_k=a([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,["v","i"])),this._top_k}static get slice(){return this._slice||(this._slice=a([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y")),this._slice}}re(l,"session_options",{})},"./src/pipelines.js":(e,r,t)=>{t.r(r),t.d(r,{AudioClassificationPipeline:()=>q,AutomaticSpeechRecognitionPipeline:()=>Y,BackgroundRemovalPipeline:()=>le,DepthEstimationPipeline:()=>X,DocumentQuestionAnsweringPipeline:()=>O,FeatureExtractionPipeline:()=>R,FillMaskPipeline:()=>S,ImageClassificationPipeline:()=>Q,ImageFeatureExtractionPipeline:()=>J,ImageSegmentationPipeline:()=>ie,ImageToImagePipeline:()=>ne,ImageToTextPipeline:()=>H,ObjectDetectionPipeline:()=>ge,Pipeline:()=>P,QuestionAnsweringPipeline:()=>y,SummarizationPipeline:()=>g,Text2TextGenerationPipeline:()=>x,TextClassificationPipeline:()=>A,TextGenerationPipeline:()=>k,TextToAudioPipeline:()=>G,TokenClassificationPipeline:()=>v,TranslationPipeline:()=>M,ZeroShotAudioClassificationPipeline:()=>V,ZeroShotClassificationPipeline:()=>B,ZeroShotImageClassificationPipeline:()=>ae,ZeroShotObjectDetectionPipeline:()=>N,pipeline:()=>ke});var s=t("./src/tokenizers.js"),i=t("./src/models.js"),n=t("./src/models/auto/processing_auto.js");t("./src/base/processing_utils.js");var o=t("./src/utils/generic.js"),a=t("./src/utils/core.js"),l=t("./src/utils/maths.js"),d=t("./src/utils/audio.js"),p=t("./src/utils/tensor.js"),u=t("./src/utils/image.js");async function h(Me){return Array.isArray(Me)||(Me=[Me]),await Promise.all(Me.map(K=>u.RawImage.read(K)))}async function w(Me,K){return Array.isArray(Me)||(Me=[Me]),await Promise.all(Me.map(U=>typeof U=="string"||U instanceof URL?(0,d.read_audio)(U,K):U instanceof Float64Array?new Float32Array(U):U))}function _(Me,K){K&&(Me=Me.map(Fe=>Fe|0));const[U,pe,Pe,Ee]=Me;return{xmin:U,ymin:pe,xmax:Pe,ymax:Ee}}class P extends o.Callable{constructor({task:K,model:U,tokenizer:pe=null,processor:Pe=null}){super(),this.task=K,this.model=U,this.tokenizer=pe,this.processor=Pe}async dispose(){await this.model.dispose()}}class A extends P{constructor(K){super(K)}async _call(K,{top_k:U=1}={}){const pe=this.tokenizer(K,{padding:!0,truncation:!0}),Pe=await this.model(pe),Ee=this.model.config.problem_type==="multi_label_classification"?Le=>Le.sigmoid():Le=>new p.Tensor("float32",(0,l.softmax)(Le.data),Le.dims),Fe=this.model.config.id2label,Ie=[];for(const Le of Pe.logits){const Ne=Ee(Le),Ve=await(0,p.topk)(Ne,U),D=Ve[0].tolist(),z=Ve[1].tolist().map((ee,ce)=>({label:Fe?Fe[ee]:`LABEL_${ee}`,score:D[ce]}));U===1?Ie.push(...z):Ie.push(z)}return Array.isArray(K)||U===1?Ie:Ie[0]}}class v extends P{constructor(K){super(K)}async _call(K,{ignore_labels:U=["O"]}={}){const pe=Array.isArray(K),Pe=this.tokenizer(pe?K:[K],{padding:!0,truncation:!0}),Fe=(await this.model(Pe)).logits,Ie=this.model.config.id2label,Le=[];for(let Ne=0;NeAe==this.tokenizer.sep_token_id);Le[D].map((Ae,Ue)=>Ae==1&&(Ue===0||Ue>z&&Ne.findIndex(Qe=>Qe==Z[Ue])===-1));const ee=Ee[D].tolist(),ce=Fe[D].tolist();for(let Ae=1;AeUe==Z[Ae])!==-1)&&(ee[Ae]=-1/0,ce[Ae]=-1/0);const be=(0,l.softmax)(ee).map((Ae,Ue)=>[Ae,Ue]),ve=(0,l.softmax)(ce).map((Ae,Ue)=>[Ae,Ue]);be[0][0]=0,ve[0][0]=0;const Re=(0,a.product)(be,ve).filter(Ae=>Ae[0][1]<=Ae[1][1]).map(Ae=>[Ae[0][1],Ae[1][1],Ae[0][0]*Ae[1][0]]).sort((Ae,Ue)=>Ue[2]-Ae[2]);for(let Ae=0;Aeee==this.tokenizer.mask_token_id);if(Ne===-1)throw Error(`Mask token (${this.tokenizer.mask_token}) not found in text.`);const Ve=Pe[Ie][Ne],D=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),U),Z=D[0].tolist(),z=D[1].tolist();Ee.push(z.map((ee,ce)=>{const be=Le.slice();return be[Ne]=ee,{score:Z[ce],token:Number(ee),token_str:this.tokenizer.decode([ee]),sequence:this.tokenizer.decode(be,{skip_special_tokens:!0})}}))}return Array.isArray(K)?Ee:Ee[0]}}class x extends P{constructor(U){super(U);re(this,"_key","generated_text")}async _call(U,pe={}){Array.isArray(U)||(U=[U]),this.model.config.prefix&&(U=U.map(Ne=>this.model.config.prefix+Ne));const Pe=this.model.config.task_specific_params;Pe&&Pe[this.task]&&Pe[this.task].prefix&&(U=U.map(Ne=>Pe[this.task].prefix+Ne));const Ee=this.tokenizer,Fe={padding:!0,truncation:!0};let Ie;this instanceof M&&"_build_translation_inputs"in Ee?Ie=Ee._build_translation_inputs(U,Fe,pe):Ie=Ee(U,Fe);const Le=await this.model.generate({...Ie,...pe});return Ee.batch_decode(Le,{skip_special_tokens:!0}).map(Ne=>({[this._key]:Ne}))}}class g extends x{constructor(U){super(U);re(this,"_key","summary_text")}}class M extends x{constructor(U){super(U);re(this,"_key","translation_text")}}function E(Me){return Array.isArray(Me)&&Me.every(K=>"role"in K&&"content"in K)}class k extends P{constructor(K){super(K)}async _call(K,U={}){let pe=!1,Pe=!1,Ee;if(typeof K=="string")Ee=K=[K];else if(Array.isArray(K)&&K.every(z=>typeof z=="string"))pe=!0,Ee=K;else{if(E(K))K=[K];else if(Array.isArray(K)&&K.every(E))pe=!0;else throw new Error("Input must be a string, an array of strings, a Chat, or an array of Chats");Pe=!0,Ee=K.map(z=>this.tokenizer.apply_chat_template(z,{tokenize:!1,add_generation_prompt:!0}))}const Fe=U.add_special_tokens??!1,Ie=Pe?!1:U.return_full_text??!0;this.tokenizer.padding_side="left";const Le=this.tokenizer(Ee,{add_special_tokens:Fe,padding:!0,truncation:!0}),Ne=await this.model.generate({...Le,...U}),Ve=this.tokenizer.batch_decode(Ne,{skip_special_tokens:!0});let D;!Ie&&Le.input_ids.dims.at(-1)>0&&(D=this.tokenizer.batch_decode(Le.input_ids,{skip_special_tokens:!0}).map(z=>z.length));const Z=Array.from({length:K.length},z=>[]);for(let z=0;z[U.toLowerCase(),pe])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(console.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(console.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0)}async _call(K,U,{hypothesis_template:pe="This example is {}.",multi_label:Pe=!1}={}){const Ee=Array.isArray(K);Ee||(K=[K]),Array.isArray(U)||(U=[U]);const Fe=U.map(Ne=>pe.replace("{}",Ne)),Ie=Pe||U.length===1,Le=[];for(const Ne of K){const Ve=[];for(const z of Fe){const ee=this.tokenizer(Ne,{text_pair:z,padding:!0,truncation:!0}),ce=await this.model(ee);Ie?Ve.push([ce.logits.data[this.contradiction_id],ce.logits.data[this.entailment_id]]):Ve.push(ce.logits.data[this.entailment_id])}const Z=(Ie?Ve.map(z=>(0,l.softmax)(z)[1]):(0,l.softmax)(Ve)).map((z,ee)=>[z,ee]).sort((z,ee)=>ee[0]-z[0]);Le.push({sequence:Ne,labels:Z.map(z=>U[z[1]]),scores:Z.map(z=>z[0])})}return Ee?Le:Le[0]}}class R extends P{constructor(K){super(K)}async _call(K,{pooling:U="none",normalize:pe=!1,quantize:Pe=!1,precision:Ee="binary"}={}){const Fe=this.tokenizer(K,{padding:!0,truncation:!0}),Ie=await this.model(Fe);let Le=Ie.last_hidden_state??Ie.logits??Ie.token_embeddings;if(U!=="none")if(U==="mean")Le=(0,p.mean_pooling)(Le,Fe.attention_mask);else if(U==="cls")Le=Le.slice(null,0);else throw Error(`Pooling method '${U}' not supported.`);return pe&&(Le=Le.normalize(2,-1)),Pe&&(Le=(0,p.quantize_embeddings)(Le,Ee)),Le}}class J extends P{constructor(K){super(K)}async _call(K,{pool:U=null}={}){const pe=await h(K),{pixel_values:Pe}=await this.processor(pe),Ee=await this.model({pixel_values:Pe});let Fe;if(U){if(!("pooler_output"in Ee))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");Fe=Ee.pooler_output}else Fe=Ee.last_hidden_state??Ee.logits??Ee.image_embeds;return Fe}}class q extends P{constructor(K){super(K)}async _call(K,{top_k:U=5}={}){const pe=this.processor.feature_extractor.config.sampling_rate,Pe=await w(K,pe),Ee=this.model.config.id2label,Fe=[];for(const Ie of Pe){const Le=await this.processor(Ie),Ve=(await this.model(Le)).logits[0],D=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Ve.data),Ve.dims),U),Z=D[0].tolist(),ee=D[1].tolist().map((ce,be)=>({label:Ee?Ee[ce]:`LABEL_${ce}`,score:Z[be]}));Fe.push(ee)}return Array.isArray(K)?Fe:Fe[0]}}class V extends P{constructor(K){super(K)}async _call(K,U,{hypothesis_template:pe="This is a sound of {}."}={}){const Pe=!Array.isArray(K);Pe&&(K=[K]);const Ee=U.map(Ve=>pe.replace("{}",Ve)),Fe=this.tokenizer(Ee,{padding:!0,truncation:!0}),Ie=this.processor.feature_extractor.config.sampling_rate,Le=await w(K,Ie),Ne=[];for(const Ve of Le){const D=await this.processor(Ve),Z=await this.model({...Fe,...D}),z=(0,l.softmax)(Z.logits_per_audio.data);Ne.push([...z].map((ee,ce)=>({score:ee,label:U[ce]})))}return Pe?Ne[0]:Ne}}class Y extends P{constructor(K){super(K)}async _call(K,U={}){switch(this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(K,U);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":return this._call_wav2vec2(K,U);case"moonshine":return this._call_moonshine(K,U);default:throw new Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(K,U){U.language&&console.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),U.task&&console.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');const pe=!Array.isArray(K);pe&&(K=[K]);const Pe=this.processor.feature_extractor.config.sampling_rate,Ee=await w(K,Pe),Fe=[];for(const Ie of Ee){const Le=await this.processor(Ie),Ve=(await this.model(Le)).logits[0],D=[];for(const z of Ve)D.push((0,l.max)(z.data)[1]);const Z=this.tokenizer.decode(D);Fe.push({text:Z})}return pe?Fe[0]:Fe}async _call_whisper(K,U){const pe=U.return_timestamps??!1,Pe=U.chunk_length_s??0,Ee=U.force_full_sequences??!1;let Fe=U.stride_length_s??null;const Ie={...U};pe==="word"&&(Ie.return_token_timestamps=!0,Ie.return_timestamps=!1);const Le=!Array.isArray(K);Le&&(K=[K]);const Ne=this.processor.feature_extractor.config.chunk_length/this.model.config.max_source_positions,Ve=this.processor.feature_extractor.config.hop_length,D=this.processor.feature_extractor.config.sampling_rate,Z=await w(K,D),z=[];for(const ee of Z){let ce=[];if(Pe>0){if(Fe===null)Fe=Pe/6;else if(Pe<=Fe)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");const Re=D*Pe,Ae=D*Fe,Ue=Re-2*Ae;let Qe=0;for(;;){const Xe=Qe+Re,ct=ee.subarray(Qe,Xe),vt=await this.processor(ct),nr=Qe===0,jt=Xe>=ee.length;if(ce.push({stride:[ct.length,nr?0:Ae,jt?0:Ae],input_features:vt.input_features,is_last:jt}),jt)break;Qe+=Ue}}else ce=[{stride:[ee.length,0,0],input_features:(await this.processor(ee)).input_features,is_last:!0}];for(const Re of ce){Ie.num_frames=Math.floor(Re.stride[0]/Ve);const Ae=await this.model.generate({inputs:Re.input_features,...Ie});pe==="word"?(Re.tokens=Ae.sequences.tolist()[0],Re.token_timestamps=Ae.token_timestamps.tolist()[0].map(Ue=>(0,l.round)(Ue,2))):Re.tokens=Ae[0].tolist(),Re.stride=Re.stride.map(Ue=>Ue/D)}const[be,ve]=this.tokenizer._decode_asr(ce,{time_precision:Ne,return_timestamps:pe,force_full_sequences:Ee});z.push({text:be,...ve})}return Le?z[0]:z}async _call_moonshine(K,U){const pe=!Array.isArray(K);pe&&(K=[K]);const Pe=this.processor.feature_extractor.config.sampling_rate,Ee=await w(K,Pe),Fe=[];for(const Ie of Ee){const Le=await this.processor(Ie),Ne=Math.floor(Ie.length/Pe)*6,Ve=await this.model.generate({max_new_tokens:Ne,...U,...Le}),D=this.processor.batch_decode(Ve,{skip_special_tokens:!0})[0];Fe.push({text:D})}return pe?Fe[0]:Fe}}class H extends P{constructor(K){super(K)}async _call(K,U={}){const pe=Array.isArray(K),Pe=await h(K),{pixel_values:Ee}=await this.processor(Pe),Fe=[];for(const Ie of Ee){Ie.dims=[1,...Ie.dims];const Le=await this.model.generate({inputs:Ie,...U}),Ne=this.tokenizer.batch_decode(Le,{skip_special_tokens:!0}).map(Ve=>({generated_text:Ve.trim()}));Fe.push(Ne)}return pe?Fe:Fe[0]}}class Q extends P{constructor(K){super(K)}async _call(K,{top_k:U=5}={}){const pe=await h(K),{pixel_values:Pe}=await this.processor(pe),Ee=await this.model({pixel_values:Pe}),Fe=this.model.config.id2label,Ie=[];for(const Le of Ee.logits){const Ne=await(0,p.topk)(new p.Tensor("float32",(0,l.softmax)(Le.data),Le.dims),U),Ve=Ne[0].tolist(),Z=Ne[1].tolist().map((z,ee)=>({label:Fe?Fe[z]:`LABEL_${z}`,score:Ve[ee]}));Ie.push(Z)}return Array.isArray(K)?Ie:Ie[0]}}class ie extends P{constructor(K){super(K),this.subtasks_mapping={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"}}async _call(K,{threshold:U=.5,mask_threshold:pe=.5,overlap_mask_area_threshold:Pe=.8,label_ids_to_fuse:Ee=null,target_sizes:Fe=null,subtask:Ie=null}={}){if(Array.isArray(K)&&K.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");const Ne=await h(K),Ve=Ne.map(Re=>[Re.height,Re.width]),D=await this.processor(Ne),{inputNames:Z,outputNames:z}=this.model.sessions.model;if(!Z.includes("pixel_values")){if(Z.length!==1)throw Error(`Expected a single input name, but got ${Z.length} inputs: ${Z}.`);const Re=Z[0];if(Re in D)throw Error(`Input name ${Re} already exists in the inputs.`);D[Re]=D.pixel_values}const ee=await this.model(D);let ce=null;if(Ie!==null)ce=this.subtasks_mapping[Ie];else if(this.processor.image_processor){for(const[Re,Ae]of Object.entries(this.subtasks_mapping))if(Ae in this.processor.image_processor){ce=this.processor.image_processor[Ae].bind(this.processor.image_processor),Ie=Re;break}}const be=this.model.config.id2label,ve=[];if(Ie)if(Ie==="panoptic"||Ie==="instance"){const Re=ce(ee,U,pe,Pe,Ee,Fe??Ve)[0],Ae=Re.segmentation;for(const Ue of Re.segments_info){const Qe=new Uint8ClampedArray(Ae.data.length);for(let ct=0;ctct<0||ct>1)&&Qe.sigmoid_();const Xe=await u.RawImage.fromTensor(Qe.mul_(255).to("uint8")).resize(Ue[1],Ue[0]);ve.push({label:null,score:null,mask:Xe})}}return ve}}class le extends ie{constructor(K){super(K)}async _call(K,U={}){if(Array.isArray(K)&&K.length!==1)throw Error("Background removal pipeline currently only supports a batch size of 1.");const Pe=await h(K),Ee=await super._call(K,U);return Pe.map((Ie,Le)=>{const Ne=Ie.clone();return Ne.putAlpha(Ee[Le].mask),Ne})}}class ae extends P{constructor(K){super(K)}async _call(K,U,{hypothesis_template:pe="This is a photo of {}"}={}){const Pe=Array.isArray(K),Ee=await h(K),Fe=U.map(Z=>pe.replace("{}",Z)),Ie=this.tokenizer(Fe,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:Le}=await this.processor(Ee),Ne=await this.model({...Ie,pixel_values:Le}),Ve=this.model.config.model_type==="siglip"?Z=>Z.sigmoid().data:Z=>(0,l.softmax)(Z.data),D=[];for(const Z of Ne.logits_per_image){const ee=[...Ve(Z)].map((ce,be)=>({score:ce,label:U[be]}));ee.sort((ce,be)=>be.score-ce.score),D.push(ee)}return Pe?D:D[0]}}class ge extends P{constructor(K){super(K)}async _call(K,{threshold:U=.9,percentage:pe=!1}={}){const Pe=Array.isArray(K);if(Pe&&K.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");const Ee=await h(K),Fe=pe?null:Ee.map(z=>[z.height,z.width]),{pixel_values:Ie,pixel_mask:Le}=await this.processor(Ee),Ne=await this.model({pixel_values:Ie,pixel_mask:Le}),Ve=this.processor.image_processor.post_process_object_detection(Ne,U,Fe),D=this.model.config.id2label,Z=Ve.map(z=>z.boxes.map((ee,ce)=>({score:z.scores[ce],label:D[z.classes[ce]],box:_(ee,!pe)})));return Pe?Z:Z[0]}}class N extends P{constructor(K){super(K)}async _call(K,U,{threshold:pe=.1,top_k:Pe=null,percentage:Ee=!1}={}){const Fe=Array.isArray(K),Ie=await h(K),Le=this.tokenizer(U,{padding:!0,truncation:!0}),Ne=await this.processor(Ie),Ve=[];for(let D=0;D({score:ve.scores[Ae],label:ve.labels[Ae],box:_(Re,!Ee)}))}else{const ve=this.processor.image_processor.post_process_object_detection(ce,pe,z,!0)[0];be=ve.boxes.map((Re,Ae)=>({score:ve.scores[Ae],label:U[ve.classes[Ae]],box:_(Re,!Ee)}))}be.sort((ve,Re)=>Re.score-ve.score),Pe!==null&&(be=be.slice(0,Pe)),Ve.push(be)}return Fe?Ve:Ve[0]}}class O extends P{constructor(K){super(K)}async _call(K,U,pe={}){const Pe=(await h(K))[0],{pixel_values:Ee}=await this.processor(Pe),Fe=`${U}`,Ie=this.tokenizer(Fe,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,Le=await this.model.generate({inputs:Ee,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:Ie,...pe}),Ve=this.tokenizer.batch_decode(Le)[0].match(/(.*?)<\/s_answer>/);let D=null;return Ve&&Ve.length>=2&&(D=Ve[1].trim()),[{answer:D}]}}class G extends P{constructor(U){super(U);re(this,"DEFAULT_VOCODER_ID","Xenova/speecht5_hifigan");this.vocoder=U.vocoder??null}async _call(U,{speaker_embeddings:pe=null}={}){return this.processor?this._call_text_to_spectrogram(U,{speaker_embeddings:pe}):this._call_text_to_waveform(U)}async _call_text_to_waveform(U){const pe=this.tokenizer(U,{padding:!0,truncation:!0}),{waveform:Pe}=await this.model(pe),Ee=this.model.config.sampling_rate;return new d.RawAudio(Pe.data,Ee)}async _call_text_to_spectrogram(U,{speaker_embeddings:pe}){if(this.vocoder||(console.log("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await i.AutoModel.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"})),(typeof pe=="string"||pe instanceof URL)&&(pe=new Float32Array(await(await fetch(pe)).arrayBuffer())),pe instanceof Float32Array)pe=new p.Tensor("float32",pe,[1,pe.length]);else if(!(pe instanceof p.Tensor))throw new Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");const{input_ids:Pe}=this.tokenizer(U,{padding:!0,truncation:!0}),{waveform:Ee}=await this.model.generate_speech(Pe,pe,{vocoder:this.vocoder}),Fe=this.processor.feature_extractor.config.sampling_rate;return new d.RawAudio(Ee.data,Fe)}}class ne extends P{constructor(K){super(K)}async _call(K){const U=await h(K),pe=await this.processor(U),Pe=await this.model(pe),Ee=[];for(const Fe of Pe.reconstruction){const Ie=Fe.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");Ee.push(u.RawImage.fromTensor(Ie))}return Ee.length>1?Ee:Ee[0]}}class X extends P{constructor(K){super(K)}async _call(K){const U=await h(K),pe=await this.processor(U),{predicted_depth:Pe}=await this.model(pe),Ee=[];for(let Fe=0;Fe1?Ee:Ee[0]}}const we=Object.freeze({"text-classification":{tokenizer:s.AutoTokenizer,pipeline:A,model:i.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{tokenizer:s.AutoTokenizer,pipeline:v,model:i.AutoModelForTokenClassification,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{tokenizer:s.AutoTokenizer,pipeline:y,model:i.AutoModelForQuestionAnswering,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{tokenizer:s.AutoTokenizer,pipeline:S,model:i.AutoModelForMaskedLM,default:{model:"Xenova/bert-base-uncased"},type:"text"},summarization:{tokenizer:s.AutoTokenizer,pipeline:g,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{tokenizer:s.AutoTokenizer,pipeline:M,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{tokenizer:s.AutoTokenizer,pipeline:x,model:i.AutoModelForSeq2SeqLM,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{tokenizer:s.AutoTokenizer,pipeline:k,model:i.AutoModelForCausalLM,default:{model:"Xenova/gpt2"},type:"text"},"zero-shot-classification":{tokenizer:s.AutoTokenizer,pipeline:B,model:i.AutoModelForSequenceClassification,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:q,model:i.AutoModelForAudioClassification,processor:n.AutoProcessor,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{tokenizer:s.AutoTokenizer,pipeline:V,model:i.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{tokenizer:s.AutoTokenizer,pipeline:Y,model:[i.AutoModelForSpeechSeq2Seq,i.AutoModelForCTC],processor:n.AutoProcessor,default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{tokenizer:s.AutoTokenizer,pipeline:G,model:[i.AutoModelForTextToWaveform,i.AutoModelForTextToSpectrogram],processor:[n.AutoProcessor,null],default:{model:"Xenova/speecht5_tts"},type:"text"},"image-to-text":{tokenizer:s.AutoTokenizer,pipeline:H,model:i.AutoModelForVision2Seq,processor:n.AutoProcessor,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:Q,model:i.AutoModelForImageClassification,processor:n.AutoProcessor,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:ie,model:[i.AutoModelForImageSegmentation,i.AutoModelForSemanticSegmentation,i.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:le,model:[i.AutoModelForImageSegmentation,i.AutoModelForSemanticSegmentation,i.AutoModelForUniversalSegmentation],processor:n.AutoProcessor,default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{tokenizer:s.AutoTokenizer,pipeline:ae,model:i.AutoModel,processor:n.AutoProcessor,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:ge,model:i.AutoModelForObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{tokenizer:s.AutoTokenizer,pipeline:N,model:i.AutoModelForZeroShotObjectDetection,processor:n.AutoProcessor,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{tokenizer:s.AutoTokenizer,pipeline:O,model:i.AutoModelForDocumentQuestionAnswering,processor:n.AutoProcessor,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:ne,model:i.AutoModelForImageToImage,processor:n.AutoProcessor,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:X,model:i.AutoModelForDepthEstimation,processor:n.AutoProcessor,default:{model:"Xenova/dpt-large"},type:"image"},"feature-extraction":{tokenizer:s.AutoTokenizer,pipeline:R,model:i.AutoModel,default:{model:"Xenova/all-MiniLM-L6-v2"},type:"text"},"image-feature-extraction":{processor:n.AutoProcessor,pipeline:J,model:[i.AutoModelForImageFeatureExtraction,i.AutoModel],default:{model:"Xenova/vit-base-patch16-224-in21k"},type:"image"}}),fe=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function ke(Me,K=null,{progress_callback:U=null,config:pe=null,cache_dir:Pe=null,local_files_only:Ee=!1,revision:Fe="main",device:Ie=null,dtype:Le=null,subfolder:Ne="onnx",use_external_data_format:Ve=null,model_file_name:D=null,session_options:Z={}}={}){Me=fe[Me]??Me;const z=we[Me.split("_",1)[0]];if(!z)throw Error(`Unsupported pipeline: ${Me}. Must be one of [${Object.keys(we)}]`);K||(K=z.default.model,console.log(`No model specified. Using default model: "${K}".`));const ee={progress_callback:U,config:pe,cache_dir:Pe,local_files_only:Ee,revision:Fe,device:Ie,dtype:Le,subfolder:Ne,use_external_data_format:Ve,model_file_name:D,session_options:Z},ce=new Map([["tokenizer",z.tokenizer],["model",z.model],["processor",z.processor]]),be=await He(ce,K,ee);be.task=Me,(0,a.dispatchCallback)(U,{status:"ready",task:Me,model:K});const ve=z.pipeline;return new ve(be)}async function He(Me,K,U){const pe=Object.create(null),Pe=[];for(const[Ee,Fe]of Me.entries()){if(!Fe)continue;let Ie;Array.isArray(Fe)?Ie=new Promise(async(Le,Ne)=>{var D,Z;let Ve;for(const z of Fe){if(z===null){Le(null);return}try{Le(await z.from_pretrained(K,U));return}catch(ee){if((D=ee.message)!=null&&D.includes("Unsupported model type"))Ve=ee;else if((Z=ee.message)!=null&&Z.includes("Could not locate file"))Ve=ee;else{Ne(ee);return}}}Ne(Ve)}):Ie=Fe.from_pretrained(K,U),pe[Ee]=Ie,Pe.push(Ie)}await Promise.all(Pe);for(const[Ee,Fe]of Object.entries(pe))pe[Ee]=await Fe;return pe}},"./src/tokenizers.js":(e,r,t)=>{t.r(r),t.d(r,{AlbertTokenizer:()=>Br,AutoTokenizer:()=>fn,BartTokenizer:()=>ss,BertTokenizer:()=>Wr,BlenderbotSmallTokenizer:()=>Hr,BlenderbotTokenizer:()=>kr,BloomTokenizer:()=>Gr,CLIPTokenizer:()=>pn,CamembertTokenizer:()=>it,CodeGenTokenizer:()=>Kr,CodeLlamaTokenizer:()=>Gs,CohereTokenizer:()=>mn,ConvBertTokenizer:()=>hr,DebertaTokenizer:()=>vs,DebertaV2Tokenizer:()=>xs,DistilBertTokenizer:()=>et,ElectraTokenizer:()=>zt,EsmTokenizer:()=>Qs,FalconTokenizer:()=>os,GPT2Tokenizer:()=>rs,GPTNeoXTokenizer:()=>qs,GemmaTokenizer:()=>Or,Grok1Tokenizer:()=>Es,HerbertTokenizer:()=>Is,LlamaTokenizer:()=>Ws,M2M100Tokenizer:()=>Fs,MBart50Tokenizer:()=>ns,MBartTokenizer:()=>Tr,MPNetTokenizer:()=>Hs,MarianTokenizer:()=>hn,MgpstrTokenizer:()=>Ps,MobileBertTokenizer:()=>ts,NllbTokenizer:()=>As,NougatTokenizer:()=>mr,PreTrainedTokenizer:()=>dt,Qwen2Tokenizer:()=>Xs,RoFormerTokenizer:()=>Be,RobertaTokenizer:()=>is,SiglipTokenizer:()=>Dr,SpeechT5Tokenizer:()=>lr,SqueezeBertTokenizer:()=>bs,T5Tokenizer:()=>Sr,TokenizerModel:()=>J,VitsTokenizer:()=>Ds,Wav2Vec2CTCTokenizer:()=>Os,WhisperTokenizer:()=>$r,XLMRobertaTokenizer:()=>Ks,XLMTokenizer:()=>rr,is_chinese_char:()=>S});var s=t("./src/utils/generic.js"),i=t("./src/utils/core.js"),n=t("./src/utils/hub.js"),o=t("./src/utils/maths.js"),a=t("./src/utils/tensor.js"),l=t("./src/utils/data-structures.js"),d=t("./node_modules/@huggingface/jinja/dist/index.js"),p=t("./src/models/whisper/common_whisper.js");async function u(ue,F){const j=await Promise.all([(0,n.getModelJSON)(ue,"tokenizer.json",!0,F),(0,n.getModelJSON)(ue,"tokenizer_config.json",!0,F)]);return F.legacy!==null&&(j[1].legacy=F.legacy),j}function h(ue,F){const j=[];let te=0;for(const de of ue.matchAll(F)){const he=de[0];te0&&j.push(he),te=de.index+he.length}return te=19968&&ue<=40959||ue>=13312&&ue<=19903||ue>=131072&&ue<=173791||ue>=173824&&ue<=177983||ue>=177984&&ue<=178207||ue>=178208&&ue<=183983||ue>=63744&&ue<=64255||ue>=194560&&ue<=195103}function x(ue,F,j){const te=[];let de=0;for(;dethis.tokens_to_ids.get(j)??this.unk_token_id)}convert_ids_to_tokens(F){return F.map(j=>this.vocab[j]??this.unk_token)}}class q extends J{constructor(F){super(F),this.tokens_to_ids=_(F.vocab),this.unk_token_id=this.tokens_to_ids.get(F.unk_token),this.unk_token=F.unk_token,this.max_input_chars_per_word=F.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(const[j,te]of this.tokens_to_ids)this.vocab[te]=j}encode(F){const j=[];for(const te of F){const de=[...te];if(de.length>this.max_input_chars_per_word){j.push(this.unk_token);continue}let he=!1,Ce=0;const We=[];for(;Ce0&&(Ze=this.config.continuing_subword_prefix+Ze),this.tokens_to_ids.has(Ze)){Ke=Ze;break}--qe}if(Ke===null){he=!0;break}We.push(Ke),Ce=qe}he?j.push(this.unk_token):j.push(...We)}return j}}class V extends J{constructor(F,j){super(F);const te=F.vocab.length;this.vocab=new Array(te),this.scores=new Array(te);for(let de=0;de[de,he])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=j.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,o.min)(this.scores)[0],this.unk_score=this.minScore-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new l.CharTrie,this.trie.extend(this.vocab),this.fuse_unk=!0}populateNodes(F){const j=F.chars,te=1;let de=0;for(;de{const ue=[...Array.from({length:94},(de,he)=>he+33),...Array.from({length:12},(de,he)=>he+161),...Array.from({length:82},(de,he)=>he+174)],F=ue.slice();let j=0;for(let de=0;de<256;++de)ue.includes(de)||(ue.push(de),F.push(256+j),j+=1);const te=F.map(de=>String.fromCharCode(de));return Object.fromEntries(ue.map((de,he)=>[de,te[he]]))})(),H=(0,i.reverseDictionary)(Y);class Q extends J{constructor(F){super(F),this.tokens_to_ids=_(F.vocab),this.unk_token_id=this.tokens_to_ids.get(F.unk_token),this.unk_token=F.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(const[te,de]of this.tokens_to_ids)this.vocab[de]=te;const j=Array.isArray(F.merges[0]);this.merges=j?F.merges:F.merges.map(te=>te.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((te,de)=>[JSON.stringify(te),de])),this.end_of_word_suffix=F.end_of_word_suffix,this.continuing_subword_suffix=F.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.cache=new Map}bpe(F){if(F.length===0)return[];const j=this.cache.get(F);if(j!==void 0)return j;const te=Array.from(F);this.end_of_word_suffix&&(te[te.length-1]+=this.end_of_word_suffix);let de=[];if(te.length>1){const he=new l.PriorityQueue((qe,Ke)=>qe.score`<0x${We.toString(16).toUpperCase().padStart(2,"0")}>`);Ce.every(We=>this.tokens_to_ids.has(We))?j.push(...Ce):j.push(this.unk_token)}else j.push(this.unk_token)}return j}}class ie extends J{constructor(F,j){super(F),this.tokens_to_ids=_(j.target_lang?F.vocab[j.target_lang]:F.vocab),this.bos_token=j.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=j.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=j.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=j.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[te,de]of this.tokens_to_ids)this.vocab[de]=te}encode(F){return F}}class le extends s.Callable{constructor(F){super(),this.config=F}static fromConfig(F){if(F===null)return null;switch(F.type){case"BertNormalizer":return new Me(F);case"Precompiled":return new jt(F);case"Sequence":return new He(F);case"Replace":return new ae(F);case"NFC":return new N(F);case"NFD":return new O(F);case"NFKC":return new G(F);case"NFKD":return new ne(F);case"Strip":return new X(F);case"StripAccents":return new we(F);case"Lowercase":return new fe(F);case"Prepend":return new ke(F);default:throw new Error(`Unknown Normalizer type: ${F.type}`)}}normalize(F){throw Error("normalize should be implemented in subclass.")}_call(F){return this.normalize(F)}}class ae extends le{normalize(F){const j=w(this.config.pattern);return j===null?F:F.replaceAll(j,this.config.content)}}class ge extends le{constructor(){super(...arguments);re(this,"form")}normalize(j){return j=j.normalize(this.form),j}}class N extends ge{constructor(){super(...arguments);re(this,"form","NFC")}}class O extends ge{constructor(){super(...arguments);re(this,"form","NFD")}}class G extends ge{constructor(){super(...arguments);re(this,"form","NFKC")}}class ne extends ge{constructor(){super(...arguments);re(this,"form","NFKD")}}class X extends le{normalize(F){return this.config.strip_left&&this.config.strip_right?F=F.trim():(this.config.strip_left&&(F=F.trimStart()),this.config.strip_right&&(F=F.trimEnd())),F}}class we extends le{normalize(F){return F=v(F),F}}class fe extends le{normalize(F){return F=F.toLowerCase(),F}}class ke extends le{normalize(F){return F=this.config.prepend+F,F}}class He extends le{constructor(F){super(F),this.normalizers=F.normalizers.map(j=>le.fromConfig(j))}normalize(F){return this.normalizers.reduce((j,te)=>te.normalize(j),F)}}class Me extends le{_tokenize_chinese_chars(F){const j=[];for(let te=0;tethis.pre_tokenize_text(te,j)):this.pre_tokenize_text(F,j)).flat()}_call(F,j){return this.pre_tokenize(F,j)}}class U extends K{constructor(F){super(),this.pattern=new RegExp(`[^\\s${M}]+|[${M}]`,"gu")}pre_tokenize_text(F,j){return F.trim().match(this.pattern)||[]}}class pe extends K{constructor(F){super(),this.config=F,this.add_prefix_space=this.config.add_prefix_space,this.trim_offsets=this.config.trim_offsets,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=Y,this.text_encoder=new TextEncoder}pre_tokenize_text(F,j){return this.add_prefix_space&&!F.startsWith(" ")&&(F=" "+F),(this.use_regex?F.match(this.pattern)||[]:[F]).map(de=>Array.from(this.text_encoder.encode(de),he=>this.byte_encoder[he]).join(""))}}class Pe extends K{constructor(F){super(),this.config=F,this.pattern=w(this.config.pattern,this.config.invert)}pre_tokenize_text(F,j){var te;return this.pattern===null?[]:this.config.invert?F.match(this.pattern)||[]:((te=this.config.behavior)==null?void 0:te.toLowerCase())==="removed"?F.split(this.pattern).filter(de=>de):h(F,this.pattern)}}class Ee extends K{constructor(F){super(),this.config=F,this.pattern=new RegExp(`[^${M}]+|[${M}]+`,"gu")}pre_tokenize_text(F,j){return F.match(this.pattern)||[]}}class Fe extends K{constructor(F){super(),this.config=F;const j=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(j,"gu")}pre_tokenize_text(F,j){return F.match(this.pattern)||[]}}class Ie extends s.Callable{constructor(F){super(),this.config=F}static fromConfig(F){if(F===null)return null;switch(F.type){case"TemplateProcessing":return new Ve(F);case"ByteLevel":return new D(F);case"RobertaProcessing":return new Ne(F);case"BertProcessing":return new Le(F);case"Sequence":return new Z(F);default:throw new Error(`Unknown PostProcessor type: ${F.type}`)}}post_process(F,...j){throw Error("post_process should be implemented in subclass.")}_call(F,...j){return this.post_process(F,...j)}}class Le extends Ie{constructor(F){super(F),this.cls=F.cls[0],this.sep=F.sep[0]}post_process(F,j=null,{add_special_tokens:te=!0}={}){te&&(F=(0,i.mergeArrays)([this.cls],F,[this.sep]));let de=new Array(F.length).fill(0);if(j!==null){const he=te&&this instanceof Ne?[this.sep]:[],Ce=te?[this.sep]:[];F=(0,i.mergeArrays)(F,he,j,Ce),de=(0,i.mergeArrays)(de,new Array(j.length+he.length+Ce.length).fill(1))}return{tokens:F,token_type_ids:de}}}class Ne extends Le{}class Ve extends Ie{constructor(F){super(F),this.single=F.single,this.pair=F.pair}post_process(F,j=null,{add_special_tokens:te=!0}={}){const de=j===null?this.single:this.pair;let he=[],Ce=[];for(const We of de)"SpecialToken"in We?te&&(he.push(We.SpecialToken.id),Ce.push(We.SpecialToken.type_id)):"Sequence"in We&&(We.Sequence.id==="A"?(he=(0,i.mergeArrays)(he,F),Ce=(0,i.mergeArrays)(Ce,new Array(F.length).fill(We.Sequence.type_id))):We.Sequence.id==="B"&&(he=(0,i.mergeArrays)(he,j),Ce=(0,i.mergeArrays)(Ce,new Array(j.length).fill(We.Sequence.type_id))));return{tokens:he,token_type_ids:Ce}}}class D extends Ie{post_process(F,j=null){return j&&(F=(0,i.mergeArrays)(F,j)),{tokens:F}}}class Z extends Ie{constructor(F){super(F),this.processors=F.processors.map(j=>Ie.fromConfig(j))}post_process(F,j=null,te={}){let de;for(const he of this.processors)if(he instanceof D)F=he.post_process(F).tokens,j&&(j=he.post_process(j).tokens);else{const Ce=he.post_process(F,j,te);F=Ce.tokens,de=Ce.token_type_ids}return{tokens:F,token_type_ids:de}}}class z extends s.Callable{constructor(F){super(),this.config=F,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=F.trim_offsets}static fromConfig(F){if(F===null)return null;switch(F.type){case"WordPiece":return new Re(F);case"Metaspace":return new nr(F);case"ByteLevel":return new Ae(F);case"Replace":return new ee(F);case"ByteFallback":return new ce(F);case"Fuse":return new be(F);case"Strip":return new ve(F);case"Sequence":return new Qe(F);case"CTC":return new Ue(F);case"BPEDecoder":return new Xe(F);default:throw new Error(`Unknown Decoder type: ${F.type}`)}}_call(F){return this.decode(F)}decode(F){return this.decode_chain(F).join("")}decode_chain(F){throw Error("`decode_chain` should be implemented in subclass.")}}class ee extends z{decode_chain(F){const j=w(this.config.pattern);return j===null?F:F.map(te=>te.replaceAll(j,this.config.content))}}class ce extends z{constructor(F){super(F),this.text_decoder=new TextDecoder}decode_chain(F){const j=[];let te=[];for(const de of F){let he=null;if(de.length===6&&de.startsWith("<0x")&&de.endsWith(">")){const Ce=parseInt(de.slice(3,5),16);isNaN(Ce)||(he=Ce)}if(he!==null)te.push(he);else{if(te.length>0){const Ce=this.text_decoder.decode(Uint8Array.from(te));j.push(Ce),te=[]}j.push(de)}}if(te.length>0){const de=this.text_decoder.decode(Uint8Array.from(te));j.push(de),te=[]}return j}}class be extends z{decode_chain(F){return[F.join("")]}}class ve extends z{constructor(F){super(F),this.content=this.config.content,this.start=this.config.start,this.stop=this.config.stop}decode_chain(F){return F.map(j=>{let te=0;for(let he=0;he(te!==0&&(j.startsWith(this.config.prefix)?j=j.replace(this.config.prefix,""):j=" "+j),this.cleanup&&(j=A(j)),j))}}class Ae extends z{constructor(F){super(F),this.byte_decoder=H,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(F){const j=F.join(""),te=new Uint8Array([...j].map(he=>this.byte_decoder[he]));return this.text_decoder.decode(te)}decode_chain(F){const j=[];let te=[];for(const de of F)this.added_tokens.find(he=>he.content===de)!==void 0?(te.length>0&&(j.push(this.convert_tokens_to_string(te)),te=[]),j.push(de)):te.push(de);return te.length>0&&j.push(this.convert_tokens_to_string(te)),j}}class Ue extends z{constructor(F){super(F),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(F){if(F.length===0)return"";const j=[F[0]];for(let he=1;hehe!==this.pad_token).join("");return this.cleanup&&(de=A(de).replaceAll(this.word_delimiter_token," ").trim()),de}decode_chain(F){return[this.convert_tokens_to_string(F)]}}class Qe extends z{constructor(F){super(F),this.decoders=F.decoders.map(j=>z.fromConfig(j))}decode_chain(F){return this.decoders.reduce((j,te)=>te.decode_chain(j),F)}}class Xe extends z{constructor(F){super(F),this.suffix=this.config.suffix}decode_chain(F){return F.map((j,te)=>j.replaceAll(this.suffix,te===F.length-1?"":" "))}}class ct extends z{decode_chain(F){let j="";for(let te=1;tete.normalize("NFKC")).join("~"):F=F.normalize("NFKC"),F}}class ar extends K{constructor(F){super(),this.tokenizers=F.pretokenizers.map(j=>K.fromConfig(j))}pre_tokenize_text(F,j){return this.tokenizers.reduce((te,de)=>de.pre_tokenize(te,j),[F])}}class Zr extends K{constructor(F){super()}pre_tokenize_text(F,j){return F.match(/\w+|[^\w\s]+/g)||[]}}class $s extends K{constructor(F){super()}pre_tokenize_text(F,j){return g(F)}}class Fr extends K{constructor(F){super(),this.config=F,this.pattern=w(this.config.pattern),this.content=this.config.content}pre_tokenize_text(F,j){return this.pattern===null?[F]:[F.replaceAll(this.pattern,this.config.content)]}}const es=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function ks(ue,F,j,te){for(const de of Object.keys(ue)){const he=F-ue[de].length,Ce=j(de),We=new Array(he).fill(Ce);ue[de]=te==="right"?(0,i.mergeArrays)(ue[de],We):(0,i.mergeArrays)(We,ue[de])}}function zr(ue,F){for(const j of Object.keys(ue))ue[j].length=F}class dt extends s.Callable{constructor(j,te){super();re(this,"return_token_type_ids",!1);re(this,"padding_side","right");this._tokenizer_config=te,this.normalizer=le.fromConfig(j.normalizer),this.pre_tokenizer=K.fromConfig(j.pre_tokenizer),this.model=J.fromConfig(j.model,te),this.post_processor=Ie.fromConfig(j.post_processor),this.decoder=z.fromConfig(j.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];for(const de of j.added_tokens){const he=new R(de);this.added_tokens.push(he),this.model.tokens_to_ids.set(he.content,he.id),this.model.vocab[he.id]=he.content,he.special&&(this.special_tokens.push(he.content),this.all_special_ids.push(he.id))}if(this.additional_special_tokens=te.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_regex=this.added_tokens.length>0?new RegExp(this.added_tokens.slice().sort((de,he)=>he.content.length-de.content.length).map(de=>`${de.lstrip?"\\s*":""}(${(0,i.escapeRegExp)(de.content)})${de.rstrip?"\\s*":""}`).join("|")):null,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=te.model_max_length,this.remove_space=te.remove_space,this.clean_up_tokenization_spaces=te.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=te.do_lowercase_and_remove_accent??!1,te.padding_side&&(this.padding_side=te.padding_side),this.legacy=!1,this.chat_template=te.chat_template??null,Array.isArray(this.chat_template)){const de=Object.create(null);for(const{name:he,template:Ce}of this.chat_template){if(typeof he!="string"||typeof Ce!="string")throw new Error('Chat template must be a list of objects with "name" and "template" properties');de[he]=Ce}this.chat_template=de}this._compiled_template_cache=new Map}getToken(...j){for(const te of j){const de=this._tokenizer_config[te];if(de)if(typeof de=="object"){if(de.__type==="AddedToken")return de.content;throw Error(`Unknown token: ${de}`)}else return de}return null}static async from_pretrained(j,{progress_callback:te=null,config:de=null,cache_dir:he=null,local_files_only:Ce=!1,revision:We="main",legacy:qe=null}={}){const Ke=await u(j,{progress_callback:te,config:de,cache_dir:he,local_files_only:Ce,revision:We,legacy:qe});return new this(...Ke)}_call(j,{text_pair:te=null,add_special_tokens:de=!0,padding:he=!1,truncation:Ce=null,max_length:We=null,return_tensor:qe=!0,return_token_type_ids:Ke=null}={}){const Ze=Array.isArray(j);let pt;if(Ze){if(j.length===0)throw Error("text array must be non-empty");if(te!==null){if(Array.isArray(te)){if(j.length!==te.length)throw Error("text and text_pair must have the same length")}else throw Error("text_pair must also be an array");pt=j.map(($t,Vt)=>this._encode_plus($t,{text_pair:te[Vt],add_special_tokens:de,return_token_type_ids:Ke}))}else pt=j.map($t=>this._encode_plus($t,{add_special_tokens:de,return_token_type_ids:Ke}))}else{if(j==null)throw Error("text may not be null or undefined");if(Array.isArray(te))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");pt=[this._encode_plus(j,{text_pair:te,add_special_tokens:de,return_token_type_ids:Ke})]}if(We===null?he==="max_length"?We=this.model_max_length:We=(0,o.max)(pt.map($t=>$t.input_ids.length))[0]:Ce||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."),We=Math.min(We,this.model_max_length??1/0),he||Ce)for(let $t=0;$tWe?Ce&&zr(pt[$t],We):he&&ks(pt[$t],We,Vt=>Vt==="input_ids"?this.pad_token_id:0,this.padding_side));const Ct={};if(qe){if(!(he&&Ce)&&pt.some(Vt=>{var At;for(const Ut of Object.keys(Vt))if(Vt[Ut].length!==((At=pt[0][Ut])==null?void 0:At.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 $t=[pt.length,pt[0].input_ids.length];for(const Vt of Object.keys(pt[0]))Ct[Vt]=new a.Tensor("int64",BigInt64Array.from(pt.flatMap(At=>At[Vt]).map(BigInt)),$t)}else{for(const $t of Object.keys(pt[0]))Ct[$t]=pt.map(Vt=>Vt[$t]);if(!Ze)for(const $t of Object.keys(Ct))Ct[$t]=Ct[$t][0]}return Ct}_encode_text(j){return j===null?null:(this.added_tokens_regex?j.split(this.added_tokens_regex).filter(he=>he):[j]).map((he,Ce)=>{if(this.added_tokens.find(qe=>qe.content===he)!==void 0)return he;{if(this.remove_space===!0&&(he=he.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(he=y(he)),this.normalizer!==null&&(he=this.normalizer(he)),he.length===0)return[];const qe=this.pre_tokenizer!==null?this.pre_tokenizer(he,{section_index:Ce}):[he];return this.model(qe)}}).flat()}_encode_plus(j,{text_pair:te=null,add_special_tokens:de=!0,return_token_type_ids:he=null}={}){const{tokens:Ce,token_type_ids:We}=this._tokenize_helper(j,{pair:te,add_special_tokens:de}),qe=this.model.convert_tokens_to_ids(Ce),Ke={input_ids:qe,attention_mask:new Array(qe.length).fill(1)};return(he??this.return_token_type_ids)&&We&&(Ke.token_type_ids=We),Ke}_tokenize_helper(j,{pair:te=null,add_special_tokens:de=!1}={}){const he=this._encode_text(j),Ce=this._encode_text(te);return this.post_processor?this.post_processor(he,Ce,{add_special_tokens:de}):{tokens:(0,i.mergeArrays)(he??[],Ce??[])}}tokenize(j,{pair:te=null,add_special_tokens:de=!1}={}){return this._tokenize_helper(j,{pair:te,add_special_tokens:de}).tokens}encode(j,{text_pair:te=null,add_special_tokens:de=!0,return_token_type_ids:he=null}={}){return this._encode_plus(j,{text_pair:te,add_special_tokens:de,return_token_type_ids:he}).input_ids}batch_decode(j,te={}){return j instanceof a.Tensor&&(j=j.tolist()),j.map(de=>this.decode(de,te))}decode(j,te={}){if(j instanceof a.Tensor&&(j=P(j)),!Array.isArray(j)||j.length===0||!(0,i.isIntegralNumber)(j[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(j,te)}decode_single(j,{skip_special_tokens:te=!1,clean_up_tokenization_spaces:de=null}){let he=this.model.convert_ids_to_tokens(j);te&&(he=he.filter(We=>!this.special_tokens.includes(We)));let Ce=this.decoder?this.decoder(he):he.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(Ce=Ce.replaceAll(this.decoder.end_of_word_suffix," "),te&&(Ce=Ce.trim())),(de??this.clean_up_tokenization_spaces)&&(Ce=A(Ce)),Ce}get_chat_template({chat_template:j=null,tools:te=null}={}){if(this.chat_template&&typeof this.chat_template=="object"){const de=this.chat_template;if(j!==null&&Object.hasOwn(de,j))j=de[j];else if(j===null)if(te!==null&&"tool_use"in de)j=de.tool_use;else if("default"in de)j=de.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(de).sort()}.`)}else if(j===null)if(this.chat_template)j=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 j}apply_chat_template(j,{tools:te=null,documents:de=null,chat_template:he=null,add_generation_prompt:Ce=!1,tokenize:We=!0,padding:qe=!1,truncation:Ke=!1,max_length:Ze=null,return_tensor:pt=!0,return_dict:Ct=!1,tokenizer_kwargs:$t={},...Vt}={}){if(he=this.get_chat_template({chat_template:he,tools:te}),typeof he!="string")throw Error(`chat_template must be a string, but got ${typeof he}`);let At=this._compiled_template_cache.get(he);At===void 0&&(At=new d.Template(he),this._compiled_template_cache.set(he,At));const Ut=Object.create(null);for(const fr of es){const qr=this.getToken(fr);qr&&(Ut[fr]=qr)}const br=At.render({messages:j,add_generation_prompt:Ce,tools:te,documents:de,...Ut,...Vt});if(We){const fr=this._call(br,{add_special_tokens:!1,padding:qe,truncation:Ke,max_length:Ze,return_tensor:pt,...$t});return Ct?fr:fr.input_ids}return br}}class Wr extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Br extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class ts extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class bs extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class vs extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class xs extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Is extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class hr extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Be extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class et extends dt{}class it extends dt{}class rr extends dt{constructor(j,te){super(j,te);re(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 zt extends dt{constructor(){super(...arguments);re(this,"return_token_type_ids",!0)}}class Sr extends dt{}class rs extends dt{}class ss extends dt{}class Tr extends dt{constructor(F,j){super(F,j),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.special_tokens.filter(te=>this.languageRegex.test(te)),this.lang_to_token=te=>te}_build_translation_inputs(F,j,te){return Mr(this,F,j,te)}}class ns extends Tr{}class is extends dt{}class Gr extends dt{}const Ts="▁";class Ws extends dt{constructor(j,te){super(j,te);re(this,"padding_side","left");this.legacy=te.legacy??!0,this.legacy||(this.normalizer=null,this.pre_tokenizer=new vt({replacement:Ts,add_prefix_space:!0,prepend_scheme:"first"}))}_encode_text(j){if(j===null)return null;if(this.legacy||j.length===0)return super._encode_text(j);let te=super._encode_text(Ts+j.replaceAll(Ts," "));return te.length>1&&te[0]===Ts&&this.special_tokens.includes(te[1])&&(te=te.slice(1)),te}}class Gs extends dt{}class Ks extends dt{}class Hs extends dt{}class os extends dt{}class qs extends dt{}class Qs extends dt{}class Xs extends dt{}class Or extends dt{}class Es extends dt{}function Mr(ue,F,j,te){if(!("language_codes"in ue)||!Array.isArray(ue.language_codes))throw new Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in ue)||!(ue.languageRegex instanceof RegExp))throw new Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in ue)||typeof ue.lang_to_token!="function")throw new Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");const de=te.src_lang,he=te.tgt_lang;if(!ue.language_codes.includes(he))throw new Error(`Target language code "${he}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);if(de!==void 0){if(!ue.language_codes.includes(de))throw new Error(`Source language code "${de}" is not valid. Must be one of: {${ue.language_codes.join(", ")}}`);for(const Ce of ue.post_processor.config.single)if("SpecialToken"in Ce&&ue.languageRegex.test(Ce.SpecialToken.id)){Ce.SpecialToken.id=ue.lang_to_token(de);break}}return te.forced_bos_token_id=ue.model.convert_tokens_to_ids([ue.lang_to_token(he)])[0],ue._call(F,j)}class As extends dt{constructor(F,j){super(F,j),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.special_tokens.filter(te=>this.languageRegex.test(te)),this.lang_to_token=te=>te}_build_translation_inputs(F,j,te){return Mr(this,F,j,te)}}class Fs extends dt{constructor(F,j){super(F,j),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.special_tokens.filter(te=>this.languageRegex.test(te)).map(te=>te.slice(2,-2)),this.lang_to_token=te=>`__${te}__`}_build_translation_inputs(F,j,te){return Mr(this,F,j,te)}}class $r extends dt{get timestamp_begin(){return this.model.convert_tokens_to_ids(["<|notimestamps|>"])[0]+1}_decode_asr(F,{return_timestamps:j=!1,return_language:te=!1,time_precision:de=null,force_full_sequences:he=!0}={}){if(de===null)throw Error("Must specify time_precision");let Ce=null;const We=j==="word";function qe(){return{language:Ce,timestamp:[null,null],text:""}}const Ke=[];let Ze=qe(),pt=0;const Ct=this.timestamp_begin,Vt=Ct+1500;let At=[],Ut=[],br=!1,fr=null;const qr=new Set(this.all_special_ids);for(const Wt of F){const Yt=Wt.tokens,_r=We?Wt.token_timestamps:null;let Qr=null,ls=Ct;if("stride"in Wt){const[Rt,Xt,qt]=Wt.stride;if(pt-=Xt,fr=Rt-qt,Xt&&(ls=Xt/de+Ct),qt)for(let Zt=Yt.length-1;Zt>=0;--Zt){const ir=Number(Yt[Zt]);if(ir>=Ct){if(Qr!==null&&(ir-Ct)*de=Ct&&Xt<=Vt){const qt=(Xt-Ct)*de+pt,Zt=(0,o.round)(qt,2);if(Qr!==null&&Xt>=Qr)br=!0;else if(br||At.length>0&&Xt0?(At.push(Ht),We&&Ut.push(dr)):At.every(Rt=>Rt.length===0)&&(Ze=qe(),At=[],Ht=[],Ut=[],dr=[])}if(At.length>0){if(he&&j)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[Wt,Yt]=this.findLongestCommonSequence(At,Ut),_r=this.decode(Wt);Ze.text=_r,We&&(Ze.words=this.collateWordTimestamps(Wt,Yt,Ce)),Ke.push(Ze)}let vr=Object.create(null);const as=Ke.map(Wt=>Wt.text).join("");if(j||te){for(let Wt=0;Wt0;let We=Ce?[]:null,qe=Ce?j[0]:null;for(let Ke=1;KeXt===ls[qt]&&qe[as+qt]<=j[Ke][_r+qt]).length:Ht=Yt.filter((Xt,qt)=>Xt===ls[qt]).length;const dr=vr/1e4,Rt=Ht/vr+dr;Ht>1&&Rt>pt&&(pt=Rt,Ct=[as,Wt,_r,Qr])}const[Vt,At,Ut,br]=Ct,fr=Math.floor((At+Vt)/2),qr=Math.floor((br+Ut)/2);he.push(...te.slice(0,fr)),te=Ze.slice(qr),de=te.length,Ce&&(We.push(...qe.slice(0,fr)),qe=j[Ke].slice(qr))}return he.push(...te),Ce?(We.push(...qe),[he,We]):[he,[]]}collateWordTimestamps(F,j,te){const[de,he,Ce]=this.combineTokensIntoWords(F,te),We=[];for(let qe=0;qe=de){const We=((Ce-de)*te).toFixed(2);he.push(`<|${We}|>`),he.push([])}else he[he.length-1].push(Ce);return he=he.map(Ce=>typeof Ce=="string"?Ce:super.decode(Ce,j)),he.join("")}splitTokensOnUnicode(F){const j=this.decode(F,{decode_with_timestamps:!0}),te="�",de=[],he=[],Ce=[];let We=[],qe=[],Ke=0;for(let Ze=0;Ze=this.model.tokens_to_ids.get("<|endoftext|>"),Vt=Ze.startsWith(" "),At=Ze.trim(),Ut=qe.test(At);if($t||Vt||Ut||he.length===0)he.push(Ze),Ce.push(pt),We.push(Ct);else{const br=he.length-1;he[br]+=Ze,Ce[br].push(...pt),We[br].push(...Ct)}}return[he,Ce,We]}mergePunctuations(F,j,te,de,he){const Ce=structuredClone(F),We=structuredClone(j),qe=structuredClone(te);let Ke=Ce.length-2,Ze=Ce.length-1;for(;Ke>=0;)Ce[Ke].startsWith(" ")&&de.includes(Ce[Ke].trim())?(Ce[Ze]=Ce[Ke]+Ce[Ze],We[Ze]=(0,i.mergeArrays)(We[Ke],We[Ze]),qe[Ze]=(0,i.mergeArrays)(qe[Ke],qe[Ze]),Ce[Ke]="",We[Ke]=[],qe[Ke]=[]):Ze=Ke,--Ke;for(Ke=0,Ze=1;Zept),We.filter(pt=>pt.length>0),qe.filter(pt=>pt.length>0)]}}class Kr extends dt{}class pn extends dt{}class Dr extends dt{}class hn extends dt{constructor(F,j){super(F,j),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=this.model.vocab.filter(te=>this.languageRegex.test(te)),console.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(F){if(F===null)return null;const[j,...te]=F.trim().split(this.languageRegex);if(te.length===0)return super._encode_text(j);if(te.length===2){const[de,he]=te;return this.supported_language_codes.includes(de)||console.warn(`Unsupported language code "${de}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),(0,i.mergeArrays)([de],super._encode_text(he))}}}class Os extends dt{}class kr extends dt{}class Hr extends dt{}class lr extends dt{}class mr extends dt{}class Ds extends dt{constructor(F,j){super(F,j),this.decoder=new ct({})}}class mn extends dt{}class Ps extends dt{}class fn{static async from_pretrained(F,{progress_callback:j=null,config:te=null,cache_dir:de=null,local_files_only:he=!1,revision:Ce="main",legacy:We=null}={}){var Ct;const[qe,Ke]=await u(F,{progress_callback:j,config:te,cache_dir:de,local_files_only:he,revision:Ce,legacy:We}),Ze=((Ct=Ke.tokenizer_class)==null?void 0:Ct.replace(/Fast$/,""))??"PreTrainedTokenizer";let pt=this.TOKENIZER_CLASS_MAPPING[Ze];return pt||(console.warn(`Unknown tokenizer class "${Ze}", attempting to construct from base class.`),pt=dt),new pt(qe,Ke)}}re(fn,"TOKENIZER_CLASS_MAPPING",{T5Tokenizer:Sr,DistilBertTokenizer:et,CamembertTokenizer:it,DebertaTokenizer:vs,DebertaV2Tokenizer:xs,BertTokenizer:Wr,HerbertTokenizer:Is,ConvBertTokenizer:hr,RoFormerTokenizer:Be,XLMTokenizer:rr,ElectraTokenizer:zt,MobileBertTokenizer:ts,SqueezeBertTokenizer:bs,AlbertTokenizer:Br,GPT2Tokenizer:rs,BartTokenizer:ss,MBartTokenizer:Tr,MBart50Tokenizer:ns,RobertaTokenizer:is,WhisperTokenizer:$r,CodeGenTokenizer:Kr,CLIPTokenizer:pn,SiglipTokenizer:Dr,MarianTokenizer:hn,BloomTokenizer:Gr,NllbTokenizer:As,M2M100Tokenizer:Fs,LlamaTokenizer:Ws,CodeLlamaTokenizer:Gs,XLMRobertaTokenizer:Ks,MPNetTokenizer:Hs,FalconTokenizer:os,GPTNeoXTokenizer:qs,EsmTokenizer:Qs,Wav2Vec2CTCTokenizer:Os,BlenderbotTokenizer:kr,BlenderbotSmallTokenizer:Hr,SpeechT5Tokenizer:lr,NougatTokenizer:mr,VitsTokenizer:Ds,Qwen2Tokenizer:Xs,GemmaTokenizer:Or,Grok1Tokenizer:Es,CohereTokenizer:mn,MgpstrTokenizer:Ps,PreTrainedTokenizer:dt})},"./src/utils/audio.js":(e,r,t)=>{t.r(r),t.d(r,{RawAudio:()=>q,hamming:()=>h,hanning:()=>u,mel_filter_bank:()=>S,read_audio:()=>d,spectrogram:()=>k,window_function:()=>B});var s=t("./src/utils/hub.js"),i=t("./src/utils/maths.js"),n=t("./src/utils/core.js"),o=t("./src/env.js"),a=t("?7a2c"),l=t("./src/utils/tensor.js");async function d(V,Y){if(typeof AudioContext>"u")throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");const H=await(await(0,s.getFile)(V)).arrayBuffer(),Q=new AudioContext({sampleRate:Y});typeof Y>"u"&&console.warn(`No sampling rate provided, using default of ${Q.sampleRate}Hz.`);const ie=await Q.decodeAudioData(H);let le;if(ie.numberOfChannels===2){const ae=Math.sqrt(2),ge=ie.getChannelData(0),N=ie.getChannelData(1);le=new Float32Array(ge.length);for(let O=0;O2595*Math.log10(1+V/700),kaldi:V=>1127*Math.log(1+V/700),slaney:(V,Y=1e3,H=15,Q=27/Math.log(6.4))=>V>=Y?H+Math.log(V/Y)*Q:3*V/200};function _(V,Y="htk"){const H=w[Y];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof V=="number"?H(V):V.map(Q=>H(Q))}const P={htk:V=>700*(10**(V/2595)-1),kaldi:V=>700*(Math.exp(V/1127)-1),slaney:(V,Y=1e3,H=15,Q=Math.log(6.4)/27)=>V>=H?Y*Math.exp(Q*(V-H)):200*V/3};function A(V,Y="htk"){const H=P[Y];if(!H)throw new Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof V=="number"?H(V):V.map(Q=>H(Q))}function v(V,Y){const H=Float64Array.from({length:Y.length-1},(ae,ge)=>Y[ge+1]-Y[ge]),Q=Array.from({length:V.length},()=>new Array(Y.length));for(let ae=0;aenew Array(V.length));for(let ae=0;aeV+Q*le)}function S(V,Y,H,Q,ie,le=null,ae="htk",ge=!1){if(le!==null&&le!=="slaney")throw new Error('norm must be one of null or "slaney"');const N=_(H,ae),O=_(Q,ae),G=y(N,O,Y+2);let ne=A(G,ae),X;if(ge){const fe=ie/(V*2);X=_(Float64Array.from({length:V},(ke,He)=>He*fe),ae),ne=G}else X=y(0,Math.floor(ie/2),V);const we=v(X,ne);if(le!==null&&le==="slaney")for(let fe=0;feie)throw Error(`frame_length (${H}) may not be larger than fft_length (${ie})`);if(Pe!==H)throw new Error(`Length of the window (${Pe}) must equal frame_length (${H})`);if(Q<=0)throw new Error("hop_length must be greater than zero");if(le===null&&G!==null)throw new Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(ae){if(ge!=="reflect")throw new Error(`pad_mode="${ge}" not implemented yet.`);const be=Math.floor((ie-1)/2)+1;V=x(V,be,be)}let Ee=Math.floor(1+Math.floor((V.length-H)/Q));Me!==null&&EeEe?U&&(Le=K):Le=Ie=K);const Ne=new i.FFT(ie),Ve=new Float64Array(ie),D=new Float64Array(Ne.outputBufferSize),Z=new Float32Array(Fe*Le);for(let be=0;be=1;--Ae)Ve[Ae]-=O*Ve[Ae-1];Ve[0]*=1-O}for(let Ae=0;AeMath.pow(ge,.85));break;default:throw new Error(`Unknown window type ${Y}.`)}if(H&&(ae=ae.subarray(0,V)),Q===null)return ae;if(V>Q)throw new Error(`Length of the window (${V}) may not be larger than frame_length (${Q})`);return ae}function R(V,Y){let H=44;const Q=new ArrayBuffer(H+V.length*4),ie=new DataView(Q);J(ie,0,"RIFF"),ie.setUint32(4,36+V.length*4,!0),J(ie,8,"WAVE"),J(ie,12,"fmt "),ie.setUint32(16,16,!0),ie.setUint16(20,3,!0),ie.setUint16(22,1,!0),ie.setUint32(24,Y,!0),ie.setUint32(28,Y*4,!0),ie.setUint16(32,4,!0),ie.setUint16(34,32,!0),J(ie,36,"data"),ie.setUint32(40,V.length*4,!0);for(let le=0;le{let le=await ie.arrayBuffer();a.writeFileSync(Q,Buffer.from(le))};else throw new Error("Unable to save because filesystem is disabled in this environment.");await H(Y,this.toBlob())}}},"./src/utils/constants.js":(e,r,t)=>{t.r(r),t.d(r,{CHAT_TEMPLATE_NAME:()=>l,CONFIG_NAME:()=>i,FEATURE_EXTRACTOR_NAME:()=>n,GENERATION_CONFIG_NAME:()=>d,GITHUB_ISSUE_URL:()=>s,IMAGE_PROCESSOR_NAME:()=>o,PROCESSOR_NAME:()=>a});const s="https://github.com/huggingface/transformers.js/issues/new/choose",i="config.json",n="preprocessor_config.json",o=n,a="processor_config.json",l="chat_template.json",d="generation_config.json"},"./src/utils/core.js":(e,r,t)=>{t.r(r),t.d(r,{calculateDimensions:()=>d,calculateReflectOffset:()=>w,count:()=>v,dispatchCallback:()=>s,escapeRegExp:()=>n,isIntegralNumber:()=>a,isNullishDimension:()=>l,isTypedArray:()=>o,len:()=>A,mergeArrays:()=>u,pick:()=>P,pop:()=>p,product:()=>h,reverseDictionary:()=>i,saveBlob:()=>_});function s(y,S){y&&y(S)}function i(y){return Object.fromEntries(Object.entries(y).map(([S,x])=>[x,S]))}function n(y){return y.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function o(y){var S,x,g;return((g=(x=(S=y==null?void 0:y.prototype)==null?void 0:S.__proto__)==null?void 0:x.constructor)==null?void 0:g.name)==="TypedArray"}function a(y){return Number.isInteger(y)||typeof y=="bigint"}function l(y){return y==null||y===-1}function d(y){const S=[];let x=y;for(;Array.isArray(x);)S.push(x.length),x=x[0];return S}function p(y,S,x=void 0){const g=y[S];if(g!==void 0)return delete y[S],g;if(x===void 0)throw Error(`Key ${S} does not exist in object.`);return x}function u(...y){return Array.prototype.concat.apply([],y)}function h(...y){return y.reduce((S,x)=>S.flatMap(g=>x.map(M=>[g,M])))}function w(y,S){return Math.abs((y+S)%(2*S)-S)}function _(y,S){const x=URL.createObjectURL(S),g=document.createElement("a");g.href=x,g.download=y,g.click(),g.remove(),URL.revokeObjectURL(x)}function P(y,S){return Object.assign({},...S.map(x=>{if(y[x]!==void 0)return{[x]:y[x]}}))}function A(y){let S=0;for(const x of y)++S;return S}function v(y,S){let x=0;for(const g of y)g===S&&++x;return x}},"./src/utils/data-structures.js":(e,r,t)=>{t.r(r),t.d(r,{CharTrie:()=>i,PriorityQueue:()=>s,TokenLattice:()=>o});class s{constructor(d=(u,h)=>u>h,p=1/0){this._heap=[],this._comparator=d,this._maxSize=p}get size(){return this._heap.length}isEmpty(){return this.size===0}peek(){return this._heap[0]}push(...d){return this.extend(d)}extend(d){for(const p of d)if(this.size0&&this._swap(0,p),this._heap.pop(),this._siftDown(),d}replace(d){const p=this.peek();return this._heap[0]=d,this._siftDown(),p}_parent(d){return(d+1>>>1)-1}_left(d){return(d<<1)+1}_right(d){return d+1<<1}_greater(d,p){return this._comparator(this._heap[d],this._heap[p])}_swap(d,p){const u=this._heap[d];this._heap[d]=this._heap[p],this._heap[p]=u}_siftUp(){this._siftUpFrom(this.size-1)}_siftUpFrom(d){for(;d>0&&this._greater(d,this._parent(d));)this._swap(d,this._parent(d)),d=this._parent(d)}_siftDown(){let d=0;for(;this._left(d)[]),this.endNodes=Array.from({length:this.len+1},()=>[]);const h=new a(this.bosTokenId,0,0,0,0),w=new a(this.eosTokenId,1,this.len,0,0);this.nodes.push(h.clone()),this.nodes.push(w.clone()),this.beginNodes[this.len].push(w),this.endNodes[0].push(h)}insert(d,p,u,h){const w=this.nodes.length,_=new a(h,w,d,p,u);this.beginNodes[d].push(_),this.endNodes[d+p].push(_),this.nodes.push(_)}viterbi(){const d=this.len;let p=0;for(;p<=d;){if(this.beginNodes[p].length==0)return[];for(let P of this.beginNodes[p]){P.prev=null;let A=0,v=null;for(let y of this.endNodes[p]){const S=y.backtraceScore+P.score;(v===null||S>A)&&(v=y.clone(),A=S)}if(v!==null)P.prev=v,P.backtraceScore=A;else return[]}++p}const u=[],w=this.beginNodes[d][0].prev;if(w===null)return[];let _=w.clone();for(;_.prev!==null;)u.push(_.clone()),_=_.clone().prev.clone();return u.reverse(),u}piece(d){return this.chars.slice(d.pos,d.pos+d.length).join("")}tokens(){return this.viterbi().map(p=>this.piece(p))}tokenIds(){return this.viterbi().map(p=>p.tokenId)}}class a{constructor(d,p,u,h,w){this.tokenId=d,this.nodeId=p,this.pos=u,this.length=h,this.score=w,this.prev=null,this.backtraceScore=0}clone(){const d=new a(this.tokenId,this.nodeId,this.pos,this.length,this.score);return d.prev=this.prev,d.backtraceScore=this.backtraceScore,d}}},"./src/utils/devices.js":(e,r,t)=>{t.r(r),t.d(r,{DEVICE_TYPES:()=>s});const s=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"})},"./src/utils/dtypes.js":(e,r,t)=>{t.r(r),t.d(r,{DATA_TYPES:()=>o,DEFAULT_DEVICE_DTYPE_MAPPING:()=>a,DEFAULT_DTYPE_SUFFIX_MAPPING:()=>l,isWebGpuFp16Supported:()=>n});var s=t("./src/env.js"),i=t("./src/utils/devices.js");const n=function(){let d;return async function(){if(d===void 0)if(!s.apis.IS_WEBGPU_AVAILABLE)d=!1;else try{d=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch{d=!1}return d}}(),o=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16"}),a=Object.freeze({[i.DEVICE_TYPES.wasm]:o.q8}),l=Object.freeze({[o.fp32]:"",[o.fp16]:"_fp16",[o.int8]:"_int8",[o.uint8]:"_uint8",[o.q8]:"_quantized",[o.q4]:"_q4",[o.q4f16]:"_q4f16",[o.bnb4]:"_bnb4"})},"./src/utils/generic.js":(e,r,t)=>{t.r(r),t.d(r,{Callable:()=>s});const s=class{constructor(){let i=function(...n){return i._call(...n)};return Object.setPrototypeOf(i,new.target.prototype)}_call(...i){throw Error("Must implement _call method in subclass")}}},"./src/utils/hub.js":(e,r,t)=>{t.r(r),t.d(r,{MAX_EXTERNAL_DATA_CHUNKS:()=>a,getFile:()=>u,getModelFile:()=>A,getModelJSON:()=>v});var s=t("?7a2c"),i=t("?a42a"),n=t("./src/env.js"),o=t("./src/utils/core.js");const a=100,l={txt:"text/plain",html:"text/html",css:"text/css",js:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif"};class d{constructor(g){if(this.filePath=g,this.headers=new Headers,this.exists=s.existsSync(g),this.exists){this.status=200,this.statusText="OK";let M=s.statSync(g);this.headers.set("content-length",M.size.toString()),this.updateContentType();const E=s.createReadStream(g);this.body=new ReadableStream({start(k){E.on("data",B=>k.enqueue(B)),E.on("end",()=>k.close()),E.on("error",B=>k.error(B))},cancel(){E.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){const g=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",l[g]??"application/octet-stream")}clone(){let g=new d(this.filePath);return g.exists=this.exists,g.status=this.status,g.statusText=this.statusText,g.headers=new Headers(this.headers),g}async arrayBuffer(){return(await s.promises.readFile(this.filePath)).buffer}async blob(){const g=await s.promises.readFile(this.filePath);return new Blob([g],{type:this.headers.get("content-type")})}async text(){return await s.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}}function p(x,g=null,M=null){let E;try{E=new URL(x)}catch{return!1}return!(g&&!g.includes(E.protocol)||M&&!M.includes(E.hostname))}async function u(x){var g;if(n.env.useFS&&!p(x,["http:","https:","blob:"]))return new d(x.toString());if(typeof process<"u"&&((g=process==null?void 0:process.release)==null?void 0:g.name)==="node"){const M=!!(Ns!=null&&Ns.TESTING_REMOTELY),E=n.env.version,k=new Headers;if(k.set("User-Agent",`transformers.js/${E}; is_ci/${M};`),p(x,["http:","https:"],["huggingface.co","hf.co"])){const R=(Ns==null?void 0:Ns.HF_TOKEN)??(Ns==null?void 0:Ns.HF_ACCESS_TOKEN);R&&k.set("Authorization",`Bearer ${R}`)}return fetch(x,{headers:k})}else return fetch(x)}const h={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 w(x,g,M){if(!M)return null;const E=h[x]??`Error (${x}) occurred while trying to load file`;throw Error(`${E}: "${g}".`)}class _{constructor(g){this.path=g}async match(g){let M=i.join(this.path,g),E=new d(M);if(E.exists)return E}async put(g,M,E=void 0){let k=i.join(this.path,g);try{const B=M.headers.get("Content-Length"),R=parseInt(B??"0");let J=0;await s.promises.mkdir(i.dirname(k),{recursive:!0});const q=s.createWriteStream(k),V=M.body.getReader();for(;;){const{done:Y,value:H}=await V.read();if(Y)break;await new Promise((ie,le)=>{q.write(H,ae=>{if(ae){le(ae);return}ie()})}),J+=H.length;const Q=R?J/R*100:0;E==null||E({progress:Q,loaded:J,total:R})}q.close()}catch(B){try{await s.promises.unlink(k)}catch{}throw B}}}async function P(x,...g){for(let M of g)try{let E=await x.match(M);if(E)return E}catch{continue}}async function A(x,g,M=!0,E={},k=!1){if(!n.env.allowLocalModels){if(E.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!n.env.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}(0,o.dispatchCallback)(E.progress_callback,{status:"initiate",name:x,file:g});let B;if(!B&&n.env.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{B=await caches.open("transformers-cache")}catch(G){console.warn("An error occurred while opening the browser cache:",G)}}if(!B&&n.env.useFSCache&&(B=new _(E.cache_dir??n.env.cacheDir)),!B&&n.env.useCustomCache){if(!n.env.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!n.env.customCache.match||!n.env.customCache.put)throw new Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");B=n.env.customCache}const R=E.revision??"main";let J=S(x,g),q=S(n.env.localModelPath,J),V=J,Y=S(n.env.remoteHost,n.env.remotePathTemplate.replaceAll("{model}",x).replaceAll("{revision}",encodeURIComponent(R)),g),H=R==="main"?J:S(x,R,g),Q,ie=B instanceof _?H:Y,le=!1,ae;B&&(ae=await P(B,q,ie));const ge=ae!==void 0;if(ae===void 0){if(n.env.allowLocalModels)if(p(J,["http:","https:"])){if(E.local_files_only)throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${V}.`);if(!n.env.allowRemoteModels)throw new Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${V}.`)}else try{ae=await u(V),Q=V}catch(ne){console.warn(`Unable to load from local path "${V}": "${ne}"`)}if(ae===void 0||ae.status===404){if(E.local_files_only||!n.env.allowRemoteModels){if(M)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${V}".`);return null}if(ae=await u(Y),ae.status!==200)return w(ae.status,Y,M);Q=ie}le=B&&typeof Response<"u"&&ae instanceof Response&&ae.status===200}(0,o.dispatchCallback)(E.progress_callback,{status:"download",name:x,file:g});let N;if(!(n.apis.IS_NODE_ENV&&k)){let G;E.progress_callback?ge&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent)?(G=new Uint8Array(await ae.arrayBuffer()),(0,o.dispatchCallback)(E.progress_callback,{status:"progress",name:x,file:g,progress:100,loaded:G.length,total:G.length})):G=await y(ae,ne=>{(0,o.dispatchCallback)(E.progress_callback,{status:"progress",name:x,file:g,...ne})}):G=new Uint8Array(await ae.arrayBuffer()),N=G}if(le&&Q&&await B.match(Q)===void 0&&(N?await B.put(Q,new Response(N,{headers:ae.headers})).catch(G=>{console.warn(`Unable to add response to browser cache: ${G}.`)}):await B.put(Q,ae,E.progress_callback)),(0,o.dispatchCallback)(E.progress_callback,{status:"done",name:x,file:g}),N){if(k)throw new Error("Cannot return path in a browser environment.");return N}if(ae instanceof d)return ae.filePath;const O=await B.match(Q);if(O instanceof d)return O.filePath;throw new Error("Unable to return path for response.")}async function v(x,g,M=!0,E={}){const k=await A(x,g,M,E,!1);if(k===null)return{};const R=new TextDecoder("utf-8").decode(k);return JSON.parse(R)}async function y(x,g){const M=x.headers.get("Content-Length");M===null&&console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let E=parseInt(M??"0"),k=new Uint8Array(E),B=0;const R=x.body.getReader();async function J(){const{done:q,value:V}=await R.read();if(q)return;const Y=B+V.length;if(Y>E){E=Y;const Q=new Uint8Array(E);Q.set(k),k=Q}k.set(V,B),B=Y;const H=B/E*100;return g({progress:H,loaded:B,total:E}),J()}return await J(),k}function S(...x){return x=x.map((g,M)=>(M&&(g=g.replace(new RegExp("^/"),"")),M!==x.length-1&&(g=g.replace(new RegExp("/$"),"")),g)),x.join("/")}},"./src/utils/image.js":(e,r,t)=>{t.r(r),t.d(r,{RawImage:()=>_,load_image:()=>P});var s=t("./src/utils/core.js"),i=t("./src/utils/hub.js"),n=t("./src/env.js"),o=t("./src/utils/tensor.js"),a=t("?2b25");let l,d,p;const u=n.apis.IS_BROWSER_ENV||n.apis.IS_WEBWORKER_ENV;if(u)l=(A,v)=>{if(!self.OffscreenCanvas)throw new Error("OffscreenCanvas not supported by this browser.");return new self.OffscreenCanvas(A,v)},p=self.createImageBitmap,d=self.ImageData;else if(a)p=async A=>{const y=(await A.metadata()).channels,{data:S,info:x}=await A.rotate().raw().toBuffer({resolveWithObject:!0}),g=new _(new Uint8ClampedArray(S),x.width,x.height,x.channels);return y!==void 0&&y!==x.channels&&g.convert(y),g};else throw new Error("Unable to load image processing library.");const h={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},w=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]);class _{constructor(v,y,S,x){this.data=v,this.width=y,this.height=S,this.channels=x}get size(){return[this.width,this.height]}static async read(v){if(v instanceof _)return v;if(typeof v=="string"||v instanceof URL)return await this.fromURL(v);throw new Error(`Unsupported input type: ${typeof v}`)}static fromCanvas(v){if(!u)throw new Error("fromCanvas() is only supported in browser environments.");const S=v.getContext("2d").getImageData(0,0,v.width,v.height).data;return new _(S,v.width,v.height,4)}static async fromURL(v){const y=await(0,i.getFile)(v);if(y.status!==200)throw new Error(`Unable to read image from "${v}" (${y.status} ${y.statusText})`);const S=await y.blob();return this.fromBlob(S)}static async fromBlob(v){if(u){const y=await p(v),S=l(y.width,y.height).getContext("2d");return S.drawImage(y,0,0),new this(S.getImageData(0,0,y.width,y.height).data,y.width,y.height,4)}else{const y=a(await v.arrayBuffer());return await p(y)}}static fromTensor(v,y="CHW"){if(v.dims.length!==3)throw new Error(`Tensor should have 3 dimensions, but has ${v.dims.length} dimensions.`);if(y==="CHW")v=v.transpose(1,2,0);else if(y!=="HWC")throw new Error(`Unsupported channel format: ${y}`);if(!(v.data instanceof Uint8ClampedArray||v.data instanceof Uint8Array))throw new Error(`Unsupported tensor type: ${v.type}`);switch(v.dims[2]){case 1:case 2:case 3:case 4:return new _(v.data,v.dims[1],v.dims[0],v.dims[2]);default:throw new Error(`Unsupported number of channels: ${v.dims[2]}`)}}grayscale(){if(this.channels===1)return this;const v=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let y=0,S=0;y=0?k=S:R=-S,x>=0?B=x:J=-x,E.drawImage(M,k,B,v,y,R,J,v,y),new _(E.getImageData(0,0,v,y).data,v,y,4).convert(g)}else{let g=this.toSharp();if(S>=0&&x>=0)g=g.extract({left:Math.floor(S),top:Math.floor(x),width:v,height:y});else if(S<=0&&x<=0){const M=Math.floor(-x),E=Math.floor(-S);g=g.extend({top:M,left:E,right:v-this.width-E,bottom:y-this.height-M})}else{let M=[0,0],E=0;x<0?(M[0]=Math.floor(-x),M[1]=y-this.height-M[0]):E=Math.floor(x);let k=[0,0],B=0;S<0?(k[0]=Math.floor(-S),k[1]=v-this.width-k[0]):B=Math.floor(S),g=g.extend({top:M[0],bottom:M[1],left:k[0],right:k[1]}).extract({left:B,top:E,width:v,height:y})}return await p(g)}}async toBlob(v="image/png",y=1){if(!u)throw new Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:v,quality:y})}toTensor(v="CHW"){let y=new o.Tensor("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(v!=="HWC")if(v==="CHW")y=y.permute(2,0,1);else throw new Error(`Unsupported channel format: ${v}`);return y}toCanvas(){if(!u)throw new Error("toCanvas() is only supported in browser environments.");const v=this.clone().rgba(),y=l(v.width,v.height),S=new d(v.data,v.width,v.height);return y.getContext("2d").putImageData(S,0,0),y}split(){const{data:v,width:y,height:S,channels:x}=this,g=v.constructor,M=v.length/x,E=Array.from({length:x},()=>new g(M));for(let k=0;knew _(k,y,S,1))}_update(v,y,S,x=null){return this.data=v,this.width=y,this.height=S,x!==null&&(this.channels=x),this}clone(){return new _(this.data.slice(),this.width,this.height,this.channels)}convert(v){if(this.channels===v)return this;switch(v){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(v){if(u){if(n.apis.IS_WEBWORKER_ENV)throw new Error("Unable to save an image from a Web Worker.");const y=v.split(".").pop().toLowerCase(),S=w.get(y)??"image/png",x=await this.toBlob(S);(0,s.saveBlob)(v,x)}else{if(n.apis.IS_FS_AVAILABLE)return await this.toSharp().toFile(v);throw new Error("Unable to save the image because filesystem is disabled in this environment.")}}toSharp(){if(u)throw new Error("toSharp() is only supported in server-side environments.");return a(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}}const P=_.read.bind(_)},"./src/utils/maths.js":(e,r,t)=>{t.r(r),t.d(r,{FFT:()=>P,bankers_round:()=>y,cos_sim:()=>l,dot:()=>a,dynamic_time_warping:()=>S,interpolate_data:()=>s,log_softmax:()=>o,magnitude:()=>d,max:()=>u,medianFilter:()=>A,min:()=>p,permute_data:()=>i,round:()=>v,softmax:()=>n});function s(x,[g,M,E],[k,B],R="bilinear",J=!1){const q=B/E,V=k/M,Y=new x.constructor(k*B*g),H=M*E,Q=k*B;for(let ie=0;ie=0;--J)k[J]=q,E[J]=g[M[J]],q*=E[J];const B=M.map((J,q)=>k[M.indexOf(q)]),R=new x.constructor(x.length);for(let J=0;J=0;--V)q+=Y%g[V]*B[V],Y=Math.floor(Y/g[V]);R[q]=x[J]}return[R,E]}function n(x){const g=u(x)[0],M=x.map(B=>Math.exp(B-g)),E=M.reduce((B,R)=>B+R,0);return M.map(B=>B/E)}function o(x){const g=u(x)[0];let M=0;for(let B=0;BB-g-E)}function a(x,g){let M=0;for(let E=0;Eg+M*M,0))}function p(x){if(x.length===0)throw Error("Array must not be empty");let g=x[0],M=0;for(let E=1;Eg&&(g=x[E],M=E);return[g,M]}function h(x){return x>0&&(x&x-1)===0}class w{constructor(g){if(this.size=g|0,this.size<=1||!h(this.size))throw new Error("FFT size must be a power of two larger than 1");this._csize=g<<1,this.table=new Float64Array(this.size*2);for(let E=0;EE;E<<=1)++M;this._width=M%2===0?M-1:M,this._bitrev=new Int32Array(1<>>k&3)<>>1);for(let k=0;k>>1]=g[k];return E}toComplexArray(g,M){const E=M||this.createComplexArray();for(let k=0;k>>1],E[k+1]=0;return E}transform(g,M){if(g===M)throw new Error("Input and output buffers must be different");this._transform4(g,M,1)}realTransform(g,M){if(g===M)throw new Error("Input and output buffers must be different");this._realTransform4(g,M,1)}inverseTransform(g,M){if(g===M)throw new Error("Input and output buffers must be different");this._transform4(g,M,-1);for(let E=0;E>=2;R>=2;R>>=2){J=k/R<<1;const Q=J>>>2;for(q=0;q>>1,R>>>1)}else for(q=0,V=0;q>>1,R>>>1,E)}const H=this.table;for(R>>=2;R>=2;R>>=2){J=k/R<<1;const ie=J>>>1,le=ie>>>1,ae=le>>>1;for(q=0;q>>1;for(let ie=2;ie>1;++Y){const H=(Y+1-g)**2/2,Q=Math.sqrt(q**2+V**2)**H,ie=H*Math.atan2(V,q),le=2*Y;B[le]=Q*Math.cos(ie),B[le+1]=Q*Math.sin(ie),R[le]=B[le],R[le+1]=-B[le+1]}this._slicedChirpBuffer=B.subarray(M,E),this._f=new w(k>>1),this._f.transform(this._chirpBuffer,R)}_transform(g,M,E){const k=this._buffer1,B=this._buffer2,R=this._outBuffer1,J=this._outBuffer2,q=this._chirpBuffer,V=this._slicedChirpBuffer,Y=this._a;if(E)for(let H=0;H>1,le=M[ie];k[H]=le*V[H],k[Q]=le*V[Q]}else for(let H=0;H=x.length&&(q=2*(x.length-1)-q),E[R++]=x[q]}E.sort(),M[B]=E[k]}return M}function v(x,g){const M=Math.pow(10,g);return Math.round(x*M)/M}function y(x){const g=Math.round(x);return Math.abs(x)%1===.5?g%2===0?g:g-1:g}function S(x){const g=x.length,M=x[0].length,E=[g+1,M+1],k=Array.from({length:E[0]},()=>Array(E[1]).fill(1/0));k[0][0]=0;const B=Array.from({length:E[0]},()=>Array(E[1]).fill(-1));for(let Y=1;Y0||J>0;)switch(q.push(R-1),V.push(J-1),B[R][J]){case 0:--R,--J;break;case 1:--R;break;case 2:--J;break;default:throw new Error(`Internal error in dynamic time warping. Unexpected trace[${R}, ${J}]. Please file a bug report.`)}return q.reverse(),V.reverse(),[q,V]}},"./src/utils/tensor.js":(e,r,t)=>{t.r(r),t.d(r,{DataTypeMap:()=>o,Tensor:()=>a,cat:()=>M,full:()=>V,full_like:()=>Y,interpolate:()=>p,interpolate_4d:()=>u,layer_norm:()=>y,matmul:()=>h,mean:()=>R,mean_pooling:()=>v,ones:()=>H,ones_like:()=>Q,permute:()=>d,quantize_embeddings:()=>ge,rand:()=>ae,rfft:()=>w,slice:()=>A,stack:()=>E,std_mean:()=>B,topk:()=>_,zeros:()=>ie,zeros_like:()=>le});var s=t("./src/utils/maths.js"),i=t("./src/backends/onnx.js"),n=t("./src/ops/registry.js");const o=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array});class a{constructor(...O){re(this,"ort_tensor");return(0,i.isONNXTensor)(O[0])?this.ort_tensor=O[0]:this.ort_tensor=new i.Tensor(O[0],O[1],O[2]),new Proxy(this,{get:(G,ne)=>{if(typeof ne=="string"){let X=Number(ne);if(Number.isInteger(X))return G._getitem(X)}return G[ne]},set:(G,ne,X)=>G[ne]=X})}get dims(){return this.ort_tensor.dims}set dims(O){this.ort_tensor.dims=O}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[O,...G]=this.dims;if(G.length>0){const ne=G.reduce((X,we)=>X*we);for(let X=0;X0){const X=ne.reduce((we,fe)=>we*fe);return this._subarray(O,X,ne)}else return new a(this.type,[this.data[O]],ne)}indexOf(O){const G=this.data;for(let ne=0;nepe)throw new Error(`Invalid slice: ${K}`);const Pe=[Math.max(U,0),Math.min(pe,this.dims[Me])];ne.push(Pe),G.push(Pe[1]-Pe[0])}else throw new Error(`Invalid slice: ${K}`)}const X=ne.map(([Me,K])=>K-Me),we=X.reduce((Me,K)=>Me*K),fe=this.data,ke=new fe.constructor(we),He=this.stride();for(let Me=0;Me=0;--U){const Pe=X[U];K+=(pe%Pe+ne[U][0])*He[U],pe=Math.floor(pe/Pe)}ke[Me]=fe[K]}return new a(this.type,ke,G)}permute(...O){return d(this,O)}transpose(...O){return this.permute(...O)}sum(O=null,G=!1){return this.norm(1,O,G)}norm(O="fro",G=null,ne=!1){if(O==="fro")O=2;else if(typeof O=="string")throw Error(`Unsupported norm: ${O}`);const X=this.data,we=(Me,K)=>Me+K**O;if(G===null){const Me=X.reduce(we,0)**(1/O);return new a(this.type,[Me],[])}const[fe,ke,He]=k(we,this,G,ne);if(O!==1)for(let Me=0;Me=0;--He){const U=this.dims[He];if(He!==G){const pe=Me%U;ke+=pe*K,K*=this.dims[He]}Me=Math.floor(Me/U)}X[fe]/=we[ke]}return this}normalize(O=2,G=1){return this.clone().normalize_(O,G)}stride(){return J(this.dims)}squeeze(O=null){return new a(this.type,this.data,S(this.dims,O))}squeeze_(O=null){return this.dims=S(this.dims,O),this}unsqueeze(O=null){return new a(this.type,this.data,x(this.dims,O))}unsqueeze_(O=null){return this.dims=x(this.dims,O),this}flatten_(O=0,G=-1){G=(G+this.dims.length)%this.dims.length;let ne=this.dims.slice(0,O),X=this.dims.slice(O,G+1),we=this.dims.slice(G+1);return this.dims=[...ne,X.reduce((fe,ke)=>fe*ke,1),...we],this}flatten(O=0,G=-1){return this.clone().flatten_(O,G)}view(...O){let G=-1;for(let X=0;Xke!==G?we*fe:we,1);O[G]=ne.length/X}return new a(this.type,ne,O)}neg_(){const O=this.data;for(let G=0;GO?1:0;return new a("bool",G,this.dims)}lt(O){const G=new Uint8Array(this.data.length),ne=this.data;for(let X=0;XMath.min(fe,ke),this,O,G,1/0);return new a(ne,X,we)}max(O=null,G=!1){if(O===null){const fe=(0,s.max)(this.data)[0];return new a(this.type,[fe],[])}const[ne,X,we]=k((fe,ke)=>Math.max(fe,ke),this,O,G,-1/0);return new a(ne,X,we)}argmin(O=null,G=!1){if(O!==null)throw new Error("`dim !== null` not yet implemented.");const ne=(0,s.min)(this.data)[1];return new a("int64",[BigInt(ne)],[])}argmax(O=null,G=!1){if(O!==null)throw new Error("`dim !== null` not yet implemented.");const ne=(0,s.max)(this.data)[1];return new a("int64",[BigInt(ne)],[])}to(O){if(this.type===O)return this;if(!o.hasOwnProperty(O))throw new Error(`Unsupported type: ${O}`);let G;const ne=["int64","uint64"].includes(this.type),X=["int64","uint64"].includes(O);return ne&&!X?G=Number:!ne&&X&&(G=BigInt),new a(O,o[O].from(this.data,G),this.dims)}}function l(N,O){const G=N.length,ne=O.reduce((we,fe)=>we*fe);if(G!==ne)throw Error(`cannot reshape array of size ${G} into shape (${O})`);let X=N;for(let we=O.length-1;we>=0;we--)X=X.reduce((fe,ke)=>{let He=fe[fe.length-1];return He.lengthnew a("int64",N,[N.length]);async function A(N,O,G,ne,X){return await(await n.TensorOpRegistry.slice)({x:N,s:P(O),e:P(G),a:P(ne),t:P(X??new Array(ne.length).fill(1))})}function v(N,O){const G=N.data,ne=O.data,X=[N.dims[0],N.dims[2]],we=new G.constructor(X[0]*X[1]),[fe,ke,He]=N.dims;let Me=0;for(let K=0;KG!==1):typeof O=="number"?N[O]===1&&N.splice(O,1):Array.isArray(O)&&(N=N.filter((G,ne)=>G!==1||!O.includes(ne))),N}function x(N,O){return O=g(O,N.length+1),N=N.slice(),N.splice(O,0,1),N}function g(N,O,G=null,ne=!0){if(ne&&(N<-O||N>=O))throw new Error(`IndexError: index ${N} is out of bounds for dimension${G===null?"":" "+G} with size ${O}`);return N<0&&(N=(N%O+O)%O),N}function M(N,O=0){O=g(O,N[0].dims.length);const G=N[0].dims.slice();G[O]=N.reduce((fe,ke)=>fe+ke.dims[O],0);const ne=G.reduce((fe,ke)=>fe*ke,1),X=new N[0].data.constructor(ne),we=N[0].type;if(O===0){let fe=0;for(const ke of N){const He=ke.data;X.set(He,fe),fe+=He.length}}else{let fe=0;for(let ke=0;ke=0;--pe){const Fe=Me[pe];let Ie=Pe%Fe;pe===O&&(Ie+=fe),U+=Ie*Ee,Ee*=G[pe],Pe=Math.floor(Pe/Fe)}X[U]=He[K]}fe+=Me[O]}}return new a(we,X,G)}function E(N,O=0){return M(N.map(G=>G.unsqueeze(O)),O)}function k(N,O,G=null,ne=!1,X=null){const we=O.data,fe=O.dims;G=g(G,fe.length);const ke=fe.slice();ke[G]=1;const He=new we.constructor(we.length/fe[G]);X!==null&&He.fill(X);for(let Me=0;Me=0;--U){const Ee=fe[U];if(U!==G){const Fe=pe%Ee;K+=Fe*Pe,Pe*=ke[U]}pe=Math.floor(pe/Ee)}He[K]=N(He[K],we[Me],Me,K)}return ne||ke.splice(G,1),[O.type,He,ke]}function B(N,O=null,G=1,ne=!1){const X=N.data,we=N.dims;if(O===null){const Pe=X.reduce((Le,Ne)=>Le+Ne,0)/X.length,Ee=Math.sqrt(X.reduce((Le,Ne)=>Le+(Ne-Pe)**2,0)/(X.length-G)),Fe=new a(N.type,[Pe],[]);return[new a(N.type,[Ee],[]),Fe]}O=g(O,we.length);const fe=R(N,O,ne),ke=fe.data,[He,Me,K]=k((pe,Pe,Ee,Fe)=>pe+(Pe-ke[Fe])**2,N,O,ne);for(let pe=0;peMe+K,0);return new a(N.type,[He/X.length],[])}O=g(O,ne.length);const[we,fe,ke]=k((He,Me)=>He+Me,N,O,G);if(ne[O]!==1)for(let He=0;He=0;--G)O[G]=ne,ne*=N[G];return O}function q(N,O,G,ne){const X=N.reduce((we,fe)=>we*fe,1);return new a(G,new ne(X).fill(O),N)}function V(N,O){let G,ne;if(typeof O=="number")G="float32",ne=Float32Array;else if(typeof O=="bigint")G="int64",ne=BigInt64Array;else if(typeof O=="boolean")G="bool",ne=Uint8Array;else throw new Error(`Unsupported data type: ${typeof O}`);return q(N,O,G,ne)}function Y(N,O){return V(N.dims,O)}function H(N){return q(N,1n,"int64",BigInt64Array)}function Q(N){return H(N.dims)}function ie(N){return q(N,0n,"int64",BigInt64Array)}function le(N){return ie(N.dims)}function ae(N){const O=N.reduce((G,ne)=>G*ne,1);return new a("float32",Float32Array.from({length:O},()=>Math.random()),N)}function ge(N,O){if(N.dims.length!==2)throw new Error("The tensor must have 2 dimensions");if(N.dims.at(-1)%8!==0)throw new Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(O))throw new Error("The precision must be either 'binary' or 'ubinary'");const G=O==="binary",ne=G?"int8":"uint8",X=G?Int8Array:Uint8Array,we=N.data,fe=new X(we.length/8);for(let ke=0;ke0?1:0,Me=Math.floor(ke/8),K=ke%8;fe[Me]|=He<<7-K,G&&K===0&&(fe[Me]-=128)}return new a(ne,fe,[N.dims[0],N.dims[1]/8])}},"./src/utils/video.js":(e,r,t)=>{t.r(r),t.d(r,{RawVideo:()=>o,RawVideoFrame:()=>n,load_video:()=>a});var s=t("./src/utils/image.js"),i=t("./src/env.js");class n{constructor(d,p){this.image=d,this.timestamp=p}}class o{constructor(d,p){d.length>0&&d[0]instanceof s.RawImage&&(d=d.map((u,h)=>new n(u,(h+1)/(d.length+1)*p))),this.frames=d,this.duration=p}get width(){return this.frames[0].image.width}get height(){return this.frames[0].image.height}get fps(){return this.frames.length/this.duration}}async function a(l,{num_frames:d=null,fps:p=null}={}){if(!i.apis.IS_BROWSER_ENV)throw new Error("`load_video` is currently only supported in browser environments.");if(d==null&&p==null)throw new Error("Either num_frames or fps must be provided.");const u=[],h=document.createElement("video");if(h.crossOrigin="anonymous",h.muted=!0,typeof l=="string")h.src=l;else if(l instanceof Blob)h.src=URL.createObjectURL(l);else if(l instanceof HTMLVideoElement)h.src=l.src;else throw new Error("Invalid URL or video element provided.");if(await new Promise(S=>h.onloadedmetadata=S),h.seekable.start(0)===h.seekable.end(0)){const x=await(await fetch(h.src)).blob();h.src=URL.createObjectURL(x),await new Promise(g=>h.onloadedmetadata=g)}const w=h.duration;let _,P;d!=null?(_=d,P=d===1?0:w/(d-1)):(P=1/p,_=Math.floor(w/P));let A=[];for(let S=0;S<_;++S)A.push(d===1?w/2:S*P);const v=document.createElement("canvas");v.width=h.videoWidth,v.height=h.videoHeight;const y=v.getContext("2d",{willReadFrequently:!0});for(const S of A){h.currentTime=S,await new Promise(E=>{h.onseeked=E}),y.drawImage(h,0,0,v.width,v.height);const x=y.getImageData(0,0,v.width,v.height),g=new s.RawImage(x.data,v.width,v.height,4),M=new n(g,S);u.push(M)}return h.remove(),new o(u,w)}}},Lw={};function Ft(e){var r=Lw[e];if(r!==void 0)return r.exports;var t=Lw[e]={exports:{}};return Dx[e](t,t.exports,Ft),t.exports}(()=>{var e=Object.getPrototypeOf?t=>Object.getPrototypeOf(t):t=>t.__proto__,r;Ft.t=function(t,s){if(s&1&&(t=this(t)),s&8||typeof t=="object"&&t&&(s&4&&t.__esModule||s&16&&typeof t.then=="function"))return t;var i=Object.create(null);Ft.r(i);var n={};r=r||[null,e({}),e([]),e(e)];for(var o=s&2&&t;typeof o=="object"&&!~r.indexOf(o);o=e(o))Object.getOwnPropertyNames(o).forEach(a=>n[a]=()=>t[a]);return n.default=()=>t,Ft.d(i,n),i}})();Ft.d=(e,r)=>{for(var t in r)Ft.o(r,t)&&!Ft.o(e,t)&&Object.defineProperty(e,t,{enumerable:!0,get:r[t]})};Ft.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r);Ft.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var f={};(()=>{/*!*****************************!*\ + !*** ./src/transformers.js ***! + \*****************************/Ft.r(f),Ft.d(f,{ASTFeatureExtractor:()=>u.ASTFeatureExtractor,ASTForAudioClassification:()=>t.ASTForAudioClassification,ASTModel:()=>t.ASTModel,ASTPreTrainedModel:()=>t.ASTPreTrainedModel,AlbertForMaskedLM:()=>t.AlbertForMaskedLM,AlbertForQuestionAnswering:()=>t.AlbertForQuestionAnswering,AlbertForSequenceClassification:()=>t.AlbertForSequenceClassification,AlbertModel:()=>t.AlbertModel,AlbertPreTrainedModel:()=>t.AlbertPreTrainedModel,AlbertTokenizer:()=>s.AlbertTokenizer,AudioClassificationPipeline:()=>r.AudioClassificationPipeline,AutoConfig:()=>i.AutoConfig,AutoFeatureExtractor:()=>h.AutoFeatureExtractor,AutoImageProcessor:()=>P.AutoImageProcessor,AutoModel:()=>t.AutoModel,AutoModelForAudioClassification:()=>t.AutoModelForAudioClassification,AutoModelForAudioFrameClassification:()=>t.AutoModelForAudioFrameClassification,AutoModelForAudioTextToText:()=>t.AutoModelForAudioTextToText,AutoModelForCTC:()=>t.AutoModelForCTC,AutoModelForCausalLM:()=>t.AutoModelForCausalLM,AutoModelForDepthEstimation:()=>t.AutoModelForDepthEstimation,AutoModelForDocumentQuestionAnswering:()=>t.AutoModelForDocumentQuestionAnswering,AutoModelForImageClassification:()=>t.AutoModelForImageClassification,AutoModelForImageFeatureExtraction:()=>t.AutoModelForImageFeatureExtraction,AutoModelForImageMatting:()=>t.AutoModelForImageMatting,AutoModelForImageSegmentation:()=>t.AutoModelForImageSegmentation,AutoModelForImageTextToText:()=>t.AutoModelForImageTextToText,AutoModelForImageToImage:()=>t.AutoModelForImageToImage,AutoModelForMaskGeneration:()=>t.AutoModelForMaskGeneration,AutoModelForMaskedLM:()=>t.AutoModelForMaskedLM,AutoModelForNormalEstimation:()=>t.AutoModelForNormalEstimation,AutoModelForObjectDetection:()=>t.AutoModelForObjectDetection,AutoModelForPoseEstimation:()=>t.AutoModelForPoseEstimation,AutoModelForQuestionAnswering:()=>t.AutoModelForQuestionAnswering,AutoModelForSemanticSegmentation:()=>t.AutoModelForSemanticSegmentation,AutoModelForSeq2SeqLM:()=>t.AutoModelForSeq2SeqLM,AutoModelForSequenceClassification:()=>t.AutoModelForSequenceClassification,AutoModelForSpeechSeq2Seq:()=>t.AutoModelForSpeechSeq2Seq,AutoModelForTextToSpectrogram:()=>t.AutoModelForTextToSpectrogram,AutoModelForTextToWaveform:()=>t.AutoModelForTextToWaveform,AutoModelForTokenClassification:()=>t.AutoModelForTokenClassification,AutoModelForUniversalSegmentation:()=>t.AutoModelForUniversalSegmentation,AutoModelForVision2Seq:()=>t.AutoModelForVision2Seq,AutoModelForXVector:()=>t.AutoModelForXVector,AutoModelForZeroShotObjectDetection:()=>t.AutoModelForZeroShotObjectDetection,AutoProcessor:()=>y.AutoProcessor,AutoTokenizer:()=>s.AutoTokenizer,AutomaticSpeechRecognitionPipeline:()=>r.AutomaticSpeechRecognitionPipeline,BackgroundRemovalPipeline:()=>r.BackgroundRemovalPipeline,BartForConditionalGeneration:()=>t.BartForConditionalGeneration,BartForSequenceClassification:()=>t.BartForSequenceClassification,BartModel:()=>t.BartModel,BartPretrainedModel:()=>t.BartPretrainedModel,BartTokenizer:()=>s.BartTokenizer,BaseModelOutput:()=>t.BaseModelOutput,BaseStreamer:()=>S.BaseStreamer,BeitFeatureExtractor:()=>_.BeitFeatureExtractor,BeitForImageClassification:()=>t.BeitForImageClassification,BeitModel:()=>t.BeitModel,BeitPreTrainedModel:()=>t.BeitPreTrainedModel,BertForMaskedLM:()=>t.BertForMaskedLM,BertForQuestionAnswering:()=>t.BertForQuestionAnswering,BertForSequenceClassification:()=>t.BertForSequenceClassification,BertForTokenClassification:()=>t.BertForTokenClassification,BertModel:()=>t.BertModel,BertPreTrainedModel:()=>t.BertPreTrainedModel,BertTokenizer:()=>s.BertTokenizer,BitImageProcessor:()=>_.BitImageProcessor,BlenderbotForConditionalGeneration:()=>t.BlenderbotForConditionalGeneration,BlenderbotModel:()=>t.BlenderbotModel,BlenderbotPreTrainedModel:()=>t.BlenderbotPreTrainedModel,BlenderbotSmallForConditionalGeneration:()=>t.BlenderbotSmallForConditionalGeneration,BlenderbotSmallModel:()=>t.BlenderbotSmallModel,BlenderbotSmallPreTrainedModel:()=>t.BlenderbotSmallPreTrainedModel,BlenderbotSmallTokenizer:()=>s.BlenderbotSmallTokenizer,BlenderbotTokenizer:()=>s.BlenderbotTokenizer,BloomForCausalLM:()=>t.BloomForCausalLM,BloomModel:()=>t.BloomModel,BloomPreTrainedModel:()=>t.BloomPreTrainedModel,BloomTokenizer:()=>s.BloomTokenizer,CLIPFeatureExtractor:()=>_.CLIPFeatureExtractor,CLIPImageProcessor:()=>_.CLIPImageProcessor,CLIPModel:()=>t.CLIPModel,CLIPPreTrainedModel:()=>t.CLIPPreTrainedModel,CLIPSegForImageSegmentation:()=>t.CLIPSegForImageSegmentation,CLIPSegModel:()=>t.CLIPSegModel,CLIPSegPreTrainedModel:()=>t.CLIPSegPreTrainedModel,CLIPTextModel:()=>t.CLIPTextModel,CLIPTextModelWithProjection:()=>t.CLIPTextModelWithProjection,CLIPTokenizer:()=>s.CLIPTokenizer,CLIPVisionModel:()=>t.CLIPVisionModel,CLIPVisionModelWithProjection:()=>t.CLIPVisionModelWithProjection,CamembertForMaskedLM:()=>t.CamembertForMaskedLM,CamembertForQuestionAnswering:()=>t.CamembertForQuestionAnswering,CamembertForSequenceClassification:()=>t.CamembertForSequenceClassification,CamembertForTokenClassification:()=>t.CamembertForTokenClassification,CamembertModel:()=>t.CamembertModel,CamembertPreTrainedModel:()=>t.CamembertPreTrainedModel,CamembertTokenizer:()=>s.CamembertTokenizer,CausalLMOutput:()=>t.CausalLMOutput,CausalLMOutputWithPast:()=>t.CausalLMOutputWithPast,ChineseCLIPFeatureExtractor:()=>_.ChineseCLIPFeatureExtractor,ChineseCLIPModel:()=>t.ChineseCLIPModel,ChineseCLIPPreTrainedModel:()=>t.ChineseCLIPPreTrainedModel,ClapAudioModelWithProjection:()=>t.ClapAudioModelWithProjection,ClapFeatureExtractor:()=>u.ClapFeatureExtractor,ClapModel:()=>t.ClapModel,ClapPreTrainedModel:()=>t.ClapPreTrainedModel,ClapTextModelWithProjection:()=>t.ClapTextModelWithProjection,ClassifierFreeGuidanceLogitsProcessor:()=>g.ClassifierFreeGuidanceLogitsProcessor,CodeGenForCausalLM:()=>t.CodeGenForCausalLM,CodeGenModel:()=>t.CodeGenModel,CodeGenPreTrainedModel:()=>t.CodeGenPreTrainedModel,CodeGenTokenizer:()=>s.CodeGenTokenizer,CodeLlamaTokenizer:()=>s.CodeLlamaTokenizer,CohereForCausalLM:()=>t.CohereForCausalLM,CohereModel:()=>t.CohereModel,CoherePreTrainedModel:()=>t.CoherePreTrainedModel,CohereTokenizer:()=>s.CohereTokenizer,ConvBertForMaskedLM:()=>t.ConvBertForMaskedLM,ConvBertForQuestionAnswering:()=>t.ConvBertForQuestionAnswering,ConvBertForSequenceClassification:()=>t.ConvBertForSequenceClassification,ConvBertForTokenClassification:()=>t.ConvBertForTokenClassification,ConvBertModel:()=>t.ConvBertModel,ConvBertPreTrainedModel:()=>t.ConvBertPreTrainedModel,ConvBertTokenizer:()=>s.ConvBertTokenizer,ConvNextFeatureExtractor:()=>_.ConvNextFeatureExtractor,ConvNextForImageClassification:()=>t.ConvNextForImageClassification,ConvNextImageProcessor:()=>_.ConvNextImageProcessor,ConvNextModel:()=>t.ConvNextModel,ConvNextPreTrainedModel:()=>t.ConvNextPreTrainedModel,ConvNextV2ForImageClassification:()=>t.ConvNextV2ForImageClassification,ConvNextV2Model:()=>t.ConvNextV2Model,ConvNextV2PreTrainedModel:()=>t.ConvNextV2PreTrainedModel,DPTFeatureExtractor:()=>_.DPTFeatureExtractor,DPTForDepthEstimation:()=>t.DPTForDepthEstimation,DPTImageProcessor:()=>_.DPTImageProcessor,DPTModel:()=>t.DPTModel,DPTPreTrainedModel:()=>t.DPTPreTrainedModel,DacDecoderModel:()=>t.DacDecoderModel,DacDecoderOutput:()=>t.DacDecoderOutput,DacEncoderModel:()=>t.DacEncoderModel,DacEncoderOutput:()=>t.DacEncoderOutput,DacFeatureExtractor:()=>u.DacFeatureExtractor,DacModel:()=>t.DacModel,DacPreTrainedModel:()=>t.DacPreTrainedModel,DataTypeMap:()=>l.DataTypeMap,DebertaForMaskedLM:()=>t.DebertaForMaskedLM,DebertaForQuestionAnswering:()=>t.DebertaForQuestionAnswering,DebertaForSequenceClassification:()=>t.DebertaForSequenceClassification,DebertaForTokenClassification:()=>t.DebertaForTokenClassification,DebertaModel:()=>t.DebertaModel,DebertaPreTrainedModel:()=>t.DebertaPreTrainedModel,DebertaTokenizer:()=>s.DebertaTokenizer,DebertaV2ForMaskedLM:()=>t.DebertaV2ForMaskedLM,DebertaV2ForQuestionAnswering:()=>t.DebertaV2ForQuestionAnswering,DebertaV2ForSequenceClassification:()=>t.DebertaV2ForSequenceClassification,DebertaV2ForTokenClassification:()=>t.DebertaV2ForTokenClassification,DebertaV2Model:()=>t.DebertaV2Model,DebertaV2PreTrainedModel:()=>t.DebertaV2PreTrainedModel,DebertaV2Tokenizer:()=>s.DebertaV2Tokenizer,DecisionTransformerModel:()=>t.DecisionTransformerModel,DecisionTransformerPreTrainedModel:()=>t.DecisionTransformerPreTrainedModel,DeiTFeatureExtractor:()=>_.DeiTFeatureExtractor,DeiTForImageClassification:()=>t.DeiTForImageClassification,DeiTImageProcessor:()=>_.DeiTImageProcessor,DeiTModel:()=>t.DeiTModel,DeiTPreTrainedModel:()=>t.DeiTPreTrainedModel,DepthAnythingForDepthEstimation:()=>t.DepthAnythingForDepthEstimation,DepthAnythingPreTrainedModel:()=>t.DepthAnythingPreTrainedModel,DepthEstimationPipeline:()=>r.DepthEstimationPipeline,DepthProForDepthEstimation:()=>t.DepthProForDepthEstimation,DepthProPreTrainedModel:()=>t.DepthProPreTrainedModel,DetrFeatureExtractor:()=>_.DetrFeatureExtractor,DetrForObjectDetection:()=>t.DetrForObjectDetection,DetrForSegmentation:()=>t.DetrForSegmentation,DetrImageProcessor:()=>_.DetrImageProcessor,DetrModel:()=>t.DetrModel,DetrObjectDetectionOutput:()=>t.DetrObjectDetectionOutput,DetrPreTrainedModel:()=>t.DetrPreTrainedModel,DetrSegmentationOutput:()=>t.DetrSegmentationOutput,Dinov2ForImageClassification:()=>t.Dinov2ForImageClassification,Dinov2Model:()=>t.Dinov2Model,Dinov2PreTrainedModel:()=>t.Dinov2PreTrainedModel,Dinov2WithRegistersForImageClassification:()=>t.Dinov2WithRegistersForImageClassification,Dinov2WithRegistersModel:()=>t.Dinov2WithRegistersModel,Dinov2WithRegistersPreTrainedModel:()=>t.Dinov2WithRegistersPreTrainedModel,DistilBertForMaskedLM:()=>t.DistilBertForMaskedLM,DistilBertForQuestionAnswering:()=>t.DistilBertForQuestionAnswering,DistilBertForSequenceClassification:()=>t.DistilBertForSequenceClassification,DistilBertForTokenClassification:()=>t.DistilBertForTokenClassification,DistilBertModel:()=>t.DistilBertModel,DistilBertPreTrainedModel:()=>t.DistilBertPreTrainedModel,DistilBertTokenizer:()=>s.DistilBertTokenizer,DocumentQuestionAnsweringPipeline:()=>r.DocumentQuestionAnsweringPipeline,DonutFeatureExtractor:()=>_.DonutFeatureExtractor,DonutImageProcessor:()=>_.DonutImageProcessor,DonutSwinModel:()=>t.DonutSwinModel,DonutSwinPreTrainedModel:()=>t.DonutSwinPreTrainedModel,EfficientNetForImageClassification:()=>t.EfficientNetForImageClassification,EfficientNetImageProcessor:()=>_.EfficientNetImageProcessor,EfficientNetModel:()=>t.EfficientNetModel,EfficientNetPreTrainedModel:()=>t.EfficientNetPreTrainedModel,ElectraForMaskedLM:()=>t.ElectraForMaskedLM,ElectraForQuestionAnswering:()=>t.ElectraForQuestionAnswering,ElectraForSequenceClassification:()=>t.ElectraForSequenceClassification,ElectraForTokenClassification:()=>t.ElectraForTokenClassification,ElectraModel:()=>t.ElectraModel,ElectraPreTrainedModel:()=>t.ElectraPreTrainedModel,ElectraTokenizer:()=>s.ElectraTokenizer,EncodecFeatureExtractor:()=>u.EncodecFeatureExtractor,EosTokenCriteria:()=>x.EosTokenCriteria,EsmForMaskedLM:()=>t.EsmForMaskedLM,EsmForSequenceClassification:()=>t.EsmForSequenceClassification,EsmForTokenClassification:()=>t.EsmForTokenClassification,EsmModel:()=>t.EsmModel,EsmPreTrainedModel:()=>t.EsmPreTrainedModel,EsmTokenizer:()=>s.EsmTokenizer,ExaoneForCausalLM:()=>t.ExaoneForCausalLM,ExaoneModel:()=>t.ExaoneModel,ExaonePreTrainedModel:()=>t.ExaonePreTrainedModel,FFT:()=>d.FFT,FalconForCausalLM:()=>t.FalconForCausalLM,FalconModel:()=>t.FalconModel,FalconPreTrainedModel:()=>t.FalconPreTrainedModel,FalconTokenizer:()=>s.FalconTokenizer,FastViTForImageClassification:()=>t.FastViTForImageClassification,FastViTModel:()=>t.FastViTModel,FastViTPreTrainedModel:()=>t.FastViTPreTrainedModel,FeatureExtractionPipeline:()=>r.FeatureExtractionPipeline,FeatureExtractor:()=>p.FeatureExtractor,FillMaskPipeline:()=>r.FillMaskPipeline,Florence2ForConditionalGeneration:()=>t.Florence2ForConditionalGeneration,Florence2PreTrainedModel:()=>t.Florence2PreTrainedModel,Florence2Processor:()=>v.Florence2Processor,ForcedBOSTokenLogitsProcessor:()=>g.ForcedBOSTokenLogitsProcessor,ForcedEOSTokenLogitsProcessor:()=>g.ForcedEOSTokenLogitsProcessor,GLPNFeatureExtractor:()=>_.GLPNFeatureExtractor,GLPNForDepthEstimation:()=>t.GLPNForDepthEstimation,GLPNModel:()=>t.GLPNModel,GLPNPreTrainedModel:()=>t.GLPNPreTrainedModel,GPT2LMHeadModel:()=>t.GPT2LMHeadModel,GPT2Model:()=>t.GPT2Model,GPT2PreTrainedModel:()=>t.GPT2PreTrainedModel,GPT2Tokenizer:()=>s.GPT2Tokenizer,GPTBigCodeForCausalLM:()=>t.GPTBigCodeForCausalLM,GPTBigCodeModel:()=>t.GPTBigCodeModel,GPTBigCodePreTrainedModel:()=>t.GPTBigCodePreTrainedModel,GPTJForCausalLM:()=>t.GPTJForCausalLM,GPTJModel:()=>t.GPTJModel,GPTJPreTrainedModel:()=>t.GPTJPreTrainedModel,GPTNeoForCausalLM:()=>t.GPTNeoForCausalLM,GPTNeoModel:()=>t.GPTNeoModel,GPTNeoPreTrainedModel:()=>t.GPTNeoPreTrainedModel,GPTNeoXForCausalLM:()=>t.GPTNeoXForCausalLM,GPTNeoXModel:()=>t.GPTNeoXModel,GPTNeoXPreTrainedModel:()=>t.GPTNeoXPreTrainedModel,GPTNeoXTokenizer:()=>s.GPTNeoXTokenizer,Gemma2ForCausalLM:()=>t.Gemma2ForCausalLM,Gemma2Model:()=>t.Gemma2Model,Gemma2PreTrainedModel:()=>t.Gemma2PreTrainedModel,GemmaForCausalLM:()=>t.GemmaForCausalLM,GemmaModel:()=>t.GemmaModel,GemmaPreTrainedModel:()=>t.GemmaPreTrainedModel,GemmaTokenizer:()=>s.GemmaTokenizer,GlmForCausalLM:()=>t.GlmForCausalLM,GlmModel:()=>t.GlmModel,GlmPreTrainedModel:()=>t.GlmPreTrainedModel,GraniteForCausalLM:()=>t.GraniteForCausalLM,GraniteModel:()=>t.GraniteModel,GranitePreTrainedModel:()=>t.GranitePreTrainedModel,Grok1Tokenizer:()=>s.Grok1Tokenizer,GroundingDinoForObjectDetection:()=>t.GroundingDinoForObjectDetection,GroundingDinoImageProcessor:()=>_.GroundingDinoImageProcessor,GroundingDinoPreTrainedModel:()=>t.GroundingDinoPreTrainedModel,GroundingDinoProcessor:()=>v.GroundingDinoProcessor,GroupViTModel:()=>t.GroupViTModel,GroupViTPreTrainedModel:()=>t.GroupViTPreTrainedModel,HeliumForCausalLM:()=>t.HeliumForCausalLM,HeliumModel:()=>t.HeliumModel,HeliumPreTrainedModel:()=>t.HeliumPreTrainedModel,HerbertTokenizer:()=>s.HerbertTokenizer,HieraForImageClassification:()=>t.HieraForImageClassification,HieraModel:()=>t.HieraModel,HieraPreTrainedModel:()=>t.HieraPreTrainedModel,HubertForCTC:()=>t.HubertForCTC,HubertForSequenceClassification:()=>t.HubertForSequenceClassification,HubertModel:()=>t.HubertModel,HubertPreTrainedModel:()=>t.HubertPreTrainedModel,IJepaForImageClassification:()=>t.IJepaForImageClassification,IJepaModel:()=>t.IJepaModel,IJepaPreTrainedModel:()=>t.IJepaPreTrainedModel,Idefics3ForConditionalGeneration:()=>t.Idefics3ForConditionalGeneration,Idefics3ImageProcessor:()=>_.Idefics3ImageProcessor,Idefics3PreTrainedModel:()=>t.Idefics3PreTrainedModel,Idefics3Processor:()=>v.Idefics3Processor,ImageClassificationPipeline:()=>r.ImageClassificationPipeline,ImageFeatureExtractionPipeline:()=>r.ImageFeatureExtractionPipeline,ImageFeatureExtractor:()=>u.ImageFeatureExtractor,ImageMattingOutput:()=>t.ImageMattingOutput,ImageProcessor:()=>w.ImageProcessor,ImageSegmentationPipeline:()=>r.ImageSegmentationPipeline,ImageToImagePipeline:()=>r.ImageToImagePipeline,ImageToTextPipeline:()=>r.ImageToTextPipeline,InterruptableStoppingCriteria:()=>x.InterruptableStoppingCriteria,JAISLMHeadModel:()=>t.JAISLMHeadModel,JAISModel:()=>t.JAISModel,JAISPreTrainedModel:()=>t.JAISPreTrainedModel,JinaCLIPImageProcessor:()=>_.JinaCLIPImageProcessor,JinaCLIPModel:()=>t.JinaCLIPModel,JinaCLIPPreTrainedModel:()=>t.JinaCLIPPreTrainedModel,JinaCLIPProcessor:()=>v.JinaCLIPProcessor,JinaCLIPTextModel:()=>t.JinaCLIPTextModel,JinaCLIPVisionModel:()=>t.JinaCLIPVisionModel,LiteWhisperForConditionalGeneration:()=>t.LiteWhisperForConditionalGeneration,LlamaForCausalLM:()=>t.LlamaForCausalLM,LlamaModel:()=>t.LlamaModel,LlamaPreTrainedModel:()=>t.LlamaPreTrainedModel,LlamaTokenizer:()=>s.LlamaTokenizer,LlavaForConditionalGeneration:()=>t.LlavaForConditionalGeneration,LlavaOnevisionForConditionalGeneration:()=>t.LlavaOnevisionForConditionalGeneration,LlavaOnevisionImageProcessor:()=>_.LlavaOnevisionImageProcessor,LlavaPreTrainedModel:()=>t.LlavaPreTrainedModel,LogitsProcessor:()=>g.LogitsProcessor,LogitsProcessorList:()=>g.LogitsProcessorList,LogitsWarper:()=>g.LogitsWarper,LongT5ForConditionalGeneration:()=>t.LongT5ForConditionalGeneration,LongT5Model:()=>t.LongT5Model,LongT5PreTrainedModel:()=>t.LongT5PreTrainedModel,M2M100ForConditionalGeneration:()=>t.M2M100ForConditionalGeneration,M2M100Model:()=>t.M2M100Model,M2M100PreTrainedModel:()=>t.M2M100PreTrainedModel,M2M100Tokenizer:()=>s.M2M100Tokenizer,MBart50Tokenizer:()=>s.MBart50Tokenizer,MBartForCausalLM:()=>t.MBartForCausalLM,MBartForConditionalGeneration:()=>t.MBartForConditionalGeneration,MBartForSequenceClassification:()=>t.MBartForSequenceClassification,MBartModel:()=>t.MBartModel,MBartPreTrainedModel:()=>t.MBartPreTrainedModel,MBartTokenizer:()=>s.MBartTokenizer,MPNetForMaskedLM:()=>t.MPNetForMaskedLM,MPNetForQuestionAnswering:()=>t.MPNetForQuestionAnswering,MPNetForSequenceClassification:()=>t.MPNetForSequenceClassification,MPNetForTokenClassification:()=>t.MPNetForTokenClassification,MPNetModel:()=>t.MPNetModel,MPNetPreTrainedModel:()=>t.MPNetPreTrainedModel,MPNetTokenizer:()=>s.MPNetTokenizer,MT5ForConditionalGeneration:()=>t.MT5ForConditionalGeneration,MT5Model:()=>t.MT5Model,MT5PreTrainedModel:()=>t.MT5PreTrainedModel,MarianMTModel:()=>t.MarianMTModel,MarianModel:()=>t.MarianModel,MarianPreTrainedModel:()=>t.MarianPreTrainedModel,MarianTokenizer:()=>s.MarianTokenizer,Mask2FormerImageProcessor:()=>_.Mask2FormerImageProcessor,MaskFormerFeatureExtractor:()=>_.MaskFormerFeatureExtractor,MaskFormerForInstanceSegmentation:()=>t.MaskFormerForInstanceSegmentation,MaskFormerImageProcessor:()=>_.MaskFormerImageProcessor,MaskFormerModel:()=>t.MaskFormerModel,MaskFormerPreTrainedModel:()=>t.MaskFormerPreTrainedModel,MaskedLMOutput:()=>t.MaskedLMOutput,MaxLengthCriteria:()=>x.MaxLengthCriteria,MgpstrForSceneTextRecognition:()=>t.MgpstrForSceneTextRecognition,MgpstrModelOutput:()=>t.MgpstrModelOutput,MgpstrPreTrainedModel:()=>t.MgpstrPreTrainedModel,MgpstrProcessor:()=>v.MgpstrProcessor,MgpstrTokenizer:()=>s.MgpstrTokenizer,MimiDecoderModel:()=>t.MimiDecoderModel,MimiDecoderOutput:()=>t.MimiDecoderOutput,MimiEncoderModel:()=>t.MimiEncoderModel,MimiEncoderOutput:()=>t.MimiEncoderOutput,MimiModel:()=>t.MimiModel,MimiPreTrainedModel:()=>t.MimiPreTrainedModel,MinLengthLogitsProcessor:()=>g.MinLengthLogitsProcessor,MinNewTokensLengthLogitsProcessor:()=>g.MinNewTokensLengthLogitsProcessor,MistralForCausalLM:()=>t.MistralForCausalLM,MistralModel:()=>t.MistralModel,MistralPreTrainedModel:()=>t.MistralPreTrainedModel,MobileBertForMaskedLM:()=>t.MobileBertForMaskedLM,MobileBertForQuestionAnswering:()=>t.MobileBertForQuestionAnswering,MobileBertForSequenceClassification:()=>t.MobileBertForSequenceClassification,MobileBertModel:()=>t.MobileBertModel,MobileBertPreTrainedModel:()=>t.MobileBertPreTrainedModel,MobileBertTokenizer:()=>s.MobileBertTokenizer,MobileLLMForCausalLM:()=>t.MobileLLMForCausalLM,MobileLLMModel:()=>t.MobileLLMModel,MobileLLMPreTrainedModel:()=>t.MobileLLMPreTrainedModel,MobileNetV1FeatureExtractor:()=>_.MobileNetV1FeatureExtractor,MobileNetV1ForImageClassification:()=>t.MobileNetV1ForImageClassification,MobileNetV1ForSemanticSegmentation:()=>t.MobileNetV1ForSemanticSegmentation,MobileNetV1ImageProcessor:()=>_.MobileNetV1ImageProcessor,MobileNetV1Model:()=>t.MobileNetV1Model,MobileNetV1PreTrainedModel:()=>t.MobileNetV1PreTrainedModel,MobileNetV2FeatureExtractor:()=>_.MobileNetV2FeatureExtractor,MobileNetV2ForImageClassification:()=>t.MobileNetV2ForImageClassification,MobileNetV2ForSemanticSegmentation:()=>t.MobileNetV2ForSemanticSegmentation,MobileNetV2ImageProcessor:()=>_.MobileNetV2ImageProcessor,MobileNetV2Model:()=>t.MobileNetV2Model,MobileNetV2PreTrainedModel:()=>t.MobileNetV2PreTrainedModel,MobileNetV3FeatureExtractor:()=>_.MobileNetV3FeatureExtractor,MobileNetV3ForImageClassification:()=>t.MobileNetV3ForImageClassification,MobileNetV3ForSemanticSegmentation:()=>t.MobileNetV3ForSemanticSegmentation,MobileNetV3ImageProcessor:()=>_.MobileNetV3ImageProcessor,MobileNetV3Model:()=>t.MobileNetV3Model,MobileNetV3PreTrainedModel:()=>t.MobileNetV3PreTrainedModel,MobileNetV4FeatureExtractor:()=>_.MobileNetV4FeatureExtractor,MobileNetV4ForImageClassification:()=>t.MobileNetV4ForImageClassification,MobileNetV4ForSemanticSegmentation:()=>t.MobileNetV4ForSemanticSegmentation,MobileNetV4ImageProcessor:()=>_.MobileNetV4ImageProcessor,MobileNetV4Model:()=>t.MobileNetV4Model,MobileNetV4PreTrainedModel:()=>t.MobileNetV4PreTrainedModel,MobileViTFeatureExtractor:()=>_.MobileViTFeatureExtractor,MobileViTForImageClassification:()=>t.MobileViTForImageClassification,MobileViTImageProcessor:()=>_.MobileViTImageProcessor,MobileViTModel:()=>t.MobileViTModel,MobileViTPreTrainedModel:()=>t.MobileViTPreTrainedModel,MobileViTV2ForImageClassification:()=>t.MobileViTV2ForImageClassification,MobileViTV2Model:()=>t.MobileViTV2Model,MobileViTV2PreTrainedModel:()=>t.MobileViTV2PreTrainedModel,ModelOutput:()=>t.ModelOutput,ModernBertForMaskedLM:()=>t.ModernBertForMaskedLM,ModernBertForSequenceClassification:()=>t.ModernBertForSequenceClassification,ModernBertForTokenClassification:()=>t.ModernBertForTokenClassification,ModernBertModel:()=>t.ModernBertModel,ModernBertPreTrainedModel:()=>t.ModernBertPreTrainedModel,Moondream1ForConditionalGeneration:()=>t.Moondream1ForConditionalGeneration,MoonshineFeatureExtractor:()=>u.MoonshineFeatureExtractor,MoonshineForConditionalGeneration:()=>t.MoonshineForConditionalGeneration,MoonshineModel:()=>t.MoonshineModel,MoonshinePreTrainedModel:()=>t.MoonshinePreTrainedModel,MoonshineProcessor:()=>v.MoonshineProcessor,MptForCausalLM:()=>t.MptForCausalLM,MptModel:()=>t.MptModel,MptPreTrainedModel:()=>t.MptPreTrainedModel,MultiModalityCausalLM:()=>t.MultiModalityCausalLM,MultiModalityPreTrainedModel:()=>t.MultiModalityPreTrainedModel,MusicgenForCausalLM:()=>t.MusicgenForCausalLM,MusicgenForConditionalGeneration:()=>t.MusicgenForConditionalGeneration,MusicgenModel:()=>t.MusicgenModel,MusicgenPreTrainedModel:()=>t.MusicgenPreTrainedModel,NllbTokenizer:()=>s.NllbTokenizer,NoBadWordsLogitsProcessor:()=>g.NoBadWordsLogitsProcessor,NoRepeatNGramLogitsProcessor:()=>g.NoRepeatNGramLogitsProcessor,NomicBertModel:()=>t.NomicBertModel,NomicBertPreTrainedModel:()=>t.NomicBertPreTrainedModel,NougatImageProcessor:()=>_.NougatImageProcessor,NougatTokenizer:()=>s.NougatTokenizer,OPTForCausalLM:()=>t.OPTForCausalLM,OPTModel:()=>t.OPTModel,OPTPreTrainedModel:()=>t.OPTPreTrainedModel,ObjectDetectionPipeline:()=>r.ObjectDetectionPipeline,Olmo2ForCausalLM:()=>t.Olmo2ForCausalLM,Olmo2Model:()=>t.Olmo2Model,Olmo2PreTrainedModel:()=>t.Olmo2PreTrainedModel,OlmoForCausalLM:()=>t.OlmoForCausalLM,OlmoModel:()=>t.OlmoModel,OlmoPreTrainedModel:()=>t.OlmoPreTrainedModel,OpenELMForCausalLM:()=>t.OpenELMForCausalLM,OpenELMModel:()=>t.OpenELMModel,OpenELMPreTrainedModel:()=>t.OpenELMPreTrainedModel,OwlViTFeatureExtractor:()=>_.OwlViTFeatureExtractor,OwlViTForObjectDetection:()=>t.OwlViTForObjectDetection,OwlViTImageProcessor:()=>_.OwlViTImageProcessor,OwlViTModel:()=>t.OwlViTModel,OwlViTPreTrainedModel:()=>t.OwlViTPreTrainedModel,OwlViTProcessor:()=>v.OwlViTProcessor,Owlv2ForObjectDetection:()=>t.Owlv2ForObjectDetection,Owlv2ImageProcessor:()=>_.Owlv2ImageProcessor,Owlv2Model:()=>t.Owlv2Model,Owlv2PreTrainedModel:()=>t.Owlv2PreTrainedModel,PaliGemmaForConditionalGeneration:()=>t.PaliGemmaForConditionalGeneration,PaliGemmaPreTrainedModel:()=>t.PaliGemmaPreTrainedModel,PaliGemmaProcessor:()=>v.PaliGemmaProcessor,PatchTSMixerForPrediction:()=>t.PatchTSMixerForPrediction,PatchTSMixerModel:()=>t.PatchTSMixerModel,PatchTSMixerPreTrainedModel:()=>t.PatchTSMixerPreTrainedModel,PatchTSTForPrediction:()=>t.PatchTSTForPrediction,PatchTSTModel:()=>t.PatchTSTModel,PatchTSTPreTrainedModel:()=>t.PatchTSTPreTrainedModel,Phi3ForCausalLM:()=>t.Phi3ForCausalLM,Phi3Model:()=>t.Phi3Model,Phi3PreTrainedModel:()=>t.Phi3PreTrainedModel,Phi3VForCausalLM:()=>t.Phi3VForCausalLM,Phi3VImageProcessor:()=>_.Phi3VImageProcessor,Phi3VPreTrainedModel:()=>t.Phi3VPreTrainedModel,Phi3VProcessor:()=>v.Phi3VProcessor,PhiForCausalLM:()=>t.PhiForCausalLM,PhiModel:()=>t.PhiModel,PhiPreTrainedModel:()=>t.PhiPreTrainedModel,Pipeline:()=>r.Pipeline,PreTrainedModel:()=>t.PreTrainedModel,PreTrainedTokenizer:()=>s.PreTrainedTokenizer,PretrainedConfig:()=>i.PretrainedConfig,PretrainedMixin:()=>t.PretrainedMixin,Processor:()=>A.Processor,PvtForImageClassification:()=>t.PvtForImageClassification,PvtImageProcessor:()=>_.PvtImageProcessor,PvtModel:()=>t.PvtModel,PvtPreTrainedModel:()=>t.PvtPreTrainedModel,PyAnnoteFeatureExtractor:()=>u.PyAnnoteFeatureExtractor,PyAnnoteForAudioFrameClassification:()=>t.PyAnnoteForAudioFrameClassification,PyAnnoteModel:()=>t.PyAnnoteModel,PyAnnotePreTrainedModel:()=>t.PyAnnotePreTrainedModel,PyAnnoteProcessor:()=>v.PyAnnoteProcessor,QuestionAnsweringModelOutput:()=>t.QuestionAnsweringModelOutput,QuestionAnsweringPipeline:()=>r.QuestionAnsweringPipeline,Qwen2ForCausalLM:()=>t.Qwen2ForCausalLM,Qwen2Model:()=>t.Qwen2Model,Qwen2PreTrainedModel:()=>t.Qwen2PreTrainedModel,Qwen2Tokenizer:()=>s.Qwen2Tokenizer,Qwen2VLForConditionalGeneration:()=>t.Qwen2VLForConditionalGeneration,Qwen2VLImageProcessor:()=>_.Qwen2VLImageProcessor,Qwen2VLPreTrainedModel:()=>t.Qwen2VLPreTrainedModel,Qwen2VLProcessor:()=>v.Qwen2VLProcessor,RTDetrForObjectDetection:()=>t.RTDetrForObjectDetection,RTDetrImageProcessor:()=>_.RTDetrImageProcessor,RTDetrModel:()=>t.RTDetrModel,RTDetrObjectDetectionOutput:()=>t.RTDetrObjectDetectionOutput,RTDetrPreTrainedModel:()=>t.RTDetrPreTrainedModel,RawAudio:()=>n.RawAudio,RawImage:()=>o.RawImage,RawVideo:()=>a.RawVideo,RawVideoFrame:()=>a.RawVideoFrame,RepetitionPenaltyLogitsProcessor:()=>g.RepetitionPenaltyLogitsProcessor,ResNetForImageClassification:()=>t.ResNetForImageClassification,ResNetModel:()=>t.ResNetModel,ResNetPreTrainedModel:()=>t.ResNetPreTrainedModel,RoFormerForMaskedLM:()=>t.RoFormerForMaskedLM,RoFormerForQuestionAnswering:()=>t.RoFormerForQuestionAnswering,RoFormerForSequenceClassification:()=>t.RoFormerForSequenceClassification,RoFormerForTokenClassification:()=>t.RoFormerForTokenClassification,RoFormerModel:()=>t.RoFormerModel,RoFormerPreTrainedModel:()=>t.RoFormerPreTrainedModel,RoFormerTokenizer:()=>s.RoFormerTokenizer,RobertaForMaskedLM:()=>t.RobertaForMaskedLM,RobertaForQuestionAnswering:()=>t.RobertaForQuestionAnswering,RobertaForSequenceClassification:()=>t.RobertaForSequenceClassification,RobertaForTokenClassification:()=>t.RobertaForTokenClassification,RobertaModel:()=>t.RobertaModel,RobertaPreTrainedModel:()=>t.RobertaPreTrainedModel,RobertaTokenizer:()=>s.RobertaTokenizer,SamImageProcessor:()=>_.SamImageProcessor,SamImageSegmentationOutput:()=>t.SamImageSegmentationOutput,SamModel:()=>t.SamModel,SamPreTrainedModel:()=>t.SamPreTrainedModel,SamProcessor:()=>v.SamProcessor,SapiensForDepthEstimation:()=>t.SapiensForDepthEstimation,SapiensForNormalEstimation:()=>t.SapiensForNormalEstimation,SapiensForSemanticSegmentation:()=>t.SapiensForSemanticSegmentation,SapiensPreTrainedModel:()=>t.SapiensPreTrainedModel,SeamlessM4TFeatureExtractor:()=>u.SeamlessM4TFeatureExtractor,SegformerFeatureExtractor:()=>_.SegformerFeatureExtractor,SegformerForImageClassification:()=>t.SegformerForImageClassification,SegformerForSemanticSegmentation:()=>t.SegformerForSemanticSegmentation,SegformerImageProcessor:()=>_.SegformerImageProcessor,SegformerModel:()=>t.SegformerModel,SegformerPreTrainedModel:()=>t.SegformerPreTrainedModel,Seq2SeqLMOutput:()=>t.Seq2SeqLMOutput,SequenceClassifierOutput:()=>t.SequenceClassifierOutput,SiglipImageProcessor:()=>_.SiglipImageProcessor,SiglipModel:()=>t.SiglipModel,SiglipPreTrainedModel:()=>t.SiglipPreTrainedModel,SiglipTextModel:()=>t.SiglipTextModel,SiglipTokenizer:()=>s.SiglipTokenizer,SiglipVisionModel:()=>t.SiglipVisionModel,SmolVLMForConditionalGeneration:()=>t.SmolVLMForConditionalGeneration,SmolVLMImageProcessor:()=>_.SmolVLMImageProcessor,SmolVLMProcessor:()=>v.SmolVLMProcessor,SpeechT5FeatureExtractor:()=>u.SpeechT5FeatureExtractor,SpeechT5ForSpeechToText:()=>t.SpeechT5ForSpeechToText,SpeechT5ForTextToSpeech:()=>t.SpeechT5ForTextToSpeech,SpeechT5HifiGan:()=>t.SpeechT5HifiGan,SpeechT5Model:()=>t.SpeechT5Model,SpeechT5PreTrainedModel:()=>t.SpeechT5PreTrainedModel,SpeechT5Processor:()=>v.SpeechT5Processor,SpeechT5Tokenizer:()=>s.SpeechT5Tokenizer,SqueezeBertForMaskedLM:()=>t.SqueezeBertForMaskedLM,SqueezeBertForQuestionAnswering:()=>t.SqueezeBertForQuestionAnswering,SqueezeBertForSequenceClassification:()=>t.SqueezeBertForSequenceClassification,SqueezeBertModel:()=>t.SqueezeBertModel,SqueezeBertPreTrainedModel:()=>t.SqueezeBertPreTrainedModel,SqueezeBertTokenizer:()=>s.SqueezeBertTokenizer,StableLmForCausalLM:()=>t.StableLmForCausalLM,StableLmModel:()=>t.StableLmModel,StableLmPreTrainedModel:()=>t.StableLmPreTrainedModel,Starcoder2ForCausalLM:()=>t.Starcoder2ForCausalLM,Starcoder2Model:()=>t.Starcoder2Model,Starcoder2PreTrainedModel:()=>t.Starcoder2PreTrainedModel,StoppingCriteria:()=>x.StoppingCriteria,StoppingCriteriaList:()=>x.StoppingCriteriaList,StyleTextToSpeech2Model:()=>t.StyleTextToSpeech2Model,StyleTextToSpeech2PreTrainedModel:()=>t.StyleTextToSpeech2PreTrainedModel,SummarizationPipeline:()=>r.SummarizationPipeline,SuppressTokensAtBeginLogitsProcessor:()=>g.SuppressTokensAtBeginLogitsProcessor,Swin2SRForImageSuperResolution:()=>t.Swin2SRForImageSuperResolution,Swin2SRImageProcessor:()=>_.Swin2SRImageProcessor,Swin2SRModel:()=>t.Swin2SRModel,Swin2SRPreTrainedModel:()=>t.Swin2SRPreTrainedModel,SwinForImageClassification:()=>t.SwinForImageClassification,SwinForSemanticSegmentation:()=>t.SwinForSemanticSegmentation,SwinModel:()=>t.SwinModel,SwinPreTrainedModel:()=>t.SwinPreTrainedModel,T5ForConditionalGeneration:()=>t.T5ForConditionalGeneration,T5Model:()=>t.T5Model,T5PreTrainedModel:()=>t.T5PreTrainedModel,T5Tokenizer:()=>s.T5Tokenizer,TableTransformerForObjectDetection:()=>t.TableTransformerForObjectDetection,TableTransformerModel:()=>t.TableTransformerModel,TableTransformerObjectDetectionOutput:()=>t.TableTransformerObjectDetectionOutput,TableTransformerPreTrainedModel:()=>t.TableTransformerPreTrainedModel,TemperatureLogitsWarper:()=>g.TemperatureLogitsWarper,Tensor:()=>l.Tensor,Text2TextGenerationPipeline:()=>r.Text2TextGenerationPipeline,TextClassificationPipeline:()=>r.TextClassificationPipeline,TextGenerationPipeline:()=>r.TextGenerationPipeline,TextStreamer:()=>S.TextStreamer,TextToAudioPipeline:()=>r.TextToAudioPipeline,TokenClassificationPipeline:()=>r.TokenClassificationPipeline,TokenClassifierOutput:()=>t.TokenClassifierOutput,TokenizerModel:()=>s.TokenizerModel,TopKLogitsWarper:()=>g.TopKLogitsWarper,TopPLogitsWarper:()=>g.TopPLogitsWarper,TrOCRForCausalLM:()=>t.TrOCRForCausalLM,TrOCRPreTrainedModel:()=>t.TrOCRPreTrainedModel,TranslationPipeline:()=>r.TranslationPipeline,UltravoxModel:()=>t.UltravoxModel,UltravoxPreTrainedModel:()=>t.UltravoxPreTrainedModel,UltravoxProcessor:()=>v.UltravoxProcessor,UniSpeechForCTC:()=>t.UniSpeechForCTC,UniSpeechForSequenceClassification:()=>t.UniSpeechForSequenceClassification,UniSpeechModel:()=>t.UniSpeechModel,UniSpeechPreTrainedModel:()=>t.UniSpeechPreTrainedModel,UniSpeechSatForAudioFrameClassification:()=>t.UniSpeechSatForAudioFrameClassification,UniSpeechSatForCTC:()=>t.UniSpeechSatForCTC,UniSpeechSatForSequenceClassification:()=>t.UniSpeechSatForSequenceClassification,UniSpeechSatModel:()=>t.UniSpeechSatModel,UniSpeechSatPreTrainedModel:()=>t.UniSpeechSatPreTrainedModel,VLChatProcessor:()=>v.VLChatProcessor,VLMImageProcessor:()=>_.VLMImageProcessor,ViTFeatureExtractor:()=>_.ViTFeatureExtractor,ViTForImageClassification:()=>t.ViTForImageClassification,ViTImageProcessor:()=>_.ViTImageProcessor,ViTMAEModel:()=>t.ViTMAEModel,ViTMAEPreTrainedModel:()=>t.ViTMAEPreTrainedModel,ViTMSNForImageClassification:()=>t.ViTMSNForImageClassification,ViTMSNModel:()=>t.ViTMSNModel,ViTMSNPreTrainedModel:()=>t.ViTMSNPreTrainedModel,ViTModel:()=>t.ViTModel,ViTPreTrainedModel:()=>t.ViTPreTrainedModel,VisionEncoderDecoderModel:()=>t.VisionEncoderDecoderModel,VitMatteForImageMatting:()=>t.VitMatteForImageMatting,VitMatteImageProcessor:()=>_.VitMatteImageProcessor,VitMattePreTrainedModel:()=>t.VitMattePreTrainedModel,VitPoseForPoseEstimation:()=>t.VitPoseForPoseEstimation,VitPoseImageProcessor:()=>_.VitPoseImageProcessor,VitPosePreTrainedModel:()=>t.VitPosePreTrainedModel,VitsModel:()=>t.VitsModel,VitsModelOutput:()=>t.VitsModelOutput,VitsPreTrainedModel:()=>t.VitsPreTrainedModel,VitsTokenizer:()=>s.VitsTokenizer,Wav2Vec2BertForCTC:()=>t.Wav2Vec2BertForCTC,Wav2Vec2BertForSequenceClassification:()=>t.Wav2Vec2BertForSequenceClassification,Wav2Vec2BertModel:()=>t.Wav2Vec2BertModel,Wav2Vec2BertPreTrainedModel:()=>t.Wav2Vec2BertPreTrainedModel,Wav2Vec2CTCTokenizer:()=>s.Wav2Vec2CTCTokenizer,Wav2Vec2FeatureExtractor:()=>u.Wav2Vec2FeatureExtractor,Wav2Vec2ForAudioFrameClassification:()=>t.Wav2Vec2ForAudioFrameClassification,Wav2Vec2ForCTC:()=>t.Wav2Vec2ForCTC,Wav2Vec2ForSequenceClassification:()=>t.Wav2Vec2ForSequenceClassification,Wav2Vec2Model:()=>t.Wav2Vec2Model,Wav2Vec2PreTrainedModel:()=>t.Wav2Vec2PreTrainedModel,Wav2Vec2Processor:()=>v.Wav2Vec2Processor,Wav2Vec2ProcessorWithLM:()=>v.Wav2Vec2ProcessorWithLM,WavLMForAudioFrameClassification:()=>t.WavLMForAudioFrameClassification,WavLMForCTC:()=>t.WavLMForCTC,WavLMForSequenceClassification:()=>t.WavLMForSequenceClassification,WavLMForXVector:()=>t.WavLMForXVector,WavLMModel:()=>t.WavLMModel,WavLMPreTrainedModel:()=>t.WavLMPreTrainedModel,WeSpeakerFeatureExtractor:()=>u.WeSpeakerFeatureExtractor,WeSpeakerResNetModel:()=>t.WeSpeakerResNetModel,WeSpeakerResNetPreTrainedModel:()=>t.WeSpeakerResNetPreTrainedModel,WhisperFeatureExtractor:()=>u.WhisperFeatureExtractor,WhisperForConditionalGeneration:()=>t.WhisperForConditionalGeneration,WhisperModel:()=>t.WhisperModel,WhisperPreTrainedModel:()=>t.WhisperPreTrainedModel,WhisperProcessor:()=>v.WhisperProcessor,WhisperTextStreamer:()=>S.WhisperTextStreamer,WhisperTimeStampLogitsProcessor:()=>g.WhisperTimeStampLogitsProcessor,WhisperTokenizer:()=>s.WhisperTokenizer,XLMForQuestionAnswering:()=>t.XLMForQuestionAnswering,XLMForSequenceClassification:()=>t.XLMForSequenceClassification,XLMForTokenClassification:()=>t.XLMForTokenClassification,XLMModel:()=>t.XLMModel,XLMPreTrainedModel:()=>t.XLMPreTrainedModel,XLMRobertaForMaskedLM:()=>t.XLMRobertaForMaskedLM,XLMRobertaForQuestionAnswering:()=>t.XLMRobertaForQuestionAnswering,XLMRobertaForSequenceClassification:()=>t.XLMRobertaForSequenceClassification,XLMRobertaForTokenClassification:()=>t.XLMRobertaForTokenClassification,XLMRobertaModel:()=>t.XLMRobertaModel,XLMRobertaPreTrainedModel:()=>t.XLMRobertaPreTrainedModel,XLMRobertaTokenizer:()=>s.XLMRobertaTokenizer,XLMTokenizer:()=>s.XLMTokenizer,XLMWithLMHeadModel:()=>t.XLMWithLMHeadModel,XVectorOutput:()=>t.XVectorOutput,YolosFeatureExtractor:()=>_.YolosFeatureExtractor,YolosForObjectDetection:()=>t.YolosForObjectDetection,YolosImageProcessor:()=>_.YolosImageProcessor,YolosModel:()=>t.YolosModel,YolosObjectDetectionOutput:()=>t.YolosObjectDetectionOutput,YolosPreTrainedModel:()=>t.YolosPreTrainedModel,ZeroShotAudioClassificationPipeline:()=>r.ZeroShotAudioClassificationPipeline,ZeroShotClassificationPipeline:()=>r.ZeroShotClassificationPipeline,ZeroShotImageClassificationPipeline:()=>r.ZeroShotImageClassificationPipeline,ZeroShotObjectDetectionPipeline:()=>r.ZeroShotObjectDetectionPipeline,bankers_round:()=>d.bankers_round,cat:()=>l.cat,cos_sim:()=>d.cos_sim,dot:()=>d.dot,dynamic_time_warping:()=>d.dynamic_time_warping,env:()=>e.env,full:()=>l.full,full_like:()=>l.full_like,getKeyValueShapes:()=>i.getKeyValueShapes,hamming:()=>n.hamming,hanning:()=>n.hanning,interpolate:()=>l.interpolate,interpolate_4d:()=>l.interpolate_4d,interpolate_data:()=>d.interpolate_data,is_chinese_char:()=>s.is_chinese_char,layer_norm:()=>l.layer_norm,load_image:()=>o.load_image,load_video:()=>a.load_video,log_softmax:()=>d.log_softmax,magnitude:()=>d.magnitude,matmul:()=>l.matmul,max:()=>d.max,mean:()=>l.mean,mean_pooling:()=>l.mean_pooling,medianFilter:()=>d.medianFilter,mel_filter_bank:()=>n.mel_filter_bank,min:()=>d.min,ones:()=>l.ones,ones_like:()=>l.ones_like,permute:()=>l.permute,permute_data:()=>d.permute_data,pipeline:()=>r.pipeline,quantize_embeddings:()=>l.quantize_embeddings,rand:()=>l.rand,read_audio:()=>n.read_audio,rfft:()=>l.rfft,round:()=>d.round,slice:()=>l.slice,softmax:()=>d.softmax,spectrogram:()=>n.spectrogram,stack:()=>l.stack,std_mean:()=>l.std_mean,topk:()=>l.topk,window_function:()=>n.window_function,zeros:()=>l.zeros,zeros_like:()=>l.zeros_like});var e=Ft("./src/env.js"),r=Ft("./src/pipelines.js"),t=Ft("./src/models.js"),s=Ft("./src/tokenizers.js"),i=Ft("./src/configs.js"),n=Ft("./src/utils/audio.js"),o=Ft("./src/utils/image.js"),a=Ft("./src/utils/video.js"),l=Ft("./src/utils/tensor.js"),d=Ft("./src/utils/maths.js"),p=Ft("./src/base/feature_extraction_utils.js"),u=Ft("./src/models/feature_extractors.js"),h=Ft("./src/models/auto/feature_extraction_auto.js"),w=Ft("./src/base/image_processors_utils.js"),_=Ft("./src/models/image_processors.js"),P=Ft("./src/models/auto/image_processing_auto.js"),A=Ft("./src/base/processing_utils.js"),v=Ft("./src/models/processors.js"),y=Ft("./src/models/auto/processing_auto.js"),S=Ft("./src/generation/streamers.js"),x=Ft("./src/generation/stopping_criteria.js"),g=Ft("./src/generation/logits_process.js")})();f.ASTFeatureExtractor;f.ASTForAudioClassification;f.ASTModel;f.ASTPreTrainedModel;f.AlbertForMaskedLM;f.AlbertForQuestionAnswering;f.AlbertForSequenceClassification;f.AlbertModel;f.AlbertPreTrainedModel;f.AlbertTokenizer;f.AudioClassificationPipeline;f.AutoConfig;f.AutoFeatureExtractor;f.AutoImageProcessor;var Lx=f.AutoModel;f.AutoModelForAudioClassification;f.AutoModelForAudioFrameClassification;f.AutoModelForAudioTextToText;f.AutoModelForCTC;f.AutoModelForCausalLM;f.AutoModelForDepthEstimation;f.AutoModelForDocumentQuestionAnswering;f.AutoModelForImageClassification;f.AutoModelForImageFeatureExtraction;f.AutoModelForImageMatting;f.AutoModelForImageSegmentation;f.AutoModelForImageTextToText;f.AutoModelForImageToImage;f.AutoModelForMaskGeneration;f.AutoModelForMaskedLM;f.AutoModelForNormalEstimation;f.AutoModelForObjectDetection;f.AutoModelForPoseEstimation;f.AutoModelForQuestionAnswering;f.AutoModelForSemanticSegmentation;f.AutoModelForSeq2SeqLM;f.AutoModelForSequenceClassification;f.AutoModelForSpeechSeq2Seq;f.AutoModelForTextToSpectrogram;f.AutoModelForTextToWaveform;f.AutoModelForTokenClassification;f.AutoModelForUniversalSegmentation;f.AutoModelForVision2Seq;f.AutoModelForXVector;f.AutoModelForZeroShotObjectDetection;f.AutoProcessor;f.AutoTokenizer;f.AutomaticSpeechRecognitionPipeline;f.BackgroundRemovalPipeline;f.BartForConditionalGeneration;f.BartForSequenceClassification;f.BartModel;f.BartPretrainedModel;f.BartTokenizer;f.BaseModelOutput;f.BaseStreamer;f.BeitFeatureExtractor;f.BeitForImageClassification;f.BeitModel;f.BeitPreTrainedModel;f.BertForMaskedLM;f.BertForQuestionAnswering;f.BertForSequenceClassification;f.BertForTokenClassification;f.BertModel;f.BertPreTrainedModel;f.BertTokenizer;f.BitImageProcessor;f.BlenderbotForConditionalGeneration;f.BlenderbotModel;f.BlenderbotPreTrainedModel;f.BlenderbotSmallForConditionalGeneration;f.BlenderbotSmallModel;f.BlenderbotSmallPreTrainedModel;f.BlenderbotSmallTokenizer;f.BlenderbotTokenizer;f.BloomForCausalLM;f.BloomModel;f.BloomPreTrainedModel;f.BloomTokenizer;f.CLIPFeatureExtractor;f.CLIPImageProcessor;f.CLIPModel;f.CLIPPreTrainedModel;f.CLIPSegForImageSegmentation;f.CLIPSegModel;f.CLIPSegPreTrainedModel;f.CLIPTextModel;f.CLIPTextModelWithProjection;f.CLIPTokenizer;f.CLIPVisionModel;f.CLIPVisionModelWithProjection;f.CamembertForMaskedLM;f.CamembertForQuestionAnswering;f.CamembertForSequenceClassification;f.CamembertForTokenClassification;f.CamembertModel;f.CamembertPreTrainedModel;f.CamembertTokenizer;f.CausalLMOutput;f.CausalLMOutputWithPast;f.ChineseCLIPFeatureExtractor;f.ChineseCLIPModel;f.ChineseCLIPPreTrainedModel;f.ClapAudioModelWithProjection;f.ClapFeatureExtractor;f.ClapModel;f.ClapPreTrainedModel;f.ClapTextModelWithProjection;f.ClassifierFreeGuidanceLogitsProcessor;f.CodeGenForCausalLM;f.CodeGenModel;f.CodeGenPreTrainedModel;f.CodeGenTokenizer;f.CodeLlamaTokenizer;f.CohereForCausalLM;f.CohereModel;f.CoherePreTrainedModel;f.CohereTokenizer;f.ConvBertForMaskedLM;f.ConvBertForQuestionAnswering;f.ConvBertForSequenceClassification;f.ConvBertForTokenClassification;f.ConvBertModel;f.ConvBertPreTrainedModel;f.ConvBertTokenizer;f.ConvNextFeatureExtractor;f.ConvNextForImageClassification;f.ConvNextImageProcessor;f.ConvNextModel;f.ConvNextPreTrainedModel;f.ConvNextV2ForImageClassification;f.ConvNextV2Model;f.ConvNextV2PreTrainedModel;f.DPTFeatureExtractor;f.DPTForDepthEstimation;f.DPTImageProcessor;f.DPTModel;f.DPTPreTrainedModel;f.DacDecoderModel;f.DacDecoderOutput;f.DacEncoderModel;f.DacEncoderOutput;f.DacFeatureExtractor;f.DacModel;f.DacPreTrainedModel;f.DataTypeMap;f.DebertaForMaskedLM;f.DebertaForQuestionAnswering;f.DebertaForSequenceClassification;f.DebertaForTokenClassification;f.DebertaModel;f.DebertaPreTrainedModel;f.DebertaTokenizer;f.DebertaV2ForMaskedLM;f.DebertaV2ForQuestionAnswering;f.DebertaV2ForSequenceClassification;f.DebertaV2ForTokenClassification;f.DebertaV2Model;f.DebertaV2PreTrainedModel;f.DebertaV2Tokenizer;f.DecisionTransformerModel;f.DecisionTransformerPreTrainedModel;f.DeiTFeatureExtractor;f.DeiTForImageClassification;f.DeiTImageProcessor;f.DeiTModel;f.DeiTPreTrainedModel;f.DepthAnythingForDepthEstimation;f.DepthAnythingPreTrainedModel;f.DepthEstimationPipeline;f.DepthProForDepthEstimation;f.DepthProPreTrainedModel;f.DetrFeatureExtractor;f.DetrForObjectDetection;f.DetrForSegmentation;f.DetrImageProcessor;f.DetrModel;f.DetrObjectDetectionOutput;f.DetrPreTrainedModel;f.DetrSegmentationOutput;f.Dinov2ForImageClassification;f.Dinov2Model;f.Dinov2PreTrainedModel;f.Dinov2WithRegistersForImageClassification;f.Dinov2WithRegistersModel;f.Dinov2WithRegistersPreTrainedModel;f.DistilBertForMaskedLM;f.DistilBertForQuestionAnswering;f.DistilBertForSequenceClassification;f.DistilBertForTokenClassification;f.DistilBertModel;f.DistilBertPreTrainedModel;f.DistilBertTokenizer;f.DocumentQuestionAnsweringPipeline;f.DonutFeatureExtractor;f.DonutImageProcessor;f.DonutSwinModel;f.DonutSwinPreTrainedModel;f.EfficientNetForImageClassification;f.EfficientNetImageProcessor;f.EfficientNetModel;f.EfficientNetPreTrainedModel;f.ElectraForMaskedLM;f.ElectraForQuestionAnswering;f.ElectraForSequenceClassification;f.ElectraForTokenClassification;f.ElectraModel;f.ElectraPreTrainedModel;f.ElectraTokenizer;f.EncodecFeatureExtractor;f.EosTokenCriteria;f.EsmForMaskedLM;f.EsmForSequenceClassification;f.EsmForTokenClassification;f.EsmModel;f.EsmPreTrainedModel;f.EsmTokenizer;f.ExaoneForCausalLM;f.ExaoneModel;f.ExaonePreTrainedModel;f.FFT;f.FalconForCausalLM;f.FalconModel;f.FalconPreTrainedModel;f.FalconTokenizer;f.FastViTForImageClassification;f.FastViTModel;f.FastViTPreTrainedModel;f.FeatureExtractionPipeline;f.FeatureExtractor;f.FillMaskPipeline;f.Florence2ForConditionalGeneration;f.Florence2PreTrainedModel;f.Florence2Processor;f.ForcedBOSTokenLogitsProcessor;f.ForcedEOSTokenLogitsProcessor;f.GLPNFeatureExtractor;f.GLPNForDepthEstimation;f.GLPNModel;f.GLPNPreTrainedModel;f.GPT2LMHeadModel;f.GPT2Model;f.GPT2PreTrainedModel;f.GPT2Tokenizer;f.GPTBigCodeForCausalLM;f.GPTBigCodeModel;f.GPTBigCodePreTrainedModel;f.GPTJForCausalLM;f.GPTJModel;f.GPTJPreTrainedModel;f.GPTNeoForCausalLM;f.GPTNeoModel;f.GPTNeoPreTrainedModel;f.GPTNeoXForCausalLM;f.GPTNeoXModel;f.GPTNeoXPreTrainedModel;f.GPTNeoXTokenizer;f.Gemma2ForCausalLM;f.Gemma2Model;f.Gemma2PreTrainedModel;f.GemmaForCausalLM;f.GemmaModel;f.GemmaPreTrainedModel;f.GemmaTokenizer;f.GlmForCausalLM;f.GlmModel;f.GlmPreTrainedModel;f.GraniteForCausalLM;f.GraniteModel;f.GranitePreTrainedModel;f.Grok1Tokenizer;f.GroundingDinoForObjectDetection;f.GroundingDinoImageProcessor;f.GroundingDinoPreTrainedModel;f.GroundingDinoProcessor;f.GroupViTModel;f.GroupViTPreTrainedModel;f.HeliumForCausalLM;f.HeliumModel;f.HeliumPreTrainedModel;f.HerbertTokenizer;f.HieraForImageClassification;f.HieraModel;f.HieraPreTrainedModel;f.HubertForCTC;f.HubertForSequenceClassification;f.HubertModel;f.HubertPreTrainedModel;f.IJepaForImageClassification;f.IJepaModel;f.IJepaPreTrainedModel;f.Idefics3ForConditionalGeneration;f.Idefics3ImageProcessor;f.Idefics3PreTrainedModel;f.Idefics3Processor;f.ImageClassificationPipeline;f.ImageFeatureExtractionPipeline;f.ImageFeatureExtractor;f.ImageMattingOutput;f.ImageProcessor;f.ImageSegmentationPipeline;f.ImageToImagePipeline;f.ImageToTextPipeline;f.InterruptableStoppingCriteria;f.JAISLMHeadModel;f.JAISModel;f.JAISPreTrainedModel;f.JinaCLIPImageProcessor;f.JinaCLIPModel;f.JinaCLIPPreTrainedModel;f.JinaCLIPProcessor;f.JinaCLIPTextModel;f.JinaCLIPVisionModel;f.LiteWhisperForConditionalGeneration;f.LlamaForCausalLM;f.LlamaModel;f.LlamaPreTrainedModel;f.LlamaTokenizer;f.LlavaForConditionalGeneration;f.LlavaOnevisionForConditionalGeneration;f.LlavaOnevisionImageProcessor;f.LlavaPreTrainedModel;f.LogitsProcessor;f.LogitsProcessorList;f.LogitsWarper;f.LongT5ForConditionalGeneration;f.LongT5Model;f.LongT5PreTrainedModel;f.M2M100ForConditionalGeneration;f.M2M100Model;f.M2M100PreTrainedModel;f.M2M100Tokenizer;f.MBart50Tokenizer;f.MBartForCausalLM;f.MBartForConditionalGeneration;f.MBartForSequenceClassification;f.MBartModel;f.MBartPreTrainedModel;f.MBartTokenizer;f.MPNetForMaskedLM;f.MPNetForQuestionAnswering;f.MPNetForSequenceClassification;f.MPNetForTokenClassification;f.MPNetModel;f.MPNetPreTrainedModel;f.MPNetTokenizer;f.MT5ForConditionalGeneration;f.MT5Model;f.MT5PreTrainedModel;f.MarianMTModel;f.MarianModel;f.MarianPreTrainedModel;f.MarianTokenizer;f.Mask2FormerImageProcessor;f.MaskFormerFeatureExtractor;f.MaskFormerForInstanceSegmentation;f.MaskFormerImageProcessor;f.MaskFormerModel;f.MaskFormerPreTrainedModel;f.MaskedLMOutput;f.MaxLengthCriteria;f.MgpstrForSceneTextRecognition;f.MgpstrModelOutput;f.MgpstrPreTrainedModel;f.MgpstrProcessor;f.MgpstrTokenizer;f.MimiDecoderModel;f.MimiDecoderOutput;f.MimiEncoderModel;f.MimiEncoderOutput;f.MimiModel;f.MimiPreTrainedModel;f.MinLengthLogitsProcessor;f.MinNewTokensLengthLogitsProcessor;f.MistralForCausalLM;f.MistralModel;f.MistralPreTrainedModel;f.MobileBertForMaskedLM;f.MobileBertForQuestionAnswering;f.MobileBertForSequenceClassification;f.MobileBertModel;f.MobileBertPreTrainedModel;f.MobileBertTokenizer;f.MobileLLMForCausalLM;f.MobileLLMModel;f.MobileLLMPreTrainedModel;f.MobileNetV1FeatureExtractor;f.MobileNetV1ForImageClassification;f.MobileNetV1ForSemanticSegmentation;f.MobileNetV1ImageProcessor;f.MobileNetV1Model;f.MobileNetV1PreTrainedModel;f.MobileNetV2FeatureExtractor;f.MobileNetV2ForImageClassification;f.MobileNetV2ForSemanticSegmentation;f.MobileNetV2ImageProcessor;f.MobileNetV2Model;f.MobileNetV2PreTrainedModel;f.MobileNetV3FeatureExtractor;f.MobileNetV3ForImageClassification;f.MobileNetV3ForSemanticSegmentation;f.MobileNetV3ImageProcessor;f.MobileNetV3Model;f.MobileNetV3PreTrainedModel;f.MobileNetV4FeatureExtractor;f.MobileNetV4ForImageClassification;f.MobileNetV4ForSemanticSegmentation;f.MobileNetV4ImageProcessor;f.MobileNetV4Model;f.MobileNetV4PreTrainedModel;f.MobileViTFeatureExtractor;f.MobileViTForImageClassification;f.MobileViTImageProcessor;f.MobileViTModel;f.MobileViTPreTrainedModel;f.MobileViTV2ForImageClassification;f.MobileViTV2Model;f.MobileViTV2PreTrainedModel;f.ModelOutput;f.ModernBertForMaskedLM;f.ModernBertForSequenceClassification;f.ModernBertForTokenClassification;f.ModernBertModel;f.ModernBertPreTrainedModel;f.Moondream1ForConditionalGeneration;f.MoonshineFeatureExtractor;f.MoonshineForConditionalGeneration;f.MoonshineModel;f.MoonshinePreTrainedModel;f.MoonshineProcessor;f.MptForCausalLM;f.MptModel;f.MptPreTrainedModel;f.MultiModalityCausalLM;f.MultiModalityPreTrainedModel;f.MusicgenForCausalLM;f.MusicgenForConditionalGeneration;f.MusicgenModel;f.MusicgenPreTrainedModel;f.NllbTokenizer;f.NoBadWordsLogitsProcessor;f.NoRepeatNGramLogitsProcessor;f.NomicBertModel;f.NomicBertPreTrainedModel;f.NougatImageProcessor;f.NougatTokenizer;f.OPTForCausalLM;f.OPTModel;f.OPTPreTrainedModel;f.ObjectDetectionPipeline;f.Olmo2ForCausalLM;f.Olmo2Model;f.Olmo2PreTrainedModel;f.OlmoForCausalLM;f.OlmoModel;f.OlmoPreTrainedModel;f.OpenELMForCausalLM;f.OpenELMModel;f.OpenELMPreTrainedModel;f.OwlViTFeatureExtractor;f.OwlViTForObjectDetection;f.OwlViTImageProcessor;f.OwlViTModel;f.OwlViTPreTrainedModel;f.OwlViTProcessor;f.Owlv2ForObjectDetection;f.Owlv2ImageProcessor;f.Owlv2Model;f.Owlv2PreTrainedModel;f.PaliGemmaForConditionalGeneration;f.PaliGemmaPreTrainedModel;f.PaliGemmaProcessor;f.PatchTSMixerForPrediction;f.PatchTSMixerModel;f.PatchTSMixerPreTrainedModel;f.PatchTSTForPrediction;f.PatchTSTModel;f.PatchTSTPreTrainedModel;f.Phi3ForCausalLM;f.Phi3Model;f.Phi3PreTrainedModel;f.Phi3VForCausalLM;f.Phi3VImageProcessor;f.Phi3VPreTrainedModel;f.Phi3VProcessor;f.PhiForCausalLM;f.PhiModel;f.PhiPreTrainedModel;f.Pipeline;f.PreTrainedModel;f.PreTrainedTokenizer;f.PretrainedConfig;f.PretrainedMixin;f.Processor;f.PvtForImageClassification;f.PvtImageProcessor;f.PvtModel;f.PvtPreTrainedModel;f.PyAnnoteFeatureExtractor;f.PyAnnoteForAudioFrameClassification;f.PyAnnoteModel;f.PyAnnotePreTrainedModel;f.PyAnnoteProcessor;f.QuestionAnsweringModelOutput;f.QuestionAnsweringPipeline;f.Qwen2ForCausalLM;f.Qwen2Model;f.Qwen2PreTrainedModel;f.Qwen2Tokenizer;f.Qwen2VLForConditionalGeneration;f.Qwen2VLImageProcessor;f.Qwen2VLPreTrainedModel;f.Qwen2VLProcessor;f.RTDetrForObjectDetection;f.RTDetrImageProcessor;f.RTDetrModel;f.RTDetrObjectDetectionOutput;f.RTDetrPreTrainedModel;f.RawAudio;f.RawImage;f.RawVideo;f.RawVideoFrame;f.RepetitionPenaltyLogitsProcessor;f.ResNetForImageClassification;f.ResNetModel;f.ResNetPreTrainedModel;f.RoFormerForMaskedLM;f.RoFormerForQuestionAnswering;f.RoFormerForSequenceClassification;f.RoFormerForTokenClassification;f.RoFormerModel;f.RoFormerPreTrainedModel;f.RoFormerTokenizer;f.RobertaForMaskedLM;f.RobertaForQuestionAnswering;f.RobertaForSequenceClassification;f.RobertaForTokenClassification;f.RobertaModel;f.RobertaPreTrainedModel;f.RobertaTokenizer;f.SamImageProcessor;f.SamImageSegmentationOutput;f.SamModel;f.SamPreTrainedModel;f.SamProcessor;f.SapiensForDepthEstimation;f.SapiensForNormalEstimation;f.SapiensForSemanticSegmentation;f.SapiensPreTrainedModel;f.SeamlessM4TFeatureExtractor;f.SegformerFeatureExtractor;f.SegformerForImageClassification;f.SegformerForSemanticSegmentation;f.SegformerImageProcessor;f.SegformerModel;f.SegformerPreTrainedModel;f.Seq2SeqLMOutput;f.SequenceClassifierOutput;f.SiglipImageProcessor;f.SiglipModel;f.SiglipPreTrainedModel;f.SiglipTextModel;f.SiglipTokenizer;f.SiglipVisionModel;f.SmolVLMForConditionalGeneration;f.SmolVLMImageProcessor;f.SmolVLMProcessor;f.SpeechT5FeatureExtractor;f.SpeechT5ForSpeechToText;f.SpeechT5ForTextToSpeech;f.SpeechT5HifiGan;f.SpeechT5Model;f.SpeechT5PreTrainedModel;f.SpeechT5Processor;f.SpeechT5Tokenizer;f.SqueezeBertForMaskedLM;f.SqueezeBertForQuestionAnswering;f.SqueezeBertForSequenceClassification;f.SqueezeBertModel;f.SqueezeBertPreTrainedModel;f.SqueezeBertTokenizer;f.StableLmForCausalLM;f.StableLmModel;f.StableLmPreTrainedModel;f.Starcoder2ForCausalLM;f.Starcoder2Model;f.Starcoder2PreTrainedModel;f.StoppingCriteria;f.StoppingCriteriaList;f.StyleTextToSpeech2Model;f.StyleTextToSpeech2PreTrainedModel;f.SummarizationPipeline;f.SuppressTokensAtBeginLogitsProcessor;f.Swin2SRForImageSuperResolution;f.Swin2SRImageProcessor;f.Swin2SRModel;f.Swin2SRPreTrainedModel;f.SwinForImageClassification;f.SwinForSemanticSegmentation;f.SwinModel;f.SwinPreTrainedModel;f.T5ForConditionalGeneration;f.T5Model;f.T5PreTrainedModel;f.T5Tokenizer;f.TableTransformerForObjectDetection;f.TableTransformerModel;f.TableTransformerObjectDetectionOutput;f.TableTransformerPreTrainedModel;f.TemperatureLogitsWarper;var Nu=f.Tensor;f.Text2TextGenerationPipeline;f.TextClassificationPipeline;f.TextGenerationPipeline;f.TextStreamer;f.TextToAudioPipeline;f.TokenClassificationPipeline;f.TokenClassifierOutput;f.TokenizerModel;f.TopKLogitsWarper;f.TopPLogitsWarper;f.TrOCRForCausalLM;f.TrOCRPreTrainedModel;f.TranslationPipeline;f.UltravoxModel;f.UltravoxPreTrainedModel;f.UltravoxProcessor;f.UniSpeechForCTC;f.UniSpeechForSequenceClassification;f.UniSpeechModel;f.UniSpeechPreTrainedModel;f.UniSpeechSatForAudioFrameClassification;f.UniSpeechSatForCTC;f.UniSpeechSatForSequenceClassification;f.UniSpeechSatModel;f.UniSpeechSatPreTrainedModel;f.VLChatProcessor;f.VLMImageProcessor;f.ViTFeatureExtractor;f.ViTForImageClassification;f.ViTImageProcessor;f.ViTMAEModel;f.ViTMAEPreTrainedModel;f.ViTMSNForImageClassification;f.ViTMSNModel;f.ViTMSNPreTrainedModel;f.ViTModel;f.ViTPreTrainedModel;f.VisionEncoderDecoderModel;f.VitMatteForImageMatting;f.VitMatteImageProcessor;f.VitMattePreTrainedModel;f.VitPoseForPoseEstimation;f.VitPoseImageProcessor;f.VitPosePreTrainedModel;f.VitsModel;f.VitsModelOutput;f.VitsPreTrainedModel;f.VitsTokenizer;f.Wav2Vec2BertForCTC;f.Wav2Vec2BertForSequenceClassification;f.Wav2Vec2BertModel;f.Wav2Vec2BertPreTrainedModel;f.Wav2Vec2CTCTokenizer;f.Wav2Vec2FeatureExtractor;f.Wav2Vec2ForAudioFrameClassification;f.Wav2Vec2ForCTC;f.Wav2Vec2ForSequenceClassification;f.Wav2Vec2Model;f.Wav2Vec2PreTrainedModel;f.Wav2Vec2Processor;f.Wav2Vec2ProcessorWithLM;f.WavLMForAudioFrameClassification;f.WavLMForCTC;f.WavLMForSequenceClassification;f.WavLMForXVector;f.WavLMModel;f.WavLMPreTrainedModel;f.WeSpeakerFeatureExtractor;f.WeSpeakerResNetModel;f.WeSpeakerResNetPreTrainedModel;f.WhisperFeatureExtractor;f.WhisperForConditionalGeneration;f.WhisperModel;f.WhisperPreTrainedModel;f.WhisperProcessor;f.WhisperTextStreamer;f.WhisperTimeStampLogitsProcessor;f.WhisperTokenizer;f.XLMForQuestionAnswering;f.XLMForSequenceClassification;f.XLMForTokenClassification;f.XLMModel;f.XLMPreTrainedModel;f.XLMRobertaForMaskedLM;f.XLMRobertaForQuestionAnswering;f.XLMRobertaForSequenceClassification;f.XLMRobertaForTokenClassification;f.XLMRobertaModel;f.XLMRobertaPreTrainedModel;f.XLMRobertaTokenizer;f.XLMTokenizer;f.XLMWithLMHeadModel;f.XVectorOutput;f.YolosFeatureExtractor;f.YolosForObjectDetection;f.YolosImageProcessor;f.YolosModel;f.YolosObjectDetectionOutput;f.YolosPreTrainedModel;f.ZeroShotAudioClassificationPipeline;f.ZeroShotClassificationPipeline;f.ZeroShotImageClassificationPipeline;f.ZeroShotObjectDetectionPipeline;f.bankers_round;f.cat;f.cos_sim;f.dot;f.dynamic_time_warping;f.env;f.full;f.full_like;f.getKeyValueShapes;f.hamming;f.hanning;f.interpolate;f.interpolate_4d;f.interpolate_data;f.is_chinese_char;f.layer_norm;f.load_image;f.load_video;f.log_softmax;f.magnitude;f.matmul;f.max;f.mean;f.mean_pooling;f.medianFilter;f.mel_filter_bank;f.min;f.ones;f.ones_like;f.permute;f.permute_data;var zx=f.pipeline;f.quantize_embeddings;f.rand;f.read_audio;f.rfft;f.round;f.slice;f.softmax;f.spectrogram;f.stack;f.std_mean;f.topk;f.window_function;f.zeros;f.zeros_like;const Ci=16e3,ju=Ci/1e3,Bx=.3,Rx=.1,Nx=400,jx=Nx*ju,Ux=80,lu=Ux*ju,Vx=250*ju,Wx=30,Gx=512,Kx=Math.ceil(lu/Gx);async function Hx(){try{return!("gpu"in navigator)||!navigator.gpu?!1:(await navigator.gpu.requestAdapter(),!0)}catch(e){return console.error(e),!1}}var Us=(e=>(e.Status="status",e.Output="output",e.Info="info",e.Request="request",e.Error="error",e.Load="load",e))(Us||{}),Uu=(e=>(e.RecordingStart="recording_start",e.RecordingEnd="recording_end",e.Ready="ready",e))(Uu||{}),ud=(e=>(e.UntilNext="until_next",e))(ud||{});let du,pd,hd=Promise.resolve();const Ti=new Float32Array(Wx*Ci);let js=0;const qx=new Nu("int64",[Ci],[]);let zw=new Nu("float32",new Float32Array(2*1*128),[2,1,128]),ua=!1,pa=0;const Qx={webgpu:{encoder_model:"fp32",decoder_model_merged:"q4"},wasm:{encoder_model:"fp32",decoder_model_merged:"q8"}};async function Xx(){return await Lx.from_pretrained("onnx-community/silero-vad",{config:{model_type:"custom"},dtype:"fp32"}).catch(e=>{throw self.postMessage({type:Us.Error,error:e}),e})}async function Jx(e){return await zx("automatic-speech-recognition","onnx-community/moonshine-base-ONNX",{device:e,dtype:Qx[e]}).catch(r=>{throw self.postMessage({type:Us.Error,error:r}),r})}async function Yx(e){if(du===void 0)return console.warn("VAD model not loaded yet"),!1;const r=new Nu("float32",e,[1,e.length]),{stateN:t,output:s}=await(hd=hd.then(n=>du({input:r,sr:qx,state:zw})));zw=t;const i=s.data[0];return i>Bx||ua&&i>=Rx}async function Zx(e,r){if(pd===void 0){console.warn("Transcriber model not loaded yet");return}const{text:t}=await(hd=hd.then(s=>pd(e)));self.postMessage({type:Us.Output,buffer:e,message:t,...r})}function Eb(e=0){self.postMessage({type:Us.Status,status:Uu.RecordingEnd,message:"Transcribing...",duration:ud.UntilNext}),Ti.fill(0,e),js=e,ua=!1,pa=0}const ha=[];function Bw(e){const t=Date.now()-(pa+lu)/Ci*1e3,s=t-js/Ci*1e3,i=t-s,n=(e==null?void 0:e.length)??0,o=Ti.slice(0,js+lu),a=ha.reduce((p,u)=>p+u.length,0),l=new Float32Array(a+o.length);let d=0;for(const p of ha)l.set(p,d),d+=p.length;l.set(o,d),Zx(l,{start:s,end:t,duration:i}),e&&Ti.set(e,0),Eb(n)}async function eT(){const e=await Hx()?"webgpu":"wasm";self.postMessage({type:Us.Info,message:`Using device: "${e}"`}),self.postMessage({type:Us.Info,message:"Loading models...",duration:ud.UntilNext}),du=await Xx(),pd=await Jx(e),await pd(new Float32Array(Ci)),self.postMessage({type:"status",status:"ready",message:"Ready!"}),self.onmessage=async r=>{const{buffer:t}=r.data,s=ua,i=await Yx(t);if(!s&&!i){ha.length>=Kx&&ha.shift(),ha.push(t);return}const n=Ti.length-js;if(t.length>=n){Ti.set(t.subarray(0,n),js),js+=n;const o=t.subarray(n);Bw(o);return}else Ti.set(t,js),js+=t.length;if(i){ua||self.postMessage({type:Us.Status,status:Uu.RecordingStart,message:"Listening...",duration:ud.UntilNext}),ua=!0,pa=0;return}if(pa+=t.length,!(pa{const{type:r}=e.data;switch(r){case Us.Load:eT();break}});